forgedock 1.71.0 → 1.72.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 (53) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +5 -4
  3. package/bin/init-detect.mjs +35 -2
  4. package/bin/lean/admit.mjs +152 -0
  5. package/bin/lean/admit.test.mjs +120 -0
  6. package/bin/lean/attempts.mjs +1 -1
  7. package/bin/lean/batch.mjs +8 -0
  8. package/bin/lean/batch.test.mjs +17 -0
  9. package/bin/lean/concurrency.mjs +7 -2
  10. package/bin/lean/concurrency.test.mjs +16 -3
  11. package/bin/lean/conformance.mjs +2 -0
  12. package/bin/lean/conformance.test.mjs +9 -0
  13. package/bin/lean/effects.mjs +22 -0
  14. package/bin/lean/failure-census.mjs +1 -1
  15. package/bin/lean/heavy.mjs +20 -6
  16. package/bin/lean/heavy.test.mjs +24 -3
  17. package/bin/lean/lean.mjs +97 -5
  18. package/bin/lean/lean.test.mjs +38 -0
  19. package/bin/lean/orchestrate-envhold.test.mjs +14 -0
  20. package/bin/lean/orchestrate-heldroot.test.mjs +32 -0
  21. package/bin/lean/orchestrate.mjs +33 -11
  22. package/bin/lean/queuecause.mjs +42 -0
  23. package/bin/lean/release-cigreen.mjs +18 -4
  24. package/bin/lean/release-cigreen.test.mjs +23 -0
  25. package/bin/lean/release-review.mjs +24 -10
  26. package/bin/lean/release-review.test.mjs +65 -0
  27. package/bin/lean/release.mjs +1 -1
  28. package/bin/lean/release.test.mjs +19 -0
  29. package/bin/lean/schedd.mjs +24 -1
  30. package/bin/lean/schedd.test.mjs +38 -0
  31. package/bin/pool/agent.mjs +61 -18
  32. package/bin/pool/docker-dns.mjs +39 -0
  33. package/bin/pool/docker.mjs +7 -3
  34. package/bin/pool/engine-placement.test.mjs +2 -2
  35. package/bin/pool/image-manifest.test.mjs +13 -0
  36. package/bin/pool/lane-image.mjs +56 -15
  37. package/bin/pool/lane-tools.mjs +26 -12
  38. package/bin/pool/lane-tools.test.mjs +63 -1
  39. package/bin/pool/project-layer.mjs +2 -2
  40. package/bin/pool/router.mjs +2 -1
  41. package/bin/review-staging.mjs +14 -11
  42. package/bin/review-staging.test.mjs +20 -1
  43. package/bin/stats/escapes.mjs +124 -0
  44. package/bin/stats/index.mjs +5 -1
  45. package/bin/stats/quality-ledger.mjs +49 -0
  46. package/bin/stats/quality-ledger.test.mjs +84 -0
  47. package/bin/stats/weekly.mjs +230 -0
  48. package/docs/OUTCOME-CODES.md +2 -1
  49. package/package.json +1 -1
  50. package/pool/README.md +2 -0
  51. package/pool/image/Dockerfile +4 -1
  52. package/pool/image/lane-tools-sets.json +6 -0
  53. package/scripts/lane-variants.mjs +51 -0
@@ -30,6 +30,8 @@ import { lowerPriority } from "./hostload.mjs";
30
30
 
31
31
  export const HEAVY_DEFAULTS = Object.freeze({ enabled: true, max: null, step_mem_mb: 2048, reserve_mb: 1024, ramp_s: 60, max_wait_s: 1800 });
32
32
  export const HEAVY_POLL_MS = 2000;
33
+ export const HEAVY_ERROR_BUDGET_MS = 120000; // #6235: how long an erroring or unreachable agent is retried before the step is deferred
34
+ export const HEAVY_DEFER_CODE = 75; // EX_TEMPFAIL: the step did not run because no heavy token could be leased
33
35
  const LOCK_WAIT_MS = 2000, EMPTY_LOCK_STALE_MS = 5000;
34
36
 
35
37
  const PMS = new Set(["npm", "pnpm", "yarn", "bun"]);
