forgedock 1.53.0 → 1.54.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) 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 +258 -0
  6. package/bin/auth/app-token.test.mjs +240 -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 +6 -3
  12. package/bin/engine/telemetry-seam.mjs +8 -2
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +57 -20
  15. package/bin/first-run.mjs +122 -0
  16. package/bin/forgedock.mjs +128 -146
  17. package/bin/help-text.mjs +144 -0
  18. package/bin/hooks/pre-tool-use.mjs +7 -0
  19. package/bin/journey.mjs +82 -83
  20. package/bin/lean/acceptance.mjs +313 -0
  21. package/bin/lean/acceptance.test.mjs +215 -0
  22. package/bin/lean/activation.mjs +18 -0
  23. package/bin/lean/activation.test.mjs +23 -1
  24. package/bin/lean/batch-health.mjs +74 -1
  25. package/bin/lean/batch-health.test.mjs +54 -1
  26. package/bin/lean/batch.test.mjs +11 -9
  27. package/bin/lean/branchlock.mjs +54 -0
  28. package/bin/lean/branchlock.test.mjs +49 -0
  29. package/bin/lean/ceiling.mjs +72 -0
  30. package/bin/lean/ceiling.test.mjs +54 -0
  31. package/bin/lean/ci-budget.mjs +366 -0
  32. package/bin/lean/ci-budget.test.mjs +167 -0
  33. package/bin/lean/conformance.e2e.test.mjs +7 -0
  34. package/bin/lean/conformance.mjs +77 -19
  35. package/bin/lean/conformance.test.mjs +129 -3
  36. package/bin/lean/context.mjs +35 -6
  37. package/bin/lean/context.test.mjs +27 -1
  38. package/bin/lean/depcache.mjs +25 -1
  39. package/bin/lean/depcache.test.mjs +26 -0
  40. package/bin/lean/e2e.mjs +18 -2
  41. package/bin/lean/e2e.test.mjs +26 -1
  42. package/bin/lean/effects.mjs +40 -11
  43. package/bin/lean/execution.test.mjs +24 -0
  44. package/bin/lean/facts.mjs +3 -3
  45. package/bin/lean/facts.test.mjs +5 -0
  46. package/bin/lean/fixround.mjs +14 -0
  47. package/bin/lean/fixround.test.mjs +25 -2
  48. package/bin/lean/gh-assoc.test.mjs +2 -1
  49. package/bin/lean/integration.mjs +100 -9
  50. package/bin/lean/integration.test.mjs +98 -0
  51. package/bin/lean/issuewatch-parity.mjs +64 -0
  52. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  53. package/bin/lean/issuewatch-release.test.mjs +1 -1
  54. package/bin/lean/issuewatch.mjs +34 -5
  55. package/bin/lean/issuewatch.test.mjs +3 -2
  56. package/bin/lean/lean.mjs +316 -74
  57. package/bin/lean/lean.test.mjs +397 -24
  58. package/bin/lean/mechfix.mjs +136 -0
  59. package/bin/lean/mechfix.test.mjs +95 -0
  60. package/bin/lean/orchestrate.mjs +20 -2
  61. package/bin/lean/phaseledger.mjs +47 -5
  62. package/bin/lean/phaseledger.test.mjs +30 -1
  63. package/bin/lean/precheck.mjs +23 -4
  64. package/bin/lean/precheck.test.mjs +14 -1
  65. package/bin/lean/prereq.mjs +28 -0
  66. package/bin/lean/prereq.test.mjs +20 -0
  67. package/bin/lean/probe.mjs +4 -2
  68. package/bin/lean/prodparity.mjs +52 -0
  69. package/bin/lean/prodparity.test.mjs +67 -0
  70. package/bin/lean/prompts.mjs +69 -12
  71. package/bin/lean/recovery.test.mjs +1 -1
  72. package/bin/lean/release-io.test.mjs +42 -0
  73. package/bin/lean/release-postmerge.mjs +6 -0
  74. package/bin/lean/release-preflight.mjs +58 -0
  75. package/bin/lean/release-preflight.test.mjs +114 -0
  76. package/bin/lean/release-rehearsal.mjs +8 -7
  77. package/bin/lean/release-review.mjs +67 -11
  78. package/bin/lean/release-review.test.mjs +128 -1
  79. package/bin/lean/release-snapshot.mjs +188 -0
  80. package/bin/lean/release-snapshot.test.mjs +190 -0
  81. package/bin/lean/release.mjs +87 -13
  82. package/bin/lean/release.test.mjs +104 -0
  83. package/bin/lean/render.mjs +1 -1
  84. package/bin/lean/replan.mjs +184 -0
  85. package/bin/lean/replan.test.mjs +110 -0
  86. package/bin/lean/resume.mjs +9 -7
  87. package/bin/lean/resume.test.mjs +16 -0
  88. package/bin/lean/schedd.mjs +34 -1
  89. package/bin/lean/schedd.test.mjs +21 -1
  90. package/bin/lean/selfreview.mjs +94 -0
  91. package/bin/lean/selfreview.test.mjs +58 -1
  92. package/bin/lean/selftest-gate.mjs +22 -0
  93. package/bin/lean/selftest-gate.test.mjs +18 -1
  94. package/bin/lean/selftest-journey.mjs +234 -0
  95. package/bin/lean/selftest-journey.test.mjs +130 -0
  96. package/bin/lean/selftest-live.mjs +2 -1
  97. package/bin/lean/seqlease.mjs +35 -1
  98. package/bin/lean/seqlease.test.mjs +15 -0
  99. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  100. package/bin/lean/seqreserve.mjs +73 -0
  101. package/bin/lean/seqreserve.test.mjs +134 -0
  102. package/bin/lean/sequence.mjs +35 -6
  103. package/bin/lean/seqversioned.mjs +147 -0
  104. package/bin/lean/stagestamp.mjs +28 -0
  105. package/bin/lean/stagestamp.test.mjs +32 -0
  106. package/bin/lean/surfaces.mjs +75 -0
  107. package/bin/lean/surfaces.test.mjs +59 -0
  108. package/bin/lean/toolplace.mjs +28 -0
  109. package/bin/lean/toolplace.test.mjs +24 -0
  110. package/bin/lean/toolstats.mjs +3 -1
  111. package/bin/lean/toolstats.test.mjs +11 -0
  112. package/bin/lean/validatebest.mjs +28 -0
  113. package/bin/lean/validatebest.test.mjs +27 -0
  114. package/bin/pool/agent.mjs +9 -0
  115. package/bin/pool/docker.mjs +5 -0
  116. package/bin/pool/router.mjs +8 -4
  117. package/bin/prereqs.mjs +111 -0
  118. package/bin/replay-timelapse.mjs +149 -0
  119. package/bin/review-staging.mjs +100 -16
  120. package/bin/review-staging.test.mjs +18 -0
  121. package/bin/runner.mjs +49 -7
  122. package/bin/splash-install.mjs +157 -0
  123. package/bin/stats/aggregate.mjs +8 -1
  124. package/bin/stats/conformance-outcomes.mjs +100 -19
  125. package/bin/stats/conformance-outcomes.test.mjs +87 -1
  126. package/bin/stats/depth.mjs +88 -31
  127. package/bin/stats/depth.test.mjs +63 -38
  128. package/bin/stats/efficiency.mjs +26 -5
  129. package/bin/stats/efficiency.test.mjs +45 -1
  130. package/bin/stats/first-review.mjs +77 -0
  131. package/bin/stats/first-review.test.mjs +36 -0
  132. package/bin/stats/firstmerge.mjs +40 -0
  133. package/bin/stats/firstmerge.test.mjs +41 -0
  134. package/bin/stats/github-source.mjs +51 -13
  135. package/bin/stats/index.mjs +91 -15
  136. package/bin/stats/local-source.mjs +1 -0
  137. package/bin/stats/origin.mjs +80 -0
  138. package/bin/stats/origin.test.mjs +58 -0
  139. package/bin/stats/render.mjs +3 -1
  140. package/bin/stats/scoreboard.mjs +137 -0
  141. package/bin/stats/scoreboard.test.mjs +87 -0
  142. package/bin/stats/stats.test.mjs +80 -0
  143. package/bin/tui.mjs +3 -2
  144. package/commands/bootstrap.md +15 -14
  145. package/commands/deploy-pr.md +18 -3
  146. package/commands/forge-stats.md +1 -1
  147. package/commands/forgedock-ci-setup.md +28 -0
  148. package/commands/forgedock-init.md +4 -5
  149. package/commands/issue.md +2 -0
  150. package/commands/milestone.md +9 -1
  151. package/commands/replay.md +2 -0
  152. package/commands/review-pr-staging.md +4 -1
  153. package/commands/work-on/close.md +8 -0
  154. package/docs/CI.md +1 -1
  155. package/docs/CONFIG.md +105 -10
  156. package/docs/ISSUE-WATCH.md +23 -0
  157. package/docs/OUTCOME-CODES.md +1 -0
  158. package/docs/REPLAY.md +9 -0
  159. package/docs/SELFTEST.md +11 -0
  160. package/docs/STATS.md +19 -2
  161. package/docs/eval/README.md +6 -0
  162. package/docs/eval/adversarial-bench.md +68 -0
  163. package/docs/eval/corpus/adversarial-v1.json +285 -0
  164. package/docs/eval/feature-bench.md +42 -0
  165. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  166. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  167. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  168. package/docs/site/start-a-new-project.md +2 -1
  169. package/package.json +5 -2
  170. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  171. package/plugins/forgedock-splash/README.md +27 -0
  172. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  173. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  174. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  175. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  176. package/scripts/bench-adversarial.mjs +216 -0
  177. package/scripts/bench-feature.mjs +170 -0
  178. package/scripts/bench-lightlane.mjs +2 -2
  179. package/scripts/bootstrap-create.mjs +2 -2
  180. package/scripts/bootstrap-validate.mjs +35 -2
  181. package/scripts/check-spec-size.sh +4 -3
  182. package/scripts/check-spec-size.test.sh +3 -0
  183. package/scripts/plan-validate-live.mjs +40 -6
  184. package/scripts/review-pr-staging-scope.test.sh +1 -1
  185. package/scripts/review-staging-post.sh +23 -0
  186. package/scripts/review-staging-post.test.sh +8 -0
