forgedock 1.68.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 (52) hide show
  1. package/bin/engine-cli.mjs +4 -9
  2. package/bin/lean/advisory.test.mjs +14 -5
  3. package/bin/lean/batch.mjs +11 -1
  4. package/bin/lean/capsample.mjs +25 -0
  5. package/bin/lean/conformance.mjs +6 -1
  6. package/bin/lean/conformance.test.mjs +6 -0
  7. package/bin/lean/depcache.mjs +2 -0
  8. package/bin/lean/effects.mjs +15 -1
  9. package/bin/lean/envgap.mjs +18 -0
  10. package/bin/lean/envgap.test.mjs +12 -1
  11. package/bin/lean/execution.mjs +3 -0
  12. package/bin/lean/execution.test.mjs +21 -0
  13. package/bin/lean/failure-stop.mjs +12 -1
  14. package/bin/lean/failure-stop.test.mjs +14 -1
  15. package/bin/lean/hostconfig.mjs +54 -0
  16. package/bin/lean/hostconfig.test.mjs +67 -0
  17. package/bin/lean/lane-audit-llm.mjs +51 -4
  18. package/bin/lean/lane-audit-llm.test.mjs +57 -0
  19. package/bin/lean/lane-audit.mjs +1 -1
  20. package/bin/lean/lean.mjs +63 -26
  21. package/bin/lean/lean.test.mjs +99 -19
  22. package/bin/lean/live-execution.mjs +3 -0
  23. package/bin/lean/live-execution.test.mjs +23 -0
  24. package/bin/lean/orchestrate-dispatch-placement.test.mjs +81 -0
  25. package/bin/lean/orchestrate-envhold.test.mjs +15 -1
  26. package/bin/lean/orchestrate.mjs +27 -9
  27. package/bin/lean/preflight.mjs +10 -3
  28. package/bin/lean/preflight.test.mjs +21 -1
  29. package/bin/lean/prompts.mjs +1 -0
  30. package/bin/lean/release-deploy.mjs +35 -5
  31. package/bin/lean/release-deploy.test.mjs +50 -3
  32. package/bin/lean/release-flakes.mjs +34 -0
  33. package/bin/lean/release-flakes.test.mjs +28 -0
  34. package/bin/lean/release.mjs +2 -1
  35. package/bin/lean/sandbox-remote.mjs +35 -4
  36. package/bin/lean/schedd.mjs +2 -2
  37. package/bin/pool/agent.mjs +105 -15
  38. package/bin/pool/cli.mjs +22 -4
  39. package/bin/pool/docker.mjs +2 -0
  40. package/bin/pool/image-manifest.mjs +24 -0
  41. package/bin/pool/image-manifest.test.mjs +20 -0
  42. package/bin/pool/lane-tools.mjs +23 -4
  43. package/bin/pool/lane-tools.test.mjs +27 -7
  44. package/bin/pool/project-layer.mjs +142 -0
  45. package/bin/pool/project-layer.test.mjs +73 -0
  46. package/bin/pool/router.mjs +20 -6
  47. package/bin/pool/version.mjs +45 -2
  48. package/bin/stats/tool-parks.mjs +29 -0
  49. package/bin/stats/tool-parks.test.mjs +21 -0
  50. package/package.json +1 -1
  51. package/pool/image/Dockerfile +1 -1
  52. package/scripts/ci-local.test.sh +3 -2
package/bin/lean/lean.mjs CHANGED
@@ -35,8 +35,9 @@ import { checksAt, mergeCheckEntries, CHECKS_FILE } from "./postdeploy-check.mjs
35
35
  import { matchBaselines, baselineFailures, foldRegression } from "./baselines.mjs";
36
36
  import { readRollouts, detectNewOffKeys, rolloutModes, liveDeferralBlocks } from "./activation.mjs";
37
37
  import { toolMisses } from "./toolplace.mjs";
38
- import { hasRecipe, installLaneTools, genericInstallCommands, RECIPES } from "../pool/lane-tools.mjs";
39
- import { testRunnerProblems, hostOnlyProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract, declaredEnv, depInstallFailures, toolMissingInstalls, testRunSummary, projectBinDirs, withLocalBins, manifestDepOwner, collectOnlyCommand, collectImportMiss, contractCommands } from "./preflight.mjs";
38
+ import { loadImageManifest, manifestProvides } from "../pool/image-manifest.mjs";
39
+ import { hasRecipe, installLaneTools, genericInstallCommands, missingPythonModules, RECIPES } from "../pool/lane-tools.mjs";
40
+ import { testRunnerProblems, hostOnlyProblems, preflightProbes, preflightProblems, hostEnvDefects, unsetEnvVars, runPreflight, knownToContract, declaredEnv, depInstallFailures, toolMissingInstalls, testRunSummary, projectBinDirs, withLocalBins, manifestDepOwner, collectOnlyCommand, collectImportMiss, contractCommands } from "./preflight.mjs";
40
41
  import { resolveLane, isDefaultLane, isShippedLane, DEFAULT_STAGING_BRANCH } from "./lane.mjs";
41
42
  import { splitGate, rationaleLine } from "./decompose.mjs";
42
43
  import { ceilingFor, modelInfo, restartDecision, DEFAULT_CEILING, WINDOW_SHARE, RESTART_COST_USD, CACHE_READ_USD, REAL_LIMIT_SHARE, predictRestart, handoffFacts, routeHandoff, buildReadsOf, NARROW_NOTE } from "./ceiling.mjs";
@@ -44,6 +45,7 @@ import { dockerLabels, LEDGER_TTL_MS } from "./ledger.mjs";
44
45
  import { batchImageCache, envNamesOf, provisionSandboxes } from "./testsandbox.mjs";
45
46
  import { repoKey, estimateCostUsd } from "../runner.mjs";
46
47
  import { depcacheNamespace } from "./depcache.mjs";
48
+ import { laneConfigEnv } from "./hostconfig.mjs"; // #5917
47
49
  import { prepareToolchain } from "./toolchain.mjs";
48
50
  import { toolStats } from "./toolstats.mjs";
49
51
  import { readTestMap, readTestMapAtRef, selectCommands, mergeChecks, factsPath, TEST_MAP_FILE } from "./testmap.mjs";
