forgedock 1.62.0 → 1.64.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 (87) hide show
  1. package/bin/config-schema.mjs +5 -0
  2. package/bin/engine/outcome-codes.mjs +5 -0
  3. package/bin/engine-cli.mjs +109 -21
  4. package/bin/env/cli.mjs +18 -1
  5. package/bin/lean/basered.mjs +56 -11
  6. package/bin/lean/basered.test.mjs +58 -5
  7. package/bin/lean/batch-health.mjs +46 -4
  8. package/bin/lean/batch-health.test.mjs +55 -1
  9. package/bin/lean/batch.mjs +9 -1
  10. package/bin/lean/batch.test.mjs +74 -7
  11. package/bin/lean/ceiling.mjs +47 -3
  12. package/bin/lean/ceiling.test.mjs +32 -1
  13. package/bin/lean/conformance.e2e.test.mjs +32 -6
  14. package/bin/lean/conformance.mjs +57 -13
  15. package/bin/lean/conformance.test.mjs +93 -1
  16. package/bin/lean/execution.mjs +24 -12
  17. package/bin/lean/execution.test.mjs +59 -9
  18. package/bin/lean/forgedock-lane-workflow.test.mjs +62 -2
  19. package/bin/lean/issuewatch-reconcile.mjs +2 -0
  20. package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
  21. package/bin/lean/issuewatch.mjs +3 -0
  22. package/bin/lean/lanecheck.test.mjs +13 -1
  23. package/bin/lean/lean.mjs +214 -32
  24. package/bin/lean/lean.test.mjs +406 -21
  25. package/bin/lean/live-execution.mjs +25 -0
  26. package/bin/lean/live-execution.test.mjs +35 -1
  27. package/bin/lean/merged-park.mjs +76 -0
  28. package/bin/lean/merged-park.test.mjs +64 -0
  29. package/bin/lean/mergetrain.mjs +357 -0
  30. package/bin/lean/mergetrain.test.mjs +348 -0
  31. package/bin/lean/orchestrate-envhold.test.mjs +62 -0
  32. package/bin/lean/orchestrate-stacking.test.mjs +144 -0
  33. package/bin/lean/orchestrate-train.test.mjs +130 -0
  34. package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
  35. package/bin/lean/orchestrate.mjs +234 -17
  36. package/bin/lean/prompts.mjs +4 -3
  37. package/bin/lean/release-review.mjs +8 -1
  38. package/bin/lean/release-review.test.mjs +42 -2
  39. package/bin/lean/release-status.test.mjs +53 -1
  40. package/bin/lean/release.mjs +6 -3
  41. package/bin/lean/render.mjs +6 -1
  42. package/bin/lean/run-issue-placement.test.mjs +27 -3
  43. package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
  44. package/bin/lean/sandbox-remote.mjs +12 -2
  45. package/bin/lean/sched.mjs +19 -2
  46. package/bin/lean/sched.test.mjs +33 -1
  47. package/bin/lean/schedd-health.mjs +2 -1
  48. package/bin/lean/schedd-health.test.mjs +7 -0
  49. package/bin/lean/schedd.mjs +55 -7
  50. package/bin/lean/schedd.test.mjs +42 -1
  51. package/bin/lean/stacking.mjs +140 -0
  52. package/bin/lean/stacking.test.mjs +98 -0
  53. package/bin/lean/statuscomment.mjs +14 -8
  54. package/bin/lean/statuscomment.test.mjs +18 -1
  55. package/bin/lean/validate-catalog.mjs +1 -1
  56. package/bin/lean/validate-catalog.test.mjs +3 -0
  57. package/bin/lean/worktree.mjs +8 -3
  58. package/bin/lean/worktree.test.mjs +18 -0
  59. package/bin/pool/agent.mjs +325 -46
  60. package/bin/pool/cache-sweep.mjs +2 -0
  61. package/bin/pool/cli.mjs +120 -6
  62. package/bin/pool/disk.mjs +43 -0
  63. package/bin/pool/docker.mjs +21 -5
  64. package/bin/pool/health.mjs +95 -0
  65. package/bin/pool/router.mjs +274 -27
  66. package/bin/runner.mjs +3 -1
  67. package/bin/stats/chains.mjs +101 -0
  68. package/bin/stats/chains.test.mjs +53 -0
  69. package/bin/stats/efficiency.mjs +7 -6
  70. package/bin/stats/efficiency.test.mjs +48 -7
  71. package/bin/stats/index.mjs +11 -3
  72. package/bin/stats/stats.test.mjs +9 -0
  73. package/docs/CONFIG.md +23 -1
  74. package/docs/OUTCOME-CODES.md +4 -0
  75. package/package.json +1 -1
  76. package/pool/README.md +10 -0
  77. package/pool/image/Dockerfile +2 -1
  78. package/pool/image/entrypoint.sh +6 -6
  79. package/pool/image/mirror.sh +71 -0
  80. package/pool/install/install-agent-linux.sh +57 -5
  81. package/pool/install/install-agent-macos.sh +148 -0
  82. package/pool/install/install-agent.ps1 +11 -0
  83. package/pool/install/install-agent.sh +59 -7
  84. package/pool/install/uninstall-agent-linux.sh +75 -0
  85. package/pool/install/uninstall-agent-macos.sh +60 -0
  86. package/pool/install/uninstall-agent.ps1 +1 -0
  87. package/scripts/transition-label.sh +11 -0
package/bin/lean/lean.mjs CHANGED
@@ -25,7 +25,7 @@ import { stampText, checkStamp } from "./stagestamp.mjs";
25
25
  import { acquireBranchLock, waitPidsExit } from "./branchlock.mjs";
26
26
  import { parseRecurrenceConfig, recurrenceFacts, recursLinks, designLaneNote } from "./recurrence.mjs"; // #5751
27
27
  import { areaOf, acquireHotArea, countCounters } from "./hotarea.mjs"; // #5751
28
- import { contractRuleCounts, onlyTestPlanProblems, isTestPath, applyValidateRecipes, rewriteProjectDirCommand, deferChecklessPostDeploy, autoPostDeployE2e, applyRequirementDecisions, dedupeAddRequirements, loneE2eRows, reproEnvMiss, resolveForgedockPaths, resolvingIo, portableForgedockPaths, FORGEDOCK_CHECKS_VAR, FORGEDOCK_ENTRY_VAR, describesUnrunnableCommand, removedPathsOf, TRACKED, normalizeKindModes, blockingFailures, unverifiedRequirements, mutationTargets, mutationFailures, runMutationCheck, MUTATION_SURVIVED, isBugIssue, scopeText, explainFailures, inIssue, validateContract, snapQuotes, cliUsageError, normalizeRunnerCommand, applyAmendments, amendmentKindProblems, precheck, alreadyFixedOnBase, READONLY_PROD_RE, EXTERNAL_NEED_RE, intakeHostWork, repoTracks, dropScopeValidates, tagOutOfBand, parseReview, decide, mergeReviewRows, reaskable, criterionLines, closePlan, followupItems, renderPendingFollowups, bucketTally, pendingTracking, unnamedEdges, structureNote, impliedDocDeliverables, convertDelivered } from "./conformance.mjs";
28
+ import { isEnvValidateFailure, outputTail, contractRuleCounts, onlyTestPlanProblems, isTestPath, applyValidateRecipes, rewriteProjectDirCommand, deferChecklessPostDeploy, autoPostDeployE2e, applyRequirementDecisions, dedupeAddRequirements, loneE2eRows, reproEnvMiss, resolveForgedockPaths, resolvingIo, portableForgedockPaths, FORGEDOCK_CHECKS_VAR, FORGEDOCK_ENTRY_VAR, describesUnrunnableCommand, removedPathsOf, TRACKED, normalizeKindModes, blockingFailures, unverifiedRequirements, mutationTargets, mutationFailures, runMutationCheck, MUTATION_SURVIVED, isBugIssue, scopeText, explainFailures, inIssue, validateContract, snapQuotes, cliUsageError, normalizeRunnerCommand, applyAmendments, amendmentKindProblems, precheck, alreadyFixedOnBase, READONLY_PROD_RE, EXTERNAL_NEED_RE, intakeHostWork, repoTracks, dropScopeValidates, tagOutOfBand, parseReview, decide, mergeReviewRows, reaskable, criterionLines, closePlan, followupItems, renderPendingFollowups, bucketTally, pendingTracking, unnamedEdges, structureNote, impliedDocDeliverables, convertDelivered } from "./conformance.mjs";
29
29
  import { checkAdmission, hostParallelism, ADMISSION_RETRY_SECONDS } from "./admission.mjs";
30
30
  import { namedPaths, isTrustedIssueComment, prodFailureSignal } from "./prefilter.mjs";
31
31
  import { writeStatus, postUpsert, isStatusPost, isUpsertPost, hasSection, clearPipelineLabels } from "./statuscomment.mjs";
@@ -37,7 +37,7 @@ import { hasRecipe, installLaneTools, RECIPES } from "../pool/lane-tools.mjs";
37
37
  import { testRunnerProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract, declaredEnv, depInstallFailures, toolMissingInstalls, testRunSummary, projectBinDirs, withLocalBins, manifestDepOwner } from "./preflight.mjs";
38
38
  import { resolveLane, isDefaultLane, isShippedLane, DEFAULT_STAGING_BRANCH } from "./lane.mjs";