package/bin/lean/lean.mjs CHANGED
@@ -11,26 +11,30 @@ import { existsSync, readFileSync } from "node:fs";
11
11
  import { join, dirname, basename, delimiter } from "node:path";
12
12
  import { hostname as osHostname } from "node:os";
13
13
  import { appendEvent } from "../engine/runlog.mjs";
14
- import { readSelfReview, compareSelfReview } from "./selfreview.mjs";
15
- 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";
16
16
  import { ciPollDelayMs, ENGINE_VERSION, DEFAULT_MAX_SESSION_LIMIT_PAUSES, DEFAULT_SESSION_LIMIT_WAIT_MS, parseLeaseHolder, sanitizeLeaseHost } from "../engine.mjs";
17
17
  import { openDependency, laneMergedPrs, dependencyOnLane, isTrustedComment, decomposedSubissues, isDecomposedRecord, reopenRevokedDecomposition } from "../engine/phases.mjs";
18
18
  import { createHash, randomBytes } from "node:crypto";
19
19
  import { otherLaneOwner } from "./lanelock.mjs";
20
- 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 } 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";
21
23
  import { checkAdmission, hostParallelism, ADMISSION_RETRY_SECONDS } from "./admission.mjs";
22
24
  import { namedPaths, isTrustedIssueComment } from "./prefilter.mjs";
23
25
  import { checksAt } from "./postdeploy-check.mjs";
24
- import { readRollouts, detectNewOffKeys, rolloutModes } from "./activation.mjs";
26
+ import { readRollouts, detectNewOffKeys, rolloutModes, liveDeferralBlocks } from "./activation.mjs";
27
+ import { toolMisses } from "./toolplace.mjs";
25
28
  import { testRunnerProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract } from "./preflight.mjs";
26
29
  import { resolveLane, isDefaultLane, isShippedLane, DEFAULT_STAGING_BRANCH } from "./lane.mjs";
27
30
  import { splitGate, rationaleLine } from "./decompose.mjs";
31
+ import { ceilingFor, predictRestart, handoffFacts, NARROW_NOTE } from "./ceiling.mjs";
28
32
  import { dockerLabels, LEDGER_TTL_MS } from "./ledger.mjs";
29
- import { repoKey } from "../runner.mjs";
33
+ import { repoKey, estimateCostUsd } from "../runner.mjs";
30
34
  import { prepareToolchain } from "./toolchain.mjs";
31
35
  import { toolStats } from "./toolstats.mjs";
32
- import { readTestMap, readTestMapAtRef, mergeChecks, factsPath, TEST_MAP_FILE } from "./testmap.mjs";
33
- 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";
34
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";
35
39
  import { renderInvestigation, renderImplementation, renderReview, renderPrBody, renderTrajectory, renderContract, renderAmendments, renderShadowReview, parseContractComment, parseAmendmentsComment, contractJson, capComment, sanitizeMd, MAX_COMMENT_CHARS, recoveryEvidence } from "./render.mjs";
36
40
  import { parseVerifierConfig, pickVerifierModel, changedSymbols, callersOf, verifierBudget, verifierPrompt, parseVerifierFindings, findingsToFailures, renderVerifierNote, VERIFIER_SYSTEM } from "./verifier.mjs";
@@ -40,22 +44,26 @@ import { hostCapabilityBlock, contractHostNeeds } from "./execution.mjs";
40
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;
41
45
  /** #4685: true when a builder's block summary names a missing tool or module (environment), not a credential. */
42
46
  export function missingToolBlock(summary) { return MISSING_TOOL_RE.test(String(summary ?? "")); }
43
- 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";
44
49
  import { postMergeCommands } from "./postmerge.mjs";
45
50
  import { classifyBaseRed, attribute as attributeBaseRed, runOnBase, reportBaseRed } from "./basered.mjs"; // #5239
46
51
  import { guardAfterMerge, withHistoryRows } from "./guards.mjs";
52
+ import { parseProdParity, prodParityFailures as prodParityOf } from "./prodparity.mjs";
47
53
  import { routePathsFromFiles, routeReachabilityFailures } from "./routecheck.mjs";