@@ -54,7 +56,7 @@ import { renderInvestigation, renderImplementation, renderReview, renderPrBody,
54
56
  import { parseVerifierConfig, pickVerifierModel, changedSymbols, callersOf, verifierBudget, verifierPrompt, parseVerifierFindings, findingsToFailures, renderVerifierNote, VERIFIER_SYSTEM } from "./verifier.mjs";
55
57
  import { computeTrigger, riskPathHits, TRIGGER_MODES, pathDomains, parseEnforceDomains } from "./review-trigger.mjs";
56
58
  import { hostCapabilityBlock, contractHostNeeds } from "./execution.mjs";
57
- import { envGapBlockCode, toolGapFailures, packageDirsMissingDeps, failureOutsideDiff } from "./envgap.mjs"; // #6106
59
+ import { baseMergeOnlyBlock, envGapBlockCode, toolGapFailures, packageDirsMissingDeps, failureOutsideDiff } from "./envgap.mjs"; // #6106
58
60
 
59
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;
60
62
  /** #4685: true when a builder's block summary names a missing tool or module (environment), not a credential. */
@@ -128,6 +130,7 @@ import { createLedger, flattenPhases, overheadStats } from "./phaseledger.mjs";
128
130
  import { DEFAULT_CATALOG_SOURCES, deriveCatalog, mergeRecipes, rewriteMissed, isDriftFailure, rewriteSubprojectVenv, deriveTestEnvMap, rewriteToCiEnv } from "./validate-catalog.mjs";
129
131
  import { holderGone } from "./liveness.mjs";
130
132
  import { runLaneAudit, buildStamp, forgeYamlHash } from "./lane-audit.mjs"; // #6076
133
+ import { classifyWithLlm } from "./lane-audit-llm.mjs"; // #6079
131
134
  import { makeGapAuditor, parseGapConfig } from "./lane-audit-gap.mjs"; // #6078
132
135
  import { parseForgeYaml } from "../forge-utils.mjs";
133
136
  import { planStale, stackedBaseBlock, validStackedOn, cascadeDecision, invalidatedChecks } from "./stacking.mjs";
@@ -798,7 +801,7 @@ export async function runCore(o) {
798
801
  if (reason === "needs-human" || reason === "engine-error" || (recoverUnlabelled && recover.final && (reason === "ci-pending" || reason === "budget-exceeded"))) { // #6076: one version-stamped FORGE:LANE_AUDIT at the unhappy terminals; never changes how the lane ends
799
802
  try {
800
803
  let gapCfg; try { gapCfg = parseGapConfig(parseForgeYaml(readFileSync(join(o.cwd ?? wt, "forge.yaml"), "utf8"))); } catch { gapCfg = parseGapConfig({}); }
801
- await runLaneAudit({ gap: makeGapAuditor({ gh: ghc, cfg: gapCfg, repo }), issue, reason, code, detail, comments: allComments(), trusted: (c) => c?.__mine === true || isTrustedIssueComment(c), phases: phaseLedger.snapshot(), post: (m, b) => post(m, b),
804
+ await runLaneAudit({ gap: makeGapAuditor({ gh: ghc, cfg: gapCfg, repo }), issue, reason, code, detail, comments: allComments(), trusted: (c) => c?.__mine === true || isTrustedIssueComment(c), phases: phaseLedger.snapshot(), post: (m, b) => post(m, b), llm: (ev) => classifyWithLlm(ev, { runner: io.runner, cwd: o.cwd ?? wt }),
802
805
  stamp: buildStamp({ engineVersion: ENGINE_VERSION, forgeYamlHash: forgeYamlHash(o.cwd ?? wt), batchId: o.batchId ?? null, attempt: recover?.attempt ?? o.attempt ?? 1 }) });
803
806
  } catch { /* the audit is best effort */ }
804
807
  }
@@ -982,7 +985,7 @@ export async function runCore(o) {
982
985
  const set = String(process.env.FORGE_HOST_PARALLELISM ?? "").trim();
983
986
  if (/^\d+$/.test(set) && Number(set) > 0) return set;
984
987
  if (!io.host?.cores) return null;
985
- try { return String(hostParallelism({ cores: quotaCores({ cores: io.host.cores(), read: (f) => readFileSync(f, "utf8"), env: process.env }), lanes: io.host.activeLanes?.() })); } catch { return null; }
988
+ try { return String(hostParallelism({ cores: quotaCores({ cores: io.host.cores(), read: (f) => (io.host.readFile ?? readFileSync)(f, "utf8"), env: process.env }), lanes: io.host.activeLanes?.() })); } catch { return null; }
986
989
  }
987
990
  /**
988
991
  * #4325: the lane env every engine-run command shares with the builder: shared package-manager stores (#4220), the run
@@ -1004,11 +1007,14 @@ export async function runCore(o) {
1004
1007
  ev({ event: "SIGNOFF_HOOK", dir });
1005
1008
  } catch { signoffEnv = {}; }
1006
1009
  }
1010
+ /** #5917: tool user-config redirected into the run dir (created once), beneath every engine key; {} without a run dir. */
1011
+ let laneCfgEnv = null, laneCfgDir = null;
1012
+ function laneCfg() { if (!runTmp) return {}; if (laneCfgDir !== runTmp) { laneCfgDir = runTmp; laneCfgEnv = laneConfigEnv({ dir: runTmp }); } return laneCfgEnv; }
1007
1013
  function laneEnv() {
1008
1014
  let deps = {};
1009
1015
  try { deps = io.deps?.env?.() ?? {}; } catch { deps = {}; }
1010
1016
  const par = verifyParallelism();
1011
- return { ...deps, ...(runTmp ? { TMPDIR: runTmp } : {}), ...(par ? { FORGE_HOST_PARALLELISM: par } : {}), FORGE_LANE_WORKTREE: "1", ...laneGitEnv, [FORGEDOCK_CHECKS_VAR]: CHECKS_CLI, [FORGEDOCK_ENTRY_VAR]: FORGEDOCK_CLI, ...sandboxEnv, ...(toolchain?.env ?? {}) }; // #5333: the hook denies git stash where this is set; #5825: git in a lane child never walks up out of the worktree
1017
+ return { ...laneCfg(), ...deps, ...(runTmp ? { TMPDIR: runTmp } : {}), ...(par ? { FORGE_HOST_PARALLELISM: par } : {}), FORGE_LANE_WORKTREE: "1", ...laneGitEnv, [FORGEDOCK_CHECKS_VAR]: CHECKS_CLI, [FORGEDOCK_ENTRY_VAR]: FORGEDOCK_CLI, ...sandboxEnv, ...(toolchain?.env ?? {}) }; // #5333: the hook denies git stash where this is set; #5825: git in a lane child never walks up out of the worktree
1012
1018
  }
1013
1019
  /** #5168: a failed claude login ends the lane `deferred` `backend.auth`, held per account by the batch (never the relaunch or the breaker). */
1014
1020
  const authDeferral = (e, account = null) => Object.assign(e, { deferCode: OUTCOME_CODES.BACKEND_AUTH, retryInSeconds: AUTH_RETRY_SECONDS, backendId: laneBackendId(process.env, rotator), ...cliDeferFacts(e, account),
@@ -1511,6 +1517,10 @@ export async function runCore(o) {
1511
1517
  // #4685: a tool the sandbox lacks (docker, promtool, a Python module) is an environment gap the host recovers, never a credential.
1512
1518
  return await needsHuman(`Remote sandbox lacks a validate tool (Builder is blocked (credentials)): ${s}\n\nNot a credential: the lane is recovered where the tool exists.`, OUTCOME_CODES.ENV_TOOL_MISSING);
1513
1519
  }
1520
+ if (b.kind === "human" && baseMergeOnlyBlock(b.why, s)) { // #6137: merging the base into the lane's own branch is the engine's base-sync, never a human gate
1521
+ T.decisions.push(`Builder block (${b.why}) reclassified to base-sync: it only asks for a merge of the base into the lane branch`);
1522
+ return await needsHuman(`Base merge, not a human decision (Builder reported blocked (${b.why})): ${s}\n\nMerging ${base} into the lane's own branch is the engine's base-sync: the lane is recovered with the base merged.`, OUTCOME_CODES.BASE_CONFLICT);
1523
+ }
1514
1524
  if (b.kind === "human") { // #6106: a missing tool/interpreter/recipe/package/sandbox capability is an env gap that recovers, whatever reason the builder typed; genuine human reasons stay human
1515
1525
  const envCode = envGapBlockCode(b.why, s);
1516
1526
  if (envCode) { T.decisions.push(`Builder block (${b.why}) reclassified to ${envCode}: it names an environment gap, not a human decision`); return await needsHuman(`Environment gap, not a human decision (Builder reported blocked (${b.why})): ${s}\n\nThe lane is recovered where the tool, interpreter or capability exists.`, envCode); }
@@ -2237,7 +2247,9 @@ export async function runCore(o) {
2237
2247
  if (d.converted.length) T.decisions.push(`Post-deploy with no registered check deferred to the orchestrator: ${d.converted.join(", ")}`);
2238
2248
  return d.contract;
2239
2249
  }
2250
+ const imageManifest = loadImageManifest();
2240
2251
  async function preflightValidates(contract) {
2252
+ for (const d of hostEnvDefects()) { T.anomalies.push(`Host environment defect (${d.code}): ${d.detail}`); ev({ event: "HOST_ENV_DEFECT", code: d.code, detail: d.detail }); } // #5917: an env defect, never a miss that blames the contract
2241
2253
  if ((!io.probeCommand && !io.preflightRun) || !contract || typeof contract !== "object") return [];
2242
2254
  const files = String(await git(["ls-files"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean);
2243
2255
  const env = laneEnv(), missing = new Set(), misses = []; // #4325: the env the validate commands run with
@@ -2245,7 +2257,7 @@ export async function runCore(o) {
2245
2257
  const local = projectBinDirs(wt, files);
2246
2258
  if (local.length) env.PATH = withLocalBins(env.PATH ?? process.env.PATH ?? "", local);
2247
2259
  if (io.probeCommand) {
2248
- const { probes, dropped } = preflightProbes(contract, { repoHas: repoTracks(files) });
2260
+ const { probes, dropped } = preflightProbes(contract, { repoHas: repoTracks(files), provided: (t) => manifestProvides(imageManifest, t) });
2249
2261
  if (dropped) T.anomalies.push(`Validate preflight probed ${probes.length} tool(s); ${dropped} more not probed`);
2250
2262
  for (const p of probes) {
2251
2263
  if (p.needs && missing.has(p.needs)) continue;
@@ -2782,7 +2794,10 @@ export async function runCore(o) {
2782
2794
  } catch { /* keep the original miss */ }
2783
2795
  }
2784
2796
  if (tm.tools.length) { // #5652: a recipe-backed tool is installed in this sandbox and re-probed before any host re-placement
2785
- const withRecipe = tm.tools.filter(hasRecipe), noRecipe = tm.tools.filter((t) => !hasRecipe(t));
2797
+ const inImage = tm.tools.filter((t) => manifestProvides(imageManifest, t)); // #6037: the image ships it; a miss is an image defect, never a recipe or generic install
2798
+ if (inImage.length) ev({ event: "REMOTE_TOOL_IMAGE_DEFECT", tools: inImage });
2799
+ const installable = tm.tools.filter((t) => !inImage.includes(t));
2800
+ const withRecipe = installable.filter(hasRecipe), noRecipe = installable.filter((t) => !hasRecipe(t));
2786
2801
  if (withRecipe.length && io.runCommand) {
2787
2802
  const ins = await installLaneTools(withRecipe, { run: (a) => io.runCommand({ command: a.command, cwd: wt, timeoutMs: a.timeoutMs, env: laneEnv() }), root: process.getuid?.() === 0 });
2788
2803
  ev({ event: "REMOTE_TOOLS_INSTALLED", tools: withRecipe, ok: ins.ok });
@@ -2933,27 +2948,35 @@ export async function runCore(o) {
2933
2948
  }
2934
2949
  // #6107: a ci.red recovery must not judge a stale tree: the base's current head is merged in before any check runs. A conflict
2935
2950
  // the engine cannot resolve deterministically ends base.conflict (recoverable), never ci.red for a branch that is only behind.
2936
- if (recover?.code === OUTCOME_CODES.CI_RED && !isSplit && io.runCommand) {
2951
+ // #6153: the same sync runs for an env.tool_missing recovery, and once more when a precheck round fails on a branch that is behind
2952
+ // its base (the base may have fixed the failing guard script): the lane's own stale copy of a check never decides a verdict.
2953
+ let precheckBaseSynced = false;
2954
+ const syncBaseForChecks = async (why, { parkOnConflict = false } = {}) => { // -> {ended} (a terminal result), {merged: true} (rerun the checks) or {merged: false}
2955
+ if (precheckBaseSynced || isSplit || !io.runCommand) return { merged: false };
2937
2956
  try { await git(["fetch", "origin", lane]); } catch { /* offline: the local ref */ }
2938
2957
  const behind = Number(String(await git(["rev-list", "--count", `HEAD..${base}`]).catch(() => "0")).trim()) || 0;
2939
- if (behind > 0) {
2940
- let merged = true, conflicted = [];
2941
- try { await git(["merge", "--no-edit", base]); } catch { merged = false; conflicted = String(await git(["diff", "--name-only", "--diff-filter=U"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean); }
2942
- if (!merged && conflicted.length) {
2943
- const bm = o.baseMerge, cr = io.conflictResolve && bm && Object.values(bm).some((v) => v?.length) ? await io.conflictResolve({ cwd: wt, files: conflicted, cfg: bm }).catch(() => null) : null;
2944
- if (cr?.resolved?.length && !(cr.remaining ?? []).length) { try { await git(["commit", "--no-edit"]); merged = true; } catch { /* abort below */ } }
2945
- if (!merged) {
2946
- await git(["merge", "--abort"]).catch(() => {});
2947
- ev({ event: "RECOVERY_BASE_SYNC", base, behind, result: "conflict", files: conflicted.slice(0, 20) });
2948
- return await needsHuman(`The branch conflicts with ${base} in ${conflicted.slice(0, 20).join(", ")}; the recovery's checks were not run on the stale tree (a conflicting base is not a check failure); nothing merged.`, OUTCOME_CODES.BASE_CONFLICT);
2949
- }
2950
- } else if (!merged) { await git(["merge", "--abort"]).catch(() => {}); T.anomalies.push(`Recovery base-sync could not merge ${base} (${behind} commit(s) behind, no conflict files); checks run on the branch as it is`); }
2951
- if (merged) {
2952
- ev({ event: "RECOVERY_BASE_SYNC", base, behind, result: "merged" });
2953
- T.decisions.push(`Recovery: merged ${base} (${behind} commit(s) behind) before re-running the checks`);
2954
- files = await changedFiles();
2958
+ if (behind <= 0) return { merged: false };
2959
+ precheckBaseSynced = true;
2960
+ let merged = true, conflicted = [];
2961
+ try { await git(["merge", "--no-edit", base]); } catch { merged = false; conflicted = String(await git(["diff", "--name-only", "--diff-filter=U"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean); }
2962
+ if (!merged && conflicted.length) {
2963
+ const bm = o.baseMerge, cr = io.conflictResolve && bm && Object.values(bm).some((v) => v?.length) ? await io.conflictResolve({ cwd: wt, files: conflicted, cfg: bm }).catch(() => null) : null;
2964
+ if (cr?.resolved?.length && !(cr.remaining ?? []).length) { try { await git(["commit", "--no-edit"]); merged = true; } catch { /* abort below */ } }
2965
+ if (!merged) { // first-failure sync: a conflict falls back to the old path (builder fix round, PR-time base-sync resolves it); a recovery lane parks base.conflict (#6107)
2966
+ await git(["merge", "--abort"]).catch(() => {});
2967
+ ev({ event: "RECOVERY_BASE_SYNC", base, behind, result: "conflict", why, files: conflicted.slice(0, 20) });
2968
+ if (parkOnConflict) return { ended: await needsHuman(`The branch conflicts with ${base} in ${conflicted.slice(0, 20).join(", ")}; the checks were not judged on the stale tree (a conflicting base is not a check failure); nothing merged.`, OUTCOME_CODES.BASE_CONFLICT) };
2969
+ T.anomalies.push(`Base-sync before the checks hit a conflict with ${base} in ${conflicted.slice(0, 20).join(", ")}; checks judged on the branch as it is, the PR-time base-sync resolves it`);
2970
+ return { merged: false };
2955
2971
  }
2956
- }
2972
+ } else if (!merged) { await git(["merge", "--abort"]).catch(() => {}); T.anomalies.push(`Base-sync before the checks could not merge ${base} (${behind} commit(s) behind, no conflict files); checks judged on the branch as it is`); return { merged: false }; }
2973
+ ev({ event: "RECOVERY_BASE_SYNC", base, behind, result: "merged", why });
2974
+ T.decisions.push(`Merged ${base} (${behind} commit(s) behind) ${why}`);
2975
+ files = await changedFiles();
2976
+ return { merged: true };
2977
+ };
2978
+ if ((recover?.code === OUTCOME_CODES.CI_RED || recover?.code === OUTCOME_CODES.ENV_TOOL_MISSING) && !isSplit && io.runCommand) {
2979
+ const sy = await syncBaseForChecks("before the recovery's first check run", { parkOnConflict: true }); if (sy.ended) return sy.ended;
2957
2980
  }
2958
2981
  let ciCommands = await ciPrecheckPlan(0);
2959
2982
  const pickChecks = () => planPrecheck({ testMap, files, learned: [...learnedCommands, ...ciCommands], maxMinutes: o.precheck?.maxMinutes, verify: vcfg });
@@ -2966,6 +2989,7 @@ export async function runCore(o) {
2966
2989
  // #6106: dependencies for every package the checks touch are prepared before the checks run; a missing tool afterwards is env, not ci.red
2967
2990
  let depsReprovisioned = false;
2968
2991
  const flakeReran = new Set();
2992
+ const pyModTried = new Set(); // #6138
2969
2993
  const reprovisionDeps = async (why) => {
2970
2994
  if (depsReprovisioned || !io.deps?.prepare) return false;
2971
2995
  depsReprovisioned = true;
@@ -3012,10 +3036,23 @@ export async function runCore(o) {
3012
3036
  const names = failed.map((f) => `\`${f.command}\` (exit ${f.rc})`).join(", ");
3013
3037
  // #5749/#6107: the park names each failing check and carries the last ~40 lines of its output, secrets redacted (run log too)
3014
3038
  const failTail = (fs) => { const rows = fs.map((f) => ({ name: ciDerived.get(f.command)?.name ?? null, command: f.command, rc: f.rc, tail: checkFailureTail(f, { name: ciDerived.get(f.command)?.name }) })); ev({ event: "PRECHECK_FAILED", round, checks: rows.map(({ name, command, rc, tail }) => ({ name, command, rc, tail })) }); return rows.map((r) => r.tail).join(""); };
3039
+ { // #6153: a failing check on a branch behind its base is rerun once on the merged tree before it is classified (the base may have fixed the guard script)
3040
+ const sy = await syncBaseForChecks(`after a failing check, before classifying it (the base may have fixed the check's script)`); if (sy.ended) return sy.ended;
3041
+ if (sy.merged) { picked = pickChecks(); round--; continue; }
3042
+ }
3015
3043
  if (isSplit) return await needsHuman(`Declared check command(s) fail on the refactor:split move (no builder edits a split); nothing merged: ${names}${failTail(failed)}`, OUTCOME_CODES.CI_RED);
3016
3044
  { // #6106: every failed check died on a missing tool/binary (not on its own assertion): prepare dependencies once and rerun, then it is env.tool_missing
3017
3045
  const gap = toolGapFailures(failed);
3018
3046
  if (gap.length && gap.length === failed.length) {
3047
+ { // #6138: the probe passed but the run still lacks a module (isolated interpreter ignores user site): install it system-wide once, rerun, then it is env
3048
+ const mods = missingPythonModules(gap.map((f) => f.output).join("\n")).filter((m) => !pyModTried.has(m));
3049
+ if (mods.length && io.runCommand) {
3050
+ const root = process.getuid?.() === 0;
3051
+ for (const m of mods) { pyModTried.add(m); for (const command of genericInstallCommands({ kind: "python-module", tool: m }, { root })) await io.runCommand({ command, cwd: wt, timeoutMs: 600000, env: laneEnv() }).catch(() => null); }
3052
+ ev({ event: "PRECHECK_PYTHON_MODULE_INSTALL", modules: mods });
3053
+ round--; continue;
3054
+ }
3055
+ }
3019
3056
  if (await reprovisionDeps("check failed on a missing tool")) { round--; continue; }
3020
3057
  ev({ event: "PRECHECK_TOOL_MISSING", commands: gap.map((f) => f.command) });
3021
3058
  return await needsHuman(`Environment error (not a check failure): declared check command(s) could not run because a tool or binary is missing, even after the dependencies were prepared; nothing merged: ${names}${failTail(gap)}`, OUTCOME_CODES.ENV_TOOL_MISSING);
@@ -198,6 +198,7 @@ function world(o = {}) {
198
198
  return "";
199
199
  },
200
200
  runner: async (c) => {
201
+ if (c.role === "lane-audit") return { text: "" }; // #6079: the post-terminal audit classification is not a lane session
201
202
  w.calls.push(["runner", c.role, c.resume ?? null, c.model ?? null, c.prompt, c.readOnly ?? false, c.system]);
202
203
  w.seq.push(c.role + (c.resume ? "-resume" : ""));
203
204
  w.envs.push(c.env ?? null);
@@ -559,6 +560,21 @@ describe("core work-on", () => {
559
560
  assert.equal(real.code, "builder.blocked");
560
561
  });
561
562
 
563
+ it("#6122 a FORGE:DECISION posted after the park resets the repeat: the next identical failure is a first (NEEDS_HUMAN), not failure.repeated", async () => {
564
+ const block = { status: "blocked", summary: "need creds", block: { kind: "human", why: "credentials" } };
565
+ const first = world({ changed: [] });
566
+ await run(first);
567
+ const nh = first.comments.find((c) => c.includes("<!-- FORGE:NEEDS_HUMAN -->"));
568
+ const bot = (body) => ({ author: { login: "rapiercraft-forgedock" }, body });
569
+ const decision = bot('<!-- FORGE:DECISION {"requirement":"R4","disposition":"post-deploy","quote":"x"} -->');
570
+ const after = world({ changed: [], viewComments: [bot(nh), decision] });
571
+ const r = await run(after);
572
+ assert.notEqual(r.code, "failure.repeated");
573
+ assert.ok(after.comments.some((c) => c.includes("<!-- FORGE:NEEDS_HUMAN -->")));
574
+ const before = world({ changed: [], viewComments: [decision, bot(nh)] });
575
+ assert.equal((await run(before)).code, "failure.repeated", "a decision older than the park does not clear it");
576
+ });
577
+
562
578
  it("#6076 an unhappy terminal posts one FORGE:LANE_AUDIT; a failing audit post leaves the terminal reason unchanged", async () => {
563
579
  const block = { status: "blocked", summary: "need creds", block: { kind: "human", why: "credentials" } };
564
580
  const w = world({ changed: [], result: block });
@@ -1024,11 +1040,11 @@ describe("core work-on", () => {
1024
1040
  assert.notEqual(r.code, "env.tool_missing");
1025
1041
  assert.notEqual(r.terminalReason, "needs-human");
1026
1042
  });
1027
- it("#5764 a python3 miss maps to the python recipe: installed in the sandbox and re-probed, no needs-human", async () => {
1028
- const w = world({ contract: withTool("python3") }); let ok = false; const cmds = [];
1043
+ it("#5764 a pip3 miss maps to the python recipe: installed in the sandbox and re-probed, no needs-human", async () => {
1044
+ const w = world({ contract: withTool("pip3") }); let ok = false; const cmds = [];
1029
1045
  const base = w.io.runCommand;
1030
1046
  w.io.runCommand = async (a) => { if (/apt-get install/.test(a.command) && /python3 python3-venv/.test(a.command)) { cmds.push(a.command); ok = true; return { rc: 0 }; } return base(a); };
1031
- probing(w, "python3", () => ok);
1047
+ probing(w, "pip3", () => ok);
1032
1048
  const r = await run(w, { dir: tmpDir("lean-5764a-"), ...remote });
1033
1049
  assert.equal(cmds.length, 1);
1034
1050
  assert.notEqual(r.code, "env.tool_missing");
@@ -1093,6 +1109,8 @@ describe("core work-on", () => {
1093
1109
  const pd = (summary) => code(world({ result: { status: "blocked", summary, block: { kind: "human", why: "product-decision" } } }));
1094
1110
  assert.equal(await pd("the yaml lane-tools recipe lives in the engine, so the lane cannot install it"), "env.tool_missing");
1095
1111
  assert.equal(await rb("no Python 3.11 interpreter in the sandbox (only 3.12.3)"), "env.tool_missing");
1112
+ assert.equal(await pd("needs a user-approved merge of staging (CLAUDE.md forbids agent git merge)"), "base.conflict"); // #6137
1113
+ assert.equal(await pd("needs a user-approved merge of staging, plus owner approval of the Stripe pricing"), "builder.blocked");
1096
1114
  assert.equal(await pd("needs Stripe approval before the pricing change ships"), "builder.blocked");
1097
1115
  assert.equal(await rb("needs the production API key and credentials from the owner"), "builder.blocked");
1098
1116
  assert.equal(await rb("this lane has no sops/age key", { ...remote, hostCaps: undefined }), "builder.blocked");
@@ -2232,17 +2250,18 @@ describe("conformance shadow mode (the default)", () => {
2232
2250
  assert.ok(traj(s).some((t) => /Validate preflight: the host lacks yaml after the contract correction/.test(t)));
2233
2251
  // every tool present: no correction, no event
2234
2252
  const dir3 = tmpDir("preflight-");
2235
- const ok = world({ contract: uvC, validation: [{ id: "V1", command: uvC.validate[0].command, exit: 0 }] }); const ran3 = probe(ok);
2253
+ const rgC = { ...CONTRACT, validate: [{ id: "V1", command: "ripgrep foo" }] };
2254
+ const ok = world({ contract: rgC, validation: [{ id: "V1", command: rgC.validate[0].command, exit: 0 }] }); const ran3 = probe(ok);
2236
2255
  assert.equal((await run(ok, { dir: dir3 })).terminalReason, "merged"); assert.equal(builders(ok).length, 2);
2237
- assert.deepEqual(ran3.map((a) => a.command), ["command -v -- 'uv' >/dev/null 2>&1"]);
2256
+ assert.deepEqual(ran3.map((a) => a.command), ["command -v -- 'ripgrep' >/dev/null 2>&1"]);
2238
2257
  assert.equal(readLog(dir3, 7).filter((e) => e.event === "VALIDATE_PREFLIGHT").length, 0);
2239
2258
  });
2240
2259
  it("#4328 an invalid contract and a preflight miss share one correction; still invalid is contract.invalid as before", async () => {
2241
- const bad = { ...CONTRACT, requirements: [{ id: "R1", quote: "make foo nicer", disposition: "deliver" }], validate: [{ id: "V1", command: "jq . a.json" }] };
2260
+ const bad = { ...CONTRACT, requirements: [{ id: "R1", quote: "make foo nicer", disposition: "deliver" }], validate: [{ id: "V1", command: "ripgrep . a.json" }] };
2242
2261
  const w = world({ contract: bad, fixedContract: bad });
2243
2262
  w.io.probeCommand = async () => ({ rc: 1, output: "" });
2244
2263
  assert.equal((await run(w)).code, "contract.invalid"); assert.equal(builders(w).length, 2, "plan + one correction");
2245
- assert.match(builders(w)[1][4], /R1: quote is not verbatim[\s\S]*V1: needs command 'jq'/);
2264
+ assert.match(builders(w)[1][4], /R1: quote is not verbatim[\s\S]*V1: needs command 'ripgrep'/);
2246
2265
  });
2247
2266
  it("#4393 replaying the AlterLab#36619 contract flags V4 at preflight, before the builder starts", async () => {
2248
2267
  const V4 = "uv run --no-project --python 3.12 python -m shared.detection.corpus.tools.check_manifest";
@@ -2684,7 +2703,7 @@ describe("hotspot prevention (forge#4195): plan facts, build rule, unexempted gr
2684
2703
  assert.equal(hotspotBuildRule(null), ""); assert.equal(hotspotBuildRule(facts([], { enabled: false })), "");
2685
2704
  const plan = builderPlanPrompt(7) + hotspotPlanNote(facts([HOT, { ...HOT, path: "a/b.py" }, { ...HOT, path: "c/d.py" }]));
2686
2705
  // 2750: #5750 (outcome vs guidance rows). 2650: #5557 (classification record line) on top of the base's growth. 1850: #4404 (verify out_of_band) and #4396 (split size rule) grew the plan prompt to ~1803 tokens on CI paths; 1900: #4589 (check timeout is not a block, one block-rule line). 2050: #4724 (deferred-row bucket rule). 1675 (hotspot case): #5284 (rubric prod_parity clause). 2375/1825: #5345 (self-check and pitfall lines).
2687
- assert.ok(approxTokens(plan) <= 2750, `plan prompt with hotspots is ${approxTokens(plan)} tokens`);
2706
+ assert.ok(approxTokens(plan) <= 2800, `plan prompt with hotspots is ${approxTokens(plan)} tokens`); // 2800: #6137 (base merge is base-sync)
2688
2707
  assert.ok(approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([]))) <= 2075, `implement prompt with the hotspot rule is ${approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([])))} of 2075 tokens`); // 2075: #5979 (substitute-validate and out-of-band from the shared amendment schema); 2025: #5752 (mechanism supersedes, negative examples, outcome evidence) // 1600: #4591 (never hand-name migration files) and #4596 (i18n translate rule), one line each; 1650: #4726 (e2e rule) // 1925: #5760 (CI budget rule)
2689
2708
  });
2690
2709
 
@@ -2766,7 +2785,8 @@ describe("bug lanes freeze a red-green repro_test (#4271)", () => {
2766
2785
  const prev = process.env.FORGE_HOST_PARALLELISM; process.env.FORGE_HOST_PARALLELISM = "3";
2767
2786
  try { assert.equal((await run(w, { envSetup: "make setup", precheck: { commands: ["npm run lint"] } })).terminalReason, "merged"); }
2768
2787
  finally { if (prev === undefined) delete process.env.FORGE_HOST_PARALLELISM; else process.env.FORGE_HOST_PARALLELISM = prev; }
2769
- const lane = { UV_CACHE_DIR: "/c/uv", TMPDIR: w.envs[0].TMPDIR, FORGE_HOST_PARALLELISM: "3", FORGE_LANE_WORKTREE: "1", GIT_CEILING_DIRECTORIES: w.envs[0].GIT_CEILING_DIRECTORIES, FORGEDOCK_CHECKS_CLI: CHECKS_CLI, FORGEDOCK_ENTRY_CLI: FORGEDOCK_CLI, PATH: "/rt/toolchain/bin:/usr/bin" };
2788
+ const cfg = (d) => ({ POETRY_CONFIG_DIR: `${d}/hostconfig/poetry`, npm_config_userconfig: `${d}/hostconfig/npmrc`, PIP_CONFIG_FILE: `${d}/hostconfig/pip.conf`, UV_CONFIG_FILE: `${d}/hostconfig/uv.toml`, GIT_CONFIG_GLOBAL: `${d}/hostconfig/gitconfig` }); // #5917
2789
+ const lane = { ...cfg(w.envs[0].TMPDIR), UV_CACHE_DIR: "/c/uv", TMPDIR: w.envs[0].TMPDIR, FORGE_HOST_PARALLELISM: "3", FORGE_LANE_WORKTREE: "1", GIT_CEILING_DIRECTORIES: w.envs[0].GIT_CEILING_DIRECTORIES, FORGEDOCK_CHECKS_CLI: CHECKS_CLI, FORGEDOCK_ENTRY_CLI: FORGEDOCK_CLI, PATH: "/rt/toolchain/bin:/usr/bin" };
2770
2790
  assert.equal(lane.GIT_CEILING_DIRECTORIES.split(":")[0], "/wt", "#5825: lane children are ceiled at the worktree parent");
2771
2791
  assert.match(lane.TMPDIR, /\/runs\/7-/, "the builder ran with the run TMPDIR");
2772
2792
  assert.deepEqual(w.rgCalls.map((x) => x.env), [lane], "red-green gets the lane env, not the daemon's");
@@ -5568,12 +5588,12 @@ describe("batch robustness (#4112-#4115)", () => {
5568
5588
 
5569
5589
  it("#5653 a validate command freeze preflight finds unrunnable is rewritten from the CI-derived catalogue before any builder correction", async () => {
5570
5590
  const d = tmpDir("lean-5653-"); const src = join(d, "ci.yml"); writeFileSync(src, "run: uv run --with-requirements r.txt pytest tests\n");
5571
- const contract = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: "poetry run pytest t.py" }] };
5572
- const w = world({ contract }); w.io.probeCommand = async (a) => ({ rc: /poetry/.test(JSON.stringify(a)) ? 127 : 0, output: "" });
5573
- const r = await run(w, { dir: d, validateCatalogSources: [`../..${src.replace(/^[A-Za-z]:/, "").split("\\").join("/")}`] }); // #5753: drive-less posix path on Windows
5591
+ const contract = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: "pipenv run pytest t.py" }] };
5592
+ const w = world({ contract }); w.io.probeCommand = async (a) => ({ rc: /pipenv/.test(JSON.stringify(a)) ? 127 : 0, output: "" });
5593
+ const r = await run(w, { dir: d, validateRecipes: [{ match: "\\bpipenv run pytest\\b", replace: "uv run --with-requirements r.txt pytest" }], validateCatalogSources: [`../..${src.replace(/^[A-Za-z]:/, "").split("\\").join("/")}`] }); // #5753: drive-less posix path on Windows
5574
5594
  assert.notEqual(r.code, "env.tool_missing");
5575
5595
  assert.ok(w.comments.some((c) => c.includes("FORGE:CONTRACT") && c.includes("uv run --with-requirements r.txt pytest t.py")));
5576
- assert.ok(!w.comments.some((c) => c.includes("FORGE:CONTRACT") && c.includes("poetry run pytest")));
5596
+ assert.ok(!w.comments.some((c) => c.includes("FORGE:CONTRACT") && c.includes("pipenv run pytest")));
5577
5597
  });
5578
5598
 
5579
5599
  // ---- #4112 ----
@@ -6676,9 +6696,17 @@ describe("two repos with the same issue number on one host (#4432)", () => {
6676
6696
  });
6677
6697
 
6678
6698
  describe("host-aware verification concurrency (#4182)", () => {
6679
- const host = (o = {}) => ({ memAvailableMb: () => 8192, freeMb: async () => 8192, loadAvg1: () => o.load ?? 1, cores: () => o.cores ?? 4, activeLanes: o.activeLanes ?? (() => o.lanes ?? 2), tmpPaths: () => ["/tmp"] });
6680
- const withEnv = async (v, fn) => { const prev = process.env.FORGE_HOST_PARALLELISM; if (v === undefined) delete process.env.FORGE_HOST_PARALLELISM; else process.env.FORGE_HOST_PARALLELISM = v;
6681
- try { return await fn(); } finally { if (prev === undefined) delete process.env.FORGE_HOST_PARALLELISM; else process.env.FORGE_HOST_PARALLELISM = prev; } };
6699
+ const host = (o = {}) => ({ memAvailableMb: () => 8192, freeMb: async () => 8192, loadAvg1: () => o.load ?? 1, cores: () => o.cores ?? 4, activeLanes: o.activeLanes ?? (() => o.lanes ?? 2), tmpPaths: () => ["/tmp"], readFile: o.readFile ?? (() => { throw new Error("ENOENT"); }) });
6700
+ const withEnv = async (v, fn) => { const prev = process.env.FORGE_HOST_PARALLELISM, prevQ = process.env.CS_CPU_QUOTA; delete process.env.CS_CPU_QUOTA; if (v === undefined) delete process.env.FORGE_HOST_PARALLELISM; else process.env.FORGE_HOST_PARALLELISM = v;
6701
+ try { return await fn(); } finally { if (prev === undefined) delete process.env.FORGE_HOST_PARALLELISM; else process.env.FORGE_HOST_PARALLELISM = prev; if (prevQ !== undefined) process.env.CS_CPU_QUOTA = prevQ; } };
6702
+
6703
+ it("#4182 a cgroup cpu quota below the VM cores caps the workers (read through io.host.readFile)", async () => {
6704
+ await withEnv(undefined, async () => {
6705
+ const w = world(); w.io.host = host({ cores: 8, lanes: 1, readFile: (f) => { if (f === "/sys/fs/cgroup/cpu.max") return "200000 100000"; throw new Error("ENOENT"); } });
6706
+ await run(w, { governor: false });
6707
+ for (const e of w.envs) assert.equal(e?.FORGE_HOST_PARALLELISM, "2");
6708
+ });
6709
+ });
6682
6710
 
6683
6711
  it("#4182 hostParallelism = max(1, floor(cores / lanes)); bad inputs count as 1", () => {
6684
6712
  assert.equal(hostParallelism({ cores: 4, lanes: 2 }), 2);
@@ -8110,7 +8138,7 @@ describe("#4363 fresh fix sessions", () => {
8110
8138
  const FRESH = /no earlier session/;
8111
8139
  const prechecked = (o = {}) => {
8112
8140
  const w = world(o); let rc = 1;
8113
- w.io.runCommand = async () => ({ rc, output: rc ? `${"x".repeat(300000)}\nlint: src/foo.js:3 unused var` : "" });
8141
+ w.io.runCommand = async () => ({ rc, output: rc ? `${"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n".repeat(4700)}lint: src/foo.js:3 unused var` /* many lines: one unbroken 300K line makes the output redaction quadratic and stalls the file */ : "" });
8114
8142
  const inner = w.io.runner;
8115
8143
  w.io.runner = async (c) => { const res = await inner(c); if (/declared check commands failed/.test(c.prompt) && !o.freshNoCommit) rc = 0; return res; };
8116
8144
  return w;
@@ -10191,9 +10219,9 @@ describe("#5749 freeze-time runnability: host-only commands, recipes, check tail
10191
10219
  });
10192
10220
  it("#5749 remote probe installs a recipe tool or re-places before the builder", async () => {
10193
10221
  const installed = []; let ok = false;
10194
- const w = world({ contract: V2("shellcheck scripts/x.sh") });
10222
+ const w = world({ contract: V2("pg_dump x") });
10195
10223
  w.io.runCommand = async ({ command }) => { if (/apt-get/.test(command)) { installed.push(command); ok = true; } return { rc: 0, output: "" }; };
10196
- w.io.probeCommand = async (a) => ({ rc: /shellcheck/.test(JSON.stringify(a)) && !ok ? 127 : 0, output: "" });
10224
+ w.io.probeCommand = async (a) => ({ rc: /pg_dump/.test(JSON.stringify(a)) && !ok ? 127 : 0, output: "" });
10197
10225
  assert.notEqual((await run(w, { dir: tmpDir("lean-5749b-"), ...remote })).code, "env.tool_missing");
10198
10226
  assert.equal(installed.length, 1);
10199
10227
  const n = world({ contract: V2("nopetool-5749 x") }); n.io.probeCommand = async (a) => ({ rc: /nopetool-5749/.test(JSON.stringify(a)) ? 127 : 0, output: "" });
@@ -10215,6 +10243,14 @@ describe("#5749 freeze-time runnability: host-only commands, recipes, check tail
10215
10243
  assert.ok(prepared.length >= 2, "deps prepared at setup and once more after the missing tool");
10216
10244
  assert.equal(builders(w).filter((b) => /declared check commands failed/.test(b[4])).length, 0, "no builder resume");
10217
10245
  });
10246
+ it("#6138 a module missing at run time (isolated interpreter) is installed system-wide once, then env.tool_missing, never ci.red", async () => {
10247
+ const w = world(); const cmds = [];
10248
+ w.io.runCommand = async ({ command }) => { cmds.push(command); return /pip install/.test(command) ? { rc: 0, output: "" } : { rc: 1, output: "Traceback\nModuleNotFoundError: No module named 'yaml'" }; };
10249
+ const r = await atIdleLoad(() => run(w, { precheck: { commands: ["python3 -I check.py"] }, verify: { ...parseVerify({}), precheckBlock: true } }));
10250
+ assert.equal(r.code, "env.tool_missing");
10251
+ const installs = cmds.filter((c) => /pip install/.test(c));
10252
+ assert.equal(installs.length, 1); assert.doesNotMatch(installs[0], /--user/);
10253
+ });
10218
10254
  it("#6094 a check that fails in a test file the diff does not touch is rerun once: green on rerun is no fix round; red twice stays ci.red", async () => {
10219
10255
  const out = "not ok 3 - ten concurrent\n location: '/w/bin/tests/mirror-script.test.mjs:48:3'";
10220
10256
  const w = world(); let n = 0;
@@ -10278,6 +10314,50 @@ describe("#6107 precheck parks carry the failing check; a ci.red recovery runs t
10278
10314
  });
10279
10315
  });
10280
10316
 
10317
+ describe("#6153 a failing precheck on a lane behind its base is rerun once on the merged tree", () => {
10318
+ const block = { precheck: { commands: ["make lanecheck"] }, verify: { ...parseVerify({}), precheckBlock: true } };
10319
+ const track = (w, rcFor) => { const st = { merged: 0, checks: 0 }; const orig = w.io.git; w.io.git = async (a, ...rest) => { if (a[0] === "merge" && a[1] === "--no-edit") st.merged++; return orig(a, ...rest); }; w.io.runCommand = async () => { st.checks++; return rcFor(st); }; return st; };
10320
+ it("a check the base fixed passes after the base-sync: no ci.red, no builder round", async () => {
10321
+ const w = world({ behind: 2 });
10322
+ const st = track(w, (s) => (s.merged ? { rc: 0, output: "" } : { rc: 1, output: "lane-checks exit 1 (old guard script)" }));
10323
+ const r = await atIdleLoad(() => run(w, block));
10324
+ assert.equal(r.terminalReason, "merged"); assert.equal(st.merged, 1); assert.equal(st.checks, 2);
10325
+ });
10326
+ it("a tool_missing-shaped failure is also rerun on the merged tree before env.tool_missing", async () => {
10327
+ const w = world({ behind: 1 });
10328
+ const st = track(w, (s) => (s.merged ? { rc: 0, output: "" } : { rc: 127, output: "bash: shellcheck: command not found" }));
10329
+ const r = await atIdleLoad(() => run(w, block));
10330
+ assert.equal(r.terminalReason, "merged"); assert.equal(st.merged, 1);
10331
+ });
10332
+ it("still failing after the sync is classified as before, with exactly one sync", async () => {
10333
+ const w = world({ behind: 2 });
10334
+ const st = track(w, () => ({ rc: 1, output: "FAILED real failure" }));
10335
+ const r = await atIdleLoad(() => run(w, block));
10336
+ assert.equal(r.code, "ci.red"); assert.equal(st.merged, 1);
10337
+ });
10338
+ it("a lane not behind its base is not synced and fails as before", async () => {
10339
+ const w = world({ behind: 0 });
10340
+ const st = track(w, () => ({ rc: 1, output: "FAILED real failure" }));
10341
+ const r = await atIdleLoad(() => run(w, block));
10342
+ assert.equal(r.code, "ci.red"); assert.equal(st.merged, 0);
10343
+ });
10344
+ it("a base the resolvers cannot merge does not park the lane: the merge is aborted and the checks are judged as before", async () => {
10345
+ const w = world({ behind: 2, mergeResults: ["conflict"], conflictFiles: ["scripts/lane-checks.sh"] });
10346
+ track(w, () => ({ rc: 1, output: "old guard" }));
10347
+ const r = await atIdleLoad(() => run(w, block));
10348
+ assert.notEqual(r.code, "base.conflict", "the early sync never parks on a conflict; the PR-time base-sync lets the builder resolve it");
10349
+ assert.equal(r.code, "ci.red");
10350
+ });
10351
+ it("an env.tool_missing recovery base-syncs before its first check", async () => {
10352
+ const w = world({ behind: 2 }); const order = [];
10353
+ w.io.runCommand = async () => { order.push("check"); return { rc: 0, output: "" }; };
10354
+ const orig = w.io.git; w.io.git = async (a, ...rest) => { if (a[0] === "merge" && a[1] === "--no-edit") order.push("merge"); return orig(a, ...rest); };
10355
+ const r = await atIdleLoad(() => run(w, { recover: { code: "env.tool_missing", attempt: 1 }, precheck: { commands: ["make lanecheck"] } }));
10356
+ assert.equal(r.terminalReason, "merged");
10357
+ assert.ok(order.indexOf("merge") >= 0 && order.indexOf("merge") < order.indexOf("check"), `merge before check: ${order}`);
10358
+ });
10359
+ });
10360
+
10281
10361
  describe("#5844 a busy host is not an absent CLI", () => {
10282
10362
  const base = { role: "builder", issue: 5844, cwd: "/tmp/x", model: "m", prompt: "p", system: "s" };
10283
10363
  it("probe timeout does not spawn a bare name", async () => {
@@ -161,6 +161,7 @@ export function liveRemote(base, { exec, readOverride = () => null, place, onCha
161
161
  };
162
162
  return Object.defineProperties(base, {
163
163
  max: { get: () => current().maxRemote, enumerable: true, configurable: true },
164
+ mode: { get: () => current().mode, enumerable: true, configurable: true }, // #5746: the effective mode (the live override included)
164
165
  fallbackLocal: { get: () => { const e = current(); return e.mode === "hybrid" && Number.isInteger(e.maxRemote) && e.maxRemote >= 1; }, enumerable: true, configurable: true },
165
166
  place: {
166
167
  value: (n) => {
@@ -172,6 +173,8 @@ export function liveRemote(base, { exec, readOverride = () => null, place, onCha
172
173
  const reason = live?.maxRemote !== undefined ? "max_remote 0 (live override)" : "max_remote 0";
173
174
  return base.hostFallback === false ? { where: "remote", reason, hold: true } : { ...p, reason };
174
175
  }
176
+ // #5746: remote mode never places on the host unless host_fallback is true (a host-only `needs` capability, headroom, ...)
177
+ if (e.mode === "remote" && p?.where === "local" && base.hostFallback === false) return { where: "remote", reason: `host fallback off, not on the host: ${p.reason}` };
175
178
  return p;
176
179
  },
177
180
  enumerable: true, configurable: true, writable: true,
@@ -154,3 +154,26 @@ describe("#5933 drain semantics", () => {
154
154
  assert.equal(mk({ mode: "hybrid", maxRemote: 0 }).place(1).where, "local");
155
155
  });
156
156
  });
157
+
158
+ describe("#5746 remote mode never places on the host unless host_fallback is true", () => {
159
+ const exec = { mode: "remote", maxRemote: 4 };
160
+ const needsHost = () => ({ where: "local", reason: "host capability: prod-monitor" }); // placeLane: a `needs` entry the provider does not relay
161
+ it("a host-only capability stays remote when the host is not allowed", () => {
162
+ const r = liveRemote({ hostFallback: false }, { exec, readOverride: () => null, place: needsHost });
163
+ assert.deepEqual(r.place(1), { where: "remote", reason: "host fallback off, not on the host: host capability: prod-monitor" });
164
+ assert.equal(r.mode, "remote");
165
+ });
166
+ it("host_fallback true keeps the host placement", () => {
167
+ const r = liveRemote({ hostFallback: true }, { exec, readOverride: () => null, place: needsHost });
168
+ assert.equal(r.place(1).where, "local");
169
+ });
170
+ it("an operator's live --set-placement local is not a fallback", () => {
171
+ const r = liveRemote({ hostFallback: false }, { exec, readOverride: () => ({ mode: "local" }), place: needsHost });
172
+ assert.deepEqual(r.place(1), { where: "local", reason: "live placement: local" });
173
+ assert.equal(r.mode, "local");
174
+ });
175
+ it("hybrid placement is untouched by host_fallback false", () => {
176
+ const r = liveRemote({ hostFallback: false }, { exec: { mode: "hybrid", maxRemote: 2 }, readOverride: () => null, place: () => ({ where: "local", reason: "light lane, host has headroom" }) });
177
+ assert.equal(r.place(1).where, "local");
178
+ });
179
+ });
@@ -0,0 +1,81 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { orchestrate } from "./orchestrate.mjs";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+ import { openBatch } from "./batch.mjs";
8
+ import { utimesSync } from "node:fs";
9
+ import { evaluateDispatchStall } from "./batch-health.mjs";
10
+ import { makeCapacitySampler } from "./capsample.mjs";
11
+
12
+ // #5746: remote mode with host_fallback false never places a lane on the orchestrator host, whichever branch picks "local"
13
+ const runRemote = async (place, extra = {}) => {
14
+ const seen = [], saves = [];
15
+ await orchestrate({ issues: [5], parallel: 2, readBody: async () => "", pollMs: 5,
16
+ store: { load: () => null, save: (s) => saves.push(JSON.parse(JSON.stringify(s))), log: () => {} },
17
+ remote: { mode: "remote", max: 2, isRemote: () => true, hostFallback: false, place, admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0 },
18
+ runOne: async (_n, _l, ctx = {}) => { seen.push({ where: ctx.placement?.where, remote: ctx.remote }); return { terminalReason: "merged", pr: 1 }; }, ...extra });
19
+ return { seen, saves };
20
+ };
21
+
22
+ describe("#5746 remote mode keeps lanes off the host", () => {
23
+ it("a host-capability placement (placeLane `needs`) is placed remotely and recorded", async () => {
24
+ const { seen, saves } = await runRemote(() => ({ where: "local", reason: "host capability: prod-monitor" }));
25
+ assert.deepEqual(seen, [{ where: "remote", remote: true }]);
26
+ const running = saves.flatMap((s) => Object.values(s.running ?? {}));
27
+ assert.ok(running.length > 0 && running.every((r) => r.placement?.where === "remote" && r.remote === true), JSON.stringify(running));
28
+ });
29
+ it("a throwing placement never falls to the host", async () => {
30
+ const { seen } = await runRemote(() => { throw new Error("probe"); });
31
+ assert.deepEqual(seen.map((s) => s.where), ["remote"]);
32
+ });
33
+ it("host_fallback true keeps the host placement (hybrid-style config)", async () => {
34
+ const { seen } = await runRemote(() => ({ where: "local", reason: "host capability: x" }), { remote: { mode: "remote", max: 2, isRemote: () => true, hostFallback: true, place: () => ({ where: "local", reason: "host capability: x" }), admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0 } });
35
+ assert.deepEqual(seen.map((s) => s.where), ["local"]);
36
+ });
37
+ it("every running entry carries placement.where, also for a lane admitted without a recorded one", async () => {
38
+ const { saves } = await runRemote(() => ({ where: "remote", reason: "mode remote" }));
39
+ const running = saves.flatMap((s) => Object.values(s.running ?? {}));
40
+ assert.ok(running.length > 0 && running.every((r) => typeof r.placement?.where === "string"), JSON.stringify(running));
41
+ });
42
+ });
43
+
44
+ // dispatch stall: a release after a long hold is not hours of idle
45
+ describe("dispatch-stall clock after an operator release", () => {
46
+ const MIN = 60000;
47
+ it("--release / hold expiry / requeue / unpause restart the idle clock", () => {
48
+ const dir = tmpDir("stall-clock-");
49
+ const b = openBatch(dir, "b-test");
50
+ b.store.save({ v: 1, order: [1], pending: [1], running: {}, results: {} });
51
+ const old = new Date(Date.now() - 150 * MIN);
52
+ for (const f of ["state.json"]) utimesSync(`${b.dir}/${f}`, old, old);
53
+ assert.ok(Date.now() - b.lastDispatchClockMs() >= 149 * MIN, "no operator input: the clock is the last progress");
54
+ b.holdIssues([1]);
55
+ b.releaseIssues([1]);
56
+ assert.ok(Date.now() - b.lastDispatchClockMs() < MIN, "a release restarts the clock");
57
+ const state = { order: [1], pending: [1], running: {}, results: {}, parallel: 4 };
58
+ const idle = evaluateDispatchStall(state, { held: [], hosted: true, lastProgressMs: b.lastProgressMs(), now: Date.now(), windowMin: 3 });
59
+ const fresh = evaluateDispatchStall(state, { held: [], hosted: true, lastProgressMs: b.lastDispatchClockMs(), now: Date.now(), windowMin: 3 });
60
+ assert.equal(idle?.code, "dispatch-stalled"); // the old clock: declared stalled the moment the hold lifts
61
+ assert.equal(fresh, null);
62
+ b.setPause({}); b.clearPause();
63
+ assert.ok(Date.now() - b.lastDispatchClockMs() < MIN);
64
+ });
65
+ });
66
+
67
+ // a failed capacity probe clears at the next good sample (it used to stay failed forever)
68
+ describe("capacity sampler recovers from a failed probe", () => {
69
+ it("throws after a failed probe, then samples again once the pool answers", async () => {
70
+ let t = 0, ok = false, calls = 0;
71
+ const cap = makeCapacitySampler({ provider: { capacity: async () => { calls++; if (!ok) throw new Error("502"); return { free: 3, online: 2 }; } }, now: () => t, pollMs: 5000 });
72
+ assert.equal(cap(), null);
73
+ await new Promise((r) => setImmediate(r));
74
+ assert.throws(() => cap(), /capacity probe failed/);
75
+ ok = true; t += 6000;
76
+ assert.throws(() => cap(), /capacity probe failed/); // this call starts the refresh; the sample lands after it
77
+ await new Promise((r) => setImmediate(r));
78
+ assert.deepEqual(cap(), { free: 3, online: 2, at: 2 });
79
+ assert.equal(calls, 2);
80
+ });
81
+ });
@@ -20,7 +20,7 @@ const harness = ({ script, issues = Object.keys(script).map(Number), parallel =
20
20
  recovery: { maxAttempts: 1, mechanicalMaxAttempts: 3 },
21
21
  envHold: { maxMs: 120_000, watchMs: 30_000, ...envHold },
22
22
  runOne: async (n, _l, ctx = {}) => {
23
- calls.push({ n, recover: ctx.recover?.attempt ?? 0 });
23
+ calls.push({ n, recover: ctx.recover?.attempt ?? 0, at: t });
24
24
  t += 1000;
25
25
  const list = script[n] ?? [{ terminalReason: "merged", pr: 1 }];
26
26
  const k = calls.filter((c) => c.n === n).length - 1;
@@ -210,6 +210,20 @@ describe("#5755 one env issue per signature", () => {
210
210
  assert.equal(byIssue[1].outcome, "merged");
211
211
  });
212
212
 
213
+ it("#6123 an env issue that is closed but the gap persists re-admits with exponential backoff (15m, 1h, 4h), not every watch", async () => {
214
+ const e = seam(() => true); // closed from the start, the tool is still missing: every re-admit re-parks on the same signature
215
+ const { calls, byIssue } = await harness({ script: { 1: [miss("html2text"), miss("html2text"), miss("html2text"), miss("html2text"), miss("html2text"), MERGED] },
216
+ envHold: { maxMs: 5 * 3600_000, watchMs: 300_000 }, extra: { envIssue: e } });
217
+ const gaps = calls.slice(1).map((c, i) => c.at - calls[i].at);
218
+ assert.equal(calls.length, 6);
219
+ assert.equal(byIssue[1].outcome, "merged");
220
+ // gap 0 is the first re-admit (a fresh env issue closure); each later one waits 15m, 1h, 4h, 4h
221
+ assert.ok(gaps[0] < 15 * 60_000);
222
+ assert.ok(gaps[1] >= 15 * 60_000 && gaps[1] < 3600_000, String(gaps));
223
+ assert.ok(gaps[2] >= 3600_000 && gaps[2] < 4 * 3600_000, String(gaps));
224
+ assert.ok(gaps[3] >= 4 * 3600_000 && gaps[4] >= 4 * 3600_000, String(gaps));
225
+ });
226
+
213
227
  it("without the seam the env.validate_timeout flow is unchanged (needs-human)", async () => {
214
228
  const { byIssue } = await harness({ script: { 1: [timeout()] }, envHold: null });
215
229
  assert.notEqual(byIssue[1].outcome, "held");