forgedock 1.52.0 → 1.54.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 (233) hide show
  1. package/.claude-plugin/marketplace.json +51 -0
  2. package/README.md +8 -2
  3. package/bin/auth/app-manifest.mjs +89 -0
  4. package/bin/auth/app-manifest.test.mjs +75 -0
  5. package/bin/auth/app-token.mjs +256 -0
  6. package/bin/auth/app-token.test.mjs +232 -0
  7. package/bin/brand.mjs +7 -0
  8. package/bin/config-history.mjs +151 -0
  9. package/bin/config-schema.mjs +115 -0
  10. package/bin/demo.mjs +65 -11
  11. package/bin/engine/outcome-codes.mjs +9 -3
  12. package/bin/engine/telemetry-seam.mjs +11 -3
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +110 -36
  15. package/bin/experiment.mjs +58 -6
  16. package/bin/first-run.mjs +122 -0
  17. package/bin/forge-utils.mjs +6 -2
  18. package/bin/forgedock.mjs +138 -142
  19. package/bin/help-text.mjs +144 -0
  20. package/bin/hooks/pre-tool-use.mjs +7 -0
  21. package/bin/journey.mjs +82 -83
  22. package/bin/lean/acceptance.mjs +313 -0
  23. package/bin/lean/acceptance.test.mjs +215 -0
  24. package/bin/lean/account-watch.mjs +28 -0
  25. package/bin/lean/account-watch.test.mjs +30 -0
  26. package/bin/lean/activation.mjs +38 -0
  27. package/bin/lean/activation.test.mjs +36 -1
  28. package/bin/lean/basered.mjs +115 -0
  29. package/bin/lean/basered.test.mjs +66 -0
  30. package/bin/lean/batch-health.mjs +114 -7
  31. package/bin/lean/batch-health.test.mjs +87 -1
  32. package/bin/lean/batch.mjs +41 -2
  33. package/bin/lean/batch.test.mjs +115 -11
  34. package/bin/lean/branchlock.mjs +54 -0
  35. package/bin/lean/branchlock.test.mjs +49 -0
  36. package/bin/lean/ceiling.mjs +72 -0
  37. package/bin/lean/ceiling.test.mjs +54 -0
  38. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  39. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  40. package/bin/lean/ci-budget.mjs +366 -0
  41. package/bin/lean/ci-budget.test.mjs +167 -0
  42. package/bin/lean/conformance.e2e.test.mjs +8 -1
  43. package/bin/lean/conformance.mjs +269 -38
  44. package/bin/lean/conformance.test.mjs +280 -7
  45. package/bin/lean/context.mjs +35 -6
  46. package/bin/lean/context.test.mjs +27 -1
  47. package/bin/lean/depcache.mjs +25 -1
  48. package/bin/lean/depcache.test.mjs +26 -0
  49. package/bin/lean/e2e.mjs +18 -2
  50. package/bin/lean/e2e.test.mjs +26 -1
  51. package/bin/lean/effects.mjs +47 -14
  52. package/bin/lean/execution.mjs +19 -3
  53. package/bin/lean/execution.test.mjs +63 -0
  54. package/bin/lean/facts.mjs +3 -3
  55. package/bin/lean/facts.test.mjs +5 -0
  56. package/bin/lean/findinglabel.mjs +16 -0
  57. package/bin/lean/findinglabel.test.mjs +39 -0
  58. package/bin/lean/fixround.mjs +14 -0
  59. package/bin/lean/fixround.test.mjs +25 -2
  60. package/bin/lean/gh-assoc.test.mjs +2 -1
  61. package/bin/lean/integration.mjs +100 -9
  62. package/bin/lean/integration.test.mjs +98 -0
  63. package/bin/lean/issuewatch-parity.mjs +64 -0
  64. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  65. package/bin/lean/issuewatch-release.mjs +6 -2
  66. package/bin/lean/issuewatch-release.test.mjs +17 -1
  67. package/bin/lean/issuewatch.mjs +45 -6
  68. package/bin/lean/issuewatch.test.mjs +3 -2
  69. package/bin/lean/lanelock.mjs +14 -0
  70. package/bin/lean/lean.mjs +473 -100
  71. package/bin/lean/lean.test.mjs +686 -33
  72. package/bin/lean/light.mjs +48 -7
  73. package/bin/lean/light.test.mjs +37 -3
  74. package/bin/lean/limits.test.mjs +142 -9
  75. package/bin/lean/mechfix.mjs +124 -0
  76. package/bin/lean/mechfix.test.mjs +75 -0
  77. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  78. package/bin/lean/orchestrate.mjs +116 -28
  79. package/bin/lean/phaseledger.mjs +47 -5
  80. package/bin/lean/phaseledger.test.mjs +30 -1
  81. package/bin/lean/postdeploy-check.test.mjs +39 -0
  82. package/bin/lean/precheck.mjs +23 -4
  83. package/bin/lean/precheck.test.mjs +14 -1
  84. package/bin/lean/prereq.mjs +28 -0
  85. package/bin/lean/prereq.test.mjs +20 -0
  86. package/bin/lean/probe.mjs +4 -2
  87. package/bin/lean/prodparity.mjs +52 -0
  88. package/bin/lean/prodparity.test.mjs +67 -0
  89. package/bin/lean/prompts.mjs +77 -19
  90. package/bin/lean/quota.mjs +39 -0
  91. package/bin/lean/recovery.test.mjs +11 -1
  92. package/bin/lean/relaxation.mjs +73 -0
  93. package/bin/lean/relaxation.test.mjs +54 -0
  94. package/bin/lean/release-io.test.mjs +42 -0
  95. package/bin/lean/release-postmerge.mjs +125 -0
  96. package/bin/lean/release-preflight.mjs +58 -0
  97. package/bin/lean/release-preflight.test.mjs +114 -0
  98. package/bin/lean/release-rehearsal.mjs +64 -0
  99. package/bin/lean/release-rehearsal.test.mjs +93 -0
  100. package/bin/lean/release-review.e2e.test.mjs +77 -0
  101. package/bin/lean/release-review.mjs +254 -0
  102. package/bin/lean/release-review.test.mjs +307 -0
  103. package/bin/lean/release-snapshot.mjs +188 -0
  104. package/bin/lean/release-snapshot.test.mjs +190 -0
  105. package/bin/lean/release.mjs +296 -0
  106. package/bin/lean/release.test.mjs +387 -0
  107. package/bin/lean/render.mjs +1 -1
  108. package/bin/lean/replan.mjs +184 -0
  109. package/bin/lean/replan.test.mjs +110 -0
  110. package/bin/lean/resume.mjs +9 -7
  111. package/bin/lean/resume.test.mjs +16 -0
  112. package/bin/lean/rotator.mjs +150 -31
  113. package/bin/lean/rotator.test.mjs +105 -2
  114. package/bin/lean/sandbox-remote.mjs +9 -2
  115. package/bin/lean/schedd.mjs +83 -5
  116. package/bin/lean/schedd.test.mjs +108 -7
  117. package/bin/lean/selfreview.mjs +94 -0
  118. package/bin/lean/selfreview.test.mjs +58 -1
  119. package/bin/lean/selftest-gate.mjs +22 -0
  120. package/bin/lean/selftest-gate.test.mjs +18 -1
  121. package/bin/lean/selftest-journey.mjs +234 -0
  122. package/bin/lean/selftest-journey.test.mjs +130 -0
  123. package/bin/lean/selftest-live.mjs +2 -1
  124. package/bin/lean/seqlease.mjs +35 -1
  125. package/bin/lean/seqlease.test.mjs +15 -0
  126. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  127. package/bin/lean/seqreserve.mjs +73 -0
  128. package/bin/lean/seqreserve.test.mjs +134 -0
  129. package/bin/lean/sequence.mjs +35 -6
  130. package/bin/lean/seqversioned.mjs +147 -0
  131. package/bin/lean/stagestamp.mjs +28 -0
  132. package/bin/lean/stagestamp.test.mjs +32 -0
  133. package/bin/lean/surfaces.mjs +75 -0
  134. package/bin/lean/surfaces.test.mjs +59 -0
  135. package/bin/lean/toolplace.mjs +28 -0
  136. package/bin/lean/toolplace.test.mjs +24 -0
  137. package/bin/lean/toolstats.mjs +3 -1
  138. package/bin/lean/toolstats.test.mjs +11 -0
  139. package/bin/lean/validatebest.mjs +28 -0
  140. package/bin/lean/validatebest.test.mjs +27 -0
  141. package/bin/lean/verifier.mjs +3 -2
  142. package/bin/lean/verify.mjs +2 -1
  143. package/bin/lean/verify.test.mjs +6 -0
  144. package/bin/pool/agent.mjs +27 -4
  145. package/bin/pool/docker.mjs +5 -0
  146. package/bin/pool/router.mjs +74 -28
  147. package/bin/prereqs.mjs +111 -0
  148. package/bin/replay-timelapse.mjs +149 -0
  149. package/bin/review-staging.mjs +123 -16
  150. package/bin/review-staging.test.mjs +18 -0
  151. package/bin/runner.mjs +43 -6
  152. package/bin/splash-install.mjs +157 -0
  153. package/bin/stats/aggregate.mjs +8 -1
  154. package/bin/stats/conformance-outcomes.mjs +289 -0
  155. package/bin/stats/conformance-outcomes.test.mjs +274 -0
  156. package/bin/stats/depth.mjs +275 -0
  157. package/bin/stats/depth.test.mjs +158 -0
  158. package/bin/stats/efficiency.mjs +26 -5
  159. package/bin/stats/efficiency.test.mjs +45 -1
  160. package/bin/stats/experiment.mjs +7 -5
  161. package/bin/stats/first-review.mjs +77 -0
  162. package/bin/stats/first-review.test.mjs +36 -0
  163. package/bin/stats/firstmerge.mjs +40 -0
  164. package/bin/stats/firstmerge.test.mjs +41 -0
  165. package/bin/stats/github-source.mjs +53 -15
  166. package/bin/stats/index.mjs +147 -9
  167. package/bin/stats/local-source.mjs +12 -0
  168. package/bin/stats/origin.mjs +80 -0
  169. package/bin/stats/origin.test.mjs +58 -0
  170. package/bin/stats/query.mjs +69 -0
  171. package/bin/stats/render.mjs +3 -1
  172. package/bin/stats/scoreboard.mjs +137 -0
  173. package/bin/stats/scoreboard.test.mjs +87 -0
  174. package/bin/stats/selffiled.mjs +52 -0
  175. package/bin/stats/selffiled.test.mjs +71 -0
  176. package/bin/stats/stats.test.mjs +80 -0
  177. package/bin/tui.mjs +3 -2
  178. package/commands/bootstrap.md +15 -14
  179. package/commands/deploy-pr.md +18 -3
  180. package/commands/forge-stats.md +1 -1
  181. package/commands/forgedock-ci-setup.md +28 -0
  182. package/commands/forgedock-init.md +4 -5
  183. package/commands/issue.md +2 -0
  184. package/commands/milestone.md +9 -1
  185. package/commands/orchestrate.md +1 -1
  186. package/commands/replay.md +2 -0
  187. package/commands/review-pr-agents/security.md +4 -0
  188. package/commands/review-pr-staging.md +6 -1
  189. package/commands/work-on/build.md +4 -6
  190. package/commands/work-on/close.md +8 -0
  191. package/docs/CONFIG.md +170 -18
  192. package/docs/ISSUE-WATCH.md +25 -0
  193. package/docs/OUTCOME-CODES.md +4 -0
  194. package/docs/REPLAY.md +9 -0
  195. package/docs/SELFTEST.md +11 -0
  196. package/docs/STATS.md +61 -0
  197. package/docs/TELEMETRY.md +1 -1
  198. package/docs/eval/README.md +6 -0
  199. package/docs/eval/adversarial-bench.md +68 -0
  200. package/docs/eval/corpus/adversarial-v1.json +285 -0
  201. package/docs/eval/feature-bench.md +42 -0
  202. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  203. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  204. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  205. package/docs/site/start-a-new-project.md +2 -1
  206. package/package.json +5 -2
  207. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  208. package/plugins/forgedock-splash/README.md +27 -0
  209. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  210. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  211. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  212. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  213. package/pool/README.md +1 -1
  214. package/pool/image/cs-cred +14 -1
  215. package/scripts/backfill-finding-labels.mjs +50 -0
  216. package/scripts/backfill-finding-labels.test.mjs +36 -0
  217. package/scripts/bench-adversarial.mjs +216 -0
  218. package/scripts/bench-feature.mjs +170 -0
  219. package/scripts/bench-lightlane.mjs +2 -2
  220. package/scripts/bootstrap-create.mjs +2 -2
  221. package/scripts/bootstrap-validate.mjs +35 -2
  222. package/scripts/check-spec-size.sh +4 -3
  223. package/scripts/check-spec-size.test.sh +3 -0
  224. package/scripts/doctor-pipeline-state.sh +21 -6
  225. package/scripts/file-deferred-followups.sh +59 -251
  226. package/scripts/file-deferred-followups.test.sh +85 -206
  227. package/scripts/followup-route.mjs +12 -0
  228. package/scripts/owner-route-parity.test.sh +17 -1
  229. package/scripts/plan-validate-live.mjs +40 -6
  230. package/scripts/review-pr-side-effects.test.sh +40 -0
  231. package/scripts/review-pr-staging-scope.test.sh +1 -1
  232. package/scripts/review-staging-post.sh +23 -0
  233. package/scripts/review-staging-post.test.sh +8 -0
package/bin/lean/lean.mjs CHANGED
@@ -5,30 +5,36 @@
5
5
  * ForgeDock registers everything on GitHub (labels, one register comment, PR, merge). No investigation, synthesis,
6
6
  * severity taxonomy, risk tiers or local CI gates. All effects are injected through `io` so it is unit-testable.
7
7
  */
8
- import { existsSync } from "node:fs";
8
+ import { resolveFindingLabel } from "./findinglabel.mjs";
9
+ import { spawnSync } from "node:child_process";
10
+ import { existsSync, readFileSync } from "node:fs";
9
11
  import { join, dirname, basename, delimiter } from "node:path";
10
12
  import { hostname as osHostname } from "node:os";
11
13
  import { appendEvent } from "../engine/runlog.mjs";
12
- import { readSelfReview, compareSelfReview } from "./selfreview.mjs";
13
- import { codeForTerminalReason, OUTCOME_CODES, ENV_VALIDATE_TIMEOUT } from "../engine/outcome-codes.mjs";
14
+ import { readSelfReview, compareSelfReview, firstReviewRecord, selfCheckFailures } from "./selfreview.mjs";
15
+ import { codeForTerminalReason, OUTCOME_CODES, ENV_VALIDATE_TIMEOUT, ENV_VALIDATE_PLACEMENT } from "../engine/outcome-codes.mjs";
14
16
  import { ciPollDelayMs, ENGINE_VERSION, DEFAULT_MAX_SESSION_LIMIT_PAUSES, DEFAULT_SESSION_LIMIT_WAIT_MS, parseLeaseHolder, sanitizeLeaseHost } from "../engine.mjs";
15
17
  import { openDependency, laneMergedPrs, dependencyOnLane, isTrustedComment, decomposedSubissues, isDecomposedRecord, reopenRevokedDecomposition } from "../engine/phases.mjs";
16
18
  import { createHash, randomBytes } from "node:crypto";
17
19
  import { otherLaneOwner } from "./lanelock.mjs";