48
54
  import { parseCoupled, coupledFailures } from "./coupled.mjs";
49
55
  import { analyzeRelaxations, relaxationFailures } from "./relaxation.mjs";
50
56
  import { loadGuards, selectGuards, runGuards, supersededIds, supersessionComment } from "./guardgate.mjs";
51
- import { freshFix, issueSummary, firstPassOf, sessionCostDelta } from "./fixround.mjs";
57
+ import { freshFix, issueSummary, firstPassOf, sessionCostDelta, mergeNarrowTasks } from "./fixround.mjs";
52
58
  import { parseBuilderRouting, routeBuilder, shouldEscalate } from "./routing.mjs";
53
59
  import { makeTurnBudget, TURN_BUDGET_DEFAULTS, scaledExtra, laneSize, recoverySize, wrapupGrant, budgetDigest } from "./budget.mjs";
54
60
  import { pendingPitfall, pitfallRecord, foldPitfalls, selectPitfalls, failureLog } from "./pitfalls.mjs";
55
61
  import { unjustified } from "./enumerating.mjs";
62
+ import { applyEnumerating, renameDuplicates } from "./mechfix.mjs"; // #5348
56
63
  import { addLaneWorktree, DEFAULT_SPARSE_MAX_KB } from "./worktree.mjs";
57
64
  import { parseVerify, runCiVerify, collectFailedLogs, capLogs, VERIFY_MODES, VERIFY_CHECK_NAME, verifyReport, ciGate, rerunFailedOnce, rerunTarget, splitFlaky } from "./verify.mjs";
58
- 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";
59
67
  import { laneBackendId } from "./limits.mjs";
60
68
  import { openRotator, rotatorRetry } from "./rotator.mjs";
61
69
  import { poolExhausted, exhaustedDeferral, quotaFacts } from "./quota.mjs"; // #5236
@@ -67,7 +75,9 @@ import { applyArmOverrides } from "../experiment.mjs";
67
75
  import { parseExploreConfig, explorerAgents, explorePlanRule, exploreBuildRule } from "./explore.mjs";
68
76
  import { normaliseFacts, renderFactsRecord, FACTS_MARKER } from "./facts.mjs";
69
77
  import { readDecisionIndex, withDecisionRows, recordDecisions } from "./decisions.mjs";
70
- 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";
71
81
  import { isExternalKill } from "./hostkill.mjs";
72
82
  import { buildResumeDigest } from "./resume.mjs";
73
83
  import { parsePredicate, evalPredicate, premiseAnnotation, registerAsk, registryPkgVersion, closedEdgeNote, onlyAsk, fileRemainder } from "./needs-human-premise.mjs";
@@ -91,6 +101,7 @@ export const RECOVER_HOW = Object.freeze({
91
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",
92
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",
93
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",
94
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",
95
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",
96
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",
@@ -171,6 +182,10 @@ export function classifyBlock(result, issue) {
171
182
  ...(Array.isArray(x.files) ? { files: [...new Set(x.files.filter((f) => typeof f === "string").map((f) => f.trim().replace(/^\.?\/+/, "")).filter(Boolean))] } : {}) }));
172
183
  return { kind: "split", rationale: gate.rationale, subissues, serialized: serializeShared(subissues) };