@@ -255,26 +257,34 @@ export async function acquireHeavy(h, entry = {}, { pollMs = HEAVY_POLL_MS, slee
255
257
 
256
258
  /**
257
259
  * #6047: remote-token backend, chosen when CS_HEAVY_BASE (the pool agent's per-sandbox /heavy route) is set. Acquire polls
258
- * while the agent denies, renews the lease on a timer, release is best effort; an unreachable or erroring agent, or a wait past
259
- * `maxWaitMs`, fails open (the step runs, `failOpen: true`). `fetchFn` returns {status, json()}.
260
+ * while the agent denies and renews the lease on a timer; release is best effort. #6235: fails CLOSED. Under elastic accounting a
261
+ * lane is charged only its base, so a step that runs without a token can overcommit host memory. An unreachable or erroring agent is
262
+ * retried with backoff for `errorBudgetMs`; that budget, or a wait past `maxWaitMs`, returns `{denied: true, reason}` and the
263
+ * caller defers the step (it does not run). `fetchFn` returns {status, json()}.
260
264
  */
261
- export async function acquireRemote({ base, credToken = "", fetchFn = (u, o) => fetch(u, o), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = () => Date.now(), pollMs = 5000, renewMs = 60000, maxWaitMs = HEAVY_DEFAULTS.max_wait_s * 1000, setTimer = setInterval, clearTimer = clearInterval } = {}) {
265
+ export async function acquireRemote({ base, credToken = "", fetchFn = (u, o) => fetch(u, o), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = () => Date.now(), pollMs = 5000, renewMs = 60000, maxWaitMs = HEAVY_DEFAULTS.max_wait_s * 1000, errorBudgetMs = HEAVY_ERROR_BUDGET_MS, setTimer = setInterval, clearTimer = clearInterval } = {}) {
262
266
  const call = async (action, body) => {
263
267
  const r = await fetchFn(`${base}/${action}`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${credToken}` }, body: JSON.stringify(body ?? {}), signal: AbortSignal.timeout(10000) });
264
268
  if (r.status !== 200) throw new Error(`heavy ${action}: HTTP ${r.status}`);
265
269
  return r.json();
266
270
  };
267
271
  const t0 = now(), open = { waitMs: 0, queued: 0, holders: 1, release: () => {} };
272
+ let errSince = null, errN = 0;
268
273
  for (;;) {
269
274
  let r;
270
- try { r = await call("acquire"); } catch { return { ...open, waitMs: now() - t0, failOpen: true }; }
275
+ try { r = await call("acquire"); errSince = null; errN = 0; } catch (e) {
276
+ errSince ??= now();
277
+ if (now() - errSince >= errorBudgetMs || now() - t0 >= maxWaitMs) return { ...open, waitMs: now() - t0, denied: true, reason: `heavy gate unavailable: ${e?.message ?? e}` };
278
+ await sleep(Math.min(15000, 1000 * 2 ** Math.min(errN++, 4)));
279
+ continue;
280
+ }
271
281
  if (r?.granted && r.token) {
272
282
  const token = r.token, timer = setTimer(() => { call("renew", { token }).catch(() => {}); }, renewMs);
273
283
  timer?.unref?.();
274
284
  let released = false;
275
285
  return { ...open, waitMs: now() - t0, token, release: () => { if (released) return; released = true; clearTimer(timer); call("release", { token }).catch(() => {}); } };
276
286
  }
277
- if (now() - t0 >= maxWaitMs) return { ...open, waitMs: now() - t0, failOpen: true, timedOut: true };
287
+ if (now() - t0 >= maxWaitMs) return { ...open, waitMs: now() - t0, denied: true, timedOut: true, reason: `no heavy token after ${Math.round((now() - t0) / 1000)}s` };
278
288
  await sleep(Math.min(pollMs, Math.max(1, Number(r?.retry_after_s) * 1000 || pollMs)));
279
289
  }
280
290
  }
@@ -427,9 +437,13 @@ export async function runWrapped(argv, { env: env0 = process.env, open = openHea
427
437
  const hostP = host ?? defaultHost();
428
438
  const priority = Number.isFinite(Number(env.FORGE_LANE_PRIORITY)) && String(env.FORGE_LANE_PRIORITY).trim() !== "" ? Number(env.FORGE_LANE_PRIORITY) : DEFAULT_PRIORITY;
429
439
  const phase = env.FORGE_LANE_PHASE || "step";
430
- const useRemote = Boolean(env.CS_HEAVY_BASE); // #6047: the pool agent's token semaphore; fail-open, else the local file semaphore
440
+ const useRemote = Boolean(env.CS_HEAVY_BASE); // #6047: the pool agent's token semaphore (#6235: fail closed), else the local file semaphore
431
441
  const g = useRemote ? await remote({ base: env.CS_HEAVY_BASE, credToken: env.CS_CRED_TOKEN ?? "", maxWaitMs: c.max_wait_s * 1000 })
432
442
  : await acquireHeavy(open(env.FORGEDOCK_SCHED_DIR || schedDir(env), { env, host: hostP }), { issue: Number(env.FORGE_LANE_ISSUE) || null, phase, priority, mb: c.step_mem_mb });
443
+ if (g.denied && env.FORGE_HEAVY_FAIL_OPEN !== "1") { // #6235: never run a heavy step ungated under elastic accounting; the caller retries or defers
444
+ process.stderr.write(`forgedock heavy: ${name} deferred, ${g.reason ?? "no heavy token"} (exit ${HEAVY_DEFER_CODE}; FORGE_HEAVY_FAIL_OPEN=1 runs it ungated)\n`);
445
+ return { code: HEAVY_DEFER_CODE, signal: null };
446
+ }
433
447
  if (env.FORGE_HEAVY_WAITS) { try { appendFileSync(env.FORGE_HEAVY_WAITS, JSON.stringify({ phase, name, waitMs: g.waitMs, queued: g.queued }) + "\n"); } catch { /* metrics are best effort */ } }
434
448
  let cores = 1; try { cores = hostP.cores() || 1; } catch { /* 1 */ }
435
449
  cores = quotaCores({ cores, read, env }); // #6047: the container's CPU quota, never the VM
@@ -504,9 +504,30 @@ describe("remote token backend (#6047)", () => {
504
504
  const calls = [], g = await acquireRemote(opts(calls, [resp(200, { granted: false, retry_after_s: 1 }), resp(200, { granted: false }), resp(200, { granted: true, token: "t2" })]));
505
505
  assert.equal(g.token, "t2"); assert.equal(calls.filter((c) => c === "acquire").length, 3);
506
506
  });
507
- it("fails open when the agent is unreachable or errors", async () => {
508
- assert.equal((await acquireRemote(opts([], [new Error("ECONNREFUSED")]))).failOpen, true);
509
- assert.equal((await acquireRemote(opts([], [resp(500, {})]))).failOpen, true);
507
+ it("fails closed (#6235): an unreachable or erroring agent is retried with backoff, then denies", async () => {
508
+ let t = 0; const clock = { now: () => t, sleep: async (ms) => { t += ms; } };
509
+ const calls = [], g = await acquireRemote({ ...opts(calls, [new Error("ECONNREFUSED")]), ...clock, errorBudgetMs: 20000, fetchFn: async (u) => { calls.push(u); throw new Error("ECONNREFUSED"); } });
510
+ assert.equal(g.denied, true); assert.ok(!g.failOpen); assert.match(g.reason, /ECONNREFUSED/); assert.ok(calls.length > 2, "retried before giving up");
511
+ const h = await acquireRemote({ ...opts([], [resp(500, {})]), ...clock, errorBudgetMs: 1000, fetchFn: async () => resp(500, {}) });
512
+ assert.equal(h.denied, true);
513
+ });
514
+ it("a transient agent error recovers into a grant", async () => {
515
+ const calls = [], g = await acquireRemote(opts(calls, [new Error("reset"), resp(502, {}), resp(200, { granted: true, token: "t3" })]));
516
+ assert.equal(g.token, "t3"); assert.ok(!g.denied);
517
+ });
518
+ it("a wait past maxWaitMs denies instead of running the step", async () => {
519
+ let t = 0;
520
+ const g = await acquireRemote({ ...opts([], []), now: () => t, sleep: async (ms) => { t += ms; }, maxWaitMs: 3000, fetchFn: async () => resp(200, { granted: false, retry_after_s: 1 }) });
521
+ assert.equal(g.denied, true); assert.equal(g.timedOut, true);
522
+ });
523
+ it("runWrapped defers (exit 75) a denied step and never runs it; FORGE_HEAVY_FAIL_OPEN=1 is the explicit escape", async () => {
524
+ const ran = [], run = async (cmd, args, env) => { ran.push(env); return { code: 0, signal: null }; };
525
+ const remote = async () => ({ waitMs: 0, holders: 1, denied: true, reason: "heavy gate unavailable: x", release() {} });
526
+ const host = { memAvailableMb: () => 12000, cores: () => 4 }, dir = tmpDir("heavy-rw-");
527
+ const r = await runWrapped(["run", "--name", "pnpm", "--", "pnpm", "install"], { env: { CS_HEAVY_BASE: "http://h/x", FORGEDOCK_SCHED_DIR: dir }, run, remote, host, read: () => { throw new Error("none"); } });
528
+ assert.equal(r.code, 75); assert.equal(ran.length, 0);
529
+ const o = await runWrapped(["run", "--name", "pnpm", "--", "pnpm", "install"], { env: { CS_HEAVY_BASE: "http://h/x", FORGEDOCK_SCHED_DIR: dir, FORGE_HEAVY_FAIL_OPEN: "1" }, run, remote, host, read: () => { throw new Error("none"); } });
530
+ assert.equal(o.code, 0); assert.equal(ran.length, 1);
510
531
  });
511
532
  it("runWrapped uses the remote backend only when CS_HEAVY_BASE is set; otherwise the local file semaphore", async () => {
512
533
  const ran = [], run = async (cmd, args, env) => { ran.push(env); return { code: 0, signal: null }; };
package/bin/lean/lean.mjs CHANGED
@@ -31,6 +31,7 @@ import { namedPaths, isTrustedIssueComment, prodFailureSignal } from "./prefilte
31
31
  import { writeStatus, postUpsert, postKeyed, isKeyedPost, isStatusPost, isUpsertPost, hasSection, clearPipelineLabels, IN_PLACE_MARKERS, commentId, contractKey } from "./statuscomment.mjs";
32
32
  import { decidePost } from "./commentstate.mjs"; // #5979
33
33
  import { repeatSignature, countIdentical, shouldPark, summaryComment } from "./failure-stop.mjs"; // #5979
34
+ import { baseHealth, fetchBaseChecks, baseRedComment, hasAdmitComment, classifyDryRun, renderStamp, stampable, isNonStoppable, inputOf, fingerprintStop, stopReason, admitEvent } from "./admit.mjs"; // #6206
34
35
  import { checksAt, mergeCheckEntries, CHECKS_FILE } from "./postdeploy-check.mjs";
35
36
  import { matchBaselines, baselineFailures, foldRegression } from "./baselines.mjs";
36
37
  import { readRollouts, detectNewOffKeys, rolloutModes, liveDeferralBlocks } from "./activation.mjs";
@@ -58,7 +59,7 @@ import { computeTrigger, riskPathHits, TRIGGER_MODES, pathDomains, parseEnforceD
58
59
  import { hostCapabilityBlock, contractHostNeeds } from "./execution.mjs";
59
60
  import { baseMergeOnlyBlock, envGapBlockCode, toolGapFailures, packageDirsMissingDeps, failureOutsideDiff } from "./envgap.mjs"; // #6106
60
61
 
61
- const MISSING_TOOL_RE = /command not found|not found in PATH|no such file or directory.*\b(?:docker|promtool)\b|\b(?:docker|promtool)\b[^\n]{0,80}(?:not (?:installed|found|available)|no such file|cannot connect|daemon)|cannot connect to the docker daemon|no docker daemon|no module named|ModuleNotFoundError|\bENOENT\b[^\n]{0,60}spawn/i;
62
+ const MISSING_TOOL_RE = /command not found|not found in PATH|no such file or directory.*\b(?:docker|promtool)\b|\b(?:docker|promtool)\b[^\n]{0,80}(?:not (?:installed|found|available)|no such file|cannot connect|daemon)|cannot connect to the docker daemon|no docker daemon|image[^\n]{0,30}present locally|unable to find image|valid docker environment|no module named|ModuleNotFoundError|\bENOENT\b[^\n]{0,60}spawn/i;
62
63
  /** #4685: true when a builder's block summary names a missing tool or module (environment), not a credential. */
63
64
  /** #5623: a contract problem the builder can fix in its own session (shape, typed fields, test-plan rules, check ids), as
64
65
  * opposed to one that needs the issue changed (quote not verbatim) or a person. */
@@ -85,6 +86,7 @@ import { parseCoupled, coupledFailures } from "./coupled.mjs";
85
86
  import { analyzeRelaxations, relaxationFailures } from "./relaxation.mjs";
86
87
  import { startSpeculative } from "./overlap.mjs";
87
88
  import { loadGuards, selectGuards, runGuards, supersededIds, supersessionComment, weakGuardNotes } from "./guardgate.mjs";
89
+ import { buildMergeLedger } from "../stats/quality-ledger.mjs";
88
90
  import { freshFix, issueSummary, firstPassOf, sessionCostDelta, mergeNarrowTasks } from "./fixround.mjs";
89
91
  import { floorRoute, parseBuilderRouting, provisionalRoute, routeBuilder, shouldEscalate } from "./routing.mjs";
90
92
  import { makeTurnBudget, TURN_BUDGET_DEFAULTS, scaledExtra, laneSize, recoverySize, wrapupGrant, budgetDigest } from "./budget.mjs";
@@ -150,6 +152,7 @@ export const RECOVER_HOW = Object.freeze({
150
152
  [OUTCOME_CODES.ENV_TOOL_MISSING]: "a validate command could not run because the host lacks the tool or module named in the earlier run's detail; the change may already be correct. Do not edit the deliverables for it and never install anything globally: run the same check through the repo's own toolchain (its virtualenv, lockfile-pinned runner or package scripts), record that exit under the same validate id and name the command you used in your summary",
151
153
  [ENV_VALIDATE_PLACEMENT]: "an earlier run in a remote sandbox saw a frozen validate command fail; this host is a different environment (Docker, browsers, network, repo-local services). Rerun the frozen command unchanged here and record its real exit under the same validate id; change the deliverables only if it fails here too, and never substitute or narrow it for an environment gap",
152
154
  [ENV_VALIDATE_TIMEOUT]: "a validate command timed out (exit 124) on the engine's rerun, even after one longer retry: host load, not a failed check; the change may already be correct. Do not edit the deliverables for it: run the same command narrowed to the changed files (or through the repo's own cached toolchain) with a longer timeout, record that exit under the same validate id and name the command in your summary",
155
+ [OUTCOME_CODES.ENV_CAPABILITY_DOCKER]: "the earlier run's validate command needed a Docker daemon or image the sandbox lacked; this placement has Docker (or the validate is deferred to CI by a FORGE:DECISION). Re-run the checks here and fix only real failures; never stub out the container the test needs",
153
156
  [OUTCOME_CODES.ENV_CAPABILITY_REMOTE]: "the earlier run ran in a remote sandbox that lacks a host-only capability (SOPS/age key, ops credentials, read-only prod monitor SSH); this host has it. Do the work that needed it now, with the host's own tools and credentials, and never print or commit a secret in the clear",
154
157
  [OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED]: "an earlier run's conformance check found a requirement or validate command not done after one builder resume; the branch holds its work. For each named gap deliver the requirement against the frozen contract, adding any file it needs as an `add-deliverable` amendment, and re-run the validate commands",
155
158
  [OUTCOME_CODES.CONFORMANCE_OMISSION]: "an earlier run's review found a requirement the change left out or narrowed after one builder resume; the branch holds its work. For each named gap either deliver the requirement (adding any needed file as an `add-deliverable` amendment) or, when the clause is optional, unquantified or outside the issue's acceptance criteria, record an `add-requirement` / `defer` amendment with a why so the engine files a tracked follow-up instead of stopping",
@@ -409,7 +412,8 @@ export async function runCore(o) {
409
412
  const sessionCosts = new Map(); // #4407: session id -> last reported cumulative cost
410
413
  let sessionId = null;
411
414
 
412
- const ev = (e) => appendEvent(dir, issue, e, { repo }); // #4432: the run log is keyed by repo + issue
415
+ let ciVerifies = 0, ciMergeFixRounds = 0; // #6203: counted off the run-log events for the MERGE_LEDGER record
416
+ const ev = (e) => { if (e?.event === "CI_VERIFY") ciVerifies++; else if (e?.event === "CI_FIX_ROUND") { if (e.trigger === "merge") ciMergeFixRounds++; } return appendEvent(dir, issue, e, { repo }); }; // #4432: the run log is keyed by repo + issue
413
417
  /** #5435: time one sandbox_start step (SANDBOX_STEP event + ledger sub-timing); the result and errors pass through. */
414
418
  const step = async (name, fn) => {
415
419
  const s0 = now();
@@ -788,6 +792,12 @@ export async function runCore(o) {
788
792
  const phases = phaseLedger.snapshot(); // #4908: run log gets the nested ledger, FORGE:TELEMETRY the flattened scalars
789
793
  ev({ ...term, phases });
790
794
  await emit({ ...term, ...flattenPhases(phases) });
795
+ if (reason === "merged") { // #6203: one MERGE_LEDGER record per merge (first_pass, human touches, test delta, CI attempts, deduped cost, wall per phase)
796
+ try {
797
+ await emit(buildMergeLedger({ firstPass: firstPassOf(builderTriggers), recovered: Boolean(recover), attempt: recover?.attempt ?? o.attempt ?? 1, ciVerifies: ciVerifies + ciMergeFixRounds, ciFixRounds: builderTriggers.filter((x) => x.trigger === "ci_red" || x.trigger === "merge_ci").length,
798
+ files: String(await git(["diff", "--name-only", `${base}...HEAD`]).catch(() => "")).split("\n"), comments: allComments(), sinceMs: Date.now() - (now() - t0), costUsd: usage.cost_usd, phases, wallMs: now() - t0, engineVersion: ENGINE_VERSION, tier: route?.tier, model: route?.model, pr: extra.pr }));
799
+ } catch { /* the ledger is best effort */ }
800
+ }
791
801
  // #4297: only a final failure the runner never requeues puts needs-human back (needsHuman() relabels on its own path). invalid,
792
802
  // decomposed and dependency-* are legitimate non-failure endings; deferred/engine-error may be requeued, so the batch runner
793
803
  // (orchestrate settle, relabelNeedsHuman) relabels those once they are final. #4302: a non-final attempt never relabels; the runner
@@ -864,6 +874,15 @@ export async function runCore(o) {
864
874
  const error = String(e?.message ?? e).slice(0, 200);
865
875
  T.anomalies.push(`needs-human ${step} failed: ${error}`); ev({ event: "NEEDS_HUMAN_LABEL_FAILED", step, error });
866
876
  };
877
+ /** #6206: ` base=<12> in=<16> code=<code>` appended to a park's sig line: the fingerprint stop admits again only when the base head or the input changed. Never throws. */
878
+ async function admitStamp(code) {
879
+ if (!stampable(code)) return "";
880
+ try {
881
+ const sha = String(await git(["rev-parse", base])).trim();
882
+ const s = renderStamp({ base: sha, input: inputOf({ iss, comments: allComments(), trusted: (c) => c?.__mine === true || isTrustedIssueComment(c), engineVersion: ENGINE_VERSION }), code });
883
+ return s ? ` ${s}` : "";
884
+ } catch { return ""; }
885
+ }
867
886
  async function needsHuman(why, code = OUTCOME_CODES.ENGINE_ERROR, { ask: askText, note: askNote = "", ...extra } = {}) {
868
887
  // #4725: a recorded premise (`Premise: <kind>:<arg>`) that already holds is no blocker: no label, the lane runs again.
869
888
  const predicate = parsePredicate(why);
@@ -880,16 +899,16 @@ export async function runCore(o) {
880
899
  }
881
900
  // #5979: the second identical failure (same code and normalised detail as an earlier NEEDS_HUMAN/PARKED of this issue) parks with one summary, no recovery
882
901
  const sig = repeatSignature(code, why);
883
- const stoppable = code !== OUTCOME_CODES.BUILDER_BLOCKED && code !== OUTCOME_CODES.FAILURE_REPEATED && !ENV_ENGINE_OWNED_CODES.includes(code);
902
+ const stoppable = !isNonStoppable(code); // #6231: the one non-stoppable list (admit.mjs)
884
903
  const identical = stoppable ? countIdentical(allComments(), sig, (c) => c?.__mine === true || isTrustedIssueComment(c)) + 1 : 1;
885
904
  if (shouldPark(identical)) {
886
- try { await post("FORGE:PARKED", summaryComment({ attempts: identical, code, detail: why, sig })); } catch (e) { labelFailed("comment", e); }
905
+ try { await post("FORGE:PARKED", summaryComment({ attempts: identical, code, detail: why, sig: `${sig}${await admitStamp(code)}` })); } catch (e) { labelFailed("comment", e); }
887
906
  try { await ghc(["issue", "edit", String(issue), "-R", repo, "--add-label", "needs-human", "--add-label", parkedLabel(OUTCOME_CODES.FAILURE_REPEATED)]); } catch (e) { labelFailed("label", e); }
888
907
  T.decisions.push(`Identical failure ${code} (${sig}) seen ${identical}x: parked as ${OUTCOME_CODES.FAILURE_REPEATED}, not relaunched`);
889
908
  return finish("needs-human", why, { code: OUTCOME_CODES.FAILURE_REPEATED, ...extra, ...(recover ? { recovery: true } : {}) }, OUTCOME_CODES.FAILURE_REPEATED);
890
909
  }
891
910
  const notes = [premiseAnnotation(predicate), closedEdgeNote(closedDeps), link, askNote].filter(Boolean).join("\n");
892
- try { await post("FORGE:NEEDS_HUMAN", `## Needs human\n${why}${notes ? `\n\n${notes}` : ""}${recoverUnlabelled ? `\n\n${laneRecoveryEvidence("needs-human", code, "")}` : ""}\n\nsig=${sig}\n\n_${usageLine()}_`); }
911
+ try { await post("FORGE:NEEDS_HUMAN", `## Needs human\n${why}${notes ? `\n\n${notes}` : ""}${recoverUnlabelled ? `\n\n${laneRecoveryEvidence("needs-human", code, "")}` : ""}\n\nsig=${sig}${await admitStamp(code)}\n\n_${usageLine()}_`); } // #6206: the stamp (base head, input hash, code) lets the next admit see that nothing changed
893
912
  catch (e) { labelFailed("comment", e); }
894
913
  // #5423/#5755: an environment gap is the engine's to recover or hold on an env issue, so a first lane leaves the issue visible; a final recovery lane (no seam) still labels
895
914
  if (!(!recover && ENV_ENGINE_OWNED_CODES.includes(code))) {
@@ -2320,6 +2339,70 @@ export async function runCore(o) {
2320
2339
  return found;
2321
2340
  }
2322
2341
 
2342
+ /**
2343
+ * #6206: cheap deterministic checks before the first builder/plan session. Returns a finished lane result when the lane is doomed (the issue, the
2344
+ * base or the environment cannot succeed as things stand), else null. Every outcome is one ADMIT_PROBE telemetry event with builder_spend_usd 0.
2345
+ * `o.admitProbe: false` turns it off. Seams that are absent (no required-check read, no login probe, no run seam) skip their step.
2346
+ */
2347
+ async function admitProbe(frozenNow) {
2348
+ if (o.admitProbe === false) return null;
2349
+ const t0a = now(), trustedC = (c) => c?.__mine === true || isTrustedIssueComment(c);
2350
+ const rec = async (r) => { const e = admitEvent({ ...r, ms: now() - t0a }); ev(e); try { await emit(e); } catch { /* telemetry is best effort */ } };
2351
+ let head = ""; try { head = String(await git(["rev-parse", base])).trim(); } catch { /* unreadable base: the base steps fail open */ }
2352
+ if (!recover) { // 4. failure fingerprint: parked before on this base head and this input
2353
+ const input = inputOf({ iss, comments: allComments(), trusted: trustedC, engineVersion: ENGINE_VERSION });
2354
+ const hit = fingerprintStop({ comments: allComments(), base: head, input, trusted: trustedC });
2355
+ if (hit) {
2356
+ await rec({ outcome: "fingerprint_stop", code: OUTCOME_CODES.FAILURE_REPEATED, detail: `${hit.code} ${hit.sig}` });
2357
+ T.decisions.push(`Admit probe: ${stopReason(hit)}`);
2358
+ return await needsHuman(`Admit probe (#6206): ${stopReason(hit)}.`, OUTCOME_CODES.FAILURE_REPEATED);
2359
+ }
2360
+ }
2361
+ if (head && lane && base === `origin/${lane}` && repo && io.baseRequiredChecks) { // 1. base health
2362
+ let required = [], rows = null;
2363
+ try { required = (await io.baseRequiredChecks(lane)) ?? []; } catch { /* unreadable: no evidence */ }
2364
+ if (required.length) { try { rows = await fetchBaseChecks({ gh: ghc, repo, sha: head }); } catch { rows = null; } }
2365
+ if (rows) {
2366
+ const cs = allComments().filter(trustedC);
2367
+ const contractText = cs.filter((c) => String(c?.body ?? "").startsWith("<!-- FORGE:CONTRACT -->")).map((c) => parseContractComment(String(c.body))?.text ?? "").pop() ?? "";
2368
+ const h = baseHealth({ checks: rows, required, issue: { text: `${iss?.title ?? ""}\n${iss?.body ?? ""}`, contractText, labels: iss?.labels ?? [], linkedBaseRed: cs.some((c) => /<!--\s*FORGE:BASE_RED\b/.test(String(c?.body ?? ""))) } }); // #6232: whole-token name, contract files, label or link
2369
+ if (h.red) {
2370
+ const key = `base.red ${base}@${head.slice(0, 12)}`;
2371
+ if (!hasAdmitComment(allComments(), key)) { try { await post("FORGE:ADMIT_PROBE", baseRedComment({ base, sha: head, failing: h.failing })); } catch (e) { T.anomalies.push(`Admit probe comment not posted: ${String(e?.message ?? e).slice(0, 160)}`); } }
2372
+ const detail = `base ${base} is red on required check(s) ${h.failing.map((f) => `${f.name}${f.url ? ` (${f.url})` : ""}`).join(", ")}, which this issue does not touch; deferred before any builder session`;
2373
+ await rec({ outcome: "base_red", code: OUTCOME_CODES.BASE_RED, detail, checks: h.failing.map((f) => ({ name: f.name, url: f.url })) });
2374
+ T.decisions.push(`Admit probe: ${detail}`);
2375
+ return await finish("deferred", detail, { code: OUTCOME_CODES.BASE_RED, retryInSeconds: 900 }, OUTCOME_CODES.BASE_RED);
2376
+ }
2377
+ }
2378
+ }
2379
+ if (io.claudeAuthProbe && !smartRotator && !sandboxCred) { // 2. environment: the claude login answers (`claude auth status`, no model call)
2380
+ let a = null; try { a = await io.claudeAuthProbe({ env: { ...(io.env ?? process.env) } }); } catch { /* no verdict */ } // #6233: the lane's own env (CLAUDE_CONFIG_DIR, API key)
2381
+ if (a?.warning) T.anomalies.push(`Admit probe: ${a.warning}`); // unknown verdict: fail open, record it
2382
+ if (a && a.ok === false) {
2383
+ const detail = "claude CLI login does not answer (expired or invalid); deferred before any builder session until the login is fixed";
2384
+ await rec({ outcome: "env_auth", code: OUTCOME_CODES.BACKEND_AUTH, detail });
2385
+ return await finish("deferred", detail, { code: OUTCOME_CODES.BACKEND_AUTH, retryInSeconds: AUTH_RETRY_SECONDS }, OUTCOME_CODES.BACKEND_AUTH);
2386
+ }
2387
+ }
2388
+ if (frozenNow && o.placement?.where !== "remote" && (io.probeCommand || io.preflightRun)) { // 3. contract dry-run of the reused frozen contract (a fresh lane has none yet; a remote one runs its own preflight below)
2389
+ const w = Math.max(0, Number(contextWaitSeconds) || 0) * 1000;
2390
+ let misses = await preflightValidates(frozenNow).catch(() => []);
2391
+ if (misses.length && !depsDone) { await within(depsP, w); misses = await preflightValidates(frozenNow).catch(() => []); } // dependencies may provide the tool
2392
+ const dep = await depOwnerOf(), dr = classifyDryRun({ misses, owned: (t) => t === "forgedock" || dep.owner(t) !== null || hasRecipe(t) });
2393
+ if (dr.docker.length) {
2394
+ T.decisions.push(`FORGE:DECISION: validate ${dr.docker.join(", ")} needs Docker, which this placement lacks; it is deferred to CI instead of parking the lane later (admit probe)`);
2395
+ await rec({ outcome: "contract_docker_deferred", code: OUTCOME_CODES.ENV_CAPABILITY_DOCKER, detail: `validate ${dr.docker.join(", ")} deferred to CI`, checks: dr.docker.map((id) => ({ name: id })) });
2396
+ }
2397
+ if (dr.tools.length) {
2398
+ const detail = `the frozen contract's validate ${dr.ids.join(", ")} needs ${dr.tools.join(", ")}, which this placement lacks (probed on the base tree); the lane ends before any builder session and is re-placed or recovered`;
2399
+ await rec({ outcome: "contract_tool_missing", code: OUTCOME_CODES.ENV_TOOL_MISSING, detail, checks: dr.tools.map((t) => ({ name: t })) });
2400
+ return await needsHuman(`Admit probe (#6206): ${detail}.`, OUTCOME_CODES.ENV_TOOL_MISSING);
2401
+ }
2402
+ }
2403
+ await rec({ outcome: "admitted" });
2404
+ return null;
2405
+ }
2323
2406
  const isSplit = (iss.labels ?? []).some((l) => (l?.name ?? l) === SPLIT_LABEL);
2324
2407
  /**
2325
2408
  * #4211: the refactor:split step. One tool-less grouping call over the symbol index (none for a chained plan), the
@@ -2527,6 +2610,10 @@ export async function runCore(o) {
2527
2610
  ev(rec); await emit(rec);
2528
2611
  T.decisions.push(`Pre-contract sessions provisionally routed to the ${preRoute.tier} tier (${preRoute.class}: ${preRoute.reason})`);
2529
2612
  }
2613
+ { // #6206: the admit probe: base health, login, contract dry-run and the failure fingerprint, before any builder or plan session (zero builder spend, no LLM)
2614
+ const stop = await admitProbe(frozen);
2615
+ if (stop) return stop;
2616
+ }
2530
2617
  if (!planOnly) await label("building"); // #5831
2531
2618
  // #4450: the light lane (lean.light mode on, eligible, fresh lane): one builder session, derived contract, or an upgrade
2532
2619
  const waitMs = Math.max(0, Number(contextWaitSeconds) || 0) * 1000, tHot = now();
@@ -3934,6 +4021,11 @@ export async function runCore(o) {
3934
4021
  T.anomalies.push("Contract defect: a frozen validate command is a runner CLI usage error");
3935
4022
  return await needsHuman(`Contract defect (not a conformance failure): a frozen validate command is rejected by its runner's CLI, so no builder resume was spent and nothing merged:\n${failures.map((f) => `- ${f.code}: ${f.detail}`).join("\n")}\n\nRecovery re-plans the command (vitest: --reporter=dot, not -q).`, OUTCOME_CODES.CONTRACT_INVALID_COMMAND);
3936
4023
  }
4024
+ if (failures.every((f) => /^docker(?: daemon)?$/i.test(f.tool ?? ""))) { // #6196: no Docker daemon/image where the validate ran; re-placed on the host, else deferred to CI
4025
+ T.anomalies.push("Environment error: a validate command needs Docker (no daemon or image in this sandbox)");
4026
+ T.decisions.push("FORGE:DECISION: the Docker-dependent validate is an environment gap of this sandbox; it is re-placed on the host, else deferred to CI");
4027
+ return await needsHuman(`Environment error (not a conformance failure): a validate command needs a Docker daemon or image this sandbox lacks, so it could not run; no builder resume was spent and nothing merged:\n${failures.map((f) => `- ${f.code}: ${f.detail}`).join("\n")}\n\nRecovery re-places the lane on a host with Docker; where that is off, the validate is deferred to CI (FORGE:DECISION).`, OUTCOME_CODES.ENV_CAPABILITY_DOCKER);
4028
+ }
3937
4029
  const tools = [...new Set(failures.filter((f) => f.tool).map((f) => f.tool))].join(", ");
3938
4030
  T.anomalies.push(`Environment error: validate command(s) could not run, the host is missing ${tools}`);
3939
4031
  return await needsHuman(`Environment error (not a conformance failure): the host is missing ${tools}, so validate command(s) could not run; no builder resume was spent and nothing merged:\n${failures.map((f) => `- ${f.code}: ${f.detail}`).join("\n")}\n\nInstall it on the host or run the check through the repo's own toolchain, then rerun.`, OUTCOME_CODES.ENV_TOOL_MISSING);
@@ -575,6 +575,44 @@ describe("core work-on", () => {
575
575
  assert.equal((await run(before)).code, "failure.repeated", "a decision older than the park does not clear it");
576
576
  });
577
577
 
578
+ it("#6206 a park carries a base/input/code stamp; the same base head and input is not re-admitted (no builder session), a moved base is", async () => {
579
+ const bot = (body) => ({ author: { login: "rapiercraft-forgedock" }, body });
580
+ const first = world({ changed: [], result: { status: "fixed", summary: "x", evidence: [], tests: [] } });
581
+ await run(first);
582
+ const nh = first.comments.find((c) => c.includes("<!-- FORGE:NEEDS_HUMAN -->"));
583
+ assert.ok(nh && /sig=[0-9a-f]{12} base=\S{1,12} in=[0-9a-f]{16} code=\S+/.test(nh), nh);
584
+ const prior = first.comments.map(bot), same = world({ changed: [], viewComments: prior });
585
+ const r = await run(same);
586
+ assert.equal(r.code, "failure.repeated");
587
+ assert.equal(same.calls.filter((c) => c[0] === "runner").length, 0, "no builder session on an unchanged base and input");
588
+ assert.ok(same.telemetry.some((e) => e.event === "ADMIT_PROBE" && e.outcome === "fingerprint_stop" && e.builder_spend_usd === 0), JSON.stringify(same.telemetry));
589
+ const moved = world({ changed: [], baseHeads: ["ffffffffffff1111"], viewComments: prior });
590
+ await run(moved);
591
+ assert.ok(!moved.telemetry.some((e) => e.event === "ADMIT_PROBE" && e.outcome === "fingerprint_stop"), "a moved base head admits again");
592
+ const off = world({ changed: [], viewComments: prior });
593
+ await run(off, { admitProbe: false });
594
+ assert.ok(!off.telemetry.some((e) => e.event === "ADMIT_PROBE"));
595
+ });
596
+
597
+ it("#6206 a base red on a required check the issue does not touch defers base.red with the check links before any builder session; a red the issue names admits", async () => {
598
+ const red = (name) => JSON.stringify({ name, conclusion: "failure", url: `https://github.com/o/r/runs/${name}`, completed_at: "2026-11-28T10:00:00Z", summary: "" });
599
+ const mk = (title) => {
600
+ const w = world({ title });
601
+ const gh = w.io.gh;
602
+ w.io.baseRequiredChecks = async () => ["e2e"];
603
+ w.io.gh = async (a, opts) => (a[0] === "api" && a.some((x) => /\/check-runs$/.test(x)) ? `${red("e2e")}\n` : gh(a, opts));
604
+ return w;
605
+ };
606
+ const w = mk("foo breaks");
607
+ const r = await run(w);
608
+ assert.equal(r.code, "base.red");
609
+ assert.equal(w.calls.filter((c) => c[0] === "runner").length, 0);
610
+ assert.ok(w.comments.some((c) => c.includes("Admit probe: base is red") && /(^|[\s(<])https:\/\/github\.com\/o\/r\/runs\/e2e([\s)>]|$)/m.test(c)));
611
+ assert.ok(w.telemetry.some((e) => e.event === "ADMIT_PROBE" && e.outcome === "base_red" && e.builder_spend_usd === 0));
612
+ const named = mk("fix the red e2e check");
613
+ assert.notEqual((await run(named)).code, "base.red");
614
+ });
615
+
578
616
  it("#6076 an unhappy terminal posts one FORGE:LANE_AUDIT; a failing audit post leaves the terminal reason unchanged", async () => {
579
617
  const block = { status: "blocked", summary: "need creds", block: { kind: "human", why: "credentials" } };
580
618
  const w = world({ changed: [], result: block });
@@ -383,3 +383,17 @@ describe("#5988: breaker scoped by signature and agent", () => {
383
383
  assert.ok(r.updates.some((u) => u.outcome === "breaker"), "bounded: the batch breaker trips");
384
384
  });
385
385
  });
386
+
387
+ describe("#6196 env.capability_docker", () => {
388
+ const dock = (more = {}) => ({ terminalReason: "needs-human", code: "env.capability_docker", detail: "Environment error: a validate command needs a Docker daemon or image this sandbox lacks", placement: { where: "remote" }, ...more });
389
+ const rem = (hostFallback) => ({ max: 2, isRemote: () => true, place: () => ({ where: "remote", reason: "test" }), admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0, ...(hostFallback === undefined ? {} : { hostFallback }) });
390
+ it("is recovered on the host when host fallback is on", async () => {
391
+ const r = await harness({ script: { 3: [dock(), MERGED] }, extra: { remote: rem() }, envHold: null });
392
+ assert.deepEqual(r.calls.map((c) => c.n), [3, 3]);
393
+ assert.equal(r.byIssue[3].outcome, "merged");
394
+ });
395
+ it("records the CI-defer decision and does not re-place on the host when host fallback is off", async () => {
396
+ const r = await harness({ script: { 3: [dock()] }, extra: { remote: rem(false) }, envHold: null });
397
+ assert.ok(r.decisions.some((d) => d.issue === 3 && /no host re-placement for env\.capability_docker.*deferred to CI/.test(d.what)));
398
+ });
399
+ });
@@ -70,3 +70,35 @@ describe("#5893 held needs-human root readmit", () => {
70
70
  assert.ok(!again.updates.some((u) => u.outcome === "readmitted"));
71
71
  });
72
72
  });
73
+
74
+ // #6197: an --add reaches a batch whose every pending issue is operator-held within one poll.
75
+ describe("#6197 add to an all-held batch", () => {
76
+ for (const [name, hold] of [["hold expiry", { 1: { expiresAt: new Date(Date.now() + 3600_000).toISOString() } }], ["no expiry (finalise path)", {}]]) {
77
+ it(`held pending with ${name}: an add dispatches within one pollMs`, async () => {
78
+ const ran = [], naps = [];
79
+ let added = [], napped = 0, stop = false;
80
+ const p = orchestrate({ issues: [1], parallel: 1, pollMs: 50, store: memStore(), getHeld: () => [1], getHoldInfo: () => hold, expireHolds: () => [], getCancelled: () => (stop ? { at: new Date().toISOString(), reason: "test" } : null),
81
+ getAdded: () => { const a = added; return a; },
82
+ sleep: async (ms) => { naps.push(ms); if (++napped === 1) added = [7]; await sleep(1); },
83
+ runOne: async (n) => { ran.push(n); stop = true; return MERGED; } });
84
+ if (name.startsWith("no")) added = [7];
85
+ await Promise.race([p, sleep(1500)]);
86
+ stop = true; await Promise.race([p, sleep(500)]);
87
+ assert.deepEqual(ran, [7]);
88
+ assert.ok(naps.every((ms) => ms <= 50), `every nap is poll-capped: ${naps}`);
89
+ });
90
+ }
91
+ it("an add is read within one pollMs while the only pending issue waits on a long notBefore timer", async () => {
92
+ const ran = [], naps = [];
93
+ let added = [], napped = 0, stop = false;
94
+ const store = memStore();
95
+ store.save({ v: 1, order: [2], results: {}, running: {}, pending: [2], notBefore: { 2: Date.now() + 3600_000 } });
96
+ const p = orchestrate({ issues: [2], parallel: 1, pollMs: 50, store, getAdded: () => added,
97
+ sleep: async (ms) => { if (stop) throw new Error("test over"); naps.push(ms); if (++napped === 1) added = [7]; await sleep(1); },
98
+ runOne: async (n) => { ran.push(n); stop = true; return MERGED; } });
99
+ await Promise.race([p.catch(() => {}), sleep(1500)]);
100
+ stop = true; await Promise.race([p.catch(() => {}), sleep(500)]);
101
+ assert.deepEqual(ran, [7]);
102
+ assert.ok(naps.every((ms) => ms <= 50), `every nap is poll-capped: ${naps}`);
103
+ });
104
+ });
@@ -125,6 +125,7 @@
125
125
  * the queue order except that decomposed sub-issues go first. A settled row carries `est_minutes` (estimated vs. actual).
126
126
  */
127
127
  import { decideClear, decideAutoReset } from "./clear-breaker.mjs";
128
+ import { createQueueClock } from "./queuecause.mjs";
128
129
  import { RECONCILE_MS, BREAKER_COOLDOWN_MS, diffSelection, readmitDue, needsDecisionDigest, environmentalDetail, closesManually } from "./reconcile.mjs";
129
130
  import { parseDependsOn } from "../engine/phases.mjs";
130
131
  import { classifyNeedsHuman, recoveryCodeOf, recoveryClassOf, OUTCOME_CODES, ENV_VALIDATE_PLACEMENT, ENV_VALIDATE_TIMEOUT, MECHANICAL_CODES } from "../engine/outcome-codes.mjs";
@@ -376,6 +377,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
376
377
  const deferrals = toMap(saved?.deferrals);
377
378
  const capReasons = toMap(saved?.capReasons); // #5938: issue -> the pool's last `sandbox.capacity` / host-disk reason (read by the batch health stall verdict)
378
379
  const capDefers = toMap(saved?.capDeferrals); // #5112: issue -> `sandbox.capacity` deferrals (uncapped, so not in `deferrals`)
380
+ const capQuiet = new Set(); // #6204: issues whose current capacity wait was already logged once
379
381
  const capFellBack = new Set(); // #5112: issues already reported as a capacity fallback (one decision each)
380
382
  const engineErrors = toMap(saved?.engineErrors);
381
383
  const transients = toMap(saved?.transientRetries); // #5161: issue -> transient engine-error retries taken
@@ -404,6 +406,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
404
406
  const missingTools = async (tools) => { if (typeof envHold?.missingTools !== "function") return null; try { const m = await envHold.missingTools(tools); return Array.isArray(m) ? m : null; } catch { return null; } };
405
407
  const checked = toMap(saved?.prefilter); // issue -> pre-filter result
406
408
  const estimates = toMap(saved?.estimates); // #4409: issue -> estimated lane minutes; only with `estimate`
409
+ const queueClock = createQueueClock(saved?.queueClock); // #6203: queue_wait by cause, from first ready; a requeue does not reset it
407
410
  const enqueued = toMap(saved?.enqueued); // #4409: issue -> when it last entered the queue (starvation guard)
408
411
  const heads = new Set(saved?.heads ?? []); // #4409: decomposed sub-issues not started yet: the head of their priority band
409
412
  let errorTimes = [...(saved?.errorTimes ?? [])];
@@ -472,7 +475,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
472
475
  // #5652: with host fallback off (execution.host_fallback / host.role: orchestrator) the host is orchestrator-only: no re-placement here
473
476
  // #5931: a credentials block pinned the issue to the host (ledger hostPin): applied on readmit whatever host fallback says
474
477
  if (ledgers.get(n)?.hostPin) return { where: "local", reason: "host pin: ops_credentials block" };
475
- if (hostFallbackOn() && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_ENGINE_SKEW].includes(recovering.get(n)?.code)) return { where: "local", reason: `host capability: recovering ${recovering.get(n).code}` };
478
+ if (hostFallbackOn() && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_CAPABILITY_DOCKER, OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_ENGINE_SKEW].includes(recovering.get(n)?.code)) return { where: "local", reason: `host capability: recovering ${recovering.get(n).code}` };
476
479
  // #5371: a mechanical recovery never repeats the placement of the run that failed (a remote sandbox env defect recurs there), and a remote validate failure is rerun on the host
477
480
  if (recovering.get(n)?.code === ENV_VALIDATE_PLACEMENT || (MECHANICAL_CODES.includes(recovering.get(n)?.code) && recovering.get(n)?.where === "remote")) {
478
481
  if (hostFallbackOn()) return { where: "local", reason: `different placement: recovering ${rec.code} off the remote run` };
@@ -507,7 +510,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
507
510
  const recoveryMax = Number.isInteger(recovery?.maxAttempts) && recovery.maxAttempts > 0 ? recovery.maxAttempts : 0;
508
511
  // #4725: mechanical/env codes recover on their own budget (>= the conformance one); 0 maxAttempts still turns recovery off.
509
512
  const mechMax = recoveryMax && Number.isInteger(recovery?.mechanicalMaxAttempts) && recovery.mechanicalMaxAttempts > 0 ? Math.max(recovery.mechanicalMaxAttempts, recoveryMax) : recoveryMax;
510
- const REPEAT_ENV_CODES = [OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, OUTCOME_CODES.ENV_TOOL_MISSING]; // #5232: deterministic for a frozen command (a timeout is load, not listed)
513
+ const REPEAT_ENV_CODES = [OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_CAPABILITY_DOCKER]; // #6196: a docker-less host repeats identically // #5232: deterministic for a frozen command (a timeout is load, not listed)
511
514
  const sigOf = (d) => String(d ?? "").replace(/\s+/g, " ").trim();
512
515
  // #5592: env.tool_missing repeats are the same defect when the same tools are missing, whatever else the detail says (probe lines, ids, paths vary per run)
513
516
  const toolsOf = (d) => { const m = /(?:host|sandbox) is missing ([^\n]+?), so validate command/i.exec(String(d ?? "")); return m ? m[1].split(/\s*,\s*/).sort().join(",") : null; };
@@ -555,7 +558,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
555
558
  ...(stackedTried.size ? { stacked: toObj(stackedOf), stackedTried: [...stackedTried] } : {}),
556
559
  ...(requeueApplied.size ? { requeueApplied: [...requeueApplied], requeued: toObj(requeuedInfo) } : {}),
557
560
  ...(relabelled.size ? { relabelled: [...relabelled] } : {}), ...(cancelled ? { cancelled } : {}), ...(train ? { train: train.snapshot() } : {}),
558
- ...(estimate ? { estimates: toObj(estimates), enqueued: toObj(enqueued) } : {}), ...(heads.size ? { heads: [...heads] } : {}),
561
+ ...(estimate ? { estimates: toObj(estimates), enqueued: toObj(enqueued) } : {}), queueClock: queueClock.toJSON(), ...(heads.size ? { heads: [...heads] } : {}),
559
562
  ...(engineSigs.size ? { engineSigs: toObj(engineSigs) } : {}), ...(heldSigs.size ? { heldSigs: toObj(heldSigs) } : {}), ...(deterministic.size ? { deterministicSigs: [...deterministic] } : {}), ...(toolReadmits.size ? { toolReadmits: [...toolReadmits] } : {}), ...(select ? { select } : {}), ...(readmit.size ? { readmit: toObj(readmit) } : {}), ...(envSigs.size ? { envSigs: toObj(envSigs) } : {}), ...(ledgers.size ? { attempts: toObj(ledgers) } : {}), ...(selMatched.size ? { selMatched: [...selMatched] } : {}) });
560
563
  };
561
564
  const update = (row) => { store?.log?.(row); onUpdate(row); };
@@ -1167,7 +1170,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1167
1170
  update({ ...row, detail: `stopped by cancel: ${r?.code ?? row.outcome}${r?.detail ? ` ${r.detail}` : ""}` });
1168
1171
  return;
1169
1172
  }
1170
- if (!(row.outcome === "deferred" && r?.code === "sandbox.capacity")) capDefers.delete(n); // #5746: a lane the pool accepted resets the capacity count
1173
+ if (!(row.outcome === "deferred" && r?.code === "sandbox.capacity")) { capDefers.delete(n); capQuiet.delete(n); } // #5746: a lane the pool accepted resets the capacity count
1171
1174
  if (row.outcome === "deferred" && (r?.code === "stack.replan" || r?.code === "stack.restart") && !cancelled) {
1172
1175
  // #5833: the stacked dependent's PR and branch were dropped. replan: it builds as a normal lane on the lane base (today's held/skipped
1173
1176
  // rules decide while its dependency is unsatisfied); restart: it may stack again on the dependency's new head, from the frozen contract.
@@ -1241,6 +1244,12 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1241
1244
  return;
1242
1245
  }
1243
1246
  requeue(n, capGated ? 0 : delayMs); done(); save();
1247
+ // #6204: admit-or-don't-start: a pool refusal the capacity sample gates is a wait, not a deferral row: the issue stays pending and
1248
+ // the sample (polled every pollMs) wakes it. The first refusal of a wait is one batch event; queue_wait is attributed to `capacity` by the clock.
1249
+ if (capGated && r?.code === "sandbox.capacity") {
1250
+ if (!capQuiet.has(n)) { capQuiet.add(n); try { store?.log?.({ event: "capacity.wait", issue: n, batch: batchId ?? null, reason: r.reason ?? null }); } catch { /* best effort */ } }
1251
+ return;
1252
+ }
1244
1253
  update({ ...row, detail: `requeued in ${Math.round(pol.delayMs / 1000)}s: ${r?.code ?? "deferred"}${r?.detail ? ` ${r.detail}` : ""}` });
1245
1254
  return;
1246
1255
  }
@@ -1273,7 +1282,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1273
1282
  lostSeen.set(la, [...win, lostNow]);
1274
1283
  }