39
39
  import { splitGate, rationaleLine } from "./decompose.mjs";
40
- import { ceilingFor, predictRestart, handoffFacts, routeHandoff, buildReadsOf, NARROW_NOTE } from "./ceiling.mjs";
40
+ 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";
41
41
  import { dockerLabels, LEDGER_TTL_MS } from "./ledger.mjs";
42
42
  import { batchImageCache, envNamesOf, provisionSandboxes } from "./testsandbox.mjs";
43
43
  import { repoKey, estimateCostUsd } from "../runner.mjs";
@@ -87,7 +87,7 @@ import { makeTurnBudget, TURN_BUDGET_DEFAULTS, scaledExtra, laneSize, recoverySi
87
87
  import { pendingPitfall, pitfallRecord, foldPitfalls, selectPitfalls, failureLog } from "./pitfalls.mjs";
88
88
  import { unjustified } from "./enumerating.mjs";
89
89
  import { applyEnumerating, renameDuplicates, verifyApplied } from "./mechfix.mjs"; // #5348
90
- import { addLaneWorktree, DEFAULT_SPARSE_MAX_KB } from "./worktree.mjs";
90
+ import { addLaneWorktree, DEFAULT_SPARSE_MAX_KB, isSpawnError, repoMissing } from "./worktree.mjs";
91
91
  import { ceilingEnv, listedWorktree } from "./laneconfine.mjs";
92
92
  import { claimWarm, refillWarm, warmTreeCount, NO_HOOKS } from "./warmtree.mjs";
93
93
  import { ciSignal, cancelDecision, eventLog } from "./ci-watch.mjs";
@@ -124,6 +124,7 @@ import { reconcileCheckpoints } from "./checkpoint-reconcile.mjs";
124
124
  import { guardStagedDeletions, deletionEvidence, maxForeignDeletions } from "./delguard.mjs";
125
125
  import { createLedger, flattenPhases } from "./phaseledger.mjs";
126
126
  import { DEFAULT_CATALOG_SOURCES, deriveCatalog, mergeRecipes, rewriteMissed, isDriftFailure, rewriteSubprojectVenv } from "./validate-catalog.mjs";
127
+ import { planStale, stackedBaseBlock, validStackedOn, cascadeDecision, invalidatedChecks } from "./stacking.mjs";
127
128
  import { runLightStep, runLightTests, lightBuildPrompt, upgradeNote, renderLiteReceipt } from "./lightlane.mjs";
128
129
 
129
130
  /**
@@ -337,11 +338,21 @@ const defaultCredExec = (args) => {
337
338
  * posts FORGE:DECISION and resumes the open PR on the rerun path with a recovery note. `final`
338
339
  * (default true) is false when the runner may launch another attempt: the lane then never relabels (#4302)
339
340
  */
341
+ /** #5836: the post-merge steps shared by the lane and the merge train: close the issue as completed, then (label) `workflow:merged` and (branch) delete the lane branch on origin. All best effort. */
342
+ export async function closeMergedIssue({ gh, repo, issue, label = true, branch = null }) {
343
+ try { await gh(["issue", "close", String(issue), "-R", repo, "--reason", "completed"]); } catch { /* the issue stays open for the sweep */ }
344
+ if (label) {
345
+ await clearPipelineLabels({ gh, repo, issue });
346
+ try { await gh(["issue", "edit", String(issue), "-R", repo, "--add-label", "workflow:merged"]); } catch { /* best effort */ }
347
+ }
348
+ if (branch) { try { await gh(["api", "-X", "DELETE", `repos/${repo}/git/refs/heads/${branch}`]); } catch { /* already gone */ } }
349
+ }
350
+
340
351
  export async function runCore(o) {
341
352
  const armed = applyArmOverrides(o, o.issue); o = armed.options; // #5206: the arm's overrides shape the lane before any config is parsed
342
353
  o = { ...o, io: resolvingIo(o.io, { exists: existsSync, checksCli: CHECKS_CLI, forgedockCli: FORGEDOCK_CLI }) }; // #5727: every executed command names this install's forgedock entry points
343
354
  const { issue, repo, lane: requestedLane = null, laneOverride = false, branches = {}, cwd, dir, io, builderModel = null, reviewerModel = DEFAULT_REVIEWER_MODEL, fixModel = null,
344
- toolchainOverride = null, testRunners = null, coupledFiles = null, validateRecipes = null, validateRegenerate = null, validateCatalogSources = null, routeReachability = null, docsConfig = null, outcomeEvidenceConfig = null, ciBudget = null, pagesConfig = null, designConfig = null, prodParity = null, envSetup = null, ciMaxMinutes = 360, holdMergesDuringReleaseCi = true, conformance = "shadow", conformanceKinds = null, conformanceMutation = "off", reviewIncomplete = "needs-human", reproTest = "prefer", reproQuality = "shadow", closeParent = false, mergeWait = "required", maxSessionLimitPauses = DEFAULT_MAX_SESSION_LIMIT_PAUSES, cliIdleMinutes = 15, cliMaxMinutes = 180, cliBusyMinutes = 45, contextCeilingTokens = 120000, contextCeilingBySize = null, routeHandoffTokens = 40000, turnBudgets = null, laneLimits = null, maxMergeRetries = 5, contractMaxCorrections = 3, reviewMaxResumes = 3, sessionLimitMaxWaitMs = DEFAULT_SESSION_LIMIT_WAIT_MS, contextWaitSeconds = 5, onProgress = () => {}, emitTelemetry = null, random = Math.random } = o;
355
+ toolchainOverride = null, testRunners = null, coupledFiles = null, validateRecipes = null, validateRegenerate = null, validateCatalogSources = null, routeReachability = null, docsConfig = null, outcomeEvidenceConfig = null, ciBudget = null, pagesConfig = null, designConfig = null, prodParity = null, envSetup = null, ciMaxMinutes = 360, mergeTrain = "off", holdMergesDuringReleaseCi = true, conformance = "shadow", conformanceKinds = null, conformanceMutation = "off", reviewIncomplete = "needs-human", reproTest = "prefer", reproQuality = "shadow", closeParent = false, mergeWait = "required", maxSessionLimitPauses = DEFAULT_MAX_SESSION_LIMIT_PAUSES, cliIdleMinutes = 15, cliMaxMinutes = 180, cliBusyMinutes = 45, contextCeilingTokens = null, contextWindowShare = WINDOW_SHARE, contextRestartCostUsd = RESTART_COST_USD, contextCeilingBySize = null, routeHandoffTokens = 40000, turnBudgets = null, laneLimits = null, maxMergeRetries = 5, contractMaxCorrections = 3, reviewMaxResumes = 3, sessionLimitMaxWaitMs = DEFAULT_SESSION_LIMIT_WAIT_MS, contextWaitSeconds = 5, onProgress = () => {}, emitTelemetry = null, random = Math.random } = o;
345
356
  const now = io.now ?? (() => Date.now());
346
357
  const rotator = io.rotator !== undefined ? io.rotator : openRotator({ kind: o.accountRotator }); // #5094
347
358
  // #5205: a rotator with pick() relaunches a limited phase pinned to another account; lane-level rotations and limited accounts
@@ -369,6 +380,13 @@ export async function runCore(o) {
369
380
  let lane = null, base = null, defaults = [], milestone = null; // set by lane resolution, before the lease
370
381
  // #4267: a batch recovery lane for a mechanical needs-human ({code, attempt, final}); #4302: only a final attempt relabels.
371
382
  const recover = o.recover && typeof o.recover.code === "string" ? { code: o.recover.code, attempt: Number.isInteger(o.recover.attempt) ? o.recover.attempt : 1, final: o.recover.final !== false } : null;
383
+ // #5831 stacked lanes: `plan` plans a dependent (contract frozen, no build, no checkpoint); `stackPlanned` ({contractHash, baseSha}) is the plan a build lane reuses.
384
+ const planOnly = o.plan === true;
385
+ const stackPlanned = o.planned && typeof o.planned.contractHash === "string" && typeof o.planned.baseSha === "string" ? o.planned : null;
386
+ // #5832 stacked lanes phase 2: `stackedOn` ({dependency, branch, sha}) builds on the dependency's PR-ready lane head and opens the PR on its branch.
387
+ let stackedOn = planOnly ? null : validStackedOn(o.stackedOn);
388
+ const cascadeLog = { kinds: [], costUsd: 0, ms: 0 }; // #5833: cascades of this stacked lane and what the rework cost
389
+ let stackInvalidation = null; // #5833: {changedPaths} narrows postMergeGate to the checks the dependency's final diff invalidates
372
390
  const withLink = (body) => `${issuePrMarker(issue)}\n${body}`; // #5505: the issue → PR link GitHub does not record for a staging PR
373
391
  const closeBlockers = (reason, exceptPr = null) => openPrBlockingClose({ repo, io: { gh: ghw }, issue, reason, exceptPr }).catch(() => []); // #5505: fail open
374
392
  let branch = `feat/issue-${issue}-lean`; // #5469: an adopted PR's own head branch replaces it
@@ -416,6 +434,7 @@ export async function runCore(o) {
416
434
  };
417
435
  let pageVisual = null; // #5770: the engine's visual capture {sha, screenshots, errors, rows}, kept for the page gate and the PR body
418
436
 
437
+ const ctxStats = { restarts: 0, continues: 0, compactions: 0, turns: 0 }; // #5829: reported on the lane result
419
438
  const builderTriggers = []; // #4362: implement-attempt triggers in order, for the lane's first-pass flag
420
439
  let usageUnknown = false, inflight = null; // #5334: a killed session streamed nothing; the builder call in flight (flushed when a signal ends the run)
421
440
  const impl = { cost: 0, models: new Set() }; // #4397: implement spend and reported models, for the verifier
@@ -430,7 +449,7 @@ export async function runCore(o) {
430
449
  const rec = { event: "PHASE_ATTEMPT_USAGE", phase, attempt: n, trigger, ...(restartOf ? { restart_of: restartOf } : {}), usage: r?.usage ?? null, duration_ms: num(r?.durationMs) ?? 0,
431
450
  cost_usd: est ?? num(r?.costUsd), cost_usd_delta: c.delta, ...(est != null ? { cost_estimated: true } : {}), ...(killed && !r?.usage ? { usage_unknown: true } : {}), cost_usd_session: c.session, model: r?.model ?? null, turns: num(r?.turns), ...(mode ? { mode } : {}),
432
451
  ...(num(r?.baselineTokens) != null ? { baseline_tokens: num(r.baselineTokens) } : {}), ...(r?.tools ? { tools: r.tools } : {}), lane_profile: r?.laneProfile ?? laneProfile.name, ...expTag }; // #4410, #4629
433
- if (phase === "implement") { builderTriggers.push({ trigger, restart_of: restartOf }); impl.cost += c.delta ?? 0; if (r?.model && r.model !== "default") impl.models.add(r.model); tb.note(num(r?.turns), stage === "implement"); }
452
+ if (phase === "implement") { ctxStats.turns += num(r?.turns) ?? 0; builderTriggers.push({ trigger, restart_of: restartOf }); impl.cost += c.delta ?? 0; if (r?.model && r.model !== "default") impl.models.add(r.model); tb.note(num(r?.turns), stage === "implement"); }
434
453
  ev(rec); await emit(rec);
435
454
  modelMs += rec.duration_ms; // #4451: model time next to the lane's wall time
436
455
  const ledgerNow = phaseLedger.current(); // #5649: model time of contract and fix calls lands in those phases
@@ -604,7 +623,7 @@ export async function runCore(o) {
604
623
  // #5333: the worktree goes only after the builder processes exited (SIGTERM, then SIGKILL after a grace period).
605
624
  const stillRunning = io.proc?.alive && builderPids.length ? await waitPidsExit(builderPids, { alive: io.proc.alive, kill: io.proc.kill, sleep }).catch(() => []) : [];
606
625
  // Never discard work silently: an unmerged lane commits and pushes what is left before its worktree goes.
607
- const saved = !wtCreated || reason === "merged" || (await checkpoint(`exit (${reason})`));
626
+ const saved = !wtCreated || reason === "merged" || reason === "planned" || (await checkpoint(`exit (${reason})`)); // #5831: a plan lane built nothing: no checkpoint commit or push
608
627
  await reportLaneHead(reason);
609
628
  try { ghCache?.dispose?.(); } catch { /* best effort */ }
610
629
  if (runTmp) {
@@ -758,14 +777,15 @@ export async function runCore(o) {
758
777
  if (deferTail) { postRun.add("lane-facts", postLaneFacts); postRun.add("trajectory", postTrajectory); } else await postTrajectory();
759
778
  }
760
779
  if (deferTail) postRun.add("teardown", () => teardown(reason, extra)); // last: the structure delta and guard read the worktree
761
- if (reason === "merged" || reason === "invalid") await clearPipelineLabels({ gh: ghc, repo, issue }); // #5592: a merged or closed issue keeps no needs-human / parked:* / remediation-queue
780
+ if (reason === "merged" || reason === "invalid") await clearPipelineLabels({ gh: ghc, repo, issue, onFail: (n, e) => T.anomalies.push(`pipeline labels not cleared${n.length ? `: ${n.join(", ")}` : ""} (${String(e?.message ?? e).slice(0, 120)})`) }); // #5592/#5759: a merged or closed issue keeps no needs-human / parked:* / remediation-queue
762
781
  await releaseLease(reason, code, extra.mergedTo ?? null);
763
- done = { terminalReason: reason, detail, branch, worktree: wt, cost_usd: usage.cost_usd, tokens: { input: usage.input, output: usage.output, cache: usage.cache }, wall_ms: now() - t0, model_ms: modelMs, phases: phaseLedger.snapshot(),
782
+ done = { terminalReason: reason, detail, branch, worktree: wt, ...(cascadeLog.kinds.length ? { cascade: cascadeLog.kinds[cascadeLog.kinds.length - 1], cascades: [...cascadeLog.kinds], cascade_cost_usd: Math.round(cascadeLog.costUsd * 1e6) / 1e6, cascade_minutes: Math.round(cascadeLog.ms / 6000) / 10 } : {}), cost_usd: usage.cost_usd, tokens: { input: usage.input, output: usage.output, cache: usage.cache }, wall_ms: now() - t0, model_ms: modelMs, phases: phaseLedger.snapshot(),
764
783
  ...(laneHead && reason !== "merged" ? { laneHead: { ...laneHead } } : {}), light, ...(lightVerdict ? { light_eligibility: lightVerdict } : {}), ...(lightUpgrade ? { light_upgrade: lightUpgrade } : {}), // #4453
765
784
  ...(Object.keys(waits).length ? { waits: { ...waits } } : {}), ...(followupsFiled.length ? { followups: followupsFiled.map((f) => ({ ...f })) } : {}), ...(pendingRecord().length ? { pendingFollowups: pendingRecord() } : {}), ...(heavyQueueMax ? { heavyQueueMax } : {}), ...(precheckRan ? { precheckMs, precheckDeferred } : {}),
766
- ...(firstPassOf(builderTriggers) != null ? { firstPass: firstPassOf(builderTriggers) } : {}), ...(tb.record() ? { turns: tb.record() } : {}), // #4392
785
+ ...(firstPassOf(builderTriggers) != null ? { firstPass: firstPassOf(builderTriggers) } : {}), ...(tb.record() ? { turns: tb.record() } : {}), context: { ...ctxStats, cost_usd: impl.cost }, // #4392, #5829
767
786
  ...(route ? { builderRoute: { tier: route.tier, class: route.class, escalated, model: route.model ?? "default" } } : {}),
768
787
  ...(gateRan ? { conformance: { mode: conformance === "enforce" || riskEnforced ? "enforce" : "shadow", would: shadowWould, ...(adequacyCounts(adequacy) ? { test_adequacy: adequacyCounts(adequacy) } : {}), risk: Boolean(riskEnforced), ...(Object.keys(kinds).length ? { kinds: [...failureClasses] } : {}) } } : {}), ...extra };
788
+ if (extra.planned) done.planned = extra.planned; // #5831
769
789
  if (deferTail && o.deferPostRun) done.postRun = () => postRun.run(); // the caller runs it once the lane slot is free
770
790
  else await postRun.run();
771
791
  return done;
@@ -1143,8 +1163,10 @@ export async function runCore(o) {
1143
1163
  try { await killedAttempt(cur.n, snap ?? {}, cur.opts, cur.at); } catch { /* telemetry never blocks the teardown */ }
1144
1164
  }
1145
1165
  /** #4390: builder calls stopped at the context ceiling restart fresh; planning (and its corrections) run uncapped. */
1146
- let laneCeiling = contextCeilingTokens; // #5346: set to the lane size's ceiling once the contract is frozen
1147
- const UNCEILED = ["plan", "contract_correction", "block_correction"], CONTEXT_RESTARTS_MAX = 3;
1166
+ let laneCeiling = contextCeilingTokens ?? DEFAULT_CEILING; // #5346: set to the lane size's ceiling once the contract is frozen; #5829: model-aware when no explicit one
1167
+ let ceilingExplicit = contextCeilingTokens != null || contextCeilingBySize != null; // #5829
1168
+ let laneModelInfo = null; // #5829: the routed model's static window and cache-read price (null = unknown: kill-and-restart at the ceiling)
1169
+ const UNCEILED = ["plan", "contract_correction", "block_correction"], CONTEXT_RESTARTS_MAX = 3, CONTEXT_COMPACT_MAX = 2;
1148
1170
  /** #5812: the planning session's last-turn context, the files it read and its final reply, for the route hand-off. */
1149
1171
  let planSession = null;
1150
1172
  const notePlanSession = (r, trigger) => { planSession = { endTokens: num(r.endTokens), read: [...new Set([...(planSession?.read ?? []), ...handoffFacts(r.toolUses).read])], text: trigger === "plan" ? String(r.text ?? "") : planSession?.text ?? "" }; };
@@ -1158,16 +1180,36 @@ export async function runCore(o) {
1158
1180
  const budgeted = stage === "implement" && tb.on(); // #4392: the build and its restarts spend the implement turn budget
1159
1181
  if (budgeted && tb.remaining() <= 0) return await budgetWrapup(n, opts);
1160
1182
  opts.turnMax = budgeted ? tb.remaining() : 0;
1161
- try { return await builderOnce(n, p, resume, live, opts); } catch (e) {
1183
+ let continued = null; // #5829: the cost gate lets the session run past the ceiling, up to the model's real limit
1184
+ if (opts.contextMax > 0 && laneModelInfo && !ceilingExplicit) { // an explicit ceiling is an override: the gate only moves a model-derived one
1185
+ const limit = Math.floor(laneModelInfo.window * REAL_LIMIT_SHARE);
1186
+ const g = restartDecision({ context: opts.contextMax, turnsLeft: budgeted ? tb.remaining() : 20, cachePrice: laneModelInfo.cacheRead ?? CACHE_READ_USD, restartCost: contextRestartCostUsd, window: laneModelInfo.window });
1187
+ if (g.action === "continue" && limit > opts.contextMax) { continued = { before: opts.contextMax, limit }; opts.contextMax = limit; ctxStats.continues++; ev({ event: "CONTEXT_CONTINUE", ceiling: continued.before, limit, continue_cost_usd: g.continueCost, restart_cost_usd: g.restartCost, trigger: opts.trigger ?? null }); }
1188
+ }
1189
+ try { const r = await builderOnce(n, p, resume, live, opts); if (continued && num(r?.endTokens) > continued.before) ev({ event: "CONTEXT_CONTINUED", tokens_before: continued.before, tokens_after: num(r.endTokens), limit: continued.limit }); return r; } catch (e) {
1162
1190
  if (e?.code === "CLI_TURNS") {
1163
1191
  await attempt("implement", n, { usage: e.usage ?? null, turns: e.turns ?? null, tools: toolStats(e.toolUses), costUsd: null, model: opts.model ?? builderModel ?? null }, opts.mode, opts.trigger, opts.restartOf);
1164
1192
  return await budgetWrapup(n, opts);
1165
1193
  }
1166
1194
  if (e?.code === "CLI_CONTEXT") {
1167
- contextRestarts++;
1168
- ev({ event: "CONTEXT_CEILING", context_tokens: e.context ?? null, ceiling: laneCeiling, turns: e.turns ?? null, trigger: opts.trigger ?? null, restart: contextRestarts, last_tool: e.lastTool?.name ?? null });
1195
+ contextRestarts++; ctxStats.restarts++;
1196
+ ev({ event: "CONTEXT_CEILING", context_tokens: e.context ?? null, ceiling: e.contextMax ?? laneCeiling, real_limit: Boolean(continued), turns: e.turns ?? null, trigger: opts.trigger ?? null, restart: contextRestarts, last_tool: e.lastTool?.name ?? null });
1169
1197
  await attempt("implement", n, { usage: e.usage ?? null, turns: e.turns ?? null, tools: toolStats(e.toolUses), costUsd: null, model: opts.model ?? laneModel() ?? null }, opts.mode, opts.trigger, opts.restartOf);
1170
1198
  await checkpoint("context ceiling");
1199
+ // #5829: compact the stopped session in place (the CLI's /compact on a resume) and continue it; any failure falls through to the digest restart
1200
+ if (e.sessionId && ctxStats.compactions < CONTEXT_COMPACT_MAX) {
1201
+ ctxStats.compactions++;
1202
+ let c = null; try { c = await builderOnce(n, "/compact", e.sessionId, live, { model: opts.model ?? null, mode: opts.mode ?? null, keepSession: true, trigger: "context_compact", restartOf: opts.restartOf ?? opts.trigger ?? null }); } catch { c = null; }
1203
+ const after = num(c?.endTokens);
1204
+ if (after != null && num(e.context) != null && after < e.context * 0.8) {
1205
+ ev({ event: "CONTEXT_COMPACTED", tokens_before: e.context, tokens_after: after, session_id: e.sessionId });
1206
+ T.decisions.push(`Builder session reached ${e.context} context tokens: compacted in place to ${after} and continued the same session`);
1207
+ p = "The session context was compacted. Continue the task from where you left off; .forge-lean/contract.json stays the authority and the work so far is checkpointed on the branch."; resume = e.sessionId; opts.restartOf ??= opts.trigger ?? null; opts.trigger = "context_compact_continue";
1208
+ contextRestarts--; ctxStats.restarts--; // a compaction is not a restart
1209
+ continue;
1210
+ }
1211
+ ev({ event: "CONTEXT_COMPACT_FAILED", tokens_before: e.context ?? null, tokens_after: after, session_id: e.sessionId });
1212
+ }
1171
1213
  T.decisions.push(`Builder session reached ${e.context ?? "?"} context tokens (ceiling ${laneCeiling}): checkpointed, restarted fresh from the contract, diff and last validate result`);
1172
1214
  p = restart() + await contextRestartNote(handoffFacts(e.toolUses, e.lastTool)); resume = null; opts.restartOf ??= opts.trigger ?? null; opts.trigger = "context_restart";
1173
1215
  continue;
@@ -1477,6 +1519,12 @@ export async function runCore(o) {
1477
1519
  const laneGuard = (target, what) => {
1478
1520
  if (isDefaultLane(target, defaults)) throw Object.assign(new Error(`refusing to ${what} into the default branch ${target}`), { laneCode: OUTCOME_CODES.LANE_DEFAULT_BRANCH });
1479
1521
  };
1522
+ if (stackedOn) { // #5832: the build base is the dependency's lane head; an unreachable branch falls back to a normal lane (the Depends-on refusal then applies)
1523
+ let ok = false;
1524
+ try { await io.git(["fetch", "origin", stackedOn.branch], { cwd }); ok = Boolean(String(await io.git(["rev-parse", "--verify", "--quiet", `origin/${stackedOn.branch}`], { cwd })).trim()); } catch { ok = false; }
1525
+ if (ok) { base = `origin/${stackedOn.branch}`; T.decisions.push(`Stacked lane: building on #${stackedOn.dependency}'s head ${stackedOn.sha.slice(0, 12)} (${stackedOn.branch}); the PR targets that branch`); ev({ event: "STACK_BUILD_BASE", dependency: stackedOn.dependency, branch: stackedOn.branch, sha: stackedOn.sha }); }
1526
+ else { T.decisions.push(`Stacked lane: ${stackedOn.branch} is not reachable; building as a normal lane`); stackedOn = null; }
1527
+ }
1480
1528
  // ---- admission: Depends-on refusal, then lease ----
1481
1529
  {
1482
1530
  let dep = null;
@@ -1487,7 +1535,11 @@ export async function runCore(o) {
1487
1535
  T.decisions.push(`Dependency satisfied by lane merge: ${names}`);
1488
1536
  try { await post("FORGE:DEPENDENCY", `## Dependency satisfied\n${names} merged into ${lane}; the issue stays open until promotion, so the **Depends on** edge is met.`); } catch { /* best effort */ }
1489
1537
  }
1490
- if (dep?.open?.length) {
1538
+ if (dep?.open?.length && stackedOn && dep.open.every((n) => n === stackedOn.dependency)) { // #5832: only the stacked dependency is open; the merge guard holds the PR
1539
+ T.decisions.push(`Stacked lane: dependency #${stackedOn.dependency} still open; the merge waits for it`);
1540
+ } else if (dep?.open?.length && planOnly) { // #5831: a plan lane runs while its in-batch dependency is open
1541
+ T.decisions.push(`Plan lane: dependency ${dep.open.map((n) => `#${n}`).join(", ")} still open; planning only`);
1542
+ } else if (dep?.open?.length) {
1491
1543
  return { terminalReason: "dependency-open", code: OUTCOME_CODES.DEPENDENCY_OPEN, dependencies: dep.open,
1492
1544
  detail: `issue ${issue} **Depends on** ${dep.open.map((n) => `#${n}`).join(", ")} which is still open; re-run once it is closed` };
1493
1545
  }
@@ -1502,7 +1554,7 @@ export async function runCore(o) {
1502
1554
  return { terminalReason: "deferred", code: "lease-held", detail: `issue ${issue} leased by ${st.lease.by} until ${new Date(st.lease.until).toISOString()}`, branch, worktree: wt };
1503
1555
  }
1504
1556
  leaseState = { ...(st ?? { v: 1, run: `core_${issue}`, issue, lane, committed: [], phase: null, branch: null, pr: null, terminalReason: null }), terminal: false,
1505
- ...(o.placement ? { placement: o.placement } : {}) }; // #4256: the latest placement replaces an earlier run's
1557
+ ...(o.placement ? { placement: o.placement } : {}), ...(stackedOn ? { stackedOn } : {}) }; // #4256 (#5832: stackedOn in the lane's FORGE:STATE): the latest placement replaces an earlier run's
1506
1558
  try { await writeLease(leaseObj()); } catch { /* best effort */ }
1507
1559
  try { // #4920: read it back; a lane that wrote at the same moment and won leaves its id here, so this one defers
1508
1560
  const back = await io.projector.readState(issue);
@@ -1546,12 +1598,19 @@ export async function runCore(o) {
1546
1598
 
1547
1599
  try {
1548
1600
  // ---- 1. claim ----
1601
+ // #5890: a missing or non-git repo cwd ends the lane deferred (sandbox.repo_missing), before any lane git call
1602
+ if (io.fs?.exists) {
1603
+ let why = null;
1604
+ if (!(await io.fs.exists(cwd))) why = `repo directory ${cwd} does not exist`;
1605
+ else { try { await io.git(["rev-parse", "--git-dir"], { cwd }); } catch (e) { if (isSpawnError(e) || /not a git repository/i.test(String(e?.stderr ?? e?.message ?? ""))) why = `${cwd} is not a usable git repository`; } }
1606
+ if (why) throw Object.assign(new Error(why), { deferCode: OUTCOME_CODES.SANDBOX_REPO_MISSING, deferDetail: `${why}; the lane is requeued`, retryInSeconds: 120 });
1607
+ }
1549
1608
  // #5435: the lane fetch is independent of the claim's GitHub writes; start it now and await it before the resume probe.
1550
1609
  const fetchP = step("fetch", async () => { try { await io.git(["fetch", "origin", lane], { cwd }); } catch { /* offline: use the local ref */ } });
1551
1610
  await step("claim", async () => {
1552
1611
  await label("investigating");
1553
1612
  // #5592: a live lane is not parked: needs-human, needs-human:*, parked:* and remediation-queue from an earlier run come off (a later park puts them back)
1554
- await clearPipelineLabels({ gh: ghc, repo, issue, labels: iss.labels });
1613
+ await clearPipelineLabels({ gh: ghc, repo, issue, labels: iss.labels, onFail: (n, e) => T.anomalies.push(`pipeline labels not cleared${n.length ? `: ${n.join(", ")}` : ""} (${String(e?.message ?? e).slice(0, 120)})`) });
1555
1614
  await post("FORGE:STARTED", `Started work on #${issue} (base \`${lane}\`).`);
1556
1615
  if (recover) {
1557
1616
  // #4267: the batch decided to recover this issue itself; the label goes so the issue is live again.
@@ -2293,6 +2352,7 @@ export async function runCore(o) {
2293
2352
  }
2294
2353
  return dups;
2295
2354
  }
2355
+ if (planOnly && (adoptPr || isSplit)) return finish("deferred", `plan lane: ${adoptPr ? "an adopted PR" : "a refactor:split"} has nothing to plan ahead`, { code: "plan.unsupported" }); // #5831
2296
2356
  if (adoptPr) {
2297
2357
  // ---- 3''. #5469 adopt: the PR's diff is the change; no plan and no builder session, a location-only contract for the renderers ----
2298
2358
  { const f = await gateSetup(); if (f) return f; }
@@ -2308,13 +2368,18 @@ export async function runCore(o) {
2308
2368
  frozen = split.contract; hash = contractHash(contractJson(frozen));
2309
2369
  files = await changedFiles();
2310
2370
  } else {
2311
- if (resumed || recover) { // #5811: a recovery with no branch to resume (it ended before its first commit) still reuses the frozen contract
2371
+ if (resumed || recover || stackPlanned) { // #5811: (#5831: a build lane handed a plan reuses its contract too) a recovery with no branch to resume (it ended before its first commit) still reuses the frozen contract
2312
2372
  const fc = await readFrozenContract();
2313
2373
  if (fc) {
2314
2374
  // #4265: a contract planned from an older issue scope is stale: re-plan and freeze a new one instead of judging against it
2315
2375
  await refreshIssue("rerun contract check");
2316
2376
  const gone = (Array.isArray(fc.contract?.requirements) ? fc.contract.requirements : []).filter((r) => r?.disposition === "deliver" && !inIssue(r.quote, issueText)).map((r) => r.id);
2317
- const stale = reuseStale({ fc, scopeHash, lane, resumed: Boolean(resumed), gone });
2377
+ let stale = reuseStale({ fc, scopeHash, lane, resumed: Boolean(resumed || stackPlanned), gone });
2378
+ if (!stale && stackPlanned) { // #5831: the plan's base must still be on the lane and the dependency's merged diff must not touch a deliverable path
2379
+ const ancestor = await git(["merge-base", "--is-ancestor", stackPlanned.baseSha, base]).then(() => true, () => false);
2380
+ const changedPaths = ancestor ? String(await git(["diff", "--name-only", `${stackPlanned.baseSha}..${base}`]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean) : [];
2381
+ stale = planStale({ planned: stackPlanned, contractHash: fc.hash, ancestor, changedPaths, deliverablePaths: (fc.contract?.deliverables ?? []).map((d) => d?.path).filter(Boolean) });
2382
+ }
2318
2383
  if (stale) {
2319
2384
  ev({ event: "CONTRACT_STALE", hash: fc.hash, scope: fc.scope, now: scopeHash, base: fc.base, lane, reason: stale });
2320
2385
  T.decisions.push(`Rerun: frozen contract ${fc.hash} is stale (${stale}); re-planning`);
@@ -2343,7 +2408,7 @@ export async function runCore(o) {
2343
2408
  ev(rec); await emit(rec);
2344
2409
  T.decisions.push(`Pre-contract sessions provisionally routed to the ${preRoute.tier} tier (${preRoute.class}: ${preRoute.reason})`);
2345
2410
  }
2346
- await label("building");
2411
+ if (!planOnly) await label("building"); // #5831
2347
2412
  // #4450: the light lane (lean.light mode on, eligible, fresh lane): one builder session, derived contract, or an upgrade
2348
2413
  const waitMs = Math.max(0, Number(contextWaitSeconds) || 0) * 1000, tHot = now();
2349
2414
  if (recCfg.mode === "on" && !recurrence && (namedPaths(iss.body ?? "").length || recursLinks(iss.body ?? "").length)) { // #5751: 0 LLM calls; an issue naming no path and no Recurs link cannot recur
@@ -2364,8 +2429,8 @@ export async function runCore(o) {
2364
2429
  lightVerdict = elig.verdict;
2365
2430
  if (elig.mode !== "off") T.decisions.push(`Light lane ${elig.mode}: ${elig.verdict}${elig.reasons.length ? ` (${elig.reasons.map((x) => x.code).join(", ")})` : ""}`);
2366
2431
  // #4451: a light try skips the hotspots and the context pack; an upgrade computes them before the plan call
2367
- const ffSource = fastForwardSource(o.light), ffFresh = ffSource === "investigation" && !frozen && !resumed && !salvagedRef && !recover && !recurrence?.recurs; // #5426: the text verdict above is only a shadow signal then
2368
- const lightTry = ffSource === "text" && elig.light && !hotLate && !frozen && !resumed && !salvagedRef && !recover && !recurrence?.recurs; // #5751: a recurrence never takes the light lane
2432
+ const ffSource = fastForwardSource(o.light), ffFresh = !planOnly && ffSource === "investigation" && !frozen && !resumed && !salvagedRef && !recover && !recurrence?.recurs; // #5426: the text verdict above is only a shadow signal then
2433
+ const lightTry = !planOnly && ffSource === "text" && elig.light && !hotLate && !frozen && !resumed && !salvagedRef && !recover && !recurrence?.recurs; // #5751: a recurrence never takes the light lane
2369
2434
  if (recurrence?.recurs && elig.light) T.decisions.push("Light lane skipped: the issue recurs (design lane)");
2370
2435
  if (!lightTry) hotFacts = namedHot; // #4451: a light try still gives its builder no hotspot facts
2371
2436
  enumList = io.enumeratingTests ? ((await within(io.enumeratingTests({ cwd: wt, paths: namedPaths(iss.body ?? "") }), waitMs)) ?? []) : [];
@@ -2557,6 +2622,12 @@ export async function runCore(o) {
2557
2622
  } else {
2558
2623
  T.validate = lightDone ? "light lane (no plan session)" : resumed ? "resumed (existing branch)" : "recovered (frozen contract)";
2559
2624
  }
2625
+ if (planOnly) { // #5831: a plan lane ends right after the freeze: nothing is built, labelled, committed or pushed
2626
+ const baseSha = String(await git(["rev-parse", base]).catch(() => "")).trim();
2627
+ ev({ event: "STACK_PLANNED", hash, baseSha });
2628
+ T.validate = ["PLANNED", `contract ${hash} frozen on ${baseSha.slice(0, 12)}; build waits for its dependency`];
2629
+ return finish("planned", `contract ${hash} frozen; build starts once its dependencies merged`, { planned: { contractHash: hash, baseSha }, code: OUTCOME_CODES.COMPLETED }, OUTCOME_CODES.COMPLETED);
2630
+ }
2560
2631
  const dgFiles = (frozen?.deliverables ?? []).map((d) => d?.path).filter(Boolean);
2561
2632
  const designComments = (iss?.comments ?? []).filter(isTrustedIssueComment);
2562
2633
  const dgBase = dgFiles.length && designConfig ? String(await git(["ls-tree", "--name-only", base, "--", ...dgFiles]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean) : []; // #5648: deliverables already on the base are modified pages
@@ -2629,7 +2700,8 @@ export async function runCore(o) {
2629
2700
  { // #4392, #4505: next size on a budget recovery; #4587: a big L contract and an L recovery get extra turns
2630
2701
  const sz = recoverySize(laneSize({ contract: frozen, labels: (iss?.labels ?? []).map((l) => l?.name ?? l) }), recover);
2631
2702
  tb.setSize(sz, scaledExtra({ size: sz, contract: frozen, recover, base: (turnBudgets ?? {}).L ?? TURN_BUDGET_DEFAULTS.L }));
2632
- laneCeiling = ceilingFor(sz, { tokens: contextCeilingTokens, bySize: contextCeilingBySize }); // #5346
2703
+ laneCeiling = ceilingFor(sz, { tokens: contextCeilingTokens, bySize: contextCeilingBySize, model: laneModel(), share: contextWindowShare }); // #5346, #5829
2704
+ laneModelInfo = modelInfo(laneModel());
2633
2705
  }
2634
2706
  if (io.fs.write) { try { await io.fs.write(`${wt}/${CONTRACT_FILE}`, `${contractJson(frozen)}\n`); } catch { /* the prompt still names it */ } }
2635
2707
  // #4364: what `forgedock check` needs from the operator's forge.yaml (gitignored, so not in the worktree)
@@ -3013,7 +3085,8 @@ export async function runCore(o) {
3013
3085
  await i18nGate("hand-off");
3014
3086
  /** #4406: verify.post_merge (else the scoped typecheck) on the merged tree before the base-sync push; fix rounds up to verify.max_rounds. */
3015
3087
  async function postMergeGate(trigger) {
3016
- const commands = io.runCommand && !isSplit ? [...new Set([...postMergeCommands({ configured: vcfg.postMerge, scoped: (await io.postMergeChecks?.({ cwd: wt, base }).catch(() => [])) ?? [], mode: vcfg.mode }), ...(guardOn() ? vcfg.invariants : [])])] : []; // #5239: the guard set also runs on the merged tree
3088
+ let commands = io.runCommand && !isSplit ? [...new Set([...postMergeCommands({ configured: vcfg.postMerge, scoped: (await io.postMergeChecks?.({ cwd: wt, base }).catch(() => [])) ?? [], mode: vcfg.mode }), ...(guardOn() ? vcfg.invariants : [])])] : [];
3089
+ if (stackInvalidation) { const all = commands; commands = invalidatedChecks({ changedPaths: stackInvalidation.changedPaths, checks: commands }); if (commands.length < all.length) T.decisions.push(`Stacked lane: ${all.length - commands.length} check(s) not re-run, the dependency's final diff does not touch them`); } // #5833 // #5239: the guard set also runs on the merged tree
3017
3090
  let fixed = false, results = [];
3018
3091
  for (let round = 0; commands.length; round++) {
3019
3092
  await renew();
@@ -3044,12 +3117,27 @@ export async function runCore(o) {
3044
3117
  const g = failed.filter((f) => guardFailing([f]));
3045
3118
  if (!g.length || isSplit || !io.runCommand) return null;
3046
3119
  const baseRuns = await heavyStep("precheck", () => runOnBase({ commands: g.map((f) => f.command), git, runCommand: io.runCommand, mergeBase: base, cwd: wt, env: laneEnv(), timeoutMs: vcfg.precheckTimeoutSeconds * 1000 }));
3047
- const { baseRed } = classifyBaseRed({ failed: g, baseRuns });
3120
+ const { baseRed: red, env: envRed } = classifyBaseRed({ failed: g, baseRuns });
3121
+ const tailOf = (c) => String(baseRuns.find((b) => b.command === c)?.output ?? "").slice(-4096);
3122
+ if (envRed.length) {
3123
+ T.decisions.push(`env.base_probe: guard command(s) ${envRed.map((f) => `\`${f.command}\``).join(", ")} failed on ${base} with an environment signature, not a red base; the failure stays the lane's. Base output tail: ${envRed.map((f) => tailOf(f.command).slice(-500)).join(" | ")}`);
3124
+ ev({ event: "BASE_PROBE_ENV", code: "env.base_probe", commands: envRed.map((f) => f.command), output: envRed.map((f) => tailOf(f.command).slice(-500)) });
3125
+ }
3126
+ let baseRed = red;
3127
+ if (baseRed.length && typeof io.verifyBaseOnHost === "function") { // R6: a pass on the bare base tip at the host makes the sandbox result environment
3128
+ const ok = [];
3129
+ for (const f of baseRed) { let r = null; try { r = await io.verifyBaseOnHost({ command: f.command, base }); } catch { /* no verdict */ } if (Number(r?.rc) === 0) ok.push(f); }
3130
+ if (ok.length) { T.decisions.push(`env.base_probe: guard command(s) ${ok.map((f) => `\`${f.command}\``).join(", ")} pass on the bare ${base} tip at the host; the sandbox base failure is environment, no issue filed`); baseRed = baseRed.filter((f) => !ok.includes(f)); }
3131
+ }
3048
3132
  if (!baseRed.length) return null;
3049
3133
  const att = await attributeBaseRed({ failed: baseRed, git, base });
3050
- const cmds = baseRed.map((f) => f.command), n = await reportBaseRed({ ghc: ghw, repo, base, att, laneIssue: issue, commands: cmds });
3134
+ let baseSha = "", commitDate = "";
3135
+ try { baseSha = String(await git(["rev-parse", base])).trim(); } catch { /* key falls back to the attributed sha */ }
3136
+ try { if (att?.sha) commitDate = String(await git(["show", "-s", "--format=%cI", att.sha])).trim(); } catch { /* no reopen */ }
3137
+ const cmds = baseRed.map((f) => f.command), outputs = Object.fromEntries(cmds.map((c) => [c, tailOf(c)]));
3138
+ const n = await reportBaseRed({ ghc: ghw, repo, base, att, laneIssue: issue, commands: cmds, outputs, baseSha, commitDate });
3051
3139
  T.decisions.push(`Guard command(s) ${cmds.map((c) => `\`${c}\``).join(", ")} also fail on ${base}${att ? ` (last change ${att.sha.slice(0, 12)}${att.issue ? `, #${att.issue}` : ""})` : ""}; lane deferred behind ${n ? `#${n}` : "the base fix"}`);
3052
- ev({ event: "BASE_RED", commands: cmds, sha: att?.sha ?? null, issue: att?.issue ?? null, tracked: n });
3140
+ ev({ event: "BASE_RED", commands: cmds, output: cmds.map((c) => tailOf(c).slice(-500)), sha: att?.sha ?? null, issue: att?.issue ?? null, tracked: n });
3053
3141
  return await finish("deferred", `base ${base} is red on guard command(s) ${cmds.join(", ")}; deferred behind ${n ? `#${n}` : "the base fix"}`, { code: OUTCOME_CODES.BASE_RED, retryInSeconds: 900 }, OUTCOME_CODES.BASE_RED);
3054
3142
  }
3055
3143
  const structureLine = structureNote(structure);
@@ -3688,9 +3776,10 @@ export async function runCore(o) {
3688
3776
  if (outcome.state === "spec-only") return await needsHuman(`The page gate needs an approved FORGE:DESIGN_SPEC (run /design) or visual evidence a builder resume cannot produce, so no resume or recovery lane was spent:\n\n${list}`, OUTCOME_CODES.DESIGN_SPEC_REQUIRED, { ask: `Run /design for #${issue}` });
3689
3777
  // #5371: a remote sandbox is a different environment from the host: its failed frozen validate is rerun once in a local recovery lane before it counts
3690
3778
  // #5732: so is a repro head failure whose output carries no assertion text (an env error of the sandbox, not a red test)
3691
- if (o.placement?.where === "remote" && !recover && outcome.failures?.length && outcome.failures.every((f) => f?.kind === "validate_failed" || (f?.kind === "repro_red_green" && f.head === "FAILED" && f.assertion === false))) {
3779
+ if (o.placement?.where === "remote" && !recover && outcome.failures?.length && outcome.failures.every((f) => (f?.kind === "validate_failed" && isEnvValidateFailure(f.output)) || (f?.kind === "repro_red_green" && f.head === "FAILED" && f.assertion === false))) {
3780
+ const sandboxTail = outcome.failures.filter((f) => f?.kind === "validate_failed" && f.output).map((f) => `\nSandbox output tail (the host replay starts from this):${outputTail(f.output)}`).join(""); // #5730
3692
3781
  T.anomalies.push("Remote validate failure: rerun on the host in a local recovery lane before it is terminal");
3693
- return await needsHuman(`A frozen validate command failed in the remote sandbox (exit non-zero on the engine's rerun). The sandbox is a different environment from the host, so no builder resume was spent; the branch is pushed and a local recovery lane reruns the frozen command on the host (pass: the change stands; fail: conformance.unimplemented):\n${list}`, ENV_VALIDATE_PLACEMENT);
3782
+ return await needsHuman(`A frozen validate command failed in the remote sandbox (exit non-zero on the engine's rerun). The sandbox is a different environment from the host, so no builder resume was spent; the branch is pushed and a local recovery lane reruns the frozen command on the host (pass: the change stands; fail: conformance.unimplemented):\n${list}${sandboxTail}`, ENV_VALIDATE_PLACEMENT);
3694
3783
  }
3695
3784
  const reproProdFail = outcome.state === "already-fixed" ? prodFailureSignal(trustedComments) : null; // #5734: a passing repro is no prod outcome
3696
3785
  if (reproProdFail) return await needsHuman(prodFailNote("already-fixed (repro passes on the base)", reproProdFail), OUTCOME_CODES.BUILDER_NO_EVIDENCE);
@@ -3780,7 +3869,7 @@ export async function runCore(o) {
3780
3869
  files = await changedFiles();
3781
3870
  await gitPush(["push", "-u", "origin", branch]);
3782
3871
  laneGuard(lane, "open a PR");
3783
- const prOut = resumed?.pr ? `/pull/${resumed.pr}` : String(await ghw(["pr", "create", "-R", repo, "--base", lane, "--head", branch,
3872
+ const prOut = resumed?.pr ? `/pull/${resumed.pr}` : String(await ghw(["pr", "create", "-R", repo, "--base", stackedOn?.branch ?? lane, "--head", branch,
3784
3873
  "--title", `${iss.title} (#${issue})`, "--body", withLink(isSplit ? (o.refactorModule ?? (await import("./refactor.mjs"))).renderSplitPrBody({ issue, ...split })
3785
3874
  : renderPrBody({ issue, investigation: await readStage(STAGES[0]), contract: effective, implementation: await readStage(STAGES[1]), result, gitFiles: files, tracked: closing.tracked, visual: visualMarkdown(pageVisual, pagesConfig?.viewports) }))])).trim();
3786
3875
  const pr = Number(/\/pull\/(\d+)/.exec(prOut)?.[1] ?? /(\d+)\s*$/.exec(prOut)?.[1]);
@@ -4106,12 +4195,94 @@ export async function runCore(o) {
4106
4195
  return null;
4107
4196
  }
4108
4197
 
4198
+ // #5839: with the train on every lane kind but a split hands over at PR-ready (a split is never resolved by an LLM and is re-split on the new base, so it stays in-lane).
4199
+ // The merge-time work of e2e, sequence-file and close-record lanes travels as a persisted post-merge record the train replays.
4200
+ async function trainPlain() { return !isSplit; }
4201
+ function postMergeRecord() {
4202
+ const pend = pendingRecord(), notes = [];
4203
+ const keepOpen = Boolean(closing.checklist || closing.liveBlocked || closing.transferred || pend.length);
4204
+ if (pend.length) notes.push({ marker: "FORGE:FOLLOWUP_PENDING", body: renderPendingFollowups(pend, pr) });
4205
+ if (closing.checklist) notes.push({ marker: "FORGE:TRACKED", body: `## Left open: partial\nMerged by PR #${pr}, but these acceptance criteria are not met by it:\n${(closing.unticked ?? []).map((u) => `- [ ] ${u}`).join("\n")}${closing.tracked?.length ? `\n\nTracked in ${closing.tracked.join(", ")}.` : ""}` });
4206
+ if (closing.transferred) notes.push({ marker: "FORGE:TRACKED", body: `## Left open: transferred, not met\nMerged by PR #${pr}, but these end-to-end/manual requirements were not run in the lane:\n${(closing.transfer ?? closing.open ?? []).map((r) => `- ${r.id}`).join("\n")}` });
4207
+ if (closing.liveBlocked) notes.push({ marker: "FORGE:TRACKED", body: `## Left open: live acceptance deferred on a default-on change\nMerged by PR #${pr}, but these requirements still need live verification:\n${(closing.blocks ?? []).map((b) => `- ${b.id} (flag ${b.flag})`).join("\n")}` });
4208
+ if (!keepOpen && closing.tracked?.length) notes.push({ marker: "FORGE:TRACKED", body: `## Remaining work tracked\nClosed as completed by PR #${pr}. The contracted deferred and post-deploy requirements are tracked in ${closing.tracked.join(", ")}.` });
4209
+ return { keepOpen, notes, ...(pend.length ? { pendingFollowups: pend } : {}), ...(seqLease ? { sequence: true } : {}) };
4210
+ }
4211
+ async function trainHandover(why, conflicting = false) {
4212
+ if (!conflicting && e2eHead !== localHead) { const g = await e2eGate(); if (g?.done) return g.done; if (g?.again) return { again: true }; } // the e2e gate runs at the head in the lane; its merge-time record is replayed by the train
4213
+ ev({ event: "PR_READY", pr, head: localHead, required, policy });
4214
+ T.merge = [policyText, `pr-ready: ${why}, merge handed to the train at ${localHead.slice(0, 12)}`];
4215
+ return await finish("pr-ready", `PR #${pr} reviewed at ${localHead.slice(0, 12)}; ${why}, merge handed to the merge train`, { pr, head: localHead, required, policy, lane: resumed?.base ?? lane, ...(milestone ? { milestone } : {}), postMerge: postMergeRecord(), laneSide: { syncs, baseConflicts: conflicting ? 1 : 0 } });
4216
+ }
4217
+
4109
4218
  // ---- 7. (sync) wait per policy, (sync) merge at the reviewed head ----
4110
4219
  let lastStates = null; // the last required-check poll, reused by the DCO gate (#4651)
4220
+ // #5832: review passed and precheck green: this head is PR-ready (FORGE:STATE `prReady`, read by the orchestrator's stacked admission).
4221
+ try { if (finishing) throw new Error("finishing"); leaseState = { ...leaseState, prReady: { pr, branch, sha: localHead } }; await writeLease(leaseObj()); ev({ event: "PR_READY", pr, branch, sha: localHead }); } catch { /* best effort */ }
4222
+ const stackedState = stackedOn ?? validStackedOn(leaseState?.stackedOn);
4223
+ const depInfo = async () => { // #5833: the dependency's PRs from its branch -> {state: merged|closed|open, head}
4224
+ try {
4225
+ const l = JSON.parse(String(await ghc(["pr", "list", "-R", repo, "--head", stackedState.branch, "--state", "all", "--json", "number,state,headRefOid"])) || "[]");
4226
+ const open = l.find((x) => x?.state === "OPEN");
4227
+ if (open) return { state: "open", head: open.headRefOid ?? null }; // #5908: an open PR is the current dependency; a stale MERGED PR from a reused branch name must not satisfy it
4228
+ if (l.some((x) => x?.state === "MERGED")) return { state: "merged", head: null };
4229
+ return { state: l.length ? "closed" : "unknown", head: null };
4230
+ } catch { return { state: "unknown", head: null }; }
4231
+ };
4232
+ const depMerged = async () => (await depInfo()).state === "merged";
4233
+ const cascade = (kind, t1) => { cascadeLog.kinds.push(kind); cascadeLog.costUsd += Math.max(0, usage.cost_usd - t1.cost); cascadeLog.ms += now() - t1.at; ev({ event: "STACK_CASCADE", cascade: kind, pr, dependency: stackedState.dependency }); T.decisions.push(`Stacked lane cascade: ${kind} (dependency #${stackedState.dependency})`); };
4234
+ const dropStacked = async (why) => { // drop the stacked PR and branch; the rerun starts from the frozen contract
4235
+ try { await ghw(["pr", "close", String(pr), "-R", repo, "--comment", why]); } catch { /* best effort */ }
4236
+ try { await gitPush(["push", "origin", "--delete", branch]); } catch { /* best effort */ }
4237
+ };
4238
+ if (stackedState) { // wait for the dependency to merge, then move the PR onto the lane (merge.stacked_base never merges it before)
4239
+ const since = now();
4240
+ let curSha = stackedState.sha;
4241
+ for (;;) {
4242
+ const di = await depInfo(), t1 = { cost: usage.cost_usd, at: now() };
4243
+ if (di.state === "merged") break;
4244
+ if (di.state === "closed") { // ended unsatisfied: re-plan the dependent on the lane base
4245
+ cascade("replan", t1); await dropStacked(`stacked dependency #${stackedState.dependency} ended without merging; re-planning on ${lane}`);
4246
+ return await finish("deferred", `stacked dependency #${stackedState.dependency} ended unsatisfied; dependent re-planned on ${lane}`, { code: "stack.replan", pr, cascade: "replan" });
4247
+ }
4248
+ if (cascadeDecision({ depState: di.state, depHeadSha: di.head, stackedSha: curSha })) { // the dependency head moved: rebase and re-verify, or restart on a conflict
4249
+ try { await git(["fetch", "origin", stackedState.branch]); } catch { /* offline: use the local ref */ }
4250
+ let conflict = false;
4251
+ try { await git(["merge", "--no-commit", "--no-ff", base]); } catch { conflict = true; }
4252
+ try { await gitOut(["merge", "--abort"]); } catch { /* nothing to abort */ }
4253
+ const kind = cascadeDecision({ depState: "open", depHeadSha: di.head, stackedSha: curSha, rebaseConflict: conflict });
4254
+ if (kind === "restart") {
4255
+ cascade("restart", t1); await dropStacked(`rebase onto the moved head of #${stackedState.dependency} conflicts; restarting from the frozen contract`);
4256
+ return await finish("deferred", `stacked dependency #${stackedState.dependency} head moved and the rebase conflicts; restarting from the frozen contract`, { code: "stack.restart", pr, cascade: "restart" });
4257
+ }
4258
+ const r1 = await baseSync("stacked dependency head moved"); if (r1) return r1;
4259
+ const rv = await doReview(); // the review delta
4260
+ if (rv.env) return await envNeedsHuman(rv.env);
4261
+ if (rv.unusable || rv.fail) return await needsHuman(`Review ${rv.fail ? "FAIL" : "unusable"} after rebasing onto the moved head of #${stackedState.dependency}: ${rv.reason ?? rv.unusable}`, rv.fail ? OUTCOME_CODES.REVIEW_FAILED : UNUSABLE_REVIEW_CODES[rv.unusable]);
4262
+ await gatePassed("review");
4263
+ curSha = di.head; localHead = await gitOut(["rev-parse", "HEAD"]);
4264
+ leaseState = { ...leaseState, stackedOn: { ...stackedState, sha: curSha }, prReady: { pr, branch, sha: localHead } }; try { await writeLease(leaseObj()); } catch { /* best effort */ }
4265
+ cascade("reverify", t1); continue;
4266
+ }
4267
+ if (now() - since >= ciMaxMinutes * 60000) return await finish("ci-pending", `stacked PR #${pr} waited ${ciMaxMinutes} min for dependency #${stackedState.dependency} to merge; rerun resumes the PR`, { pr });
4268
+ onProgress({ event: "phase_paused", phase: "merge", detail: `merge.stacked_base: waiting for #${stackedState.dependency} to merge` });
4269
+ await sleep(30000);
4270
+ await renew();
4271
+ }
4272
+ const t2 = { cost: usage.cost_usd, at: now() };
4273
+ try { await ghw(["pr", "edit", String(pr), "-R", repo, "--base", lane]); ev({ event: "STACK_RETARGET", pr, from: stackedState.branch, to: lane }); }
4274
+ catch (e) { return await finish("deferred", `stacked PR #${pr}: retarget to ${lane} failed: ${String(e?.message ?? e).slice(0, 200)}`, { pr }); }
4275
+ base = `origin/${lane}`; // the PR now targets the lane: later syncs merge the lane, not the dependency branch
4276
+ try { await git(["fetch", "origin", lane]); stackInvalidation = { changedPaths: String(await git(["diff", "--name-only", curSha, `origin/${lane}`])).split("\n").map((x) => x.trim()).filter(Boolean) }; } catch { stackInvalidation = null; } // unknown diff: every check re-runs
4277
+ let r0; try { r0 = await baseSync("stacked PR moved onto the lane"); } finally { stackInvalidation = null; }
4278
+ cascade("rebase", t2); if (r0) return r0;
4279
+ }
4111
4280
  // A rerun on an existing PR goes through the same conflict check, so a conflicting PR from an earlier run recovers.
4112
4281
  for (;;) {
4113
4282
  const c0 = await prConflicting();
4283
+ if (c0 && mergeTrain === "on" && !isSplit && await trainPlain()) return await trainHandover(c0 === "conflict" ? "PR conflicts with the base, handed to the train as base.conflict" : "no lane base-sync", c0 === "conflict"); // #5839
4114
4284
  if (c0) { const r = await baseSync(c0 === "unknown" ? "PR mergeability unknown" : "PR is conflicting", c0 === "unknown"); if (r) return r; }
4285
+ if (mergeTrain === "on" && await trainPlain() && (policy === "none" || (policy === "required" && !required.length))) { const h = await trainHandover("no required checks"); if (h?.again) continue; return h; } // #5839
4115
4286
  if (policy === "none" || (policy === "required" && !required.length)) {
4116
4287
  // merge right after review
4117
4288
  T.merge = [policyText, "merged right after review"];
@@ -4141,7 +4312,7 @@ export async function runCore(o) {
4141
4312
  if (policy === "all") {
4142
4313
  // #4270: the lane's own report-only check never gates its own merge
4143
4314
  const w = await io.waitCiGreen(pr, repo, 0, ...(vcfg.checkRun === true ? [{ ignore: [VERIFY_CHECK_NAME] }] : [])).catch(() => ({ rc: 2, text: "" }));
4144
- if (w.rc === 0) { gateHead = /CI_GATE_HEAD:\s*([0-9a-f]{7,40})/.exec(w.text ?? "")?.[1] ?? null; break; }
4315
+ if (w.rc === 0) { gateHead = /CI_GATE_HEAD:\s*([0-9a-f]{7,40})/.exec(w.text ?? "")?.[1] ?? null; if (mergeTrain === "on" && await trainPlain()) { const h = await trainHandover("CI green"); if (h?.again) continue; return h; } break; }
4145
4316
  if (w.rc === 1) return await needsHuman(`Remote CI failed on PR #${pr}:\n${String(w.text).slice(-2000)}`, OUTCOME_CODES.CI_RED);
4146
4317
  } else {
4147
4318
  try { states = (await io.checkStates(pr)) ?? []; } catch { states = []; }
@@ -4155,6 +4326,10 @@ export async function runCore(o) {
4155
4326
  startedAt = now(); pollIndex = 0; // the fixed head gets the full wait budget
4156
4327
  continue;
4157
4328
  }
4329
+ // #5836/#5839: with the merge train on, a green or pending PR leaves the slot; the train is the one merge queue per base
4330
+ if (mergeTrain === "on" && required.length && await trainPlain()) {
4331
+ const h = await trainHandover(required.every((n) => st(n) === "success") ? "required checks green" : "required checks pending"); if (h?.again) continue; return h;
4332
+ }
4158
4333
  if (required.every((n) => st(n) === "success")) break;
4159
4334
  }
4160
4335
  // #4266: a PR that turns conflicting gets no merge ref, so its pull_request workflows never start: base-sync now.
@@ -4231,6 +4406,12 @@ export async function runCore(o) {
4231
4406
  await sleep(30000);
4232
4407
  await renew();
4233
4408
  }
4409
+ if (stackedState) { // #5832 engine guard merge.stacked_base: a stacked PR never merges while its base is not the lane or its dependency is unmerged
4410
+ let prBase = "";
4411
+ try { prBase = JSON.parse(String(await ghc(["pr", "view", String(pr), "-R", repo, "--json", "baseRefName"])) || "{}").baseRefName ?? ""; } catch { /* unknown base: refused below */ }
4412
+ const why = stackedBaseBlock({ prBase, lane, stackedBranch: stackedState.branch, dependencyMerged: await depMerged() });
4413
+ if (why) { T.merge = [policyText, "merge.stacked_base"]; T.decisions.push(`${why}; PR #${pr} not merged`); ev({ event: "MERGE_STACKED_BASE_REFUSED", pr, base: prBase, lane }); return await finish("deferred", `${why}; PR #${pr} stays open`, { pr, code: "merge.stacked_base" }); }
4414
+ }
4234
4415
  T.merge = [policyText, `merged at ${localHead.slice(0, 12)}`];
4235
4416
  laneGuard(resumed?.base ?? lane, "merge");
4236
4417
  try {
@@ -4296,7 +4477,7 @@ export async function runCore(o) {
4296
4477
  try { await post("FORGE:TRACKED", `## Left open: live acceptance deferred on a default-on change\nMerged by PR #${pr}, but the rollout is live and these requirements still need live verification:\n${closing.blocks.map((b) => `- ${b.id} (flag ${b.flag})`).join("\n")}\n\nKeep the flag default-off until they are verified, or verify them and close.${closing.tracked.length ? ` Tracked in ${closing.tracked.join(", ")}.` : ""}`); } catch { /* the trajectory decision records it too */ }
4297
4478
  }
4298
4479
  // #5152: a merged change is `completed` even when partial: the remainder is tracked (FORGE:TRACKED), not dropped
4299
- if (!keepOpen && !(await closeBlockers("completed", pr)).length) await ghw(["issue", "close", String(issue), "-R", repo, "--reason", "completed"]).catch(() => {}); // #5505: not while another own PR is open
4480
+ if (!keepOpen && !(await closeBlockers("completed", pr)).length) await closeMergedIssue({ gh: ghw, repo, issue, label: false }); // #5505: not while another own PR is open
4300
4481
  if (closing.transferred) { // #5339: record what is transferred, not met
4301
4482
  try { await post("FORGE:TRACKED", `## Left open: transferred, not met\nMerged by PR #${pr}, but these end-to-end/manual requirements were not run in the lane:\n${(closing.transfer ?? closing.open).map((r) => `- ${r.id}: ${r.transferred ? `transferred to epic #${r.transferred} (post-deploy journey)` : "no epic to take it"}`).join("\n")}${closing.tracked.length ? `\n\nTracked in ${closing.tracked.join(", ")}.` : ""}`); } catch { /* the PR body carries them too */ }
4302
4483
  } else if (closing.liveBlocked) { /* #5285: posted above */ } else if (closing.checklist) { // #5240: partial: left open; the unticked criteria, tracked follow-ups and any inert rollout are the record
@@ -4340,6 +4521,7 @@ export async function runCore(o) {
4340
4521
  const when = e.resetAt || (Number.isFinite(e.resetAtEpochMs) ? new Date(e.resetAtEpochMs).toISOString() : "unknown");
4341
4522
  return finish("deferred", `usage limit hit; resets at ${when}`, { code: OUTCOME_CODES.RATE_LIMITED, resetAt: when, resetAtEpochMs: Number.isFinite(e.resetAtEpochMs) ? e.resetAtEpochMs : null, backendId: laneBackendId(process.env, rotator) }, OUTCOME_CODES.RATE_LIMITED);
4342
4523
  }
4524
+ if (!e?.deferCode && isSpawnError(e) && String(e?.path ?? e?.spawnargs?.[0] ?? e?.message).match(/git/i)) repoMissing(e); // #5890: a raw spawn ENOENT/EACCES is never an untyped engine-error
4343
4525
  if (e?.deferCode) return finish("deferred", e.deferDetail ?? String(e.message), { code: e.deferCode, ...(e.retryInSeconds ? { retryInSeconds: e.retryInSeconds } : {}), ...(e.backendId ? { backendId: e.backendId } : {}), ...(e.cliResult != null ? { cliResult: e.cliResult } : {}), ...(typeof e.cliIsError === "boolean" ? { cliIsError: e.cliIsError } : {}), ...(e.account ? { account: e.account } : {}), ...quotaFacts(e) }, e.deferCode); // #5168: backendId keys the account hold; #5236 reset
4344
4526
  // #4505: a turn overrun is mechanical: a non-human end the batch recovers, needs-human only once a budget recovery failed too
4345
4527
  if (e?.laneCode === OUTCOME_CODES.BUDGET_EXCEEDED && !(recover?.final && recover.code === OUTCOME_CODES.BUDGET_EXCEEDED)) {