173
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
+ }
174
189
  if (b.kind === "human") {
175
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
176
191
  if (b.why === "product-decision" && describesUnrunnableCommand(`${result?.summary ?? ""} ${b.reason ?? ""} ${b.detail ?? ""}`)) { // #4857
@@ -248,7 +263,7 @@ const defaultCredExec = (args) => {
248
263
  export async function runCore(o) {
249
264
  const armed = applyArmOverrides(o, o.issue); o = armed.options; // #5206: the arm's overrides shape the lane before any config is parsed
250
265
  const { issue, repo, lane: requestedLane = null, laneOverride = false, branches = {}, cwd, dir, io, builderModel = null, reviewerModel = DEFAULT_REVIEWER_MODEL, fixModel = null,
251
- 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;
252
267
  const now = io.now ?? (() => Date.now());
253
268
  const rotator = io.rotator !== undefined ? io.rotator : openRotator({ kind: o.accountRotator }); // #5094
254
269
  // #5205: a rotator with pick() relaunches a limited phase pinned to another account; lane-level rotations and limited accounts
@@ -295,15 +310,19 @@ export async function runCore(o) {
295
310
  const git = (args, o = {}) => io.git(args, { cwd: wt, ...o });
296
311
 
297
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)
298
314
  const impl = { cost: 0, models: new Set() }; // #4397: implement spend and reported models, for the verifier
299
315
  // #4392: implement turn budget for the lane's size, and its turn tally; off unless given (the CLI passes readCoreLimits' defaults)
300
316
  const tb = makeTurnBudget(turnBudgets ?? { S: 0, M: 0, L: 0 });
301
317
  /** `trigger` (#4362): why the attempt ran, one of fixround.mjs TRIGGERS; `resume` (#4407): the session it resumed. */
302
318
  async function attempt(phase, n, r, mode = null, trigger = null, restartOf = null, resume = null) {
303
- 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;
304
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,
305
- 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 } : {}),
306
- ...(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
307
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"); }
308
327
  ev(rec); await emit(rec);
309
328
  modelMs += rec.duration_ms; // #4451: model time next to the lane's wall time
@@ -353,7 +372,14 @@ export async function runCore(o) {
353
372
  const failureClasses = new Set(); // forge#4275: conformance failure codes seen this run (gate failures, shadow would-fail)
354
373
  const ctxBase = parseContextPackConfig(o.contextPack ?? {});
355
374
  const ctxArm = contextArm({ mode: ctxBase.mode, repo, issue }); // #4444: ab picks a stable on|shadow arm per issue
356
- 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
+ };
357
383
  const ctxAb = ctxArm.ab ? { context_ab: true } : {};
358
384
  if (ctxArm.ab) T.decisions.push(`Context pack A/B (#4444): arm ${ctxArm.mode}`);
359
385
  const exploreCfg = parseExploreConfig(o.explore ?? {}); // #4391
@@ -362,9 +388,11 @@ export async function runCore(o) {
362
388
  let pitMatched = null; // #4375: pitfalls in the pack that match the issue's files; null when no pack was compiled
363
389
  let factsSeen = []; // #4401: trusted comment bodies on the issue, so an identical FORGE:FACTS is never posted twice
364
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)
365
392
  let shadowWould = null; // forge#4165: the shadow gate's verdict, carried on RUN_TERMINAL (no telemetry write of its own)
366
393
  const kinds = normalizeKindModes(conformanceKinds); // engine.conformance_kinds: a failure code's own mode
367
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
368
396
  let riskEnforced = null, gateRan = false; // #4398: declared risk paths that made a shadow lane enforce (sticky); the gate ran
369
397
  let done = null, finishing = null, wtCreated = false, salvagedRef = null;
370
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
@@ -380,14 +408,15 @@ export async function runCore(o) {
380
408
  // the runner PATH; `waits` ({phase: ms}) and `heavyQueueMax` ride on the lane result for the batch report.
381
409
  const heavyCfg = o.heavy ?? {}, heavyOn = Boolean(io.heavy) && heavyCfg.enabled !== false;
382
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)
383
412
  let seqLease = null; // #4386: the host sequence lease, held from the merge-gate renumber through the merge
384
413
  const waits = {};
385
414
  const followupsFiled = []; // #5078: {issue, class, count} per tracking issue this lane filed into, for the batch report
386
415
  const pendingFollowups = []; // #5141: {req, why} whose filing kept failing in-lane; filed after the merge, else recorded
387
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}` }));
388
417
  let precheckMs = 0, precheckDeferred = 0, precheckRan = false; // #4331: pre-PR check wall time and deferrals, for the batch report
389
- const addWait = (phase, ms, queued = 0) => {
390
- 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
391
420
  if (Number.isInteger(queued)) heavyQueueMax = Math.max(heavyQueueMax, queued);
392
421
  };
393
422
  const lanePriority = () => priorityFromLabels(iss?.labels);
@@ -403,9 +432,12 @@ export async function runCore(o) {
403
432
  const protectedBranch = (b) => isProtectedLaneBranch(b, { issue, lane, branches, defaults });
404
433
  /** Teardown from the ledger (#4179), on every exit path: builder pids, checkpoint of unpushed work, run tmp, worktree, branch, docker. */
405
434
  async function teardown(reason, extra) {
435
+ const builderPids = (ledger ? ledger.entries("pid") : []).map((p) => Number(p.value));
406
436
  for (const p of ledger ? ledger.entries("pid") : []) {
407
437
  try { if (await io.killGroup?.(p.value, p.marker)) ledgerDo((l) => l.release("pid", p.value)); } catch { /* keep it listed */ }
408
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(() => []) : [];
409
441
  // Never discard work silently: an unmerged lane commits and pushes what is left before its worktree goes.
410
442
  const saved = !wtCreated || reason === "merged" || (await checkpoint(`exit (${reason})`));
411
443
  await reportLaneHead(reason);
@@ -414,7 +446,7 @@ export async function runCore(o) {
414
446
  try { if ((await io.runTmp.remove(runTmp)) !== false) ledgerDo((l) => l.release("tmp", runTmp)); } catch { /* best effort */ }
415
447
  runTmp = null;
416
448
  } // every terminal, including engine-error and deferred
417
- if (wtCreated && saved) {
449
+ if (wtCreated && saved && !stillRunning.length) {
418
450
  let removed = false;
419
451
  try { await io.git(["worktree", "remove", "--force", wt], { cwd }); removed = true; } catch { /* best effort */ }
420
452
  try { await io.git(["worktree", "prune"], { cwd }); } catch { /* best effort */ }
@@ -425,7 +457,7 @@ export async function runCore(o) {
425
457
  }
426
458
  if (branchDone) ledgerDo((l) => l.release("branch", branch));
427
459
  } else if (wtCreated) {
428
- 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 });
429
461
  }
430
462
  for (const kind of ["container", "volume"]) {
431
463
  for (const r of ledger ? ledger.entries(kind) : []) {
@@ -481,19 +513,23 @@ export async function runCore(o) {
481
513
  return finishing;
482
514
  }
483
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
484
517
  try { seqLease?.release(); } catch { /* fail-open */ }
485
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) */ }
486
522
  try { await io.sequenceLease?.unreserve?.({ repo, lane, issue }); } catch { /* fail-open (#4526) */ }
487
523
  if (heavyWaitsFile) { // #4169: builder-run heavy waits, read before teardown removes the run TMPDIR
488
- 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 */ }
489
525
  }
490
526
  await postLaneFacts(); // #4401: before teardown removes the worktree's result.json
491
527
  await teardown(reason, extra); // first: unpushed work is pushed while this run still holds the lease
492
528
  const code = codeOverride ?? codeForTerminalReason(reason);
493
529
  // forge#4165: pr, milestone and the conformance verdict ride on the existing RUN_TERMINAL write (verdict-mix queries).
494
- const term = { event: "RUN_TERMINAL", reason, code, ...(extra.pr ? { pr: extra.pr } : {}), ...(milestone ? { milestone } : {}),
495
- conformance_mode: conformance === "enforce" || riskEnforced ? "enforce" : "shadow", ...(shadowWould ? { shadow_would: shadowWould } : {}),
496
- ...(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() } : {}),
497
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
498
534
  const phases = phaseLedger.snapshot(); // #4908: run log gets the nested ledger, FORGE:TELEMETRY the flattened scalars
499
535
  ev({ ...term, phases });
@@ -534,7 +570,7 @@ export async function runCore(o) {
534
570
  if (!base) return;
535
571
  try {
536
572
  const result = await readResult();
537
- 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;
538
574
  if (!rec) return;
539
575
  const body = renderFactsRecord(rec);
540
576
  if (factsSeen.some((b) => String(b ?? "").includes(body))) return;
@@ -589,7 +625,25 @@ export async function runCore(o) {
589
625
  { key: "implementation", file: IMPLEMENTATION_FILE, marker: ["FORGE:IMPLEMENTATION"], render: (md, ctx) => renderImplementation(md, ctx.result, { branch, files: ctx.files }) },
590
626
  ];
591
627
  const posted = {}; // key -> comment url (or "" when posted without a link)
592
- 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
+ }
593
647
  const usableMd = (md) => sanitizeMd(md).replace(/\s+/g, " ").length >= 20;
594
648
  const stageFiles = async () => {
595
649
  const out = String(await git(["diff", "--name-only", `${base}...HEAD`]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean);
@@ -660,7 +714,7 @@ export async function runCore(o) {
660
714
  let deps = {};
661
715
  try { deps = io.deps?.env?.() ?? {}; } catch { deps = {}; }
662
716
  const par = verifyParallelism();
663
- 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
664
718
  }
665
719
  /** #5168: a failed claude login ends the lane `deferred` `backend.auth`, held per account by the batch (never the relaunch or the breaker). */
666
720
  const authDeferral = (e) => Object.assign(e, { deferCode: OUTCOME_CODES.BACKEND_AUTH, retryInSeconds: AUTH_RETRY_SECONDS, backendId: laneBackendId(process.env, rotator),
@@ -676,7 +730,7 @@ export async function runCore(o) {
676
730
  const labels = dockerLabels({ batch: o.batchId ?? "adhoc", lane: `lean-${issue}`, issue, expires: now() + LEDGER_TTL_MS }).join(" ");
677
731
  // #4169: heavy shims first on PATH; the phase/issue/priority label each heavy step's slot and wait record.
678
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()) } : {};
679
- 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" } : {}) };
680
734
  const system = lp === "lane" && !args.resume && !args.noTools ? [args.system, laneProfile.text].filter(Boolean).join("\n\n") : args.system;
681
735
  // #5205: capture the account the run uses (the shim exports it, then execs claude) and pin a rotation relaunch.
682
736
  let account = pinned?.account ?? null;
@@ -714,7 +768,9 @@ export async function runCore(o) {
714
768
  pauses++; pinned = null; // after the wait the shim picks again
715
769
  ev({ event: "PHASE_RATE_LIMITED", phase: args.role, resetAt: epoch, resetAtDisplay: e.resetAt ?? null, waitMs });
716
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();
717
772
  await sleep(waitMs);
773
+ phaseLedger.addWait(args.role === "review" ? "review" : stage, "rate_limit", now() - limitedAt); // #5349
718
774
  }
719
775
  }
720
776
  }
@@ -810,31 +866,42 @@ export async function runCore(o) {
810
866
  try { ok = (await checkAdmission({ cfg: o.admission, host: io.host })).ok; } catch { ok = true; }
811
867
  const nowMs = Date.now();
812
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" }); } }
813
- 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" }); }
814
870
  else if (ok) forced = false;
815
- 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" }); }
816
872
  }
817
873
  })();
818
- 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"); } } };
819
875
  }
820
876
 
821
877
  /** A timeout restart starts a fresh session; by default it continues the implementation against the frozen contract. */
822
878
  let facts = null; // #4272: path of an optional .forge/repo-facts.json (worktree, then main checkout), cited in builder prompts
823
- const tcOpts = () => ({ toolchain: toolchain?.summary ?? null, sparse, ...(facts ? { facts } : {}) });
879
+ const tcOpts = () => ({ toolchain: toolchain?.summary ?? null, sparse, ...(facts ? { facts } : {}), stamp: stampText({ issue, hash: stampHash }) });
824
880
  let hotFacts = null; // forge#4195: scripts/hotspots.sh facts for the files the issue names, read once before the plan call
825
881
  let enumList = []; // #4322: tests enumerating the members of the paths the issue names, read once before the plan call
826
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
827
884
  let resumeNote = ""; // #4400: the resume digest of the last run (resume.mjs), "" on a first run or with context_pack off
828
- 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
+ }
829
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
830
897
  const UNCEILED = ["plan", "contract_correction", "block_correction"], CONTEXT_RESTARTS_MAX = 3;
831
898
  async function builder(n, prompt, resume, live = false, restart = implementRestart, opts = {}) {
832
899
  let timeoutRetries = 0, contextRestarts = 0, p = prompt;
833
900
  opts = { ...opts };
834
- 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
835
902
  for (;;) {
836
903
  // after CONTEXT_RESTARTS_MAX restarts the call runs uncapped: a loop guard, never a refusal of work
837
- opts.contextMax = ceiled && contextRestarts < CONTEXT_RESTARTS_MAX ? contextCeilingTokens : 0;
904
+ opts.contextMax = ceiled && contextRestarts < CONTEXT_RESTARTS_MAX ? laneCeiling : 0;
838
905
  const budgeted = stage === "implement" && tb.on(); // #4392: the build and its restarts spend the implement turn budget
839
906
  if (budgeted && tb.remaining() <= 0) return await budgetWrapup(n, opts);
840
907
  opts.turnMax = budgeted ? tb.remaining() : 0;
@@ -845,13 +912,16 @@ export async function runCore(o) {
845
912
  }
846
913
  if (e?.code === "CLI_CONTEXT") {
847
914
  contextRestarts++;
848
- 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 });
849
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);
850
917
  await checkpoint("context ceiling");
851
- T.decisions.push(`Builder session reached ${e.context ?? "?"} context tokens (ceiling ${contextCeilingTokens}): checkpointed, restarted fresh from the contract, diff and last validate result`);
852
- 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";
853
920
  continue;
854
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
+ }
855
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
856
926
  ev({ event: "CLI_LANE_LIMIT", limit: e.limit ?? null, unit: e.unit ?? null });
857
927
  await checkpoint(`scope ${e.limit} limit`);
@@ -883,18 +953,24 @@ export async function runCore(o) {
883
953
  }
884
954
 
885
955
  /** opts (#4363): {model, mode, keepSession, trigger and restartOf (#4362)}; a fresh fix session keeps the build session id for a fallback resume. */
886
- 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 } = {}) {
887
957
  onProgress({ event: "phase_enter", phase: "build" });
888
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() {
889
963
  const control = {};
890
964
  const governor = startGovernor(control);
891
965
  let spawned = null;
892
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 })); } };
893
- 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,
894
969
  idleMs: Math.round(cliIdleMinutes * 60000), maxMs: Math.round(cliMaxMinutes * 60000), laneLimits, ...(contextMax > 0 ? { contextMax } : {}), ...(turnMax > 0 ? { turnMax } : {}),
895
970
  busy: sessionBusy, busyMs: Math.round(cliBusyMinutes * 60000),
896
971
  onIdleExtend: (info) => ev({ event: "CLI_IDLE_EXTENDED", children: info.children, heavyQueue: info.heavyQueue }) }));
897
- 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)); });
898
974
  let r;
899
975
  call.catch(() => governor.stop());
900
976
  if (live && io.fs.stat) {
@@ -913,9 +989,20 @@ export async function runCore(o) {
913
989
  await renew();
914
990
  await registerReported();
915
991
  if (r?.sessionId && !keepSession) sessionId = r.sessionId;
916
- 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);
917
993
  onProgress({ event: "phase_exit", phase: "build", status: "committed" });
918
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` });
919
1006
  }
920
1007
  /** #4390: the restart summary: `git diff --stat` and hunks against the lane base, and the last `forgedock check` record. */
921
1008
  async function restartFacts() {
@@ -925,7 +1012,13 @@ export async function runCore(o) {
925
1012
  try { check = String(await io.fs.read(`${wt}/${SELF_CHECK_FILE}`)); } catch { /* none recorded */ }
926
1013
  return { stat, diff, base, check };
927
1014
  }
928
- 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 });
929
1022
  /**
930
1023
  * #4392: the implement turn budget is spent. Checkpoint, then one fresh session of `wrapupGrant` turns either finishes
931
1024
  * (its result flows on as usual) or stops with a digest; a stop or an overrun ends the non-human `budget-exceeded` reason
@@ -1050,6 +1143,16 @@ export async function runCore(o) {
1050
1143
  ? await finish("dependency-blocked", detail, { code: OUTCOME_CODES.DEPENDENCY_BLOCKED, dependencies: b.issues, blockers: b.blockers }, OUTCOME_CODES.DEPENDENCY_BLOCKED)
1051
1144
  : await finish("dependency-open", detail, { code: OUTCOME_CODES.DEPENDENCY_OPEN, dependencies: b.issues }, OUTCOME_CODES.DEPENDENCY_OPEN);
1052
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
+ }
1053
1156
  if (b.kind === "split") {
1054
1157
  const filed = [];
1055
1158
  try {
@@ -1435,6 +1538,7 @@ export async function runCore(o) {
1435
1538
  factsSeen = trustedComments.map((c) => c?.body);
1436
1539
  let issueText = textOf(iss, trustedComments);
1437
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)`); } }
1438
1542
  ctxLane = laneType({ resumed: Boolean(resumed || salvagedRef), attempts: priorAttempts(iss.body, trustedComments), body: iss.body });
1439
1543
  /**
1440
1544
  * forge#4275: compile (or read from the cache) the context pack, log CONTEXT_PACK and post FORGE:CONTEXT. Off, no
@@ -1448,7 +1552,7 @@ export async function runCore(o) {
1448
1552
  // #4316: linked-issue states are part of the key; a failed lookup only drops them from it
1449
1553
  const links = await linkStateStamp({ gh: ghc, repo, issue, body: iss.body }).catch(() => "");
1450
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) },
1451
- 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 }) });
1452
1556
  const p = r.pack;
1453
1557
  const inPack = Array.isArray(p.pitfalls) ? p.pitfalls : [];
1454
1558
  pitMatched = inPack.filter((x) => x.match === "files").length;
@@ -1676,7 +1780,7 @@ export async function runCore(o) {
1676
1780
  }
1677
1781
  /** #4694: the engine appends guard-derived H preserve rows from the local index (one file read; the same contract when none apply). */