1275
1284
  if (row.outcome === "engine-error") {
1276
- const ag = r?.agent ?? r?.sandbox?.agent ?? null, hs = ag && breaker ? hostSignature(r, row.detail) : null;
1285
+ const ag = r?.agent ?? r?.sandbox?.agent ?? null, hs = ag && breaker ? hostSignature(r, row.detail) ?? (isTransientEngineError(row.detail) ? "transport" : null) : null; // #6204: a host's link failures pause that host, not the batch
1277
1286
  const sc = hs ? await scopedEngineError(ag, hs) : null;
1278
1287
  const qn = sc?.quarantined ? (quarantineRequeues.get(n) ?? 0) + 1 : 0; // a lane waits out the quarantine a bounded number of times, then counts as an ordinary engine-error (batch breaker included)
1279
1288
  if (sc?.quarantined && qn <= QUARANTINE_REQUEUES) { quarantineRequeues.set(n, qn); // #5988: an agent in quarantine: its lane waits and is requeued without a relaunch or breaker count; unaffected agents keep admitting
@@ -1368,7 +1377,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1368
1377
  const sameHostReplay = !repeatEnv && !prior && row.code === OUTCOME_CODES.ENV_TOOL_MISSING && row.placement?.where !== "remote" && toolsOf(row.detail) !== null;
1369
1378
  // #5805: an env defect the host still has is held until the engine, the batch env or the host changes, not ended or re-run.
1370
1379
  // A tool-missing recovery that would run on the host (not the #5423 remote retry) is not launched while the probe still misses the tool.
1371
- const envNoHost = !hostFallbackOn() && row.placement?.where === "remote" && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(row.code);
1380
+ const envNoHost = !hostFallbackOn() && row.placement?.where === "remote" && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_CAPABILITY_DOCKER, OUTCOME_CODES.ENV_TOOL_MISSING].includes(row.code);
1372
1381
  const lacking = row.code === OUTCOME_CODES.ENV_TOOL_MISSING ? toolsOf(row.detail) : null;
1373
1382
  if (ehOn && !envNoHost && !row.securityEscalated) {
1374
1383
  let stillLacks = false;
@@ -1390,8 +1399,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1390
1399
  decided({ issue: n, what: `no further recovery for ${row.code}: the same failure repeated`, why: firstLine(row.detail), alternative: "requeue another recovery lane that rebuilds against the same frozen command" });
1391
1400
  }
1392
1401
  // #5652: a remote lane's tool/capability end is not recovered on the host when host fallback is off; the lane message names the fix
1393
- const noHostRecovery = !hostFallbackOn() && row.placement?.where === "remote" && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(row.code);
1394
- if (noHostRecovery) decided({ issue: n, what: `no host re-placement for ${row.code}: host fallback is off (execution.host_fallback / host.role: orchestrator)`, why: firstLine(row.detail), alternative: "re-place the lane on the host" });
1402
+ const noHostRecovery = !hostFallbackOn() && row.placement?.where === "remote" && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_CAPABILITY_DOCKER, OUTCOME_CODES.ENV_TOOL_MISSING].includes(row.code);
1403
+ if (noHostRecovery) decided({ issue: n, what: `no host re-placement for ${row.code}: host fallback is off (execution.host_fallback / host.role: orchestrator)${row.code === OUTCOME_CODES.ENV_CAPABILITY_DOCKER ? "; the Docker-dependent validate is deferred to CI" : ""}`, why: firstLine(row.detail), alternative: "re-place the lane on the host" }); // #6196
1395
1404
  // #5749: an env.validate_timeout is host load, so its recovery lane is not started while the host is overloaded (it would time out again)