18
- import { applyValidateRecipes, deferChecklessPostDeploy, reproEnvMiss, resolveForgedockPaths, describesUnrunnableCommand, removedPathsOf, TRACKED, normalizeKindModes, blockingFailures, unverifiedRequirements, mutationTargets, mutationFailures, runMutationCheck, MUTATION_SURVIVED, isBugIssue, scopeText, explainFailures, inIssue, validateContract, cliUsageError, normalizeRunnerCommand, applyAmendments, amendmentKindProblems, precheck, alreadyFixedOnBase, READONLY_PROD_RE, EXTERNAL_NEED_RE, repoTracks, dropScopeValidates, tagOutOfBand, parseReview, decide, mergeReviewRows, reaskable, criterionLines, closePlan, followupItems, renderPendingFollowups, bucketTally, pendingTracking, unnamedEdges, structureNote, impliedDocDeliverables } from "./conformance.mjs";
20
+ import { stampText, checkStamp } from "./stagestamp.mjs";
21
+ import { acquireBranchLock, waitPidsExit } from "./branchlock.mjs";
22
+ import { applyValidateRecipes, rewriteProjectDirCommand, deferChecklessPostDeploy, reproEnvMiss, resolveForgedockPaths, 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";
19
23
  import { checkAdmission, hostParallelism, ADMISSION_RETRY_SECONDS } from "./admission.mjs";
20
24
  import { namedPaths, isTrustedIssueComment } from "./prefilter.mjs";
21
25
  import { checksAt } from "./postdeploy-check.mjs";
22
- import { readRollouts, detectNewOffKeys } from "./activation.mjs";
26
+ import { readRollouts, detectNewOffKeys, rolloutModes, liveDeferralBlocks } from "./activation.mjs";
27
+ import { toolMisses } from "./toolplace.mjs";
23
28
  import { testRunnerProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract } from "./preflight.mjs";
24
29
  import { resolveLane, isDefaultLane, isShippedLane, DEFAULT_STAGING_BRANCH } from "./lane.mjs";
25
30
  import { splitGate, rationaleLine } from "./decompose.mjs";
31
+ import { ceilingFor, predictRestart, handoffFacts, NARROW_NOTE } from "./ceiling.mjs";
26
32
  import { dockerLabels, LEDGER_TTL_MS } from "./ledger.mjs";
27
- import { repoKey } from "../runner.mjs";
33
+ import { repoKey, estimateCostUsd } from "../runner.mjs";
28
34
  import { prepareToolchain } from "./toolchain.mjs";
29
35
  import { toolStats } from "./toolstats.mjs";
30
- import { readTestMap, readTestMapAtRef, mergeChecks, factsPath, TEST_MAP_FILE } from "./testmap.mjs";
31
- import { runChecks, runWithTimeoutRetry, planPrecheck, worktreeFingerprint, selfCheckState, quietFailure, CHECK_PLAN_FILE, SELF_CHECK_FILE, CHECK_LOG_DIR } from "./precheck.mjs";
36
+ import { readTestMap, readTestMapAtRef, selectCommands, mergeChecks, factsPath, TEST_MAP_FILE } from "./testmap.mjs";
37
+ import { runChecks, runWithTimeoutRetry, splitPrecheckResults, timedOutDetail, planPrecheck, worktreeFingerprint, selfCheckState, quietFailure, CHECK_PLAN_FILE, SELF_CHECK_FILE, CHECK_LOG_DIR } from "./precheck.mjs";
32
38
  import { retrying, ghCacheRetry, refreshAuthOnce, runRefreshScript, GH_AUTH_RE, GH_AUTH_RETRY_SECONDS, PUSH_TRANSIENT_RE, PUSH_PERMANENT_RE, GH_TRANSIENT_RE, MERGE_TRANSIENT_RE, MERGE_CONFLICT_RE } from "./retry.mjs";
33
39
  import { renderInvestigation, renderImplementation, renderReview, renderPrBody, renderTrajectory, renderContract, renderAmendments, renderShadowReview, parseContractComment, parseAmendmentsComment, contractJson, capComment, sanitizeMd, MAX_COMMENT_CHARS, recoveryEvidence } from "./render.mjs";
34
40
  import { parseVerifierConfig, pickVerifierModel, changedSymbols, callersOf, verifierBudget, verifierPrompt, parseVerifierFindings, findingsToFailures, renderVerifierNote, VERIFIER_SYSTEM } from "./verifier.mjs";
@@ -38,30 +44,40 @@ import { hostCapabilityBlock, contractHostNeeds } from "./execution.mjs";
38
44
  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;
39
45
  /** #4685: true when a builder's block summary names a missing tool or module (environment), not a credential. */
40
46
  export function missingToolBlock(summary) { return MISSING_TOOL_RE.test(String(summary ?? "")); }
41
- import { CHECKS_CLI, FORGEDOCK_CLI, REVIEWER_SYSTEM, LEAN_DIR, RESULT_FILE, INVESTIGATION_FILE, IMPLEMENTATION_FILE, CONTRACT_FILE, builderPlanPrompt, builderImplementPrompt, contractCorrectionPrompt, conformanceResumePrompt, amendmentCorrectionPrompt, reviewerPrompt, investigationVerdict, decisionNote, reviewerRepairPrompt, REVIEW_DIFF_MAX_BYTES, blockCorrectionPrompt, HUMAN_BLOCK_REASONS, structurePrompt, hotspotPlanNote, hotspotBuildRule, reproPlanNote, unrunnableValidateNote, contextPackNote, docsPrompt, ciFailurePrompt, ciUnavailablePrompt, precheckFailurePrompt, contextRestartPrompt, turnBudgetWrapupPrompt, syncChecks, GROUPING_SYSTEM, enumeratingPlanNote, enumeratingBuildRule, invariantsPlanNote, invariantsBuildRule, missingEntriesPrompt, sequencePrompt, sequenceSyncNote, sequenceSyncPrompt, fixSessionPrompt, postMergeFailurePrompt, duplicateExportsPrompt, migrationGeneratorPrompt, i18nCopiesPrompt } from "./prompts.mjs";
47
+ import { reserveForBuild, revalidate } from "./seqreserve.mjs";
48
+ import { CHECKS_CLI, FORGEDOCK_CLI, REVIEWER_SYSTEM, LEAN_DIR, RESULT_FILE, INVESTIGATION_FILE, IMPLEMENTATION_FILE, CONTRACT_FILE, builderPlanPrompt, builderImplementPrompt, contractCorrectionPrompt, conformanceResumePrompt, amendmentCorrectionPrompt, reviewerPrompt, investigationVerdict, decisionNote, reviewerRepairPrompt, REVIEW_DIFF_MAX_BYTES, blockCorrectionPrompt, HUMAN_BLOCK_REASONS, structurePrompt, hotspotPlanNote, hotspotBuildRule, reproPlanNote, unrunnableValidateNote, contextPackNote, buildOpeningNote, sequenceBuildRule, docsPrompt, ciFailurePrompt, ciUnavailablePrompt, precheckFailurePrompt, contextRestartPrompt, turnBudgetWrapupPrompt, syncChecks, GROUPING_SYSTEM, enumeratingPlanNote, enumeratingBuildRule, invariantsPlanNote, invariantsBuildRule, missingEntriesPrompt, sequencePrompt, sequenceSyncNote, sequenceSyncPrompt, fixSessionPrompt, postMergeFailurePrompt, duplicateExportsPrompt, migrationGeneratorPrompt, i18nCopiesPrompt, narrowFixPrompt } from "./prompts.mjs";
42
49
  import { postMergeCommands } from "./postmerge.mjs";
50
+ import { classifyBaseRed, attribute as attributeBaseRed, runOnBase, reportBaseRed } from "./basered.mjs"; // #5239
43
51
  import { guardAfterMerge, withHistoryRows } from "./guards.mjs";
52
+ import { parseProdParity, prodParityFailures as prodParityOf } from "./prodparity.mjs";
44
53
  import { routePathsFromFiles, routeReachabilityFailures } from "./routecheck.mjs";
45
54
  import { parseCoupled, coupledFailures } from "./coupled.mjs";
55
+ import { analyzeRelaxations, relaxationFailures } from "./relaxation.mjs";
46
56
  import { loadGuards, selectGuards, runGuards, supersededIds, supersessionComment } from "./guardgate.mjs";
47
- import { freshFix, issueSummary, firstPassOf, sessionCostDelta } from "./fixround.mjs";
57
+ import { freshFix, issueSummary, firstPassOf, sessionCostDelta, mergeNarrowTasks } from "./fixround.mjs";
48
58
  import { parseBuilderRouting, routeBuilder, shouldEscalate } from "./routing.mjs";
49
59
  import { makeTurnBudget, TURN_BUDGET_DEFAULTS, scaledExtra, laneSize, recoverySize, wrapupGrant, budgetDigest } from "./budget.mjs";
50
60
  import { pendingPitfall, pitfallRecord, foldPitfalls, selectPitfalls, failureLog } from "./pitfalls.mjs";
51
61
  import { unjustified } from "./enumerating.mjs";
62
+ import { applyEnumerating, renameDuplicates } from "./mechfix.mjs"; // #5348
52
63
  import { addLaneWorktree, DEFAULT_SPARSE_MAX_KB } from "./worktree.mjs";
53
64
  import { parseVerify, runCiVerify, collectFailedLogs, capLogs, VERIFY_MODES, VERIFY_CHECK_NAME, verifyReport, ciGate, rerunFailedOnce, rerunTarget, splitFlaky } from "./verify.mjs";
54
- import { e2eSpecs, e2eWanted, ownFailures, runE2eGate, NO_TRIGGER } from "./e2e.mjs";
65
+ import { e2eSpecs, e2eWanted, uiInteractiveChanged, ownFailures, runE2eGate, fakedPaths, NO_TRIGGER } from "./e2e.mjs";
66
+ import { transferToEpic } from "./acceptance.mjs";
55
67
  import { laneBackendId } from "./limits.mjs";
56
68
  import { openRotator, rotatorRetry } from "./rotator.mjs";
69
+ import { poolExhausted, exhaustedDeferral, quotaFacts } from "./quota.mjs"; // #5236
70
+ import { watchAccount } from "./account-watch.mjs"; // #5268
57
71
  import { SPLIT_LABEL } from "./refactor.mjs";
58
72
  import { writeHeavyShims, sumWaits, isHeavyProcess } from "./heavy.mjs";
59
73
  import { priorityFromLabels } from "./sched.mjs";
60
- import { assignArm } from "../experiment.mjs";
74
+ import { applyArmOverrides } from "../experiment.mjs";
61
75
  import { parseExploreConfig, explorerAgents, explorePlanRule, exploreBuildRule } from "./explore.mjs";
62
76
  import { normaliseFacts, renderFactsRecord, FACTS_MARKER } from "./facts.mjs";
63
77
  import { readDecisionIndex, withDecisionRows, recordDecisions } from "./decisions.mjs";
64
- import { parseContextPackConfig, contextArm, contextPackFor, renderContextRecord, laneType, priorAttempts, linkStateStamp, stateOf } from "./context.mjs";
78
+ import { normaliseInvalidation, epicOf, fileAmendment, REPLAN_MARKER } from "./replan.mjs";
79
+ import { claimSurfaces, parseSharedSurfaces, generatorNote } from "./surfaces.mjs";
80
+ import { parseContextPackConfig, resolveContextMode, parentOf, contextArm, contextPackFor, renderContextRecord, laneType, priorAttempts, linkStateStamp, stateOf } from "./context.mjs";
65
81
  import { isExternalKill } from "./hostkill.mjs";
66
82
  import { buildResumeDigest } from "./resume.mjs";
67
83
  import { parsePredicate, evalPredicate, premiseAnnotation, registerAsk, registryPkgVersion, closedEdgeNote, onlyAsk, fileRemainder } from "./needs-human-premise.mjs";
@@ -69,6 +85,7 @@ import { lightEligibility } from "./light.mjs";
69
85
  import { untrackToolState, unstageToolState, isToolState, clearLaneScratch } from "./toolstate.mjs";
70
86
  import { pickSalvage } from "./salvage-resume.mjs";
71
87
  import { ensureSignedOff, salvageBranch, dropSalvageTracking } from "./signoff.mjs";
88
+ import { reconcileCheckpoints } from "./checkpoint-reconcile.mjs";
72
89
  import { createLedger, flattenPhases } from "./phaseledger.mjs";
73
90
  import { runLightStep, runLightTests, lightBuildPrompt, upgradeNote, renderLiteReceipt } from "./lightlane.mjs";
74
91
 
@@ -84,11 +101,12 @@ export const RECOVER_HOW = Object.freeze({
84
101
  [OUTCOME_CODES.BUDGET_EXCEEDED]: "an earlier run spent the implement turn budget for this issue's size; its digest is in the earlier run's detail and the branch holds its checkpointed work. Continue from the checkpoint against the frozen contract without starting over; if the remaining work cannot fit the budget, stop with a typed split-required block naming the sub-issues instead of grinding",
85
102
  [OUTCOME_CODES.CONTRACT_INVALID_COMMAND]: "a frozen validate command was rejected by its runner's CLI (vitest 3 rejects -q). The change may already be correct: rerun the validate with the runner's own flags (vitest: --reporter=dot) and amend the command, do not rewrite the deliverables",
86
103
  [OUTCOME_CODES.ENV_TOOL_MISSING]: "a validate command could not run because the host lacks the tool or module named in the earlier run's detail; the change may already be correct. Do not edit the deliverables for it and never install anything globally: run the same check through the repo's own toolchain (its virtualenv, lockfile-pinned runner or package scripts), record that exit under the same validate id and name the command you used in your summary",
104
+ [ENV_VALIDATE_PLACEMENT]: "an earlier run in a remote sandbox saw a frozen validate command fail; this host is a different environment (Docker, browsers, network, repo-local services). Rerun the frozen command unchanged here and record its real exit under the same validate id; change the deliverables only if it fails here too, and never substitute or narrow it for an environment gap",
87
105
  [ENV_VALIDATE_TIMEOUT]: "a validate command timed out (exit 124) on the engine's rerun, even after one longer retry: host load, not a failed check; the change may already be correct. Do not edit the deliverables for it: run the same command narrowed to the changed files (or through the repo's own cached toolchain) with a longer timeout, record that exit under the same validate id and name the command in your summary",
88
106
  [OUTCOME_CODES.ENV_CAPABILITY_REMOTE]: "the earlier run ran in a remote sandbox that lacks a host-only capability (SOPS/age key, ops credentials, read-only prod monitor SSH); this host has it. Do the work that needed it now, with the host's own tools and credentials, and never print or commit a secret in the clear",
89
107
  [OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED]: "an earlier run's conformance check found a requirement or validate command not done after one builder resume; the branch holds its work. For each named gap deliver the requirement against the frozen contract, adding any file it needs as an `add-deliverable` amendment, and re-run the validate commands",
90
108
  [OUTCOME_CODES.CONFORMANCE_OMISSION]: "an earlier run's review found a requirement the change left out or narrowed after one builder resume; the branch holds its work. For each named gap either deliver the requirement (adding any needed file as an `add-deliverable` amendment) or, when the clause is optional, unquantified or outside the issue's acceptance criteria, record an `add-requirement` / `defer` amendment with a why so the engine files a tracked follow-up instead of stopping",
91
- [OUTCOME_CODES.CONFORMANCE_UNJUSTIFIED_DEFERRAL]: "an earlier run deferred a requirement without a sufficient why after one builder resume; the branch holds its work. For each named gap either deliver the requirement (adding any needed file as an `add-deliverable` amendment) or, when the clause is optional, unquantified or outside the issue's acceptance criteria, record a `defer` amendment with a concrete why so the engine files a tracked follow-up instead of stopping",
109
+ [OUTCOME_CODES.CONFORMANCE_UNJUSTIFIED_DEFERRAL]: "an earlier run deferred a requirement without a sufficient why after one builder resume; the branch holds its work. An in-lane engineering deferral (bucket new-issue or none) must be delivered, never deferred (#5207). For each other named gap either deliver the requirement (adding any needed file as an `add-deliverable` amendment) or, when the clause is optional, unquantified or outside the issue's acceptance criteria, record a `defer` amendment with a concrete why so the engine files a tracked follow-up instead of stopping",
92
110
  [OUTCOME_CODES.ENV_REPRO_UNRUNNABLE]: "the repro harness could not run the contract's repro_test on head (timeout, missing runner or dependencies); the change may already be correct. Do not edit the deliverables or stub dependencies for it and never install anything globally: run the repro command through the repo's own toolchain and installed dependencies, and when it cannot run in this checkout, fix the repro_test command (not the code) so it does",
93
111
  });
94
112
  /** #5168: retry-in for a `backend.auth` deferral; the batch holds the account for it (an operator `--set-env` fix runs under a new identity). */
@@ -102,7 +120,7 @@ export const CONFORMANCE_MODES = Object.freeze(["shadow", "enforce"]);
102
120
  * In shadow mode only what the previous two-question reviewer blocked on still blocks: a requirement not done, a regression
103
121
  * (precheck form: SHADOW_PRE_BLOCKS). A review without usable rows never merges either.
104
122
  */
105
- const SHADOW_BLOCKS = [OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, OUTCOME_CODES.CONFORMANCE_REGRESSION];
123
+ const SHADOW_BLOCKS = [OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, OUTCOME_CODES.CONFORMANCE_REGRESSION, OUTCOME_CODES.CONFORMANCE_UNJUSTIFIED_DEFERRAL]; // #5207: an engineering deferral is undelivered work
106
124
  /**
107
125
  * Precheck failures that block in shadow mode too (#4160): every precheck or amendment failure coded
108
126
  * conformance.unimplemented (a validate command that failed or has no recorded result, a deliver requirement reported as
@@ -164,6 +182,10 @@ export function classifyBlock(result, issue) {
164
182
  ...(Array.isArray(x.files) ? { files: [...new Set(x.files.filter((f) => typeof f === "string").map((f) => f.trim().replace(/^\.?\/+/, "")).filter(Boolean))] } : {}) }));
165
183
  return { kind: "split", rationale: gate.rationale, subissues, serialized: serializeShared(subissues) };
166
184
  }
185
+ if (b.kind === "design-invalidated") { // #5342
186
+ const inv = normaliseInvalidation(b, issue);
187
+ return inv ? { kind: "design-invalidated", ...inv } : { kind: "untyped", problem: "the design-invalidated block names no decision or no why" };
188
+ }
167
189
  if (b.kind === "human") {
168
190
  const remainder = (Array.isArray(b.remainder) ? b.remainder : []).filter((x) => x && typeof x.title === "string" && x.title.trim() && typeof x.body === "string").slice(0, MAX_SUBISSUES).map((x) => ({ title: x.title.trim(), body: x.body })); // #4730
169
191
  if (b.why === "product-decision" && describesUnrunnableCommand(`${result?.summary ?? ""} ${b.reason ?? ""} ${b.detail ?? ""}`)) { // #4857
@@ -184,6 +206,13 @@ export function isProtectedLaneBranch(b, { issue, lane = null, branches = {}, de
184
206
  return ["main", "master", "staging", lane, branches?.default, branches?.staging].includes(b) || /^milestone\//.test(b) || isDefaultLane(b, defaults);
185
207
  }
186
208
 
209
+ /** #5205: cap on `cs-cred claude --limited` relaunches of one phase in a sandbox. */
210
+ export const SANDBOX_CRED_RETRIES = 8;
211
+ const defaultCredExec = (args) => {
212
+ const r = spawnSync("cs-cred", args, { encoding: "utf8", timeout: 30000, windowsHide: true, stdio: ["ignore", "ignore", "pipe"] });
213
+ return { status: r.error ? null : r.status, stderr: String(r.stderr ?? "") };
214
+ };
215
+
187
216
  /**
188
217
  * @param {object} o
189
218
  * @param {number} o.issue
@@ -232,10 +261,19 @@ export function isProtectedLaneBranch(b, { issue, lane = null, branches = {}, de
232
261
  * (default true) is false when the runner may launch another attempt: the lane then never relabels (#4302)
233
262
  */
234
263
  export async function runCore(o) {
264
+ const armed = applyArmOverrides(o, o.issue); o = armed.options; // #5206: the arm's overrides shape the lane before any config is parsed
235
265
  const { issue, repo, lane: requestedLane = null, laneOverride = false, branches = {}, cwd, dir, io, builderModel = null, reviewerModel = DEFAULT_REVIEWER_MODEL, fixModel = null,
236
- toolchainOverride = null, testRunners = null, coupledFiles = null, validateRecipes = null, routeReachability = null, envSetup = null, ciMaxMinutes = 360, conformance = "shadow", conformanceKinds = null, conformanceMutation = "off", reviewIncomplete = "needs-human", reproTest = "prefer", closeParent = false, mergeWait = "required", maxSessionLimitPauses = DEFAULT_MAX_SESSION_LIMIT_PAUSES, cliIdleMinutes = 15, cliMaxMinutes = 180, cliBusyMinutes = 45, contextCeilingTokens = 120000, turnBudgets = null, laneLimits = null, maxMergeRetries = 5, sessionLimitMaxWaitMs = DEFAULT_SESSION_LIMIT_WAIT_MS, onProgress = () => {}, emitTelemetry = null, random = Math.random } = o;
266
+ toolchainOverride = null, testRunners = null, coupledFiles = null, validateRecipes = null, routeReachability = null, prodParity = null, envSetup = null, ciMaxMinutes = 360, conformance = "shadow", conformanceKinds = null, conformanceMutation = "off", reviewIncomplete = "needs-human", reproTest = "prefer", closeParent = false, mergeWait = "required", maxSessionLimitPauses = DEFAULT_MAX_SESSION_LIMIT_PAUSES, cliIdleMinutes = 15, cliMaxMinutes = 180, cliBusyMinutes = 45, contextCeilingTokens = 120000, contextCeilingBySize = null, turnBudgets = null, laneLimits = null, maxMergeRetries = 5, sessionLimitMaxWaitMs = DEFAULT_SESSION_LIMIT_WAIT_MS, onProgress = () => {}, emitTelemetry = null, random = Math.random } = o;
237
267
  const now = io.now ?? (() => Date.now());
238
268
  const rotator = io.rotator !== undefined ? io.rotator : openRotator({ kind: o.accountRotator }); // #5094
269
+ // #5205: a rotator with pick() relaunches a limited phase pinned to another account; lane-level rotations and limited accounts
270
+ const smartRotator = Boolean(rotator) && typeof rotator.pick === "function";
271
+ let laneRotations = 0;
272
+ const laneLimited = new Map(); // account -> until epoch ms
273
+ const rotationFacts = () => ({ rotations: laneRotations, limited: [...laneLimited].map(([account, until]) => ({ account, until })) });
274
+ // #5205: in a sandbox (CS_CRED_BASE) a usage limit is reported with `cs-cred claude --limited`, which hands the next login
275
+ const sandboxCred = Boolean((io.env ?? process.env).CS_CRED_BASE);
276
+ const credExec = io.credExec ?? defaultCredExec;
239
277
  const vcfg = { ...parseVerify({}), ...(o.verify ?? {}) };
240
278
  const learnedCommands = (Array.isArray(o.precheck?.commands) ? o.precheck.commands : []).map((c) => String(c ?? "").trim()).filter(Boolean);
241
279
  if (!VERIFY_MODES.includes(vcfg.mode)) vcfg.mode = "local";
@@ -261,7 +299,7 @@ export async function runCore(o) {
261
299
  let sessionId = null;
262
300
 
263
301
  const ev = (e) => appendEvent(dir, issue, e, { repo }); // #4432: the run log is keyed by repo + issue
264
- const expTag = o.experiment ? { experiment: o.experiment.id, arm: assignArm(o.experiment, issue) } : {}; // #4629: same arm for the whole run
302
+ const expTag = armed.tag; // #4629: same arm for the whole run; #5206: plus the applied overrides
265
303
  const emit = async (rec) => { try { await emitTelemetry?.({ ...rec, issue }); } catch { /* never fails a run */ } };
266
304
  let ghCache = null; // #4507: the run's own gh HTTP cache (set once the run tmp dir exists)
267
305
  const authState = { refreshed: false }; // #4662: one token refresh at a time, shared by every gh call of the run
@@ -272,15 +310,19 @@ export async function runCore(o) {
272
310
  const git = (args, o = {}) => io.git(args, { cwd: wt, ...o });
273
311
 
274
312
  const builderTriggers = []; // #4362: implement-attempt triggers in order, for the lane's first-pass flag
313
+ let usageUnknown = false, inflight = null; // #5334: a killed session streamed nothing; the builder call in flight (flushed when a signal ends the run)
275
314
  const impl = { cost: 0, models: new Set() }; // #4397: implement spend and reported models, for the verifier
276
315
  // #4392: implement turn budget for the lane's size, and its turn tally; off unless given (the CLI passes readCoreLimits' defaults)
277
316
  const tb = makeTurnBudget(turnBudgets ?? { S: 0, M: 0, L: 0 });
278
317
  /** `trigger` (#4362): why the attempt ran, one of fixround.mjs TRIGGERS; `resume` (#4407): the session it resumed. */
279
318
  async function attempt(phase, n, r, mode = null, trigger = null, restartOf = null, resume = null) {
280
- const c = sessionCostDelta(sessionCosts, { resume, sessionId: r?.sessionId ?? null, cost: num(r?.costUsd) });
319
+ const killed = r?.killed === true; // #5334: a session cut off before its result line: cost estimated from the streamed tokens, unknown when none streamed
320
+ const est = killed && num(r?.costUsd) == null ? estimateCostUsd(r?.usage, r?.model) : null;
321
+ const c = sessionCostDelta(sessionCosts, { resume, sessionId: r?.sessionId ?? null, cost: est ?? num(r?.costUsd) });
322
+ if (killed && !r?.usage) usageUnknown = true;
281
323
  const rec = { event: "PHASE_ATTEMPT_USAGE", phase, attempt: n, trigger, ...(restartOf ? { restart_of: restartOf } : {}), usage: r?.usage ?? null, duration_ms: num(r?.durationMs) ?? 0,
282
- cost_usd: num(r?.costUsd), cost_usd_delta: c.delta, cost_usd_session: c.session, model: r?.model ?? null, turns: num(r?.turns), ...(mode ? { mode } : {}),
283
- ...(num(r?.baselineTokens) != null ? { baseline_tokens: num(r.baselineTokens) } : {}), ...(r?.tools ? { tools: r.tools } : {}), lane_profile: laneProfile.name, ...expTag }; // #4410, #4629
324
+ 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 } : {}),
325
+ ...(num(r?.baselineTokens) != null ? { baseline_tokens: num(r.baselineTokens) } : {}), ...(r?.tools ? { tools: r.tools } : {}), lane_profile: r?.laneProfile ?? laneProfile.name, ...expTag }; // #4410, #4629
284
326
  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"); }
285
327
  ev(rec); await emit(rec);
286
328
  modelMs += rec.duration_ms; // #4451: model time next to the lane's wall time
@@ -330,7 +372,14 @@ export async function runCore(o) {
330
372
  const failureClasses = new Set(); // forge#4275: conformance failure codes seen this run (gate failures, shadow would-fail)
331
373
  const ctxBase = parseContextPackConfig(o.contextPack ?? {});
332
374
  const ctxArm = contextArm({ mode: ctxBase.mode, repo, issue }); // #4444: ab picks a stable on|shadow arm per issue
333
- const ctxCfg = { ...ctxBase, mode: ctxArm.mode };
375
+ let ctxCfg = { ...ctxBase, mode: ctxArm.mode }; // #5340: re-resolved once the issue is read (milestone/parent default)
376
+ let surfaceClaim = null; // #5340: the shared-surface slots held from contract freeze to teardown
377
+ const claimSurfaceSlots = async (frozen) => { // every path that settles `frozen` (light, fresh, recovered) calls this once; idempotent
378
+ const surfaces = parseSharedSurfaces(o.sharedSurfaces);
379
+ if (!surfaces.length || !io.sequenceLease || surfaceClaim || !frozen) return;
380
+ surfaceClaim = await claimSurfaces({ lease: io.sequenceLease, repo, issue, surfaces, paths: (frozen.deliverables ?? []).map((d) => d.path), maxWaitS: ciMaxMinutes * 60 }).catch(() => null);
381
+ if (surfaceClaim?.names.length) T.decisions.push(surfaceClaim.timedOut ? `Shared surface slot ${surfaceClaim.names.join(", ")} timed out (fail-open)` : `Shared surface slot held: ${surfaceClaim.names.join(", ")} (waited ${Math.round(surfaceClaim.waitMs / 1000)}s)`);
382
+ };
334
383
  const ctxAb = ctxArm.ab ? { context_ab: true } : {};
335
384
  if (ctxArm.ab) T.decisions.push(`Context pack A/B (#4444): arm ${ctxArm.mode}`);
336
385
  const exploreCfg = parseExploreConfig(o.explore ?? {}); // #4391
@@ -339,9 +388,11 @@ export async function runCore(o) {
339
388
  let pitMatched = null; // #4375: pitfalls in the pack that match the issue's files; null when no pack was compiled
340
389
  let factsSeen = []; // #4401: trusted comment bodies on the issue, so an identical FORGE:FACTS is never posted twice
341
390
  let guardAddedMs = 0; // #4705 (R12): wall time the guard gate added, summed over the lane, carried on RUN_TERMINAL
391
+ let verifiedLane = null; // #5339: true when the lane merged with no transferred or unverified requirement (carried on RUN_TERMINAL)
342
392
  let shadowWould = null; // forge#4165: the shadow gate's verdict, carried on RUN_TERMINAL (no telemetry write of its own)
343
393
  const kinds = normalizeKindModes(conformanceKinds); // engine.conformance_kinds: a failure code's own mode
344
394
  let domains = [], domainsLogged = null; // #5099: review domains the diff touches (review-roster.sh path triggers)
395
+ let firstReview = null; // #5345: the first gate judgement and review.incomplete of the first reply, on RUN_TERMINAL
345
396
  let riskEnforced = null, gateRan = false; // #4398: declared risk paths that made a shadow lane enforce (sticky); the gate ran
346
397
  let done = null, finishing = null, wtCreated = false, salvagedRef = null;
347
398
  let light = false, modelMs = 0; // #4451: the light lane finished without an upgrade (the same structure/hotspot gates as the full lane, #4502); summed session time
@@ -357,14 +408,15 @@ export async function runCore(o) {
357
408
  // the runner PATH; `waits` ({phase: ms}) and `heavyQueueMax` ride on the lane result for the batch report.
358
409
  const heavyCfg = o.heavy ?? {}, heavyOn = Boolean(io.heavy) && heavyCfg.enabled !== false;
359
410
  let heavyEnv = null, heavyWaitsFile = null, heavyQueueMax = 0, stage = "plan", iss;
411
+ let seqBuildNote = ""; // #5235: numbers reserved for this lane at build start (prompt paragraph)
360
412
  let seqLease = null; // #4386: the host sequence lease, held from the merge-gate renumber through the merge
361
413
  const waits = {};
362
414
  const followupsFiled = []; // #5078: {issue, class, count} per tracking issue this lane filed into, for the batch report
363
415
  const pendingFollowups = []; // #5141: {req, why} whose filing kept failing in-lane; filed after the merge, else recorded
364
416
  const pendingRecord = () => pendingFollowups.filter((p) => !p.req.tracked).map((p) => ({ id: p.req.id, quote: String(p.req.quote ?? ""), disposition: p.req.disposition, why: p.why, marker: `FORGE:DEFERRED_FROM: #${issue}` }));
365
417
  let precheckMs = 0, precheckDeferred = 0, precheckRan = false; // #4331: pre-PR check wall time and deferrals, for the batch report
366
- const addWait = (phase, ms, queued = 0) => {
367
- if (Number.isFinite(ms) && ms > 0) waits[phase] = (waits[phase] ?? 0) + ms;
418
+ const addWait = (phase, ms, queued = 0, cause = "heavy_queue") => {
419
+ if (Number.isFinite(ms) && ms > 0) { waits[phase] = (waits[phase] ?? 0) + ms; phaseLedger.addWait(phase, cause, ms); } // #5349: by cause into the phase ledger
368
420
  if (Number.isInteger(queued)) heavyQueueMax = Math.max(heavyQueueMax, queued);
369
421
  };
370
422
  const lanePriority = () => priorityFromLabels(iss?.labels);
@@ -380,9 +432,12 @@ export async function runCore(o) {
380
432
  const protectedBranch = (b) => isProtectedLaneBranch(b, { issue, lane, branches, defaults });
381
433
  /** Teardown from the ledger (#4179), on every exit path: builder pids, checkpoint of unpushed work, run tmp, worktree, branch, docker. */
382
434
  async function teardown(reason, extra) {
435
+ const builderPids = (ledger ? ledger.entries("pid") : []).map((p) => Number(p.value));
383
436
  for (const p of ledger ? ledger.entries("pid") : []) {
384
437
  try { if (await io.killGroup?.(p.value, p.marker)) ledgerDo((l) => l.release("pid", p.value)); } catch { /* keep it listed */ }
385
438
  }
439
+ // #5333: the worktree goes only after the builder processes exited (SIGTERM, then SIGKILL after a grace period).
440
+ const stillRunning = io.proc?.alive && builderPids.length ? await waitPidsExit(builderPids, { alive: io.proc.alive, kill: io.proc.kill, sleep }).catch(() => []) : [];
386
441
  // Never discard work silently: an unmerged lane commits and pushes what is left before its worktree goes.
387
442
  const saved = !wtCreated || reason === "merged" || (await checkpoint(`exit (${reason})`));
388
443
  await reportLaneHead(reason);
@@ -391,7 +446,7 @@ export async function runCore(o) {
391
446
  try { if ((await io.runTmp.remove(runTmp)) !== false) ledgerDo((l) => l.release("tmp", runTmp)); } catch { /* best effort */ }
392
447
  runTmp = null;
393
448
  } // every terminal, including engine-error and deferred
394
- if (wtCreated && saved) {
449
+ if (wtCreated && saved && !stillRunning.length) {
395
450
  let removed = false;
396
451
  try { await io.git(["worktree", "remove", "--force", wt], { cwd }); removed = true; } catch { /* best effort */ }
397
452
  try { await io.git(["worktree", "prune"], { cwd }); } catch { /* best effort */ }
@@ -402,7 +457,7 @@ export async function runCore(o) {
402
457
  }
403
458
  if (branchDone) ledgerDo((l) => l.release("branch", branch));
404
459
  } else if (wtCreated) {
405
- ev({ event: "TEARDOWN_KEPT", reason: "checkpoint failed: worktree and branch kept so no work is lost", worktree: wt });
460
+ ev({ event: "TEARDOWN_KEPT", reason: stillRunning.length ? `builder process ${stillRunning.join(",")} still running: worktree and branch kept` : "checkpoint failed: worktree and branch kept so no work is lost", worktree: wt });
406
461
  }
407
462
  for (const kind of ["container", "volume"]) {
408
463
  for (const r of ledger ? ledger.entries(kind) : []) {
@@ -453,23 +508,28 @@ export async function runCore(o) {
453
508
  }
454
509
  function finish(...args) {
455
510
  if (done) return Promise.resolve(done);
511
+ if (laneRotations || laneLimited.size) args[2] = { ...(args[2] ?? {}), ...rotationFacts() }; // #5205: rotations + limited accounts ride on the lane result
456
512
  finishing ??= finishOnce(...args); // a signal during a normal finish waits for the same teardown
457
513
  return finishing;
458
514
  }
459
515
  async function finishOnce(reason, detail = "", extra = {}, codeOverride = null) {
516
+ await flushInflight(); // #5334: a signal mid-attempt: the session's usage so far is recorded before RUN_TERMINAL
460
517
  try { seqLease?.release(); } catch { /* fail-open */ }
461
518
  seqLease = null;
519
+ try { surfaceClaim?.release(); } catch { /* fail-open */ }
520
+ surfaceClaim = null;
521
+ try { await io.sequenceLease?.undeclare?.({ repo, issue }); } catch { /* fail-open (#5340) */ }
462
522
  try { await io.sequenceLease?.unreserve?.({ repo, lane, issue }); } catch { /* fail-open (#4526) */ }
463
523
  if (heavyWaitsFile) { // #4169: builder-run heavy waits, read before teardown removes the run TMPDIR
464
- try { heavyQueueMax = Math.max(heavyQueueMax, sumWaits(await io.fs.read(heavyWaitsFile), waits).queueMax); } catch { /* no heavy step ran */ }
524
+ try { const sw = sumWaits(await io.fs.read(heavyWaitsFile)); heavyQueueMax = Math.max(heavyQueueMax, sw.queueMax); for (const [ph, ms] of Object.entries(sw.waits)) addWait(ph, ms); } catch { /* no heavy step ran */ }
465
525
  }
466
526
  await postLaneFacts(); // #4401: before teardown removes the worktree's result.json
467
527
  await teardown(reason, extra); // first: unpushed work is pushed while this run still holds the lease
468
528
  const code = codeOverride ?? codeForTerminalReason(reason);
469
529
  // forge#4165: pr, milestone and the conformance verdict ride on the existing RUN_TERMINAL write (verdict-mix queries).
470
- const term = { event: "RUN_TERMINAL", reason, code, ...(extra.pr ? { pr: extra.pr } : {}), ...(milestone ? { milestone } : {}),
471
- conformance_mode: conformance === "enforce" || riskEnforced ? "enforce" : "shadow", ...(shadowWould ? { shadow_would: shadowWould } : {}),
472
- ...(laneHead && reason !== "merged" ? { lane_branch: laneHead.pushedTo ?? "unpushed", lane_sha: laneHead.sha } : {}), context_pack: ctxCfg.mode, ...ctxAb, ...expTag, explore: exploreCfg.mode, wall_ms: now() - t0, ...(guardAddedMs ? { guard_added_ms: guardAddedMs } : {}), model_ms: modelMs, light, ...(ctxLane ? { lane_type: ctxLane } : {}), ...(pitMatched != null ? { pitfalls_matched: pitMatched } : {}), ...(tb.record() ? { turns: tb.record() } : {}),
530
+ const term = { event: "RUN_TERMINAL", reason, code, ...(extra.pr ? { pr: extra.pr } : {}), ...(milestone ? { milestone } : {}), ...(verifiedLane != null ? { verified: verifiedLane } : {}),
531
+ conformance_mode: conformance === "enforce" || riskEnforced ? "enforce" : "shadow", ...(shadowWould ? { shadow_would: shadowWould } : {}), ...(firstReview ? { first_review: firstReview } : {}),
532
+ ...(laneHead && reason !== "merged" ? { lane_branch: laneHead.pushedTo ?? "unpushed", lane_sha: laneHead.sha } : {}), context_pack: ctxCfg.mode, ...ctxAb, ...expTag, explore: exploreCfg.mode, wall_ms: now() - t0, ...(guardAddedMs ? { guard_added_ms: guardAddedMs } : {}), model_ms: modelMs, ...(usageUnknown ? { usage_unknown: true } : {}), light, ...(ctxLane ? { lane_type: ctxLane } : {}), ...(pitMatched != null ? { pitfalls_matched: pitMatched } : {}), ...(tb.record() ? { turns: tb.record() } : {}),
473
533
  ...(route ? { builder_tier: route.tier, builder_class: route.class, builder_escalated: escalated, builder_model: route.model ?? "default" } : {}) }; // forge#4275: the on/off A/B groups runs by these; #4394: per-tier stats
474
534
  const phases = phaseLedger.snapshot(); // #4908: run log gets the nested ledger, FORGE:TELEMETRY the flattened scalars
475
535
  ev({ ...term, phases });
@@ -510,7 +570,7 @@ export async function runCore(o) {
510
570
  if (!base) return;
511
571
  try {
512
572
  const result = await readResult();
513
- const rec = result ? normaliseFacts(result, { files: await stageFiles(), contract: await readContract() }) : null;
573
+ const rec = result ? normaliseFacts(result, { files: await stageFiles(), contract: await readContract(), head: String(await git(["rev-parse", "HEAD"]).catch(() => "")).trim() }) : null;
514
574
  if (!rec) return;
515
575
  const body = renderFactsRecord(rec);
516
576
  if (factsSeen.some((b) => String(b ?? "").includes(body))) return;
@@ -565,7 +625,25 @@ export async function runCore(o) {
565
625
  { key: "implementation", file: IMPLEMENTATION_FILE, marker: ["FORGE:IMPLEMENTATION"], render: (md, ctx) => renderImplementation(md, ctx.result, { branch, files: ctx.files }) },
566
626
  ];
567
627
  const posted = {}; // key -> comment url (or "" when posted without a link)
568
- const readStage = async (st) => { try { return await io.fs.read(`${wt}/${st.file}`); } catch { return null; } };
628
+ let stampHash = null; // #5333: the frozen contract hash the stage notes are stamped with (set before the implement call)
629
+ const stageBad = {}; // key -> true while the stage file on disk carries another issue's or contract's stamp
630
+ const readStage = async (st) => {
631
+ let md = null;
632
+ try { md = await io.fs.read(`${wt}/${st.file}`); } catch { return null; }
633
+ const c = checkStamp(md, { issue, hash: st.key === "implementation" ? stampHash : null });
634
+ if (c.ok) { delete stageBad[st.key]; return c.md; }
635
+ if (!stageBad[st.key]) { ev({ event: "STAGE_STAMP_MISMATCH", file: st.file, reason: c.reason }); T.anomalies.push(`${st.file} not posted: ${c.reason} (another lane's file, e.g. a git stash pop)`); }
636
+ stageBad[st.key] = true;
637
+ return null;
638
+ };
639
+ /** #5333: after the builder's final turn, a note posted live whose file now carries a foreign stamp is re-rendered from result.json. */
640
+ async function recheckStages(keys) {
641
+ for (const key of keys) {
642
+ if (!(key in posted)) continue;
643
+ await readStage(STAGES.find((x) => x.key === key));
644
+ if (stageBad[key]) await upsertStage(key);
645
+ }
646
+ }
569
647
  const usableMd = (md) => sanitizeMd(md).replace(/\s+/g, " ").length >= 20;
570
648
  const stageFiles = async () => {
571
649
  const out = String(await git(["diff", "--name-only", `${base}...HEAD`]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean);
@@ -636,33 +714,63 @@ export async function runCore(o) {
636
714
  let deps = {};
637
715
  try { deps = io.deps?.env?.() ?? {}; } catch { deps = {}; }
638
716
  const par = verifyParallelism();
639
- return { ...deps, ...(runTmp ? { TMPDIR: runTmp } : {}), ...(par ? { FORGE_HOST_PARALLELISM: par } : {}), ...(toolchain?.env ?? {}) };
717
+ return { ...deps, ...(runTmp ? { TMPDIR: runTmp } : {}), ...(par ? { FORGE_HOST_PARALLELISM: par } : {}), FORGE_LANE_WORKTREE: "1", ...(toolchain?.env ?? {}) }; // #5333: the hook denies git stash where this is set
640
718
  }
641
719
  /** #5168: a failed claude login ends the lane `deferred` `backend.auth`, held per account by the batch (never the relaunch or the breaker). */
642
720
  const authDeferral = (e) => Object.assign(e, { deferCode: OUTCOME_CODES.BACKEND_AUTH, retryInSeconds: AUTH_RETRY_SECONDS, backendId: laneBackendId(process.env, rotator),
643
721
  deferDetail: `claude CLI authentication failed (login expired or invalid); held until the login is fixed: ${String(e?.message ?? e).split("\n")[0].slice(0, 300)}` });
722
+ /** #5236: no account has room: the lane ends deferred `quota.exhausted` (earliest reset) and emits QUOTA_EXHAUSTED, never a spawn or a far pause. */
723
+ const exhaustedStop = (e, x, role) => { ev({ event: "QUOTA_EXHAUSTED", phase: role, earliestReset: x.earliestReset }); return exhaustedDeferral(e, { earliestReset: x.earliestReset, backendId: laneBackendId(process.env, rotator), now: now() }); };
644
724
  /** Runner call with the per-run TMPDIR and FORGE_HOST_PARALLELISM; a usage limit pauses and resumes the same step, or defers past the cap (#4101). */
645
725
  async function callRunner(args) {
646
- let pauses = 0, rotations = 0;
726
+ let pauses = 0, rotations = 0, pinned = null, credTries = 0;
647
727
  for (;;) {
728
+ if (smartRotator && !pinned) { const x = poolExhausted(rotator, laneLimited); if (x) throw exhaustedStop(new Error("no account has capacity"), x, args.role); } // #5236: the shim would fall back to the default profile
648
729
  // #4181: every Docker resource the builder creates carries the lane's ownership labels (same batch/lane as the ledger).
649
730
  const labels = dockerLabels({ batch: o.batchId ?? "adhoc", lane: `lean-${issue}`, issue, expires: now() + LEDGER_TTL_MS }).join(" ");
650
731
  // #4169: heavy shims first on PATH; the phase/issue/priority label each heavy step's slot and wait record.
651
732
  const heavy = heavyEnv ? { ...heavyEnv, FORGE_LANE_PHASE: args.role === "builder" ? stage : String(args.role ?? "step"), FORGE_LANE_ISSUE: String(issue), FORGE_LANE_PRIORITY: String(lanePriority()) } : {};
652
- const lp = laneProfile.name, profEnv = lp === "full" ? {} : { CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1", ...(lp === "lane" ? { CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1" } : {}) };
733
+ const lp = args.profile === "narrow" && laneProfile.name !== "full" ? "narrow" : laneProfile.name, profEnv = lp === "full" ? {} : { CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1", ...(lp === "lane" || lp === "narrow" ? { CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1" } : {}) };
653
734
  const system = lp === "lane" && !args.resume && !args.noTools ? [args.system, laneProfile.text].filter(Boolean).join("\n\n") : args.system;
654
- try { return await io.runner({ ...args, system, env: { ...laneEnv(), FORGE_DOCKER_LABELS: labels, ...(runTmp ? { CLAUDE_CODE_TMPDIR: runTmp } : {}), ...(toolchain?.env ?? {}), ...heavy, ...profEnv } }); }
735
+ // #5205: capture the account the run uses (the shim exports it, then execs claude) and pin a rotation relaunch.
736
+ let account = pinned?.account ?? null;
737
+ let watch = null; // #5268: the shim execs claude (same pid) after spawn, so keep reading until the account shows
738
+ const spawnHook = smartRotator ? { onSpawn: (child, ...rest) => { if (account === null && !watch) { const pid = child?.pid ?? child; watch = watchAccount(() => rotator.accountOfPid(pid), { onFound: (a) => { account = a; } }); } return args.onSpawn?.(child, ...rest); } } : {};
739
+ const pin = pinned ? { ...(pinned.bin ? { bin: pinned.bin } : {}) } : {};
740
+ try { const res = await io.runner({ ...args, ...spawnHook, ...pin, system, env: { ...laneEnv(), FORGE_DOCKER_LABELS: labels, ...(runTmp ? { CLAUDE_CODE_TMPDIR: runTmp } : {}), ...(toolchain?.env ?? {}), ...heavy, ...profEnv, ...(pinned?.env ?? {}) } }); watch?.stop(); return res; }
655
741
  catch (e) {
656
- const epoch = Number.isFinite(e?.resetAtEpochMs) ? e.resetAtEpochMs : null;
657
- if (e?.authFailure === true && e.usageLimit !== true && epoch === null) throw authDeferral(e); // #5168: an account condition, never engine-error
742
+ watch?.stop(); watch?.refresh(); // #5268: the account the shim exec'd, read before the limited child is gone or now
743
+ let epoch = Number.isFinite(e?.resetAtEpochMs) ? e.resetAtEpochMs : null;
744
+ if (e?.authFailure === true && e.usageLimit !== true && epoch === null) { const x = smartRotator ? poolExhausted(rotator, laneLimited) : null; throw x ? exhaustedStop(e, x, args.role) : authDeferral(e); } // #5236: an auth failure with no account room is exhaustion // #5168: an account condition, never engine-error
658
745
  if (!(e?.usageLimit === true || epoch !== null)) throw e;
659
- if (rotatorRetry(rotator, rotations)) { rotations++; ev({ event: "PHASE_ACCOUNT_ROTATED", phase: args.role }); continue; } // #5094: same args (resume too), next account
746
+ if (smartRotator) { // #5205: exclude the limited account and relaunch the same args (resume kept) pinned to another, at once
747
+ if (account !== null) { const until = epoch !== null && epoch > now() ? epoch : now() + DEFAULT_SESSION_LIMIT_WAIT_MS; laneLimited.set(account, until); try { rotator.markLimited(account, until); } catch { /* best effort */ } }
748
+ let next = null;
749
+ try { next = rotator.pick({ exclude: laneLimited }); } catch { next = null; }
750
+ let size = 0; try { size = rotator.accounts.length; } catch { size = 0; }
751
+ if (Number.isInteger(next?.account) && rotations < size) {
752
+ rotations++; laneRotations++;
753
+ ev({ event: "PHASE_ACCOUNT_ROTATED", phase: args.role, from: account, to: next.account });
754
+ pinned = { account: next.account, bin: rotator.realClaude() ?? null, env: { CLAUDE_CONFIG_DIR: rotator.configDir(next.account) } };
755
+ continue;
756
+ }
757
+ if (next && next.account === null) throw exhaustedStop(e, { earliestReset: Number.isFinite(next.earliestReset) ? next.earliestReset : null }, args.role); // #5236
758
+ } else if (rotatorRetry(rotator, rotations)) { rotations++; laneRotations++; ev({ event: "PHASE_ACCOUNT_ROTATED", phase: args.role }); continue; } // #5094: same args (resume too), next account
759
+ else if (!rotator && sandboxCred && credTries < SANDBOX_CRED_RETRIES) { // #5205: a sandbox reports the limit; the router hands another login
760
+ credTries++;
761
+ let ok = false;
762
+ try { ok = (await credExec(["claude", "--limited", epoch !== null ? String(Math.round(epoch / 1000)) : "unknown"]))?.status === 0; } catch { ok = false; }
763
+ if (ok) { laneRotations++; ev({ event: "PHASE_ACCOUNT_ROTATED", phase: args.role, via: "cs-cred" }); continue; }
764
+ credTries = SANDBOX_CRED_RETRIES; // the router has no login with room (429): the existing defer
765
+ }
660
766
  const waitMs = epoch !== null && epoch > now() ? epoch - now() : DEFAULT_SESSION_LIMIT_WAIT_MS;
661
767
  if (pauses >= maxSessionLimitPauses || waitMs > sessionLimitMaxWaitMs) { e.deferUsageLimit = true; throw e; }
662
- pauses++;
768
+ pauses++; pinned = null; // after the wait the shim picks again
663
769
  ev({ event: "PHASE_RATE_LIMITED", phase: args.role, resetAt: epoch, resetAtDisplay: e.resetAt ?? null, waitMs });
664
770
  onProgress({ event: "phase_paused", phase: args.role, reason: "session-limit", detail: `session limit hit; pausing until ${e.resetAt || new Date(now() + waitMs).toISOString()}` });
771
+ const limitedAt = now();
665
772
  await sleep(waitMs);
773
+ phaseLedger.addWait(args.role === "review" ? "review" : stage, "rate_limit", now() - limitedAt); // #5349
666
774
  }
667
775
  }
668
776
  }
@@ -675,8 +783,18 @@ export async function runCore(o) {
675
783
  if (r.rewritten) { T.decisions.push(`Rewrote ${r.rewritten} unpushed commit(s) with the lane identity and a sign-off (placeholder author or no Signed-off-by, #4651)`); ev({ event: "DCO_SIGNOFF_REWRITE", count: r.rewritten, ...(r.dirty ? { dirty: r.dirty } : {}) }); }
676
784
  } catch (e) { throw Object.assign(e, e?.noIdentity === true ? { laneCode: OUTCOME_CODES.CI_DCO } : { engineCode: OUTCOME_CODES.ENGINE_DCO_REWRITE }); } // #4997: a failed rewrite is mechanical (engine-error, recoverable), only a missing identity is a human block
677
785
  };
786
+ /** #5202: the lane's own pushed checkpoints a fresh session amended are merged in (-s ours) so the push stays a fast-forward. */
787
+ const reconcileLaneBranch = async () => {
788
+ const r = await reconcileCheckpoints({ git, branch });
789
+ if (r.state === "reconciled") {
790
+ ev({ event: "CHECKPOINT_RECONCILED", count: r.commits.length, sha: r.sha });
791
+ T.decisions.push(`origin/${branch} held ${r.commits.length} pushed checkpoint commit(s) the lane had rewritten locally: merged in (-s ours, ${r.sha.slice(0, 10)}) so the push stays a fast-forward`);
792
+ } else if (r.state === "foreign" || r.state === "error") ev({ event: "CHECKPOINT_RECONCILE_SKIPPED", state: r.state, ...(r.commits ? { commits: r.commits.length } : {}), ...(r.error ? { error: r.error } : {}) });
793
+ return r;
794
+ };
678
795
  const gitPush = async (args) => {
679
796
  if (!args.includes("--delete")) { await untrackToolState({ git, base, ev, keep: await keepPaths() });
797
+ await reconcileLaneBranch();
680
798
  try { await signOffUnpushed(); }
681
799
  catch (e) { // #4905: a failed rewrite must not cost the lane's finished commits: push them as-is before reporting; #5047: to a salvage ref, never the lane branch (the sign-off range excludes origin/<branch>)
682
800
  if (!e?.noIdentity) { try { const sha = String(await git(["rev-parse", "HEAD"])).trim(), ref = salvageBranch(issue, sha); await git(["push", "origin", `${sha}:refs/heads/${ref}`]); laneHead = { branch, sha, pushedTo: ref }; ev({ event: "DCO_RESCUE_PUSH", branch: ref }); } catch (pe) { ev({ event: "DCO_RESCUE_PUSH_FAILED", error: String(pe?.message ?? pe).slice(0, 200) }); } }
@@ -725,7 +843,7 @@ export async function runCore(o) {
725
843
  T.anomalies.push(line);
726
844
  if (!["invalid", "needs-human", "budget-exceeded"].includes(reason)) { try { await post("FORGE:LANE_BRANCH", `## Lane branch\n${line}`); } catch { /* best effort */ } }
727
845
  }
728
- const CONTINUE_NOTE = "\n\nThe branch already holds work from an earlier session that was interrupted (see the latest `wip(forge): checkpoint` commit). Continue from it: read `git log` and `git diff origin/BASE...HEAD`, do not start over.";
846
+ const CONTINUE_NOTE = "\n\nThe branch already holds work from an earlier session that was interrupted (see the latest `wip(forge): checkpoint` commit). Continue from it: read `git log` and `git diff origin/BASE...HEAD`, do not start over. The checkpoint commit is already pushed: do not amend, reword, squash, reset or rebase existing commits; add new commits on top.";
729
847
  const recoverNote = () => (recover ? `\n\nRecovery pass (${recover.code}): ${(RECOVER_HOW[recover.code] ?? "an earlier run ended needs-human for a mechanical reason; resolve it").replaceAll("BASE", lane)}.` : "");
730
848
  const PLAN_RERUN_NOTE = "\n\nThis is a rerun: the branch already holds commits from an earlier run. Read `git log` and `git diff origin/BASE...HEAD` to see what exists, but plan against the issue itself. This step is still planning only: do not edit code, do not commit, and do not write the result file unless the issue is invalid, already fixed or blocked.";
731
849
  const SALVAGE_NOTE = "\n\nAn earlier run on this issue stopped with uncommitted work, saved at `REF` (not on the branch). Inspect it with `git diff HEAD REF --stat` and reuse what fits the contract (`git checkout REF -- <path>`) instead of rewriting it.";
@@ -748,31 +866,42 @@ export async function runCore(o) {
748
866
  try { ok = (await checkAdmission({ cfg: o.admission, host: io.host })).ok; } catch { ok = true; }
749
867
  const nowMs = Date.now();
750
868
  if (!ok && !paused && !forced && control.pause) { if (control.pause()) { paused = true; pausedAt = nowMs; ev({ event: "LANE_PAUSED", reason: "host over ceiling" }); onProgress({ event: "phase_paused", phase: "builder", reason: "host-busy", detail: "host over the admission ceiling; lane paused" }); } }
751
- else if (ok && paused) { control.resume?.(); paused = false; forced = false; addWait(stage, nowMs - pausedAt); ev({ event: "LANE_RESUMED", reason: "host recovered" }); }
869
+ else if (ok && paused) { control.resume?.(); paused = false; forced = false; addWait(stage, nowMs - pausedAt, 0, "host_load"); ev({ event: "LANE_RESUMED", reason: "host recovered" }); }
752
870
  else if (ok) forced = false;
753
- else if (paused && nowMs - pausedAt >= maxPauseMs) { control.resume?.(); paused = false; forced = true; addWait(stage, nowMs - pausedAt); ev({ event: "LANE_RESUMED", reason: "max pause reached" }); }
871
+ else if (paused && nowMs - pausedAt >= maxPauseMs) { control.resume?.(); paused = false; forced = true; addWait(stage, nowMs - pausedAt, 0, "host_load"); ev({ event: "LANE_RESUMED", reason: "max pause reached" }); }
754
872
  }
755
873
  })();
756
- return { async stop() { stopped = true; wake?.(); clearTimeout(t); await loop; if (paused) { control.resume?.(); paused = false; addWait(stage, Date.now() - pausedAt); } } };
874
+ return { async stop() { stopped = true; wake?.(); clearTimeout(t); await loop; if (paused) { control.resume?.(); paused = false; addWait(stage, Date.now() - pausedAt, 0, "host_load"); } } };
757
875
  }
758
876
 
759
877
  /** A timeout restart starts a fresh session; by default it continues the implementation against the frozen contract. */
760
878
  let facts = null; // #4272: path of an optional .forge/repo-facts.json (worktree, then main checkout), cited in builder prompts
761
- const tcOpts = () => ({ toolchain: toolchain?.summary ?? null, sparse, ...(facts ? { facts } : {}) });
879
+ const tcOpts = () => ({ toolchain: toolchain?.summary ?? null, sparse, ...(facts ? { facts } : {}), stamp: stampText({ issue, hash: stampHash }) });
762
880
  let hotFacts = null; // forge#4195: scripts/hotspots.sh facts for the files the issue names, read once before the plan call
763
881
  let enumList = []; // #4322: tests enumerating the members of the paths the issue names, read once before the plan call
764
882
  let decisionsNote = ""; // #4901: trusted FORGE:DECISION comments newer than the frozen contract, "" otherwise
883
+ let carriedPasses = []; // #5331: validate ids that passed on the resume head (resume digest); carried into the builder result while HEAD is unchanged
765
884
  let resumeNote = ""; // #4400: the resume digest of the last run (resume.mjs), "" on a first run or with context_pack off
766
- const implementRestart = () => builderImplementPrompt(vcfg.mode, tcOpts()) + hotspotBuildRule(hotFacts) + enumeratingBuildRule(enumList) + invariantsBuildRule(vcfg.invariants) + exploreBuildRule(exploreCfg) + CONTINUE_NOTE.replace("BASE", lane) + resumeNote;
885
+ const implementRestart = () => builderImplementPrompt(vcfg.mode, tcOpts()) + seqBuildNote + hotspotBuildRule(hotFacts) + enumeratingBuildRule(enumList) + invariantsBuildRule(vcfg.invariants) + exploreBuildRule(exploreCfg) + CONTINUE_NOTE.replace("BASE", lane) + resumeNote;
886
+ /** #5334: records a builder session that ended without its result line (kill, signal) as one attempt; `at` = its start. */
887
+ const killedAttempt = (n, e, opts, at) => attempt("implement", n, { killed: true, usage: e.usage ?? null, turns: e.turns ?? null, tools: toolStats(e.toolUses), costUsd: null, durationMs: now() - at, model: opts.model ?? laneModel() ?? null }, opts.mode, opts.trigger, opts.restartOf);
888
+ async function flushInflight() {
889
+ const cur = inflight;
890
+ if (!cur || cur.flushed) return;
891
+ cur.flushed = true;
892
+ let snap = null; try { snap = cur.session.snapshot?.() ?? null; } catch { snap = null; }
893
+ try { await killedAttempt(cur.n, snap ?? {}, cur.opts, cur.at); } catch { /* telemetry never blocks the teardown */ }
894
+ }
767
895
  /** #4390: builder calls stopped at the context ceiling restart fresh; planning (and its corrections) run uncapped. */
896
+ let laneCeiling = contextCeilingTokens; // #5346: set to the lane size's ceiling once the contract is frozen
768
897
  const UNCEILED = ["plan", "contract_correction", "block_correction"], CONTEXT_RESTARTS_MAX = 3;
769
898
  async function builder(n, prompt, resume, live = false, restart = implementRestart, opts = {}) {
770
899
  let timeoutRetries = 0, contextRestarts = 0, p = prompt;
771
900
  opts = { ...opts };
772
- const ceiled = contextCeilingTokens > 0 && !UNCEILED.includes(opts.trigger);
901
+ const ceiled = laneCeiling > 0 && !opts.noCeiling && !UNCEILED.includes(opts.trigger); // #5346: per-size ceiling; noCeiling = a restart is certain
773
902
  for (;;) {
774
903
  // after CONTEXT_RESTARTS_MAX restarts the call runs uncapped: a loop guard, never a refusal of work
775
- opts.contextMax = ceiled && contextRestarts < CONTEXT_RESTARTS_MAX ? contextCeilingTokens : 0;
904
+ opts.contextMax = ceiled && contextRestarts < CONTEXT_RESTARTS_MAX ? laneCeiling : 0;
776
905
  const budgeted = stage === "implement" && tb.on(); // #4392: the build and its restarts spend the implement turn budget
777
906
  if (budgeted && tb.remaining() <= 0) return await budgetWrapup(n, opts);
778
907
  opts.turnMax = budgeted ? tb.remaining() : 0;
@@ -783,13 +912,16 @@ export async function runCore(o) {
783
912
  }
784
913
  if (e?.code === "CLI_CONTEXT") {
785
914
  contextRestarts++;
786
- ev({ event: "CONTEXT_CEILING", context_tokens: e.context ?? null, ceiling: contextCeilingTokens, turns: e.turns ?? null, trigger: opts.trigger ?? null, restart: contextRestarts });
915
+ 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 });
787
916
  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);
788
917
  await checkpoint("context ceiling");
789
- T.decisions.push(`Builder session reached ${e.context ?? "?"} context tokens (ceiling ${contextCeilingTokens}): checkpointed, restarted fresh from the contract, diff and last validate result`);
790
- p = restart() + await contextRestartNote(); resume = null; opts.restartOf ??= opts.trigger ?? null; opts.trigger = "context_restart";
918
+ T.decisions.push(`Builder session reached ${e.context ?? "?"} context tokens (ceiling ${laneCeiling}): checkpointed, restarted fresh from the contract, diff and last validate result`);
919
+ p = restart() + await contextRestartNote(handoffFacts(e.toolUses, e.lastTool)); resume = null; opts.restartOf ??= opts.trigger ?? null; opts.trigger = "context_restart";
791
920
  continue;
792
921
  }
922
+ if (["CLI_LANE_LIMIT", "CLI_IDLE", "CLI_TIMEOUT"].includes(e?.code) || isExternalKill(e)) { // #5334: a kill still spent tokens: record them before the checkpoint and retry
923
+ if (!e.usageRecorded) await killedAttempt(n, e, opts, e.sessionAt ?? now());
924
+ }
793
925
  if (e?.code === "CLI_LANE_LIMIT") { // #4690: the lane hit its own scope limit: a rerun hits it again, so typed needs-human (env.lane_limit), never engine-error
794
926
  ev({ event: "CLI_LANE_LIMIT", limit: e.limit ?? null, unit: e.unit ?? null });
795
927
  await checkpoint(`scope ${e.limit} limit`);
@@ -821,18 +953,24 @@ export async function runCore(o) {
821
953
  }
822
954
 
823
955
  /** opts (#4363): {model, mode, keepSession, trigger and restartOf (#4362)}; a fresh fix session keeps the build session id for a fallback resume. */
824
- async function builderOnce(n, prompt, resume, live = false, { model = null, mode = null, keepSession = false, trigger = null, restartOf = null, contextMax = 0, turnMax = 0 } = {}) {
956
+ async function builderOnce(n, prompt, resume, live = false, { model = null, mode = null, keepSession = false, trigger = null, restartOf = null, contextMax = 0, turnMax = 0, profile = null } = {}) {
825
957
  onProgress({ event: "phase_enter", phase: "build" });
826
958
  await renew();
959
+ if (wtCreated && io.fs.exists && !(await io.fs.exists(wt))) throw Object.assign(new Error("lane worktree is gone"), { deferCode: OUTCOME_CODES.RUN_INTERRUPTED, deferDetail: `worktree ${wt} no longer exists; no builder session starts in it, a rerun recreates it` }); // #5333
960
+ const lock = await takeBranchLock();
961
+ try { return await builderSession(); } finally { try { lock?.release(); } catch { /* best effort */ } }
962
+ async function builderSession() {
827
963
  const control = {};
828
964
  const governor = startGovernor(control);
829
965
  let spawned = null;
830
966
  const onSpawn = (child) => { if (Number.isSafeInteger(child?.pid) && !finishing) { spawned = child.pid; ledgerDo((l) => l.register("pid", child.pid, { marker: basename(String(child.spawnfile ?? "")) || null })); } };
831
- const call = Promise.resolve(callRunner({ role: "builder", issue, cwd: wt, model: model ?? laneModel(), resume, system: "", prompt, control, onSpawn, agents: explorerAgents(exploreCfg), rereadNudge: true,
967
+ const session = {}, cur = inflight = { n, session, at: now(), flushed: false, opts: { model, mode, trigger, restartOf } };
968
+ const call = Promise.resolve(callRunner({ role: "builder", issue, cwd: wt, model: model ?? laneModel(), resume, system: "", prompt, control, ...(profile ? { profile } : {}), onSpawn, session, agents: explorerAgents(exploreCfg), rereadNudge: true,
832
969
  idleMs: Math.round(cliIdleMinutes * 60000), maxMs: Math.round(cliMaxMinutes * 60000), laneLimits, ...(contextMax > 0 ? { contextMax } : {}), ...(turnMax > 0 ? { turnMax } : {}),
833
970
  busy: sessionBusy, busyMs: Math.round(cliBusyMinutes * 60000),
834
971
  onIdleExtend: (info) => ev({ event: "CLI_IDLE_EXTENDED", children: info.children, heavyQueue: info.heavyQueue }) }));
835
- call.then(() => {}, () => {}).finally(() => { if (spawned) ledgerDo((l) => l.release("pid", spawned)); });
972
+ call.catch((err) => { if (err && typeof err === "object") { err.sessionAt = cur.at; if (cur.flushed) err.usageRecorded = true; } }); // #5334
973
+ call.then(() => {}, () => {}).finally(() => { if (inflight === cur) inflight = null; if (spawned) ledgerDo((l) => l.release("pid", spawned)); });
836
974
  let r;
837
975
  call.catch(() => governor.stop());
838
976
  if (live && io.fs.stat) {
@@ -851,9 +989,20 @@ export async function runCore(o) {
851
989
  await renew();
852
990
  await registerReported();
853
991
  if (r?.sessionId && !keepSession) sessionId = r.sessionId;
854
- await attempt("implement", n, r, mode, trigger, restartOf, resume);
992
+ await attempt("implement", n, profile && r ? { ...r, laneProfile: profile === "narrow" && laneProfile.name === "full" ? "full" : profile } : r, mode, trigger, restartOf, resume);
855
993
  onProgress({ event: "phase_exit", phase: "build", status: "committed" });
856
994
  return r;
995
+ }
996
+ }
997
+ /** #5333: one writer per lane branch. A second session (a fix-up beside a recovery) waits for the holder, then defers `host.busy`. Fail-open when the shared git dir is unknown. */
998
+ async function takeBranchLock() {
999
+ let dir = null;
1000
+ try { const d = String(await io.git(["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: wt })).trim(); if (d.startsWith("/") && existsSync(d)) dir = d; } catch { dir = null; }
1001
+ if (!dir) return null;
1002
+ let lock;
1003
+ try { lock = await acquireBranchLock({ gitCommonDir: dir, branch, owner: agentId, waitMs: o.branchLockWaitMs ?? 600000, pollMs: o.branchLockPollMs ?? 15000, sleep: async (ms) => { await renew(); await sleep(ms); } }); } catch { return null; }
1004
+ if (lock.ok) return lock;
1005
+ throw Object.assign(new Error(`lane branch ${branch} is being written by another session`), { deferCode: OUTCOME_CODES.HOST_BUSY, retryInSeconds: 120, deferDetail: `another session (pid ${lock.holder?.pid ?? "?"}, ${lock.holder?.owner ?? "?"}) holds the writer lock of ${branch}; retried later` });
857
1006
  }
858
1007
  /** #4390: the restart summary: `git diff --stat` and hunks against the lane base, and the last `forgedock check` record. */
859
1008
  async function restartFacts() {
@@ -863,7 +1012,13 @@ export async function runCore(o) {
863
1012
  try { check = String(await io.fs.read(`${wt}/${SELF_CHECK_FILE}`)); } catch { /* none recorded */ }
864
1013
  return { stat, diff, base, check };
865
1014
  }
866
- const contextRestartNote = async () => contextRestartPrompt({ ...await restartFacts(), ceiling: contextCeilingTokens });
1015
+ /** #5346: bytes of the contract's deliverable files that exist in the worktree (capped at 60 files); 0 for the rest. */
1016
+ const namedFileBytes = async (c) => {
1017
+ let n = 0;
1018
+ for (const d of [...new Set((c?.deliverables ?? []).map((x) => x?.path).filter((x) => typeof x === "string" && x))].slice(0, 60)) { try { n += Buffer.byteLength(String(await io.fs.read(`${wt}/${d}`) ?? "")); } catch { /* new file */ } }
1019
+ return n;
1020
+ };
1021
+ const contextRestartNote = async (established = null) => contextRestartPrompt({ ...await restartFacts(), ceiling: laneCeiling, established });
867
1022
  /**
868
1023
  * #4392: the implement turn budget is spent. Checkpoint, then one fresh session of `wrapupGrant` turns either finishes
869
1024
  * (its result flows on as usual) or stops with a digest; a stop or an overrun ends the non-human `budget-exceeded` reason
@@ -988,6 +1143,16 @@ export async function runCore(o) {
988
1143
  ? await finish("dependency-blocked", detail, { code: OUTCOME_CODES.DEPENDENCY_BLOCKED, dependencies: b.issues, blockers: b.blockers }, OUTCOME_CODES.DEPENDENCY_BLOCKED)
989
1144
  : await finish("dependency-open", detail, { code: OUTCOME_CODES.DEPENDENCY_OPEN, dependencies: b.issues }, OUTCOME_CODES.DEPENDENCY_OPEN);
990
1145
  }
1146
+ if (b.kind === "design-invalidated") { // #5342: one amendment issue, siblings held behind it, decision superseded
1147
+ const epic = epicOf(b, iss?.body);
1148
+ if (!epic) return await needsHuman(`Builder reported a design-invalidated block but no epic: set "epic" or a **Parent** line (${b.decision}): ${s}`, OUTCOME_CODES.BUILDER_BLOCK_UNTYPED);
1149
+ let f;
1150
+ try { f = await fileAmendment({ gh: ghc, create: ghw, repo, issue, inv: b, epic, milestone }); } catch (e) { return await finish("engine-error", `filing the spike amendment failed: ${e?.message ?? e}`); }
1151
+ T.decisions.push(`Builder block: design invalidated (${b.decision}); amendment #${f.amendment} ${f.created ? "filed" : "joined"}, held ${refs(f.held)}`);
1152
+ try { await post(REPLAN_MARKER, `## Design invalidated\n${b.decision}\n\nWhy: ${b.why}\n\nAmendment: #${f.amendment}; held until it merges: ${refs(f.held)}.\n\n${s}`); } catch { /* best effort */ }
1153
+ if (b.paths.length) try { await recordDecisions([{ choice: `${b.decision} no longer holds; replaced by the amendment`, why: b.why, anchors: b.paths, ...(b.supersedes ? { supersedes: b.supersedes } : {}) }], { issue: f.amendment, repo, post }); } catch { /* the register is best effort */ }
1154
+ return await finish("dependency-open", `design invalidated; waiting on amendment #${f.amendment}`, { code: OUTCOME_CODES.DESIGN_INVALIDATED, dependencies: [f.amendment], amendment: f.amendment, epic }, OUTCOME_CODES.DESIGN_INVALIDATED);
1155
+ }
991
1156
  if (b.kind === "split") {
992
1157
  const filed = [];
993
1158
  try {
@@ -1146,6 +1311,16 @@ export async function runCore(o) {
1146
1311
  return await needsHuman(`Open PR #${resumed.pr} targets \`${resumed.base}\`, but #${issue}'s lane is \`${lane}\`; retarget or close it before rerunning.`,
1147
1312
  isDefaultLane(resumed.base, defaults) ? OUTCOME_CODES.LANE_DEFAULT_BRANCH : OUTCOME_CODES.LANE_MISMATCH);
1148
1313
  }
1314
+ if (!resumed && !recover) { // #5250: every acceptance item needs live production measurement or a real-browser capture: host work, not a code lane
1315
+ const hw = intakeHostWork(iss.body);
1316
+ if (hw.host) {
1317
+ T.decisions.push("Intake: every acceptance criterion needs live production measurement or a real-browser capture (host-task), no code lane");
1318
+ const why = `Host-task: every acceptance criterion needs live production measurement or a real-browser capture:\n${hw.items.map((t) => `- ${t}`).join("\n")}\n\nNot a code lane: run it on the host with its read-only prod tools and real browser.`;
1319
+ try { await post("FORGE:HOST_TASK", `## Host task\n${why}\n\n_${usageLine()}_`); } catch { /* best effort */ }
1320
+ try { await ghc(["issue", "edit", String(issue), "-R", repo, "--add-label", "host-task"]); } catch { /* best effort */ }
1321
+ return await finish("host-task", why, { code: OUTCOME_CODES.ENV_CAPABILITY_REMOTE }, OUTCOME_CODES.ENV_CAPABILITY_REMOTE);
1322
+ }
1323
+ }
1149
1324
  // #4162: a run that died can leave its runner writing into this worktree, and uncommitted work in it. Stop the
1150
1325
  // processes and save the work before the worktree is removed; the lease above makes this run the only one doing so.
1151
1326
  await stopWorktreeProcs();
@@ -1304,6 +1479,13 @@ export async function runCore(o) {
1304
1479
  const addedFiles = rules.some((r) => r.addedOnly) ? names(await git(["diff", "--name-only", "--diff-filter=A", `${base}...HEAD`]).catch(() => "")) : [];
1305
1480
  return coupledFailures({ rules, changedFiles: files, addedFiles });
1306
1481
  };
1482
+ /** #5237: relaxed rules in declared review.risk_paths files ({relaxations, negatives}); empty when no glob matches or git fails */
1483
+ let relaxations = [];
1484
+ const relaxationsOf = async (files) => {
1485
+ const empty = { relaxations: [], negatives: 0 };
1486
+ if (!riskPathHits(files, riskPaths).length) return empty;
1487
+ try { return analyzeRelaxations({ diff: String(await git(["diff", "-U0", `${base}...HEAD`])), riskPaths }); } catch { return empty; }
1488
+ };
1307
1489
  /** #4364: the last `forgedock check` record vs the current tree: skipped|stale|red|green; any read or git error is skipped. */
1308
1490
  const selfCheckNow = async () => {
1309
1491
  try { return selfCheckState(JSON.parse(await io.fs.read(`${wt}/${SELF_CHECK_FILE}`)), await worktreeFingerprint({ git, base })); } catch { return "skipped"; }
@@ -1356,6 +1538,7 @@ export async function runCore(o) {
1356
1538
  factsSeen = trustedComments.map((c) => c?.body);
1357
1539
  let issueText = textOf(iss, trustedComments);
1358
1540
  let scopeHash = contractHash(scopeText(iss, trustedComments)); // #4265: the edit signal and the frozen contract's provenance
1541
+ { const m = resolveContextMode(o.contextPack, ctxCfg, { milestone, parent: parentOf(iss.body ?? "") }); if (m !== ctxCfg.mode) { ctxCfg = { ...ctxCfg, mode: m }; T.decisions.push(`Context pack (${m}): lane has a milestone or parent epic (#5340)`); } }
1359
1542
  ctxLane = laneType({ resumed: Boolean(resumed || salvagedRef), attempts: priorAttempts(iss.body, trustedComments), body: iss.body });
1360
1543
  /**
1361
1544
  * forge#4275: compile (or read from the cache) the context pack, log CONTEXT_PACK and post FORGE:CONTEXT. Off, no
@@ -1369,7 +1552,7 @@ export async function runCore(o) {
1369
1552
  // #4316: linked-issue states are part of the key; a failed lookup only drops them from it
1370
1553
  const links = await linkStateStamp({ gh: ghc, repo, issue, body: iss.body }).catch(() => "");
1371
1554
  const r = await contextPackFor({ cfg: ctxCfg, issue, repo, headSha, cacheDir: dir, fs: io.fs, stamp: { scope: scopeHash, attempts: priorAttempts(iss.body, trustedComments), links, pitfalls: pits.map((x) => x.sig) },
1372
- gather: () => io.contextFacts({ repo, issue, iss, comments: trustedComments, cwd: wt, checkout: cwd, base, sources: ctxCfg.sources, days: ctxCfg.days, now: now(), pitfalls: pits }) });
1555
+ gather: () => io.contextFacts({ milestone, repo, issue, iss, comments: trustedComments, cwd: wt, checkout: cwd, base, sources: ctxCfg.sources, days: ctxCfg.days, now: now(), pitfalls: pits }) });
1373
1556
  const p = r.pack;
1374
1557
  const inPack = Array.isArray(p.pitfalls) ? p.pitfalls : [];
1375
1558
  pitMatched = inPack.filter((x) => x.match === "files").length;
@@ -1474,6 +1657,12 @@ export async function runCore(o) {
1474
1657
  /** #5020: forge.yaml validate.recipes rewrite frozen commands; a check-less post-deploy requirement becomes a defer to the orchestrator. */
1475
1658
  function freezeRewrites(c) {
1476
1659
  const r = applyValidateRecipes(c, validateRecipes);
1660
+ const pd = (id, cmd) => { const to = rewriteProjectDirCommand(cmd); if (to !== cmd) T.decisions.push(`project-dir rewrite of ${id}: \`${cmd}\` -> \`${to}\``); return to; };
1661
+ if (r.contract && typeof r.contract === "object") { // #5234
1662
+ if (Array.isArray(r.contract.validate)) r.contract = { ...r.contract, validate: r.contract.validate.map((v) => (v && typeof v.command === "string" ? { ...v, command: pd(v.id, v.command) } : v)) };
1663
+ const t = r.contract.repro_test;
1664
+ if (t && typeof t === "object" && typeof t.command === "string") r.contract = { ...r.contract, repro_test: { ...t, command: pd("repro_test", t.command) } };
1665
+ }
1477
1666
  for (const x of r.applied) T.decisions.push(`validate recipe rewrote ${x.id}: \`${x.from}\` -> \`${x.to}\``);
1478
1667
  const d = deferChecklessPostDeploy(r.contract);
1479
1668
  if (d.converted.length) T.decisions.push(`Post-deploy with no registered check deferred to the orchestrator: ${d.converted.join(", ")}`);
@@ -1591,7 +1780,7 @@ export async function runCore(o) {
1591
1780
  }
1592
1781
  /** #4694: the engine appends guard-derived H preserve rows from the local index (one file read; the same contract when none apply). */
1593
1782
  const historyRows = (c) => { const w = withHistoryRows(c, { repo, issue }); const n = (w.preserve ?? []).length - (c.preserve ?? []).length; if (w !== c && n > 0) T.decisions.push(`History preserve rows: ${w.preserve.filter((p) => p.source === "guard").map((p) => p.id).join(", ")} from guards (#4694)`); return w; };
1594
- let frozen = null, hash = null, planned = false, files = [], split = null;
1783
+ let frozen = null, hash = null, planned = false, files = [], split = null, planMisses = null; // planMisses (#5331): validate preflight misses from this run
1595
1784
  const impliedDocs = []; // add-deliverable amendments for doc edits the docs-freshness rule demanded (docs round, CI fix round)
1596
1785
  /** Doc files a fix round added to satisfy the freshness rule: recorded only when the rule failed before and passes after. */
1597
1786
  async function noteFreshnessDocs(before, wasFailing) {
@@ -1628,17 +1817,40 @@ export async function runCore(o) {
1628
1817
  * #4363: one fix round. Mechanical failures (and a conformance/review FAIL citing file:line) run in a fresh session on
1629
1818
  * the fix model with a narrow prompt; one resume of the build session follows when it made no commit. Else: a resume.
1630
1819
  */
1631
- async function fixRound(kind, task, failures, trigger, failureText = "") {
1820
+ async function fixRound(kind, task, failures, trigger, failureText = "", narrow = null) { // #5348: `narrow` {files} = the minimal profile (no diff, no lane text)
1632
1821
  await notePitfall(trigger, failureText); await escalateOn(trigger); // #4375: learned once the same gate passes; #4394
1633
1822
  if (!freshFix(kind, failures)) return await builder(++attemptN, task, sessionId ?? null, false, undefined, { mode: "resume", trigger });
1634
1823
  const before = String(await git(["rev-parse", "HEAD"])).trim();
1635
- const ex = [".", `:!${LEAN_DIR}`], diff = String(await git(["diff", `${base}...HEAD`, "--", ...ex]).catch(() => "")), stat = String(await git(["diff", "--stat", `${base}...HEAD`, "--", ...ex]).catch(() => ""));
1636
- const prompt = fixSessionPrompt({ task, diff, stat, base, contract: frozen, title: iss?.title ?? "", summary: issueSummary(iss?.body) });
1637
- const r = await builder(++attemptN, prompt, null, false, () => prompt, { model: escalated ? null : fixModel ?? reviewerModel, mode: "fresh", keepSession: true, trigger });
1824
+ const ex = [".", `:!${LEAN_DIR}`], diff = narrow ? "" : String(await git(["diff", `${base}...HEAD`, "--", ...ex]).catch(() => "")), stat = narrow ? "" : String(await git(["diff", "--stat", `${base}...HEAD`, "--", ...ex]).catch(() => ""));
1825
+ const prompt = narrow ? narrowFixPrompt({ task, contract: frozen, files: narrow.files }) : fixSessionPrompt({ task, diff, stat, base, contract: frozen, title: iss?.title ?? "", summary: issueSummary(iss?.body) });
1826
+ const r = await builder(++attemptN, prompt, null, false, () => prompt, { model: escalated ? null : fixModel ?? reviewerModel, mode: "fresh", keepSession: true, ...(narrow ? { profile: "narrow" } : {}), trigger });
1638
1827
  if (!sessionId || String(await git(["rev-parse", "HEAD"])).trim() !== before) return r;
1639
1828
  T.decisions.push(`Fresh ${kind} fix session made no commit; builder session resumed once`);
1640
1829
  return await builder(++attemptN, task, sessionId, false, undefined, { mode: "resume", trigger });
1641
1830
  }
1831
+ /** #5348: commit what the engine applied without a model (only the files it wrote); the findings it fixed were named by a detector. */
1832
+ async function mechCommit(gate, applied, paths) {
1833
+ if (!applied.length) return 0;
1834
+ ev({ event: "MECHANICAL_FIX", gate, count: applied.length });
1835
+ T.decisions.push(`Mechanical ${gate} fix applied without a model session: ${applied.slice(0, 5).map((x) => x.symbol).join(", ")}`);
1836
+ try { await git(["add", "--", ...new Set(paths)]); await git(["commit", "--no-verify", "-m", `fix(forge): ${gate} fix applied by the engine, no model session (#5348)`]); } catch { /* the detector re-run decides */ }
1837
+ files = await changedFiles();
1838
+ return applied.length;
1839
+ }
1840
+ const mech = io.mechFix ?? { applyEnumerating, renameDuplicates }; // #5348: a test seam; the engine uses mechfix.mjs
1841
+ let dupMech = 0; // #5348: duplicate renames the last dupsResidual() applied
1842
+ /** Duplicate-export findings that still need a model: the detector, then the deterministic rename, then the detector again. */
1843
+ async function dupsResidual() {
1844
+ const found = async () => (await io.duplicateExports({ cwd: wt, base }).catch(() => null)) ?? [];
1845
+ let dups = await found();
1846
+ dupMech = 0;
1847
+ if (dups.length) {
1848
+ const m = await mech.renameDuplicates({ dups, cwd: wt, git: (a) => git(a) });
1849
+ dupMech = await mechCommit("duplicate", m.applied, m.applied.map((d) => d.path));
1850
+ if (dupMech) dups = await found();
1851
+ }
1852
+ return dups;
1853
+ }
1642
1854
  if (isSplit) {
1643
1855
  // ---- 3'. refactor:split (#4211): deterministic move + proof replaces the builder; no builder session exists ----
1644
1856
  split = await splitStep();
@@ -1662,8 +1874,8 @@ export async function runCore(o) {
1662
1874
  }
1663
1875
  if ((resumed || salvagedRef || recover) && ctxCfg.mode !== "off") {
1664
1876
  // #4400: the last run's own records as a bounded digest in the builder prompts; never in issueText (contract quotes)
1665
- const d = buildResumeDigest({ state: priorState, comments: trustedComments, contract: frozen, files: resumed ? await changedFiles().catch(() => []) : [], lane });
1666
- resumeNote = d.text;
1877
+ const d = buildResumeDigest({ state: priorState, comments: trustedComments, contract: frozen, files: resumed ? await changedFiles().catch(() => []) : [], lane, head: String(await git(["rev-parse", "HEAD"]).catch(() => "")).trim() });
1878
+ resumeNote = d.text; carriedPasses = d.passes ?? [];
1667
1879
  if (d.text) {
1668
1880
  ev({ event: "RESUME_DIGEST", bytes: Buffer.byteLength(d.text, "utf8"), files: d.files, validates: d.validates, reason: d.reason });
1669
1881
  T.decisions.push(`Resume digest given to the builder: ${d.files} file(s), ${d.validates} validate result(s)${d.reason ? `, last run ${d.reason}` : ""}`);
@@ -1673,13 +1885,14 @@ export async function runCore(o) {
1673
1885
  if (decisionsNote) T.decisions.push("Trusted FORGE:DECISION comment(s) posted after the contract froze are binding notes for the builder");
1674
1886
  await label("building");
1675
1887
  // #4450: the light lane (lean.light mode on, eligible, fresh lane): one builder session, derived contract, or an upgrade
1676
- const elig = lightEligibility({ title: iss.title, body: iss.body ?? "", labels: iss.labels ?? [], predictedFiles: namedPaths(iss.body ?? ""), riskPaths, cfg: o.light ?? {} });
1677
- ev({ event: "LIGHT_ELIGIBILITY", mode: elig.mode, verdict: elig.verdict, light: elig.light, reasons: elig.reasons });
1888
+ const namedHot = await hotspotsOf({ paths: namedPaths(iss.body ?? "") }); // #5209: churn and hotspot signals for eligibility
1889
+ const elig = lightEligibility({ title: iss.title, body: iss.body ?? "", labels: iss.labels ?? [], predictedFiles: namedPaths(iss.body ?? ""), riskPaths, hotspots: namedHot?.files ?? [], cfg: o.light ?? {} });
1890
+ ev({ event: "LIGHT_ELIGIBILITY", mode: elig.mode, verdict: elig.verdict, light: elig.light, reasons: elig.reasons, signals: elig.signals });
1678
1891
  lightVerdict = elig.verdict;
1679
1892
  if (elig.mode !== "off") T.decisions.push(`Light lane ${elig.mode}: ${elig.verdict}${elig.reasons.length ? ` (${elig.reasons.map((x) => x.code).join(", ")})` : ""}`);
1680
1893
  // #4451: a light try skips the hotspots and the context pack; an upgrade computes them before the plan call
1681
1894
  const lightTry = elig.light && !frozen && !resumed && !salvagedRef && !recover;
1682
- if (!lightTry) hotFacts = await hotspotsOf({ paths: namedPaths(iss.body ?? "") });
1895
+ if (!lightTry) hotFacts = namedHot; // #4451: a light try still gives its builder no hotspot facts
1683
1896
  enumList = io.enumeratingTests ? ((await io.enumeratingTests({ cwd: wt, paths: namedPaths(iss.body ?? "") }).catch(() => null)) ?? []) : [];
1684
1897
  facts = await factsPath([wt, cwd], io.fs?.exists);
1685
1898
  let ctxPack = frozen || lightTry ? null : await contextPackStep();
@@ -1701,6 +1914,7 @@ export async function runCore(o) {
1701
1914
  let body = renderContract(frozen, hash, { scope: scopeHash });
1702
1915
  if (body.length > MAX_COMMENT_CHARS - 500) body = renderContract(frozen, hash, { compact: true, scope: scopeHash });
1703
1916
  await post(["FORGE:CONTRACT", "FORGE:PLAN"], body);
1917
+ await claimSurfaceSlots(frozen);
1704
1918
  ev({ event: "CONTRACT_FROZEN", hash, requirements: frozen.requirements.length, deferred: 0, derived: "light" });
1705
1919
  await emit({ event: "CONTRACT_FROZEN", hash, requirements: frozen.requirements.length, deferred: 0, derived: "light" });
1706
1920
  ev({ event: "LIGHT_DONE", files: lr.files.length, test_failures: lr.testFailures, repro: lr.repro, cost_usd: usage.cost_usd });
@@ -1735,6 +1949,7 @@ export async function runCore(o) {
1735
1949
  // #5152: already-fixed is delivered behaviour (`completed`); only invalid is dropped scope (`not planned`)
1736
1950
  await ghw(["issue", "close", String(issue), "-R", repo, "--reason", result.status === "already-fixed" ? "completed" : "not planned"]);
1737
1951
  await label("invalid");
1952
+ if (result.status === "invalid") { const f = await resolveFindingLabel({ io, issue, labels: iss.labels, reason: "invalid" }); if (f.error) T.anomalies.push(`finding label not resolved: ${f.error}`); } // #5254
1738
1953
  return await finish("invalid", result.summary ?? result.status, result.status === "already-fixed" ? { close: "already-fixed" } : {});
1739
1954
  }
1740
1955
  const blocked = await endIfBlocked();
@@ -1758,6 +1973,12 @@ export async function runCore(o) {
1758
1973
  let contract = dropScope(await readContract());
1759
1974
  contract = freezeRewrites(contract);
1760
1975
  await refreshIssue("contract validation");
1976
+ const snapContract = (c) => { // #5244: a near-verbatim quote snaps to the issue's exact sentence instead of ending needs-human
1977
+ const sq = snapQuotes(c, issueText);
1978
+ for (const x of sq.snapped) { ev({ event: "CONTRACT_QUOTE_SNAPPED", id: x.id }); T.decisions.push(`Contract quote ${x.id} snapped to the issue sentence "${x.to.slice(0, 120)}"`); }
1979
+ return sq.contract;
1980
+ };
1981
+ contract = snapContract(contract);
1761
1982
  let vc = validateContract(contract, issueText, { repro: reproOn() });
1762
1983
  const missed = await preflightValidates(contract); // #4328: validate commands the host cannot run share the one correction
1763
1984
  let misses = missed;
@@ -1767,9 +1988,11 @@ export async function runCore(o) {
1767
1988
  await builder(++attemptN, contractCorrectionPrompt(problems), sessionId, false, planPrompt, { trigger: "contract_correction" });
1768
1989
  contract = freezeRewrites(dropScope(await readContract()));
1769
1990
  await refreshIssue("contract validation");
1991
+ contract = snapContract(contract);
1770
1992
  vc = validateContract(contract, issueText, { repro: reproOn() });
1771
1993
  if (missed.length) misses = await preflightValidates(contract);
1772
1994
  }
1995
+ planMisses = misses;
1773
1996
  if (missed.length) {
1774
1997
  ev({ event: "VALIDATE_PREFLIGHT", misses: misses.map((m) => ({ ids: m.ids, tool: m.tool, kind: m.kind, source: m.source })), found: missed.map((m) => ({ ids: m.ids, tool: m.tool, kind: m.kind, source: m.source })), corrected: misses.length === 0 });
1775
1998
  if (misses.length) {
@@ -1798,11 +2021,18 @@ export async function runCore(o) {
1798
2021
  const relayed = new Set(o.relayCaps ?? []); // #4778: a relayed capability is served to the sandbox, so the lane builds there
1799
2022
  const hn = contractHostNeeds(frozen, o.hostCaps && { ...o.hostCaps, hostCapabilities: (o.hostCaps.hostCapabilities ?? []).filter((c) => !relayed.has(c)) });
1800
2023
  if (hn.caps.length) return await needsHuman(`Remote sandbox lacks host capability ${hn.caps.join(", ")}, which the frozen contract's validate command(s) ${hn.ids.join(", ")} need.\n\nThe dispatching host has it; the lane is recovered locally with the frozen contract.`, OUTCOME_CODES.ENV_CAPABILITY_REMOTE);
2024
+ // #5331: a tool the sandbox itself lacks (probed where the lane runs) ends the lane before the builder implements; the tool-missing recovery places it on the host (orchestrate placeOf)
2025
+ const tm = toolMisses(planMisses ?? await preflightValidates(frozen).catch(() => []));
2026
+ if (tm.tools.length) {
2027
+ ev({ event: "REMOTE_TOOL_MISSING", tools: tm.tools, ids: tm.ids });
2028
+ return await needsHuman(`Remote sandbox lacks ${tm.tools.join(", ")}, which the frozen contract's validate command(s) ${tm.ids.join(", ")} need; the lane is re-placed on the host before the builder implements.`, OUTCOME_CODES.ENV_TOOL_MISSING);
2029
+ }
1801
2030
  }
1802
2031
  T.plan = [`contract ${hash}${lightDone ? " (derived, light lane)" : ""}`, `${frozen.requirements.length} requirement(s)`];
1803
2032
  { // #4392, #4505: next size on a budget recovery; #4587: a big L contract and an L recovery get extra turns
1804
2033
  const sz = recoverySize(laneSize({ contract: frozen, labels: (iss?.labels ?? []).map((l) => l?.name ?? l) }), recover);
1805
2034
  tb.setSize(sz, scaledExtra({ size: sz, contract: frozen, recover, base: (turnBudgets ?? {}).L ?? TURN_BUDGET_DEFAULTS.L }));
2035
+ laneCeiling = ceilingFor(sz, { tokens: contextCeilingTokens, bySize: contextCeilingBySize }); // #5346
1806
2036
  }
1807
2037
  if (io.fs.write) { try { await io.fs.write(`${wt}/${CONTRACT_FILE}`, `${contractJson(frozen)}\n`); } catch { /* the prompt still names it */ } }
1808
2038
  // #4364: what `forgedock check` needs from the operator's forge.yaml (gitignored, so not in the worktree)
@@ -1813,24 +2043,59 @@ export async function runCore(o) {
1813
2043
  ev(rec); await emit(rec);
1814
2044
  T.decisions.push(`Builder routed to the ${route.tier} tier (${route.class}; ${route.model ?? "CLI default"})`);
1815
2045
  }
1816
- const implementPrompt = builderImplementPrompt(vcfg.mode, tcOpts()) + hotspotBuildRule(hotFacts) + enumeratingBuildRule(enumList) + invariantsBuildRule(vcfg.invariants) + exploreBuildRule(exploreCfg) + (planned ? "" : (fromCheckpoint ? CONTINUE_NOTE : RERUN_NOTE).replace("BASE", lane)) + (salvagedRef ? SALVAGE_NOTE.replaceAll("REF", salvagedRef) : "") + recoverNote() + (planned ? "" : resumeNote + decisionsNote);
2046
+ if (!isSplit && io.sequenceReserveBuild) { // #5235: reserve numbers / versions before the builder picks them from its stale snapshot
2047
+ const rs = await io.sequenceReserveBuild({ cwd: wt, base, lane, repo, issue, deliverables: frozen?.deliverables ?? [], versioned: o.sequenceVersioned ?? [] }).catch(() => []);
2048
+ seqBuildNote = sequenceBuildRule(rs);
2049
+ if (rs.length) { ev({ event: "SEQUENCE_RESERVED", reservations: rs }); T.decisions.push(`Sequence numbers reserved at build start: ${rs.map((r) => `${r.cls ?? r.dir}=${r.numbers.join(",")}`).join("; ")}`); }
2050
+ }
2051
+ stampHash = hash; // #5333
2052
+ await claimSurfaceSlots(frozen); // #5340: the full and recovered paths reach the builder here with the contract settled
2053
+ const openPaths = (frozen?.deliverables ?? []).map((d) => d?.path); // #5347: facts for the build's opening batch
2054
+ const openMap = io.runCommand ? await readTestMapAtRef(git, base).catch(() => null) : null;
2055
+ const implementPrompt = builderImplementPrompt(vcfg.mode, tcOpts()) + seqBuildNote + buildOpeningNote({ paths: openPaths, tests: selectCommands(openMap, openPaths), packFiles: ctxCfg.mode === "on" ? ctxPack?.files : [] }) + hotspotBuildRule(hotFacts) + enumeratingBuildRule(enumList) + invariantsBuildRule(vcfg.invariants) + exploreBuildRule(exploreCfg) + generatorNote(surfaceClaim?.generated) + (planned ? "" : (fromCheckpoint ? CONTINUE_NOTE : RERUN_NOTE).replace("BASE", lane)) + (salvagedRef ? SALVAGE_NOTE.replaceAll("REF", salvagedRef) : "") + recoverNote() + (planned ? "" : resumeNote + decisionsNote);
1817
2056
  liveKeys = ["implementation"];
1818
2057
  stage = "implement"; phaseLedger.enter("implement");
1819
- if (!lightDone) await builder(++attemptN, implementPrompt, planned ? sessionId : null, true, undefined, { trigger: "build" });
2058
+ let buildPrompt = implementPrompt, noCeiling = false;
2059
+ if (!lightDone) { // #5346: a session certain to restart is narrowed (or, when the named files alone exceed the ceiling, left uncapped) before it starts
2060
+ const pred = predictRestart({ ceiling: laneCeiling, promptBytes: Buffer.byteLength(implementPrompt), fileBytes: await namedFileBytes(frozen) });
2061
+ if (pred.predicted) {
2062
+ buildPrompt = implementPrompt.replace(exploreBuildRule(exploreCfg), "") + NARROW_NOTE;
2063
+ noCeiling = pred.certain;
2064
+ ev({ event: "CONTEXT_PREDICT", estimate_tokens: pred.estimate, ceiling: pred.ceiling, certain: pred.certain });
2065
+ T.decisions.push(`Build predicted to restart (about ${pred.estimate} of ${pred.ceiling} context tokens at start): context narrowed${pred.certain ? "; the named files alone exceed the ceiling, so this build runs without it" : ""}`);
2066
+ }
2067
+ await builder(++attemptN, buildPrompt, planned ? sessionId : null, true, undefined, { trigger: "build", noCeiling });
2068
+ }
1820
2069
  stage = "fix"; // later builder rounds fix precheck, CI, structure, docs or conformance findings
1821
2070
  result = await readResult();
2071
+ if (carriedPasses.length && result && io.fs.write) { // #5331: a validate id that passed on this same head is not re-run: its row is carried, marked
2072
+ const headNow = String(await git(["rev-parse", "HEAD"]).catch(() => "")).trim(), rows = Array.isArray(result.validation) ? result.validation : [];
2073
+ const carry = carriedPasses.filter((x) => x.head === headNow && !rows.some((r) => r?.id === x.id) && (frozen?.validate ?? []).some((v) => v.id === x.id));
2074
+ if (carry.length) {
2075
+ result = { ...result, validation: [...rows, ...carry.map((x) => ({ id: x.id, command: x.command, exit: 0, carried: true }))] };
2076
+ try { await io.fs.write(`${wt}/${RESULT_FILE}`, `${JSON.stringify(result)}\n`); T.decisions.push(`Validate result(s) ${carry.map((x) => x.id).join(", ")} carried from an earlier run: passed on this same head`); } catch { /* the gate reads what is on disk */ }
2077
+ }
2078
+ }
1822
2079
  { // #4374: the builder's self-review against the shared rubric, log only
1823
2080
  const sr = readSelfReview(result);
1824
2081
  if (sr) ev(sr.state === "present" ? { event: "SELF_REVIEW", answers: sr.items.length, no: sr.no } : { event: "SELF_REVIEW_MISSING", state: sr.state });
1825
2082
  }
1826
2083
  // #4364: a builder that writes fixed without a green `forgedock check` on its final tree; recorded, never a failure
1827
2084
  if (result?.status === "fixed") { const state = await selfCheckNow(); if (state !== "green") ev({ event: "SELF_CHECK_MISSING", state }); }
2085
+ if (result?.status === "fixed" && sessionId && !result.amendments?.length) { // #5345: a red self-check on the final tree is fixed before any reviewer runs
2086
+ let rec = null; try { rec = JSON.parse(await io.fs.read(`${wt}/${SELF_CHECK_FILE}`)); } catch { /* none recorded */ }
2087
+ const red = (await selfCheckNow()) === "red" ? selfCheckFailures(rec) : [];
2088
+ if (red.length) ev({ event: "SELF_CHECK_RED", codes: red.map((f) => f.code) });
2089
+ if (red.length) await fixRound("conformance", conformanceResumePrompt(red, vcfg.mode, lane), red, "conformance", failureLog(red));
2090
+ if (red.length) result = (await readResult()) ?? result;
2091
+ }
1828
2092
  {
1829
2093
  const blocked = await endIfBlocked();
1830
2094
  if (blocked) return blocked;
1831
2095
  }
1832
2096
  files = await changedFiles();
1833
2097
  if (!files.length) return await needsHuman(`Builder made no commit${result ? ` (status "${result.status}")` : " and wrote no result.json"}.\n\n${result?.summary ?? ""}`, OUTCOME_CODES.BUILDER_NO_COMMIT);
2098
+ await recheckStages(["implementation"]); // #5333
1834
2099
  await flushStages(result, ["implementation"]);
1835
2100
  T.implement = [`${files.length} file(s)`, branch];
1836
2101
  T.decisions.push(`Builder verdict: ${result?.status ?? "none"}`);
@@ -1868,16 +2133,20 @@ export async function runCore(o) {
1868
2133
  const { results, deferred } = round$;
1869
2134
  precheckMs += round$.ms; precheckDeferred += deferred.length;
1870
2135
  if (deferred.length) T.anomalies.push(`deferred-to-ci: pre-PR check budget ${totalMs / 1000} s reached; left to CI: ${deferred.map((c) => `\`${c}\``).join(", ")}`);
1871
- const roundFailed = results.some((r) => r.rc !== 0);
2136
+ const { failed, timedOut } = splitPrecheckResults(results); // #5332: rc 124 is host load, never a failing check
2137
+ const roundFailed = failed.length > 0 || timedOut.length > 0;
1872
2138
  ev({ event: "PRECHECK_COMMANDS", round, results: [...results.map(({ command, rc, ms }) => ({ command, rc, ms })), ...deferred.map((command) => ({ command, status: "deferred-to-ci" }))],
1873
- ms: round$.ms, parallelism, workers, ...(picked.source !== "learned" ? { source: picked.source } : {}), ...(roundFailed ? { self_check: await selfCheckNow() } : {}) });
2139
+ ms: round$.ms, parallelism, workers, ...(picked.source !== "learned" ? { source: picked.source } : {}), ...(roundFailed ? { self_check: timedOut.length ? "timed_out" : await selfCheckNow() } : {}) });
1874
2140
  verifyFacts.commands = results.map(({ command, rc }) => ({ command, rc }));
1875
- const failed = results.filter((r) => r.rc !== 0);
2141
+ const timedNames = timedOut.length ? timedOutDetail(timedOut, picked.perCommandMs) : "";
2142
+ if (timedOut.length) T.anomalies.push(`deferred-to-ci: pre-PR check timed out (host load, not a code failure); left to CI: ${timedNames}`);
2143
+ if (!failed.length && timedOut.length && (vcfg.precheckBlock || guardFailing(timedOut))) return await needsHuman(`Environment error (not a check failure): pre-PR check command(s) timed out even after one longer retry, which is host load rather than a failing check; no builder resume was spent, the branch is pushed and nothing merged: ${timedNames}`, ENV_VALIDATE_TIMEOUT);
1876
2144
  if (!failed.length) { checkCommandsFailing = false; if (round) T.decisions.push(`Declared check commands pass after ${round} builder fix round(s)`); await gatePassed("precheck"); break; }
1877
2145
  const names = failed.map((f) => `\`${f.command}\` (exit ${f.rc})`).join(", ");
1878
2146
  if (isSplit) return await needsHuman(`Declared check command(s) fail on the refactor:split move (no builder edits a split); nothing merged: ${names}`, OUTCOME_CODES.CI_RED);
1879
2147
  checkCommandsFailing = true;
1880
- if (round >= vcfg.maxRounds || !sessionId) { if (vcfg.precheckBlock) return await needsHuman(`Declared check command(s) still failing before the PR (verify.precheck_block); nothing merged: ${names}`, OUTCOME_CODES.CI_RED); T.anomalies.push(`Declared check command(s) still failing before the PR: ${names}`); break; }
2148
+ { const red = await guardRed(failed); if (red) return red; } // #5239: a guard that also fails on the base defers the lane
2149
+ if (round >= vcfg.maxRounds || !sessionId) { if (vcfg.precheckBlock || guardFailing(failed)) return await needsHuman(`Declared check command(s) still failing before the PR (verify.precheck_block); nothing merged: ${names}`, OUTCOME_CODES.CI_RED); T.anomalies.push(`Declared check command(s) still failing before the PR: ${names}`); break; }
1881
2150
  T.decisions.push(`Declared check command(s) failed: ${names}; builder resumed (round ${round + 1}/${vcfg.maxRounds})`);
1882
2151
  const before = String(await git(["rev-parse", "HEAD"])).trim();
1883
2152
  const capped = capLogs(failed.map((f) => ({ ...f, log: f.output }))).map((f) => ({ command: f.command, rc: f.rc, output: f.log }));
@@ -1891,7 +2160,7 @@ export async function runCore(o) {
1891
2160
  await fixRound("precheck", precheckFailurePrompt(quiet, vcfg.mode), [], "precheck", capped.map((f) => `${f.command}\n${f.output ?? ""}`).join("\n"));
1892
2161
  await upsertStage("implementation");
1893
2162
  result = (await readResult()) ?? result;
1894
- if (String(await git(["rev-parse", "HEAD"])).trim() === before) { if (vcfg.precheckBlock) return await needsHuman(`Declared check command(s) failing and the builder made no new commit for them (verify.precheck_block); nothing merged: ${names}`, OUTCOME_CODES.CI_RED); T.anomalies.push(`Declared check command(s) failing and the builder made no new commit for them: ${names}`); break; }
2163
+ if (String(await git(["rev-parse", "HEAD"])).trim() === before) { if (vcfg.precheckBlock || guardFailing(failed)) return await needsHuman(`Declared check command(s) failing and the builder made no new commit for them (verify.precheck_block); nothing merged: ${names}`, OUTCOME_CODES.CI_RED); T.anomalies.push(`Declared check command(s) failing and the builder made no new commit for them: ${names}`); break; }
1895
2164
  files = await changedFiles();
1896
2165
  }
1897
2166
  }
@@ -1951,10 +2220,20 @@ export async function runCore(o) {
1951
2220
  if (io.enumeratingMissing && !isSplit) {
1952
2221
  const missingNow = async () => unjustified((await io.enumeratingMissing({ cwd: wt, base }).catch(() => null)) ?? [], result?.not_members);
1953
2222
  let missing = await missingNow();
2223
+ if (missing.length) { // #5348: the detector names the list entry: write it, then re-check; a session only for the rest
2224
+ const m = await mech.applyEnumerating({ missing, cwd: wt });
2225
+ if (await mechCommit("enumerating", m.applied, m.applied.map((x) => x.test))) missing = await missingNow();
2226
+ }
1954
2227
  if (missing.length && sessionId) {
1955
2228
  ev({ event: "ENUMERATING_MISSING", count: missing.length });
1956
2229
  T.decisions.push(`Enumerating test(s) miss new symbol(s): ${missing.slice(0, 5).map((m) => `${m.symbol} → ${m.test}`).join(", ")}; builder resumed once`);
1957
- await fixRound("enumerating", missingEntriesPrompt(missing, vcfg.mode), [], "enumerating", missing.map((m) => `enumerating test ${m.test} misses new member \`${m.symbol}\``).join("\n"));
2230
+ // #5348: one narrow session per stage: pending duplicate-export and English-copy findings ride along (their gates re-check)
2231
+ const pend = [];
2232
+ if (io.duplicateExports && vcfg.duplicateExports !== false) { const d = await dupsResidual(); if (d.length) pend.push({ title: "Duplicate exports", text: duplicateExportsPrompt(d, vcfg.mode), files: d.flatMap((x) => [x.path, ...(x.others ?? [])]) }); }
2233
+ if (io.englishCopies) { const c = (await io.englishCopies({ cwd: wt, base }).catch(() => null)) ?? []; if (c.length) pend.push({ title: "English copies", text: i18nCopiesPrompt(c, vcfg.mode), files: c.map((x) => x.path) }); }
2234
+ const task = pend.length ? mergeNarrowTasks([{ title: "Enumerating tests", text: missingEntriesPrompt(missing, vcfg.mode) }, ...pend]) : missingEntriesPrompt(missing, vcfg.mode);
2235
+ if (pend.length) T.decisions.push(`Batched narrow fix: enumerating tests with ${pend.map((x) => x.title.toLowerCase()).join(", ")} in one session`);
2236
+ await fixRound("enumerating", String(task), [], "enumerating", missing.map((m) => `enumerating test ${m.test} misses new member \`${m.symbol}\``).join("\n") + pend.map((x) => `\n${x.text}`).join(""), { files: [...new Set([...missing.map((m) => m.test), ...pend.flatMap((x) => x.files)])] });
1958
2237
  await upsertStage("implementation");
1959
2238
  result = (await readResult()) ?? result;
1960
2239
  missing = await missingNow();
@@ -1967,16 +2246,32 @@ export async function runCore(o) {
1967
2246
  * sees its tip. #4386: the engine renumbers first (no builder, no session); the builder only when that is unsupported.
1968
2247
  * `laneRef`: the pre-merge lane head after a base-sync took the base side of sequence-only conflicts.
1969
2248
  */
2249
+ /** #5235: a renumber (hand-off or base-sync) reruns the frozen validates (one fix round on failure, then an anomaly) before the merge. */
2250
+ async function revalidateRenumbered(trigger) {
2251
+ if (!io.runCommand || !frozen?.validate?.length) return;
2252
+ const env = laneEnv();
2253
+ const runAll = () => revalidate({ validates: frozen.validate, runOne: async (v) => { const x = (await heavyStep("precheck", async () => (await runWithTimeoutRetry((timeoutMs) => io.runCommand({ command: resolveForgedockPaths(String(v.command), { exists: existsSync, checksCli: CHECKS_CLI, forgedockCli: FORGEDOCK_CLI }), cwd: wt, timeoutMs, env }), vcfg.precheckTimeoutSeconds * 1000)).r)) ?? {}; return { rc: x.rc, output: x.output }; } });
2254
+ let bad = await runAll();
2255
+ ev({ event: "SEQUENCE_REVALIDATED", trigger, failed: bad.map((x) => x.id) });
2256
+ if (bad.length && sessionId) {
2257
+ const log = bad.map((x) => `${x.id} (exit ${x.rc}): ${x.output.slice(-1500)}`).join("\n");
2258
+ const renumberTask = () => `The sequence renumber after ${trigger} changed the tree and these frozen validate commands now fail:\n${log}\n\nFix the cause (the renumber itself is correct), ${syncChecks(vcfg.mode)}, commit. Do not push.`; // called below so the #4362 trigger-literal check parses the call
2259
+ await fixRound("sequence", renumberTask(), [], "sequence", log);
2260
+ files = await changedFiles();
2261
+ bad = await runAll();
2262
+ }
2263
+ if (bad.length) T.anomalies.push(`Frozen validate(s) fail after the ${trigger} renumber: ${bad.map((x) => x.id).join(", ")}`);
2264
+ }
1970
2265
  async function sequenceHandoff(trigger, { laneRef = null } = {}) {
1971
2266
  if (!io.sequenceCheck || isSplit) return null;
1972
2267
  try { await git(["fetch", "origin", lane]); } catch { /* offline: use the local ref */ }
1973
- const collisions = (await io.sequenceCheck({ cwd: wt, base }).catch(() => null)) ?? [];
2268
+ const collisions = (await io.sequenceCheck({ cwd: wt, base, versioned: o.sequenceVersioned }).catch(() => null)) ?? [];
1974
2269
  if (!collisions.length) return null;
1975
2270
  const before = (await io.sequenceSnapshot?.({ cwd: wt, base }).catch(() => null)) ?? [];
1976
2271
  ev({ event: "SEQUENCE_COLLISION", trigger, files: collisions.map((c) => c.lane) });
1977
2272
  const taken = collisions.filter((c) => c.base.length).map((c) => `${c.lane} vs ${c.base.join(", ")}`).join("; ");
1978
2273
  if (io.sequenceRenumber) {
1979
- const renumber = async (ref) => (await io.sequenceRenumber({ cwd: wt, base, ...(ref ? { laneRef: ref } : {}), regenerate: o.sequenceRegenerate ?? null, reserve: io.sequenceLease?.reserve ? (x) => io.sequenceLease.reserve({ repo, lane, issue, ...x }) : null, openNumbers: io.sequenceOpenNumbers ? (x) => io.sequenceOpenNumbers({ cwd: wt, lane, ...x }) : null }).catch((e) => ({ unsupported: String(e?.message ?? e) }))) ?? { unsupported: "no result" };
2274
+ const renumber = async (ref) => (await io.sequenceRenumber({ cwd: wt, base, ...(ref ? { laneRef: ref } : {}), regenerate: o.sequenceRegenerate ?? null, versioned: o.sequenceVersioned ?? [], reserve: io.sequenceLease?.reserve ? (x) => io.sequenceLease.reserve({ repo, lane, issue, ...x }) : null, openNumbers: io.sequenceOpenNumbers ? (x) => io.sequenceOpenNumbers({ cwd: wt, lane, ...x }) : null }).catch((e) => ({ unsupported: String(e?.message ?? e) }))) ?? { unsupported: "no result" };
1980
2275
  let det = await renumber(laneRef);
1981
2276
  if (det.nonSequence?.length && !laneRef) { // #4732: base-sync first (sequence files take the base side, the builder resolves the rest), then renumber deterministically
1982
2277
  const pre = String(await git(["rev-parse", "HEAD"])).trim(), left = async () => String(await git(["diff", "--name-only", "--diff-filter=U"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean);
@@ -1994,10 +2289,11 @@ export async function runCore(o) {
1994
2289
  if (det.ok && det.moves?.length) {
1995
2290
  ev({ event: "SEQUENCE_RENUMBERED", trigger, mode: "deterministic", moves: det.moves });
1996
2291
  T.decisions.push(`Sequence number(s) taken on ${lane} (${trigger}): ${taken}; renumbered deterministically (no builder): ${det.moves.map((m) => `${m.from} → ${m.to}`).join(", ")}`);
1997
- const v = (await io.sequenceVerify?.({ cwd: wt, base, before, moves: det.moves }).catch(() => null)) ?? { ok: false, problems: ["renumber could not be verified"] };
2292
+ const v = (await io.sequenceVerify?.({ cwd: wt, base, before, moves: det.moves, versioned: o.sequenceVersioned }).catch(() => null)) ?? { ok: false, problems: ["renumber could not be verified"] };
1998
2293
  if (!v.ok) return { done: await needsHuman(`Sequence-numbered files still collide with ${lane} after the deterministic renumber (${trigger}); nothing merged:\n${v.problems.slice(0, 10).map((x) => `- ${x}`).join("\n")}`, OUTCOME_CODES.BASE_CONFLICT) };
1999
2294
  await gatePassed("sequence");
2000
2295
  files = await changedFiles();
2296
+ await revalidateRenumbered(trigger);
2001
2297
  return { renumbered: true, deterministic: true };
2002
2298
  }
2003
2299
  const why = det.unsupported ?? "no movable sequence file";
@@ -2007,10 +2303,11 @@ export async function runCore(o) {
2007
2303
  T.decisions.push(`Sequence number(s) taken on ${lane} (${trigger}): ${taken}; builder renumbers`);
2008
2304
  await fixRound("sequence", sequencePrompt(collisions, lane, vcfg.mode), [], "sequence", collisions.map((c) => `sequence number collision: ${c.lane} already taken by ${(c.base ?? []).join(", ")}`).join("\n"));
2009
2305
  result = (await readResult()) ?? result;
2010
- const v = (await io.sequenceVerify?.({ cwd: wt, base, before }).catch(() => null)) ?? { ok: false, problems: ["renumber could not be verified"] };
2306
+ const v = (await io.sequenceVerify?.({ cwd: wt, base, before, versioned: o.sequenceVersioned }).catch(() => null)) ?? { ok: false, problems: ["renumber could not be verified"] };
2011
2307
  if (!v.ok) return { done: await needsHuman(`Sequence-numbered files still collide with ${lane} after the builder renumbered (${trigger}); nothing merged:\n${v.problems.slice(0, 10).map((x) => `- ${x}`).join("\n")}`, OUTCOME_CODES.BASE_CONFLICT) };
2012
2308
  await gatePassed("sequence");
2013
2309
  files = await changedFiles();
2310
+ await revalidateRenumbered(trigger);
2014
2311
  return { renumbered: true };
2015
2312
  }
2016
2313
  { const sq = await sequenceHandoff("hand-off"); if (sq?.done) return sq.done; }
@@ -2019,13 +2316,14 @@ export async function runCore(o) {
2019
2316
  async function duplicateGate(trigger) {
2020
2317
  if (!io.duplicateExports || isSplit || vcfg.duplicateExports === false) return false;
2021
2318
  const found = async () => (await io.duplicateExports({ cwd: wt, base }).catch(() => null)) ?? [];
2022
- let dups = await found();
2319
+ let dups = await dupsResidual(); // #5348: the deterministic rename first
2320
+ const mech = dupMech > 0;
2023
2321
  if (dups.length && sessionId) {
2024
2322
  const text = dups.map((d) => `duplicate export \`${d.symbol}\`: ${d.path} and ${(d.others ?? []).join(", ")}`).join("\n");
2025
2323
  ev({ event: "DUPLICATE_EXPORTS", trigger, count: dups.length });
2026
2324
  T.decisions.push(`Duplicate export(s) (${trigger}): ${dups.slice(0, 5).map((d) => `${d.symbol} in ${d.path} vs ${(d.others ?? []).join(", ")}`).join("; ")}; builder resumed once`);
2027
2325
  engineWhy = `engine-demanded rename: duplicate export(s) ${dups.slice(0, 5).map((d) => d.symbol).join(", ")} (${trigger})`;
2028
- await fixRound("duplicate", duplicateExportsPrompt(dups, vcfg.mode), [], "duplicate", text);
2326
+ await fixRound("duplicate", duplicateExportsPrompt(dups, vcfg.mode), [], "duplicate", text, { files: dups.flatMap((d) => [d.path, ...(d.others ?? [])]) });
2029
2327
  result = (await readResult()) ?? result;
2030
2328
  files = await changedFiles();
2031
2329
  dups = await found();
@@ -2034,7 +2332,8 @@ export async function runCore(o) {
2034
2332
  return true;
2035
2333
  }
2036
2334
  if (dups.length) T.anomalies.push(`Duplicate export(s) (${trigger}): ${dups.slice(0, 5).map((d) => `${d.symbol} in ${d.path}`).join("; ")}`);
2037
- return false;
2335
+ else if (mech) await gatePassed("duplicate");
2336
+ return mech;
2038
2337
  }
2039
2338
  await duplicateGate("hand-off");
2040
2339
  /** #4591: lane-added migrations the repo's generator did not produce: one builder round (stage "sequence"), then an anomaly. */
@@ -2079,7 +2378,7 @@ export async function runCore(o) {
2079
2378
  await i18nGate("hand-off");
2080
2379
  /** #4406: verify.post_merge (else the scoped typecheck) on the merged tree before the base-sync push; fix rounds up to verify.max_rounds. */
2081
2380
  async function postMergeGate(trigger) {
2082
- const commands = io.runCommand && !isSplit ? postMergeCommands({ configured: vcfg.postMerge, scoped: (await io.postMergeChecks?.({ cwd: wt, base }).catch(() => [])) ?? [], mode: vcfg.mode }) : [];
2381
+ 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
2083
2382
  let fixed = false, results = [];
2084
2383
  for (let round = 0; commands.length; round++) {
2085
2384
  await renew();
@@ -2100,7 +2399,23 @@ export async function runCore(o) {
2100
2399
  fixed = true;
2101
2400
  if ((String(await git(["rev-parse", "HEAD"])).trim()) === before) { T.anomalies.push(`Post-merge check(s) failing and the builder made no new commit for them: ${names}`); break; }
2102
2401
  }
2103
- return { fixed, ran: results.map(({ command, rc }) => `${command}: ${rc === 0 ? "pass" : `fail (exit ${rc})`}`).join("; ") };
2402
+ return { fixed, stuck: results.filter((r) => r.rc !== 0 && guardFailing([r])), ran: results.map(({ command, rc }) => `${command}: ${rc === 0 ? "pass" : `fail (exit ${rc})`}`).join("; ") };
2403
+ }
2404
+ /** #5239: verify.invariants are the pre-merge guard set; blocking unless verify.guard_block is false. */
2405
+ function guardOn() { return vcfg.guardBlock !== false && (vcfg.invariants ?? []).length > 0; }
2406
+ function guardFailing(failed) { return guardOn() && failed.some((f) => vcfg.invariants.includes(f.command)); }
2407
+ /** #5239: guard commands failing here are run once on the base; failing there too, the lane is deferred (base.red) and the introducing issue is told. null: the failure is the lane's. */
2408
+ async function guardRed(failed) {
2409
+ const g = failed.filter((f) => guardFailing([f]));
2410
+ if (!g.length || isSplit || !io.runCommand) return null;
2411
+ 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 }));
2412
+ const { baseRed } = classifyBaseRed({ failed: g, baseRuns });
2413
+ if (!baseRed.length) return null;
2414
+ const att = await attributeBaseRed({ failed: baseRed, git, base });
2415
+ const cmds = baseRed.map((f) => f.command), n = await reportBaseRed({ ghc: ghw, repo, base, att, laneIssue: issue, commands: cmds });
2416
+ 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"}`);
2417
+ ev({ event: "BASE_RED", commands: cmds, sha: att?.sha ?? null, issue: att?.issue ?? null, tracked: n });
2418
+ 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);
2104
2419
  }
2105
2420
  const structureLine = structureNote(structure);
2106
2421
 
@@ -2117,6 +2432,7 @@ export async function runCore(o) {
2117
2432
  let fixes = 0;
2118
2433
  for (;;) {
2119
2434
  await untrackToolState({ git, base, ev, keep: await keepPaths() }); // #4621: gitPush's untrack commit would move HEAD after `head` was read; do it first so head is the pushed tip
2435
+ await reconcileLaneBranch(); // #5202: likewise the checkpoint reconcile merge
2120
2436
  await signOffUnpushed(); // #4651: likewise the sign-off rewrite
2121
2437
  const head = String(await git(["rev-parse", "HEAD"])).trim();
2122
2438
  if (head === ciVerifiedHead || ciFellBack) return { fixes };
@@ -2215,7 +2531,7 @@ export async function runCore(o) {
2215
2531
  let effective = frozen, review = null, lastAmend = "", resumes = 0, verdict = null, degraded = null, triggerSkipped = false, selfReviewCompared = false;
2216
2532
  const TRIGGER_SKIP = "skipped (review.trigger enforce: no risk trigger)";
2217
2533
  const triggerSkipNote = "## Conformance Review\n**Skipped by `review.trigger: enforce`:** no risk path, package edge or hotspot in the diff, and every deterministic gate passed; no reviewer ran (#4273).";
2218
- let pendingDecisions = [];
2534
+ let pendingDecisions = [], firstRounds = null, firstReply = null;
2219
2535
  let baseTree = null; // #4695: the base file list, read once and only when a decision amendment needs it
2220
2536
  let genPaths = null; // forge#4519: maintenance.generated_paths from hotspots.sh (plan facts; one config-only call without them, never on light lanes)
2221
2537
  async function amend() {
@@ -2245,26 +2561,30 @@ export async function runCore(o) {
2245
2561
  const diff = String(await git(["diff", `${base}...HEAD`]));
2246
2562
  const stat = Buffer.byteLength(diff, "utf-8") > REVIEW_DIFF_MAX_BYTES ? String(await git(["diff", "--stat=200", `${base}...HEAD`]).catch(() => "")) : "";
2247
2563
  const listed = new Set(String(await git(["ls-files"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean));
2248
- const ctx = { contract: effective, changedFiles: files, issueText, pathExists: (x) => listed.has(x), repoFiles: listed, ignore: IGNORE, e2e: { checks: vcfg.e2e?.checks ?? [], isSpec: (x) => e2eSpecs([x], vcfg.e2e).length > 0 } };
2564
+ // #5339: validate-command paths that fake the real path (mocks, fakes, stubs): they cannot verify an e2e/manual requirement
2565
+ const cmdPaths = [...new Set((effective.validate ?? []).flatMap((v) => String(v.command ?? "").split(/\s+/)).map((t) => t.replace(/^["']+|["']+$/g, "")).filter((t) => listed.has(t)))];
2566
+ const ctx = { contract: effective, changedFiles: files, issueText, pathExists: (x) => listed.has(x), repoFiles: listed, ignore: IGNORE, e2e: { faked: fakedPaths(cmdPaths, (x) => readFileSync(join(wt, x), "utf8")), checks: vcfg.e2e?.checks ?? [], isSpec: (x) => e2eSpecs([x], vcfg.e2e).length > 0 } };
2249
2567
  let d = null, first = null;
2250
2568
  for (let t = 0; t < 3; t++) {
2251
2569
  // #4327/#5164: a third run only when the repaired reply is incomplete solely by reviewer slips (unresolved evidence paths, coverage misquotes).
2252
2570
  if (t === 2) {
2253
2571
  if (d.state !== "review.incomplete" || !reaskable(d.failures.map((f) => f.detail))) break;
2254
- T.decisions.push(`Review incomplete only by unresolved evidence paths or coverage misquotes (${(d.missing ?? []).join(", ")}); reviewer re-asked once more`);
2572
+ T.decisions.push(`Review incomplete only by row gaps, unresolved evidence paths or coverage misquotes (${(d.missing ?? []).join(", ")}); reviewer re-asked once more`);
2255
2573
  }
2256
2574
  // #4160: a reply with rows missing is re-asked for those ids only; an unparseable one gets the full prompt again.
2257
2575
  const repair = first && (d.state === "review.incomplete" || d.state === "review.inconsistent");
2258
2576
  await renew();
2259
2577
  const rr = await callRunner({ role: "reviewer", issue, cwd: wt, model: reviewerModel, resume: null, system: REVIEWER_SYSTEM, readOnly: true,
2260
2578
  prompt: repair ? reviewerRepairPrompt({ missing: d.missing ?? [], problems: d.failures.map((f) => f.detail), rows: first, criteria: (d.missing ?? []).includes("issue_coverage") ? criterionLines(issueText) : [] })
2261
- : reviewerPrompt({ issue: iss, comments: trustedComments, contract: effective, result, files, diff, stat, base, structure: structureLine, ignore: IGNORE, domains, investigationVerdict: investigationVerdict(await io.fs.read(`${wt}/.forge-lean/investigation.md`).catch(() => null)) }) });
2579
+ : reviewerPrompt({ issue: iss, comments: trustedComments, contract: effective, result, files, diff, stat, base, structure: structureLine, ignore: IGNORE, domains, relaxations, investigationVerdict: investigationVerdict(await io.fs.read(`${wt}/.forge-lean/investigation.md`).catch(() => null)) }) });
2262
2580
  await renew();
2263
2581
  await attempt("review", ++reviewN, rr, null, "review");
2264
2582
  const parsed = parseReview(rr?.text);
2265
2583
  review = repair ? mergeReviewRows(first, parsed) : parsed;
2266
2584
  first = review;
2267
2585
  d = decide(review, ctx);
2586
+ if (d.converted?.length) effective = convertDelivered(effective, d.converted); // #5365: a defer row the review found delivered is judged as deliver
2587
+ firstReply ??= d.state;
2268
2588
  if (d.review) review = d.review;
2269
2589
  ev({ event: "CONFORMANCE", round: reviewN, state: d.state, failures: d.failures.map((x) => x.code), mode: shadow ? "shadow" : "enforce" });
2270
2590
  const cmp = selfReviewCompared ? null : compareSelfReview(readSelfReview(result), d); // #4374: once, on the first judgement
@@ -2283,7 +2603,7 @@ export async function runCore(o) {
2283
2603
  const head = String(await git(["rev-parse", "HEAD"])).trim();
2284
2604
  if (verifiedHeads.has(head)) return verifiedHeads.get(head);
2285
2605
  const diff = String(await git(["diff", `${base}...HEAD`]));
2286
- const run = { mode: verifierCfg.mode, head, findings: [], model: null, swapped: false, cost_usd: 0 };
2606
+ const run = { mode: relaxations.length ? "enforce" : verifierCfg.mode, head, findings: [], model: null, swapped: false, cost_usd: 0 };
2287
2607
  if (!diff.trim()) run.skipped = "empty_diff";
2288
2608
  else {
2289
2609
  const bytes = Buffer.byteLength(diff, "utf-8");
@@ -2295,7 +2615,7 @@ export async function runCore(o) {
2295
2615
  try {
2296
2616
  await renew();
2297
2617
  const rr = await callRunner({ role: "verifier", issue, cwd: wt, model: run.model, resume: null, system: VERIFIER_SYSTEM, readOnly: true, maxMs, maxTurns,
2298
- prompt: verifierPrompt({ issue: iss, comments: trustedComments, contract: effective, diff, stat, base, files, callers }) });
2618
+ prompt: verifierPrompt({ issue: iss, comments: trustedComments, contract: effective, diff, stat, base, files, callers, relaxations }) });
2299
2619
  await renew();
2300
2620
  await attempt("verify", ++verifyN, rr, null, "verifier");
2301
2621
  run.findings = parseVerifierFindings(rr?.text, { pathExists: (x) => listed.has(x) });
@@ -2306,7 +2626,7 @@ export async function runCore(o) {
2306
2626
  T.anomalies.push(`Independent verifier failed at ${head.slice(0, 12)}: ${run.error}`);
2307
2627
  }
2308
2628
  }
2309
- const failures = verifierCfg.mode === "enforce" ? findingsToFailures(run.findings) : [];
2629
+ const failures = run.mode === "enforce" ? findingsToFailures(run.findings) : [];
2310
2630
  ev({ event: "VERIFIER", mode: run.mode, head, model: run.model, swapped: run.swapped, findings: run.findings.length, cost_usd: run.cost_usd, implement_cost_usd: impl.cost,
2311
2631
  ratio: impl.cost > 0 ? Math.round((run.cost_usd / impl.cost) * 1000) / 1000 : null, ...(run.skipped ? { skipped: run.skipped } : {}), ...(run.error ? { error: run.error } : {}) });
2312
2632
  if (run.findings.length) T.decisions.push(`Independent verifier (${run.mode}) found ${run.findings.length} defect(s): ${run.findings.slice(0, 3).map((f) => `${f.file}:${f.line}`).join(", ")}`);
@@ -2376,6 +2696,14 @@ export async function runCore(o) {
2376
2696
  const cfg = readRollouts(wt);
2377
2697
  return cfg ? detectNewOffKeys(cfg, String(await git(["diff", "-U0", `${base}...HEAD`, "--", ...cfg.files]).catch(() => ""))) : [];
2378
2698
  }
2699
+ /** #5285: interactive UI files changed, whether a real-browser (e2e) check is configured for them, and whether a declared risk path is hit. */
2700
+ function uiBrowserOf(fs) {
2701
+ const ui = uiInteractiveChanged(fs);
2702
+ if (!ui.length) return null;
2703
+ const want = e2eWanted({ cfg: vcfg.e2e, files: fs, contract: effective });
2704
+ if (!want.run) T.decisions.push(`Real-browser check skipped for interactive UI change (${ui.slice(0, 3).join(", ")}): ${want.reason} (#5285)`);
2705
+ return { files: ui, ran: want.run, reason: want.reason, highRisk: riskPathHits(ui, riskPaths).length > 0 };
2706
+ }
2379
2707
  let amendFixed = false;
2380
2708
  async function gate() {
2381
2709
  await refreshIssue("conformance");
@@ -2421,6 +2749,9 @@ export async function runCore(o) {
2421
2749
  const [{ runs: validateRuns, subs: substitutedRuns }, guardFailures] = await Promise.all([validatePhase, guardGate(files)]);
2422
2750
  // #5087: forge.yaml topology.route_reachability gates the route handlers this diff adds; unset = no check
2423
2751
  const routeFailures = routeReachability && io.runCommand ? await routeReachabilityFailures({ command: routeReachability, paths: routePathsFromFiles(String(await git(["diff", "--name-only", "--diff-filter=A", `${base}...HEAD`]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean)), run: async ({ command }) => (await io.runCommand({ command, cwd: wt, timeoutMs: vcfg.precheckTimeoutSeconds * 1000, env: laneEnv() }).then((x) => x?.r ?? x)) ?? { rc: 127 } }) : [];
2752
+ // #5284: forge.yaml topology.prod_parity: declared production-only surfaces this diff touches need a check result or a justification
2753
+ const parityRules = parseProdParity(prodParity);
2754
+ const prodParityFailures = parityRules.length && io.runCommand ? await prodParityOf({ rules: parityRules, changedFiles: files, result, run: async ({ command }) => (await io.runCommand({ command, cwd: wt, timeoutMs: vcfg.precheckTimeoutSeconds * 1000, env: laneEnv() }).then((x) => x?.r ?? x)) ?? { rc: 127 } }) : [];
2424
2755
  // #4705: only the part not hidden behind the validate rerun; 0 when the gate errored or skipped
2425
2756
  const guardRunMs = guardEv && !guardEv.error ? Math.max(0, now() - gateT0 - validateMs) : 0;
2426
2757
  guardAddedMs += guardRunMs;
@@ -2430,7 +2761,14 @@ export async function runCore(o) {
2430
2761
  const checkIds = effective.requirements?.some((r) => r.disposition === "post-deploy") ? new Set(Object.keys(await checksAt(git, [base, "HEAD"], wt))) : null;
2431
2762
  const removedPaths = (effective.validate ?? []).some((v) => v.substituted) ? await removedPathsOf(git, base) : []; // #4990
2432
2763
  const subBaseFiles = (effective.validate ?? []).some((v) => v.substituted) ? String(await git(["ls-tree", "-r", "-z", "--name-only", base]).catch(() => "")).split("\0").filter(Boolean) : []; // #5003
2433
- const pc = precheck({ contract: effective, result, changedFiles: files, ignore: IGNORE, ciVerified, hotspots, repro: await reproOf(effective), validateRuns, repoHas, frozen, checkIds, guardFailures, coupledFailures: await coupledOf(files), routeFailures, newOffKeys: await newOffKeysOf(), substitutedRuns, removedPaths, baseFiles: subBaseFiles });
2764
+ const rx = await relaxationsOf(files); // #5237
2765
+ relaxations = rx.relaxations;
2766
+ if (relaxations.length) {
2767
+ ev({ event: "RELAXATION_DETECTED", files: [...new Set(relaxations.map((r) => r.file))], count: relaxations.length, negatives: rx.negatives });
2768
+ const note = `Relaxation in a declared risk path (${[...new Set(relaxations.map((r) => r.file))].slice(0, 5).join(", ")}): negative tests added ${rx.negatives}; independent verifier enforced`;
2769
+ if (!T.decisions.includes(note)) T.decisions.push(note);
2770
+ }
2771
+ const pc = precheck({ contract: effective, result, changedFiles: files, ignore: IGNORE, ciVerified, hotspots, repro: await reproOf(effective), validateRuns, repoHas, frozen, checkIds, guardFailures, coupledFailures: await coupledOf(files), relaxationFailures: relaxationFailures(rx), routeFailures, prodParityFailures, newOffKeys: await newOffKeysOf(), uiBrowser: uiBrowserOf(files), substitutedRuns, removedPaths, baseFiles: subBaseFiles });
2434
2772
  // #4350: a scope-check validate stale only by amended deliverables is judged by the engine's scope gate instead
2435
2773
  if (pc.superseded?.length) {
2436
2774
  ev({ event: "VALIDATE_SUPERSEDED", runs: pc.superseded });
@@ -2488,7 +2826,7 @@ export async function runCore(o) {
2488
2826
  }
2489
2827
  let d = await reviewOnce();
2490
2828
  // #4397: the verifier runs only on a change every gate and the reviewer passed; in enforce its findings block
2491
- if (verifierCfg.mode !== "off" && d.state === "conforms" && !pre.length) {
2829
+ if ((verifierCfg.mode !== "off" || relaxations.length) && d.state === "conforms" && !pre.length) { // #5237: a relaxation lane always gets the independent second look
2492
2830
  const vf = await runVerifier();
2493
2831
  if (vf.length) d = { state: "nonconforming", failures: vf, by: "verifier" };
2494
2832
  }
@@ -2528,7 +2866,7 @@ export async function runCore(o) {
2528
2866
  async function envNeedsHuman(failures) {
2529
2867
  if (failures.every((f) => f.code === OUTCOME_CODES.ENV_REPRO_UNRUNNABLE)) {
2530
2868
  T.anomalies.push("Environment error: the repro harness could not run the repro test on head");
2531
- return await needsHuman(`Environment error (not a conformance failure): the repro harness could not run the repro test on head; no builder resume was spent and nothing merged:\n${failures.map((f) => `- ${f.code}: ${f.detail}`).join("\n")}\n\nRun the repro command through the repo's own toolchain and installed dependencies, then rerun.`, OUTCOME_CODES.ENV_REPRO_UNRUNNABLE);
2869
+ return await needsHuman(`Environment error (not a conformance failure): the repro harness could not run the repro test on head; no builder resume was spent and nothing merged:\n${failures.map((f) => `- ${f.code}: ${f.detail}`).join("\n")}\n\nEnvironment defect: run the repro command above on the host with the project's real dependencies (its lockfile or toolchain), then rerun.`, OUTCOME_CODES.ENV_REPRO_UNRUNNABLE);
2532
2870
  }
2533
2871
  if (failures.every((f) => f.code === ENV_VALIDATE_TIMEOUT)) { // #4906: the teardown below pushes the lane's commits, so CI and recovery still see them
2534
2872
  T.anomalies.push("Environment error: a validate command timed out on the engine's rerun (infra, exit 124)");
@@ -2559,11 +2897,18 @@ export async function runCore(o) {
2559
2897
  if (remoteVerify) { const v = await ciVerify("build"); if (v.done) return v.done; }
2560
2898
  const outcome = await gate();
2561
2899
  verdict = outcome;
2900
+ (firstRounds ??= []).push({ state: outcome.state, failures: (outcome.failures ?? []).map((f) => f?.code) });
2901
+ firstReview = firstReviewRecord({ rounds: firstRounds, firstReply, labels: iss?.labels, files });
2562
2902
  for (const f of [...(outcome.failures ?? []), ...(outcome.wouldFail ?? [])]) if (f?.code) failureClasses.add(f.code);
2563
2903
  if (outcome.state === "conforms") { await gatePassed("conformance"); break; }
2564
2904
  const explained = explainFailures(outcome.failures, effective); // #4265: name the unmet requirement, not only the code
2565
2905
  const list = explained.slice(0, 15).map((f) => `- ${f.code}: ${f.detail}`).join("\n");
2566
2906
  if (outcome.state === "environment") return await envNeedsHuman(outcome.failures);
2907
+ // #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
2908
+ if (o.placement?.where === "remote" && !recover && outcome.failures?.length && outcome.failures.every((f) => f?.kind === "validate_failed")) {
2909
+ T.anomalies.push("Remote validate failure: rerun on the host in a local recovery lane before it is terminal");
2910
+ 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);
2911
+ }
2567
2912
  if (outcome.state === "already-fixed") { // #5080: close as delivered, citing the base commit
2568
2913
  const sha = String(await git(["rev-parse", base]).catch(() => "")).trim().slice(0, 12) || base;
2569
2914
  const note = `Already fixed on the base: the repro test passes on \`${base}\` (${sha}) without this change, and the diff changes no source file. Closing as delivered.\n\n${list}`;
@@ -2590,7 +2935,7 @@ export async function runCore(o) {
2590
2935
  // Deferrals the reviewer accepted are filed now, before any PR: the batched follow-up must exist and be linked.
2591
2936
  const toFile = pendingTracking(effective);
2592
2937
  if (toFile.length) await track(toFile, "accepted by the conformance review");
2593
- degradedReq = degraded ? { id: "REVIEW", quote: `conformance review ${degraded.state}: re-run the review`, disposition: "defer", why: `${REVIEW_DEGRADED_LABEL}: rows still missing for ${degraded.missing.join(", ") || "the verdict"}` } : null;
2938
+ degradedReq = degraded ? { id: "REVIEW", quote: `conformance review ${degraded.state}: re-run the review`, disposition: "defer", class: "ops", why: `${REVIEW_DEGRADED_LABEL}: rows still missing for ${degraded.missing.join(", ") || "the verdict"}` } : null;
2594
2939
  if (degradedReq) await track([degradedReq], "the conformance review stayed incomplete");
2595
2940
  if (triggerSkipped) {
2596
2941
  T.decisions.push("Conformance reviewer skipped by review.trigger enforce: no trigger reason (risk path, package edge, hotspot, failed or ambiguous gate)");
@@ -2614,11 +2959,27 @@ export async function runCore(o) {
2614
2959
  }
2615
2960
  }
2616
2961
  ev({ event: "PHASE_COMMIT", phase: "review" });
2617
- const closing = closePlan(effective, { title: iss.title, review });
2618
- if (closing.reason === "partial") { // #4398: an investigation whose question is not answered carries it forward
2962
+ // #5240: a delivered change behind a rollout that is not live (shadow/off) is inert in production: say so, never claim the outcome
2963
+ const rcfg = readRollouts(wt);
2964
+ const modes = rcfg ? rolloutModes(rcfg, files, (f) => readFileSync(join(wt, f), "utf8")) : [];
2965
+ const inert = modes.filter((m) => !m.live);
2966
+ const liveBlocks = liveDeferralBlocks(effective, modes); // #5285
2967
+ const closing = closePlan(effective, { title: iss.title, review, issueText, liveBlocks });
2968
+ if (closing.liveBlocked) T.decisions.push(`Default-on rollout with live acceptance deferred (${liveBlocks.map((b) => `${b.id} on ${b.flag}`).join(", ")}): issue left open as partial (#5285)`);
2969
+ if (inert.length) T.decisions.push(`Inert in production: the change touches rollout ${inert.map((m) => `${m.flag} (mode ${m.mode})`).join(", ")}; the issue's production outcome is not claimed (#5240)`);
2970
+ const xfer = closing.transfer ?? closing.open; // #5382: a liveBlocked plan carries its transferred rows apart from the live-blocked ones
2971
+ if (closing.transferred) { // #5339: unrun e2e/manual requirements go to the epic's acceptance; the issue records them transferred, not met
2972
+ let epicNo = null;
2973
+ try { epicNo = await transferToEpic({ io: { gh: ghc }, repo, milestoneTitle: milestone, issue, reqs: xfer }); } catch (e) { T.anomalies.push(`transfer to the epic failed: ${String(e?.message ?? e).slice(0, 120)}`); }
2974
+ for (const r of xfer) r.transferred = epicNo ?? false;
2975
+ T.decisions.push(epicNo ? `Requirements ${xfer.map((r) => r.id).join(", ")} transferred to epic #${epicNo} (post-deploy journey): not met, issue left open as partial (#5339)` : `Requirements ${xfer.map((r) => r.id).join(", ")} need a real run and no epic exists to take them: issue left open as partial (#5339)`);
2976
+ }
2977
+ verifiedLane = !closing.transferred && !closing.liveBlocked && !closing.checklist;
2978
+ if (closing.checklist) T.decisions.push(`Unticked acceptance criteria unmet (${closing.open.map((r) => r.id).join(", ")}): issue left open as partial (#5240)`);
2979
+ if (closing.reason === "partial" && !closing.checklist && !closing.transferred) { // #4398: an investigation whose question is not answered carries it forward
2619
2980
  const untracked = closing.open.filter((r) => !r.tracked);
2620
2981
  if (untracked.length) {
2621
- const carried = untracked.map((r) => ({ ...r, disposition: "defer", why: "investigation question not answered" }));
2982
+ const carried = untracked.map((r) => ({ ...r, disposition: "defer", class: "ops", why: "investigation question not answered" })); // #5207: the batch aggregate
2622
2983
  await track(carried, "the investigation's question is not answered");
2623
2984
  for (const [i, r] of untracked.entries()) r.tracked = carried[i].tracked;
2624
2985
  }
@@ -2756,6 +3117,7 @@ export async function runCore(o) {
2756
3117
  let pm = { fixed: false, ran: "" }, dupFixed = false;
2757
3118
  if ((await gitOut(["rev-parse", "HEAD"])) !== before) { // #4406: the merged tree, before the push
2758
3119
  pm = await postMergeGate(`base-sync ${syncs}`);
3120
+ if (pm.stuck?.length) return (await guardRed(pm.stuck)) ?? await needsHuman(`Guard command(s) still fail on the merged tree after ${base} was merged in (${pm.stuck.map((f) => f.command).join(", ")}); nothing merged.`, OUTCOME_CODES.CI_RED); // #5239
2759
3121
  if (pm.ran) tests = clean ? pm.ran : `${tests}; post-merge: ${pm.ran}`;
2760
3122
  if (pm.fixed) how += "; builder fixed post-merge check failures";
2761
3123
  dupFixed = await duplicateGate(`base-sync ${syncs}`);
@@ -3002,7 +3364,7 @@ export async function runCore(o) {
3002
3364
  }
3003
3365
  if (seqLease) {
3004
3366
  try { await git(["fetch", "origin", lane]); } catch { /* offline: use the local ref */ }
3005
- const late = (await io.sequenceCheck({ cwd: wt, base }).catch(() => null)) ?? [];
3367
+ const late = (await io.sequenceCheck({ cwd: wt, base, versioned: o.sequenceVersioned, extraBases: defaults.filter((d) => d && `origin/${d}` !== base).map((d) => `origin/${d}`) }).catch(() => null)) ?? [];
3006
3368
  if (late.length) {
3007
3369
  ev({ event: "SEQUENCE_LATE_BIND", pr, files: late.map((c) => c.lane) });
3008
3370
  const r = await baseSync("merge gate: sequence number taken"); if (r) return r;
@@ -3074,9 +3436,17 @@ export async function runCore(o) {
3074
3436
  }
3075
3437
  }
3076
3438
  const partial = closing.reason === "partial";
3439
+ if (closing.checklist || closing.liveBlocked || closing.transferred) keepOpen = true; // #5339: a transferred e2e/manual requirement is not met; // #5240: an unmet acceptance checkbox is not closed as completed; #5285: nor a default-on change with live acceptance deferred
3440
+ if (closing.liveBlocked) { // #5285: post what blocks the close
3441
+ 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 */ }
3442
+ }
3077
3443
  // #5152: a merged change is `completed` even when partial: the remainder is tracked (FORGE:TRACKED), not dropped
3078
3444
  if (!keepOpen) await ghw(["issue", "close", String(issue), "-R", repo, "--reason", "completed"]).catch(() => {});
3079
- if (keepOpen) { // #5159: the issue is not closed while a follow-up is pending, so the note must not say it is
3445
+ if (closing.transferred) { // #5339: record what is transferred, not met
3446
+ 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 */ }
3447
+ } 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
3448
+ try { await post("FORGE:TRACKED", `## 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(", ")}.` : ""}${inert.length ? `\n\nInert in production: the change takes effect only behind ${inert.map((m) => `\`${m.flag}\` (mode: ${m.mode})`).join(", ")}; the production outcome is not claimed.` : ""}`); } catch { /* the PR body and FORGE:STATE carry them */ }
3449
+ } else if (keepOpen) { // #5159: the issue is not closed while a follow-up is pending, so the note must not say it is
3080
3450
  if (partial || closing.tracked.length) try { await post("FORGE:TRACKED", `## Left open: follow-up pending\nMerged by PR #${pr}; the issue stays open until the pending follow-up is filed (FORGE:FOLLOWUP_PENDING).${partial ? " The investigation's stated question is not answered in this change." : ""}${closing.tracked.length ? ` Already tracked in ${closing.tracked.join(", ")}.` : ""}`); } catch { /* the PR body links them too */ }
3081
3451
  } else if (partial) {
3082
3452
  try { await post("FORGE:TRACKED", `## Closed as partial\nClosed as completed by PR #${pr}; the investigation's stated question is not answered in this change and is carried forward in ${closing.tracked.join(", ")}.`); } catch { /* the PR body links them too */ }
@@ -3092,6 +3462,7 @@ export async function runCore(o) {
3092
3462
  } catch (e) { T.anomalies.push(`refactor:split chain issue not filed (the maintenance scan re-files the hotspot): ${String(e?.message ?? e).slice(0, 200)}`); }
3093
3463
  }
3094
3464
  await label("merged");
3465
+ if (!keepOpen) { const f = await resolveFindingLabel({ io, issue, labels: iss.labels, reason: "merged" }); if (f.error) T.anomalies.push(`finding label not resolved: ${f.error}`); } // #5254
3095
3466
  try { // #4695/#4737: FORGE:DECISION records and supersession are persisted only after the merge
3096
3467
  const rec = await recordDecisions(pendingDecisions, { issue, repo, post });
3097
3468
  if (rec.length) T.decisions.push(`FORGE:DECISION: ${rec.map((d) => d.id).join(", ")}`);
@@ -3110,7 +3481,7 @@ export async function runCore(o) {
3110
3481
  const when = e.resetAt || (Number.isFinite(e.resetAtEpochMs) ? new Date(e.resetAtEpochMs).toISOString() : "unknown");
3111
3482
  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);
3112
3483
  }
3113
- 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.deferCode); // #5168: backendId keys the account hold
3484
+ if (e?.deferCode) return finish("deferred", e.deferDetail ?? String(e.message), { code: e.deferCode, ...(e.retryInSeconds ? { retryInSeconds: e.retryInSeconds } : {}), ...(e.backendId ? { backendId: e.backendId } : {}), ...quotaFacts(e) }, e.deferCode); // #5168: backendId keys the account hold; #5236 reset
3114
3485
  // #4505: a turn overrun is mechanical: a non-human end the batch recovers, needs-human only once a budget recovery failed too
3115
3486
  if (e?.laneCode === OUTCOME_CODES.BUDGET_EXCEEDED && !(recover?.final && recover.code === OUTCOME_CODES.BUDGET_EXCEEDED)) {
3116
3487
  return finish("budget-exceeded", e.message, { code: OUTCOME_CODES.BUDGET_EXCEEDED, branch, ...(recover ? { recovery: true } : {}) }, OUTCOME_CODES.BUDGET_EXCEEDED);
@@ -3124,6 +3495,8 @@ export async function runCore(o) {
3124
3495
  let owner = null;
3125
3496
  try { owner = await otherLaneOwner({ gh: (a) => ghc(a), repo, issue, branch, selfId: agentId, ownPr: Number(/#(\d+)/.exec(String(T.pr?.[0] ?? ""))?.[1]) || null }); } catch { /* fail-open */ }
3126
3497
  if (owner) return finish("deferred", `git push was rejected (non-fast-forward): ${owner.detail}; another lane owns ${branch}`, { code: OUTCOME_CODES.LEASE_HELD, branch }, OUTCOME_CODES.LEASE_HELD);
3498
+ // #5202: the lane's own history diverged from origin/<branch> (not reconcilable checkpoints): mechanical, never needs-human
3499
+ return finish("engine-error", `git push was rejected (non-fast-forward) and no other lane owns ${branch}: ${String(e?.stderr ?? e?.message ?? e).slice(0, 400)}`, { code: OUTCOME_CODES.ENGINE_PUSH_DIVERGED, branch }, OUTCOME_CODES.ENGINE_PUSH_DIVERGED);
3127
3500
  }
3128
3501
  if (e?.pushRejected) return await needsHuman(`git push was rejected (no retry): ${String(e?.stderr ?? e?.message ?? e).slice(0, 400)}`);
3129
3502
  if (e?.engineCode) return finish("engine-error", e?.message ?? String(e), { code: e.engineCode }, e.engineCode); // #4997