1678
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; };
1679
- 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
1680
1784
  const impliedDocs = []; // add-deliverable amendments for doc edits the docs-freshness rule demanded (docs round, CI fix round)
1681
1785
  /** Doc files a fix round added to satisfy the freshness rule: recorded only when the rule failed before and passes after. */
1682
1786
  async function noteFreshnessDocs(before, wasFailing) {
@@ -1713,17 +1817,40 @@ export async function runCore(o) {
1713
1817
  * #4363: one fix round. Mechanical failures (and a conformance/review FAIL citing file:line) run in a fresh session on
1714
1818
  * the fix model with a narrow prompt; one resume of the build session follows when it made no commit. Else: a resume.
1715
1819
  */
1716
- 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)
1717
1821
  await notePitfall(trigger, failureText); await escalateOn(trigger); // #4375: learned once the same gate passes; #4394
1718
1822
  if (!freshFix(kind, failures)) return await builder(++attemptN, task, sessionId ?? null, false, undefined, { mode: "resume", trigger });
1719
1823
  const before = String(await git(["rev-parse", "HEAD"])).trim();
1720
- const ex = [".", `:!${LEAN_DIR}`], diff = String(await git(["diff", `${base}...HEAD`, "--", ...ex]).catch(() => "")), stat = String(await git(["diff", "--stat", `${base}...HEAD`, "--", ...ex]).catch(() => ""));
1721
- const prompt = fixSessionPrompt({ task, diff, stat, base, contract: frozen, title: iss?.title ?? "", summary: issueSummary(iss?.body) });
1722
- 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 });
1723
1827
  if (!sessionId || String(await git(["rev-parse", "HEAD"])).trim() !== before) return r;