1396
1405
  if (overload && row.code === ENV_VALIDATE_TIMEOUT && classifyNeedsHuman(facts) === "recoverable" && used < max) {
1397
1406
  const isOver = () => { try { return overload()?.overloaded === true; } catch { return false; } };
@@ -1482,10 +1491,11 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1482
1491
  const pl = placed.get(n) ?? (remote ? (remoteRun.has(n) ? { where: "remote", reason: "mode remote" } : (placeOf(n) ?? undefined)) : undefined);
1483
1492
  placed.delete(n);
1484
1493
  const queueMs = Number.isFinite(enqueued.get(n)) ? Math.max(0, now() - enqueued.get(n)) : null; // #4908: queue_wait in the phase ledger
1494
+ const qc = queueClock.take(n, now()); // #6203
1485
1495
  heads.delete(n); enqueued.delete(n); busyNoted.delete(n);
1486
- const rec = { startedAt: now(), ...(plan ? { plan: true } : {}), ...(stackedOn ? { stackedOn } : {}), ...(queueMs != null ? { queueMs } : {}), ...(lane ? { lane } : {}), ...(remoteRun.has(n) ? { remote: true } : {}), ...(pl ? { placement: pl } : {}) };
1496
+ const rec = { startedAt: now(), ...(plan ? { plan: true } : {}), ...(stackedOn ? { stackedOn } : {}), ...(queueMs != null ? { queueMs } : {}), ...(qc ? { queueCauses: qc.causes, queueTotalMs: qc.total_ms } : {}), ...(lane ? { lane } : {}), ...(remoteRun.has(n) ? { remote: true } : {}), ...(pl ? { placement: pl } : {}) };
1487
1497
  if (!firstAdmit.has(n)) firstAdmit.set(n, rec.startedAt); // #5834: chain wall time starts at the first admission, plan lane included
1488
- runRecs.set(n, rec); keptBoxes.delete(n); notBefore.delete(n); capReasons.delete(n); save();
1498
+ runRecs.set(n, rec); keptBoxes.delete(n); notBefore.delete(n); capReasons.delete(n); capQuiet.delete(n); save();
1489
1499
  track(n, (async () => {
1490
1500
  // Pre-filter once per issue (a requeued issue is not re-checked); fail-open: an error means a normal lane.
1491
1501
  if (prefilter && !checked.has(n)) { let pf = null; try { pf = await prefilter(n, lane); } catch { pf = null; } checked.set(n, pf); save(); }
@@ -2175,6 +2185,15 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
2175
2185
  await refreshBlocked();
2176
2186
  await refreshBaseWaits();
2177
2187
  checkGates();
2188
+ queueClock.tick(pending, (n) => { // #6203: why each pending issue waits right now (the order is the precedence)
2189
+ if (opPause) return "pause";
2190
+ if (tripped) return "breaker";
2191
+ if (opHeld.has(n)) return "hold";
2192
+ if (blocked.has(n) || edges(n).some((d) => !(results.has(d) && SATISFIED.has(results.get(d).outcome)))) return "dependency";
2193
+ if (poolDown && isRemote(n)) return "host_offline";
2194
+ if (running.size >= K() || (notBefore.get(n) ?? 0) > t || capReasons.has(n) || baseHeld.has(n) || pfAll) return "capacity";
2195
+ return "other";
2196
+ }, t);
2178
2197
  // #4866: lane preflight. A failing check holds admission (all lanes, or only remote ones by its scope), says why once per batch,
2179
2198
  // and is re-checked every pass so the batch resumes on its own; it is not an engine-error, so the breaker never sees it.
2180
2199
  pfAll = false; pfRemote = false;
@@ -2361,9 +2380,11 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
2361
2380
  let wake = waits.length ? Math.max(0, Math.min(...waits) - t) : null;
2362
2381
  if (holdUntil && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // #4446: a cleared hold (forgedock limits clear) admits on the next poll
2363
2382
  if (getPause && pending.length && (opPause || running.size)) wake = Math.min(wake ?? pollMs, pollMs); // #5975: an --unpause or expiry
2383
+ if (pending.some((n) => capQuiet.has(n) && !(notBefore.get(n) > t))) wake = Math.min(wake ?? pollMs, pollMs); // #6204: a capacity-gated issue is woken by the next pool sample, not a per-issue timer
2364
2384
  if ((getParallel || getHeld) && pending.length) wake = Math.min(wake ?? pollMs, pollMs);
2365
2385
  if (offered.size && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // a slot another batch frees
2366
2386
  if (pending.some((n) => remoteCapped.has(n))) wake = Math.min(wake ?? pollMs, pollMs); // #5138: a live --set-max-remote raise
2387
+ if ((getAdded || getRequeued) && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // #6197: an --add/--requeue is read within one poll even when every pending issue is held or waits on a long timer
2367
2388
  if ((getAdded || getRequeued || (getChildren && addsEpicChildren(autoChildren?.mode))) && running.size) wake = Math.min(wake ?? pollMs, pollMs); // #4408/#4550: an add or requeue while only lanes run
2368
2389
  if (getRequeued && pending.some((n) => quota.has(n) || notBefore.has(n))) wake = Math.min(wake ?? pollMs, pollMs); // #5203: a --requeue releasing a quota pause
2369
2390
  if ((pfAll || pfRemote || baseRedHold) && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // #4866
@@ -2393,6 +2414,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
2393
2414
  else if (pending.length && opHeldHit.size && !pending.some((n) => !opHeldHit.has(n) && isReady(n)) && holdExpiring([...opHeldHit]) && !cancelled) await nap(wake ?? pollMs); // #5469: a hold with an expiry keeps the batch open until it expires (re-admit or alert), not finalised silently
2394
2415
  else if (pending.length && opHeldHit.size && !pending.some((n) => !opHeldHit.has(n) && isReady(n))) { if (await drainAdds()) continue; break; } // #4592: held by the operator: pending for a --resume
2395
2416
  else if (pending.length && (driftHeld.size || integHeld.size)) { if (await drainAdds()) continue; break; } // held by a drift flag (block_dispatch) or a red integration streak (#4667): pending for a later batch
2417
+ else if (pending.some((n) => capQuiet.has(n))) await nap(Math.min(wake ?? pollMs, pollMs)); // #6204: waiting for a pool slot with nothing running: the next capacity sample wakes it
2396
2418
  else if (pending.some((n) => remoteCapped.has(n))) await nap(wake ?? pollMs); // #5138: live max_remote 0: wait for a raise or another placement
2397
2419
  else if (pending.length) { // nothing runnable, nothing running, nothing waiting on time: a dependency cycle
2398
2420
  // #5162: only real cycles are labelled so; the rest name the cycle member (or failed root) that blocks them
@@ -2525,7 +2547,7 @@ export function formatTable(rows) {
2525
2547
  */
2526
2548
  export function phasesOf(r, rec) {
2527
2549
  if (!r?.phases || typeof r.phases !== "object" || !Object.keys(r.phases).length) return null;
2528
- return { ...(Number.isFinite(rec?.queueMs) && rec.queueMs > 0 ? { queue_wait: { ms: Math.round(rec.queueMs), ...((r.sandbox?.agent ?? r.agent) ? { worker: r.sandbox?.agent ?? r.agent } : {}) } } : {}), ...r.phases };
2550
+ return { ...(Number.isFinite(rec?.queueMs) && rec.queueMs > 0 ? { queue_wait: { ms: Math.round(Math.max(rec.queueMs, rec.queueTotalMs ?? 0)), ...(rec.queueCauses ? { causes: rec.queueCauses } : {}), ...((r.sandbox?.agent ?? r.agent) ? { worker: r.sandbox?.agent ?? r.agent } : {}) } } : {}), ...r.phases };
2529
2551
  }
2530
2552
 
2531
2553
  export function formatWaitSummary(rows, heavyStats = null) {