1724
1828
  T.decisions.push(`Fresh ${kind} fix session made no commit; builder session resumed once`);
1725
1829
  return await builder(++attemptN, task, sessionId, false, undefined, { mode: "resume", trigger });
1726
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
+ }
1727
1854
  if (isSplit) {
1728
1855
  // ---- 3'. refactor:split (#4211): deterministic move + proof replaces the builder; no builder session exists ----
1729
1856
  split = await splitStep();
@@ -1747,8 +1874,8 @@ export async function runCore(o) {
1747
1874
  }
1748
1875
  if ((resumed || salvagedRef || recover) && ctxCfg.mode !== "off") {
1749
1876
  // #4400: the last run's own records as a bounded digest in the builder prompts; never in issueText (contract quotes)
1750
- const d = buildResumeDigest({ state: priorState, comments: trustedComments, contract: frozen, files: resumed ? await changedFiles().catch(() => []) : [], lane });
1751
- 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 ?? [];
1752
1879
  if (d.text) {
1753
1880
  ev({ event: "RESUME_DIGEST", bytes: Buffer.byteLength(d.text, "utf8"), files: d.files, validates: d.validates, reason: d.reason });
1754
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}` : ""}`);
@@ -1787,6 +1914,7 @@ export async function runCore(o) {
1787
1914
  let body = renderContract(frozen, hash, { scope: scopeHash });
1788
1915
  if (body.length > MAX_COMMENT_CHARS - 500) body = renderContract(frozen, hash, { compact: true, scope: scopeHash });
1789
1916
  await post(["FORGE:CONTRACT", "FORGE:PLAN"], body);
1917
+ await claimSurfaceSlots(frozen);
1790
1918
  ev({ event: "CONTRACT_FROZEN", hash, requirements: frozen.requirements.length, deferred: 0, derived: "light" });
1791
1919
  await emit({ event: "CONTRACT_FROZEN", hash, requirements: frozen.requirements.length, deferred: 0, derived: "light" });
1792
1920
  ev({ event: "LIGHT_DONE", files: lr.files.length, test_failures: lr.testFailures, repro: lr.repro, cost_usd: usage.cost_usd });
@@ -1864,6 +1992,7 @@ export async function runCore(o) {
1864
1992
  vc = validateContract(contract, issueText, { repro: reproOn() });
1865
1993
  if (missed.length) misses = await preflightValidates(contract);
1866
1994
  }
1995
+ planMisses = misses;
1867
1996
  if (missed.length) {
1868
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 });
1869
1998
  if (misses.length) {
@@ -1892,11 +2021,18 @@ export async function runCore(o) {
1892
2021
  const relayed = new Set(o.relayCaps ?? []); // #4778: a relayed capability is served to the sandbox, so the lane builds there
1893
2022
  const hn = contractHostNeeds(frozen, o.hostCaps && { ...o.hostCaps, hostCapabilities: (o.hostCaps.hostCapabilities ?? []).filter((c) => !relayed.has(c)) });
1894
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
+ }
1895
2030
  }
1896
2031
  T.plan = [`contract ${hash}${lightDone ? " (derived, light lane)" : ""}`, `${frozen.requirements.length} requirement(s)`];
1897
2032
  { // #4392, #4505: next size on a budget recovery; #4587: a big L contract and an L recovery get extra turns
1898
2033
  const sz = recoverySize(laneSize({ contract: frozen, labels: (iss?.labels ?? []).map((l) => l?.name ?? l) }), recover);
1899
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
1900
2036
  }
1901
2037
  if (io.fs.write) { try { await io.fs.write(`${wt}/${CONTRACT_FILE}`, `${contractJson(frozen)}\n`); } catch { /* the prompt still names it */ } }
1902
2038
  // #4364: what `forgedock check` needs from the operator's forge.yaml (gitignored, so not in the worktree)
@@ -1907,24 +2043,59 @@ export async function runCore(o) {
1907
2043
  ev(rec); await emit(rec);
1908
2044
  T.decisions.push(`Builder routed to the ${route.tier} tier (${route.class}; ${route.model ?? "CLI default"})`);
1909
2045
  }
1910
- 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);
1911
2056
  liveKeys = ["implementation"];
1912
2057
  stage = "implement"; phaseLedger.enter("implement");
1913
- 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
+ }
1914
2069
  stage = "fix"; // later builder rounds fix precheck, CI, structure, docs or conformance findings
1915
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
+ }
1916
2079
  { // #4374: the builder's self-review against the shared rubric, log only
1917
2080
  const sr = readSelfReview(result);
1918
2081
  if (sr) ev(sr.state === "present" ? { event: "SELF_REVIEW", answers: sr.items.length, no: sr.no } : { event: "SELF_REVIEW_MISSING", state: sr.state });
1919
2082
  }
1920
2083
  // #4364: a builder that writes fixed without a green `forgedock check` on its final tree; recorded, never a failure
1921
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
+ }
1922
2092
  {
1923
2093
  const blocked = await endIfBlocked();
1924
2094
  if (blocked) return blocked;
1925
2095
  }
1926
2096
  files = await changedFiles();
1927
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
1928
2099
  await flushStages(result, ["implementation"]);
1929
2100
  T.implement = [`${files.length} file(s)`, branch];
1930
2101
  T.decisions.push(`Builder verdict: ${result?.status ?? "none"}`);
@@ -1962,11 +2133,14 @@ export async function runCore(o) {
1962
2133
  const { results, deferred } = round$;
1963
2134
  precheckMs += round$.ms; precheckDeferred += deferred.length;
1964
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(", ")}`);
1965
- 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;
1966
2138
  ev({ event: "PRECHECK_COMMANDS", round, results: [...results.map(({ command, rc, ms }) => ({ command, rc, ms })), ...deferred.map((command) => ({ command, status: "deferred-to-ci" }))],
1967
- 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() } : {}) });
1968
2140
  verifyFacts.commands = results.map(({ command, rc }) => ({ command, rc }));
1969
- 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);
1970
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; }
1971
2145
  const names = failed.map((f) => `\`${f.command}\` (exit ${f.rc})`).join(", ");
1972
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);
@@ -2046,10 +2220,20 @@ export async function runCore(o) {
2046
2220
  if (io.enumeratingMissing && !isSplit) {
2047
2221
  const missingNow = async () => unjustified((await io.enumeratingMissing({ cwd: wt, base }).catch(() => null)) ?? [], result?.not_members);
2048
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
+ }
2049
2227
  if (missing.length && sessionId) {
2050
2228
  ev({ event: "ENUMERATING_MISSING", count: missing.length });
2051
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`);
2052
- 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)])] });
2053
2237
  await upsertStage("implementation");
2054
2238
  result = (await readResult()) ?? result;
2055
2239
  missing = await missingNow();
@@ -2062,16 +2246,32 @@ export async function runCore(o) {
2062
2246
  * sees its tip. #4386: the engine renumbers first (no builder, no session); the builder only when that is unsupported.
2063
2247
  * `laneRef`: the pre-merge lane head after a base-sync took the base side of sequence-only conflicts.
2064
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
+ }
2065
2265
  async function sequenceHandoff(trigger, { laneRef = null } = {}) {
2066
2266
  if (!io.sequenceCheck || isSplit) return null;
2067
2267
  try { await git(["fetch", "origin", lane]); } catch { /* offline: use the local ref */ }
2068
- const collisions = (await io.sequenceCheck({ cwd: wt, base }).catch(() => null)) ?? [];
2268
+ const collisions = (await io.sequenceCheck({ cwd: wt, base, versioned: o.sequenceVersioned }).catch(() => null)) ?? [];
2069
2269
  if (!collisions.length) return null;
2070
2270
  const before = (await io.sequenceSnapshot?.({ cwd: wt, base }).catch(() => null)) ?? [];
2071
2271
  ev({ event: "SEQUENCE_COLLISION", trigger, files: collisions.map((c) => c.lane) });
2072
2272
  const taken = collisions.filter((c) => c.base.length).map((c) => `${c.lane} vs ${c.base.join(", ")}`).join("; ");
2073
2273
  if (io.sequenceRenumber) {
2074
- 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" };
2075
2275
  let det = await renumber(laneRef);
2076
2276
  if (det.nonSequence?.length && !laneRef) { // #4732: base-sync first (sequence files take the base side, the builder resolves the rest), then renumber deterministically
2077
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);
@@ -2089,10 +2289,11 @@ export async function runCore(o) {
2089
2289
  if (det.ok && det.moves?.length) {
2090
2290
  ev({ event: "SEQUENCE_RENUMBERED", trigger, mode: "deterministic", moves: det.moves });
2091
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(", ")}`);
2092
- 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"] };
2093
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) };
2094
2294
  await gatePassed("sequence");
2095
2295
  files = await changedFiles();
2296
+ await revalidateRenumbered(trigger);
2096
2297
  return { renumbered: true, deterministic: true };
2097
2298
  }
2098
2299
  const why = det.unsupported ?? "no movable sequence file";
@@ -2102,10 +2303,11 @@ export async function runCore(o) {
2102
2303
  T.decisions.push(`Sequence number(s) taken on ${lane} (${trigger}): ${taken}; builder renumbers`);
2103
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"));
2104
2305
  result = (await readResult()) ?? result;
2105
- 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"] };
2106
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) };
2107
2308
  await gatePassed("sequence");
2108
2309
  files = await changedFiles();
2310
+ await revalidateRenumbered(trigger);
2109
2311
  return { renumbered: true };
2110
2312
  }
2111
2313
  { const sq = await sequenceHandoff("hand-off"); if (sq?.done) return sq.done; }
@@ -2114,13 +2316,14 @@ export async function runCore(o) {
2114
2316
  async function duplicateGate(trigger) {
2115
2317
  if (!io.duplicateExports || isSplit || vcfg.duplicateExports === false) return false;
2116
2318
  const found = async () => (await io.duplicateExports({ cwd: wt, base }).catch(() => null)) ?? [];
2117
- let dups = await found();
2319
+ let dups = await dupsResidual(); // #5348: the deterministic rename first
2320
+ const mech = dupMech > 0;
2118
2321
  if (dups.length && sessionId) {
2119
2322
  const text = dups.map((d) => `duplicate export \`${d.symbol}\`: ${d.path} and ${(d.others ?? []).join(", ")}`).join("\n");
2120
2323
  ev({ event: "DUPLICATE_EXPORTS", trigger, count: dups.length });
2121
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`);
2122
2325
  engineWhy = `engine-demanded rename: duplicate export(s) ${dups.slice(0, 5).map((d) => d.symbol).join(", ")} (${trigger})`;
2123
- 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 ?? [])]) });
2124
2327
  result = (await readResult()) ?? result;
2125
2328
  files = await changedFiles();
2126
2329
  dups = await found();
@@ -2129,7 +2332,8 @@ export async function runCore(o) {
2129
2332
  return true;
2130
2333
  }
2131
2334
  if (dups.length) T.anomalies.push(`Duplicate export(s) (${trigger}): ${dups.slice(0, 5).map((d) => `${d.symbol} in ${d.path}`).join("; ")}`);
2132
- return false;
2335
+ else if (mech) await gatePassed("duplicate");
2336
+ return mech;
2133
2337
  }
2134
2338
  await duplicateGate("hand-off");
2135
2339
  /** #4591: lane-added migrations the repo's generator did not produce: one builder round (stage "sequence"), then an anomaly. */
@@ -2327,7 +2531,7 @@ export async function runCore(o) {
2327
2531
  let effective = frozen, review = null, lastAmend = "", resumes = 0, verdict = null, degraded = null, triggerSkipped = false, selfReviewCompared = false;
2328
2532
  const TRIGGER_SKIP = "skipped (review.trigger enforce: no risk trigger)";
2329
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).";
2330
- let pendingDecisions = [];
2534
+ let pendingDecisions = [], firstRounds = null, firstReply = null;
2331
2535
  let baseTree = null; // #4695: the base file list, read once and only when a decision amendment needs it
2332
2536
  let genPaths = null; // forge#4519: maintenance.generated_paths from hotspots.sh (plan facts; one config-only call without them, never on light lanes)
2333
2537
  async function amend() {
@@ -2357,13 +2561,15 @@ export async function runCore(o) {
2357
2561
  const diff = String(await git(["diff", `${base}...HEAD`]));
2358
2562
  const stat = Buffer.byteLength(diff, "utf-8") > REVIEW_DIFF_MAX_BYTES ? String(await git(["diff", "--stat=200", `${base}...HEAD`]).catch(() => "")) : "";
2359
2563
  const listed = new Set(String(await git(["ls-files"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean));
2360
- 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 } };
2361
2567
  let d = null, first = null;
2362
2568
  for (let t = 0; t < 3; t++) {
2363
2569
  // #4327/#5164: a third run only when the repaired reply is incomplete solely by reviewer slips (unresolved evidence paths, coverage misquotes).
2364
2570
  if (t === 2) {
2365
2571
  if (d.state !== "review.incomplete" || !reaskable(d.failures.map((f) => f.detail))) break;
2366
- 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`);
2367
2573
  }
2368
2574
  // #4160: a reply with rows missing is re-asked for those ids only; an unparseable one gets the full prompt again.
2369
2575
  const repair = first && (d.state === "review.incomplete" || d.state === "review.inconsistent");
@@ -2377,6 +2583,8 @@ export async function runCore(o) {
2377
2583
  review = repair ? mergeReviewRows(first, parsed) : parsed;
2378
2584
  first = review;
2379
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;
2380
2588
  if (d.review) review = d.review;
2381
2589
  ev({ event: "CONFORMANCE", round: reviewN, state: d.state, failures: d.failures.map((x) => x.code), mode: shadow ? "shadow" : "enforce" });
2382
2590
  const cmp = selfReviewCompared ? null : compareSelfReview(readSelfReview(result), d); // #4374: once, on the first judgement
@@ -2488,6 +2696,14 @@ export async function runCore(o) {
2488
2696
  const cfg = readRollouts(wt);
2489
2697
  return cfg ? detectNewOffKeys(cfg, String(await git(["diff", "-U0", `${base}...HEAD`, "--", ...cfg.files]).catch(() => ""))) : [];
2490
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
+ }
2491
2707
  let amendFixed = false;
2492
2708
  async function gate() {
2493
2709
  await refreshIssue("conformance");
@@ -2533,6 +2749,9 @@ export async function runCore(o) {
2533
2749
  const [{ runs: validateRuns, subs: substitutedRuns }, guardFailures] = await Promise.all([validatePhase, guardGate(files)]);
2534
2750
  // #5087: forge.yaml topology.route_reachability gates the route handlers this diff adds; unset = no check
2535
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 } }) : [];
2536
2755
  // #4705: only the part not hidden behind the validate rerun; 0 when the gate errored or skipped
2537
2756
  const guardRunMs = guardEv && !guardEv.error ? Math.max(0, now() - gateT0 - validateMs) : 0;
2538
2757
  guardAddedMs += guardRunMs;
@@ -2549,7 +2768,7 @@ export async function runCore(o) {
2549
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`;
2550
2769
  if (!T.decisions.includes(note)) T.decisions.push(note);
2551
2770
  }
2552
- 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, newOffKeys: await newOffKeysOf(), substitutedRuns, removedPaths, baseFiles: subBaseFiles });
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 });
2553
2772
  // #4350: a scope-check validate stale only by amended deliverables is judged by the engine's scope gate instead
2554
2773
  if (pc.superseded?.length) {
2555
2774
  ev({ event: "VALIDATE_SUPERSEDED", runs: pc.superseded });
@@ -2678,11 +2897,18 @@ export async function runCore(o) {
2678
2897
  if (remoteVerify) { const v = await ciVerify("build"); if (v.done) return v.done; }
2679
2898
  const outcome = await gate();
2680
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 });
2681
2902
  for (const f of [...(outcome.failures ?? []), ...(outcome.wouldFail ?? [])]) if (f?.code) failureClasses.add(f.code);
2682
2903
  if (outcome.state === "conforms") { await gatePassed("conformance"); break; }
2683
2904
  const explained = explainFailures(outcome.failures, effective); // #4265: name the unmet requirement, not only the code
2684
2905
  const list = explained.slice(0, 15).map((f) => `- ${f.code}: ${f.detail}`).join("\n");
2685
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
+ }
2686
2912
  if (outcome.state === "already-fixed") { // #5080: close as delivered, citing the base commit
2687
2913
  const sha = String(await git(["rev-parse", base]).catch(() => "")).trim().slice(0, 12) || base;
2688
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}`;
@@ -2733,13 +2959,24 @@ export async function runCore(o) {
2733
2959
  }
2734
2960
  }
2735
2961
  ev({ event: "PHASE_COMMIT", phase: "review" });
2736
- const closing = closePlan(effective, { title: iss.title, review, issueText });
2737
2962
  // #5240: a delivered change behind a rollout that is not live (shadow/off) is inert in production: say so, never claim the outcome
2738
2963
  const rcfg = readRollouts(wt);
2739
- const inert = (rcfg ? rolloutModes(rcfg, files, (f) => readFileSync(join(wt, f), "utf8")) : []).filter((m) => !m.live);
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)`);
2740
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;
2741
2978
  if (closing.checklist) T.decisions.push(`Unticked acceptance criteria unmet (${closing.open.map((r) => r.id).join(", ")}): issue left open as partial (#5240)`);
2742
- if (closing.reason === "partial" && !closing.checklist) { // #4398: an investigation whose question is not answered carries it forward
2979
+ if (closing.reason === "partial" && !closing.checklist && !closing.transferred) { // #4398: an investigation whose question is not answered carries it forward
2743
2980
  const untracked = closing.open.filter((r) => !r.tracked);
2744
2981
  if (untracked.length) {
2745
2982
  const carried = untracked.map((r) => ({ ...r, disposition: "defer", class: "ops", why: "investigation question not answered" })); // #5207: the batch aggregate
@@ -3127,7 +3364,7 @@ export async function runCore(o) {
3127
3364
  }
3128
3365
  if (seqLease) {
3129
3366
  try { await git(["fetch", "origin", lane]); } catch { /* offline: use the local ref */ }
3130
- 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)) ?? [];
3131
3368
  if (late.length) {
3132
3369
  ev({ event: "SEQUENCE_LATE_BIND", pr, files: late.map((c) => c.lane) });
3133
3370
  const r = await baseSync("merge gate: sequence number taken"); if (r) return r;
@@ -3199,10 +3436,15 @@ export async function runCore(o) {
3199
3436
  }
3200
3437
  }
3201
3438
  const partial = closing.reason === "partial";
3202
- if (closing.checklist) keepOpen = true; // #5240: an unmet acceptance checkbox is not closed as completed
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
+ }
3203
3443
  // #5152: a merged change is `completed` even when partial: the remainder is tracked (FORGE:TRACKED), not dropped
3204
3444
  if (!keepOpen) await ghw(["issue", "close", String(issue), "-R", repo, "--reason", "completed"]).catch(() => {});
3205
- if (closing.checklist) { // #5240: partial: left open; the unticked criteria, tracked follow-ups and any inert rollout are the record
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
3206
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 */ }
3207
3449
  } else if (keepOpen) { // #5159: the issue is not closed while a follow-up is pending, so the note must not say it is
3208
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 */ }