forgedock 1.61.1 → 1.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/bin/config-schema.mjs +10 -1
  2. package/bin/engine/outcome-codes.mjs +4 -0
  3. package/bin/engine-cli.mjs +160 -18
  4. package/bin/env/env.mjs +6 -4
  5. package/bin/forge-home-check.mjs +91 -0
  6. package/bin/forgedock.mjs +50 -7
  7. package/bin/gc.mjs +2 -0
  8. package/bin/hooks/pre-tool-use.mjs +4 -0
  9. package/bin/journey.mjs +55 -5
  10. package/bin/lean/admission.mjs +16 -5
  11. package/bin/lean/batch-health.mjs +55 -16
  12. package/bin/lean/batch-health.test.mjs +67 -1
  13. package/bin/lean/batch.mjs +8 -0
  14. package/bin/lean/batch.test.mjs +5 -0
  15. package/bin/lean/ceiling.mjs +20 -0
  16. package/bin/lean/ceiling.test.mjs +33 -2
  17. package/bin/lean/ci-gate.mjs +240 -0
  18. package/bin/lean/ci-gate.test.mjs +227 -0
  19. package/bin/lean/ci-precheck.mjs +178 -0
  20. package/bin/lean/ci-precheck.test.mjs +149 -0
  21. package/bin/lean/conformance.mjs +118 -20
  22. package/bin/lean/conformance.test.mjs +193 -3
  23. package/bin/lean/context.test.mjs +7 -6
  24. package/bin/lean/dag.mjs +128 -0
  25. package/bin/lean/dag.test.mjs +131 -0
  26. package/bin/lean/decisions.mjs +5 -4
  27. package/bin/lean/decisions.test.mjs +11 -0
  28. package/bin/lean/delguard.mjs +84 -0
  29. package/bin/lean/delguard.test.mjs +104 -0
  30. package/bin/lean/depcache.mjs +125 -17
  31. package/bin/lean/depcache.test.mjs +111 -0
  32. package/bin/lean/design-gate.mjs +5 -5
  33. package/bin/lean/design-gate.test.mjs +14 -0
  34. package/bin/lean/effects.mjs +81 -7
  35. package/bin/lean/execution.mjs +81 -15
  36. package/bin/lean/execution.test.mjs +156 -3
  37. package/bin/lean/forgedock-lane-workflow.test.mjs +35 -0
  38. package/bin/lean/guardgate.mjs +30 -7
  39. package/bin/lean/guardgate.test.mjs +44 -1
  40. package/bin/lean/guards.test.mjs +1 -1
  41. package/bin/lean/heavy.test.mjs +87 -0
  42. package/bin/lean/hotarea.mjs +73 -0
  43. package/bin/lean/hotarea.test.mjs +73 -0
  44. package/bin/lean/issuewatch-reconcile.mjs +20 -1
  45. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  46. package/bin/lean/lanecheck.mjs +27 -3
  47. package/bin/lean/lanecheck.test.mjs +47 -5
  48. package/bin/lean/laneconfine.mjs +83 -0
  49. package/bin/lean/laneconfine.test.mjs +113 -0
  50. package/bin/lean/lean.mjs +398 -91
  51. package/bin/lean/lean.test.mjs +792 -26
  52. package/bin/lean/live-reconcile.mjs +169 -0
  53. package/bin/lean/live-reconcile.test.mjs +176 -0
  54. package/bin/lean/orchestrate-envhold.test.mjs +245 -0
  55. package/bin/lean/orchestrate-hostfallback.test.mjs +39 -0
  56. package/bin/lean/orchestrate.mjs +207 -17
  57. package/bin/lean/outcomeevidence.mjs +104 -0
  58. package/bin/lean/outcomeevidence.test.mjs +78 -0
  59. package/bin/lean/page-capture.mjs +68 -0
  60. package/bin/lean/page-capture.test.mjs +44 -0
  61. package/bin/lean/pagegate.mjs +46 -7
  62. package/bin/lean/pagegate.test.mjs +66 -1
  63. package/bin/lean/postdeploy-check.mjs +18 -4
  64. package/bin/lean/postdeploy-check.test.mjs +32 -1
  65. package/bin/lean/prefilter.mjs +36 -4
  66. package/bin/lean/prefilter.test.mjs +31 -1
  67. package/bin/lean/preflight.mjs +22 -0
  68. package/bin/lean/preflight.test.mjs +19 -1
  69. package/bin/lean/probe.mjs +18 -0
  70. package/bin/lean/probe.test.mjs +40 -0
  71. package/bin/lean/prompts.mjs +41 -4
  72. package/bin/lean/recovery.test.mjs +20 -0
  73. package/bin/lean/recurrence.mjs +133 -0
  74. package/bin/lean/recurrence.test.mjs +99 -0
  75. package/bin/lean/release-config.mjs +2 -1
  76. package/bin/lean/release-config.test.mjs +18 -0
  77. package/bin/lean/release-control.mjs +4 -2
  78. package/bin/lean/release-control.test.mjs +15 -0
  79. package/bin/lean/release-merge-hold.mjs +65 -0
  80. package/bin/lean/release-merge-hold.test.mjs +69 -0
  81. package/bin/lean/release-review.mjs +26 -9
  82. package/bin/lean/release-review.test.mjs +53 -0
  83. package/bin/lean/release-status.mjs +3 -1
  84. package/bin/lean/release-status.test.mjs +11 -0
  85. package/bin/lean/release.test.mjs +26 -1
  86. package/bin/lean/render.mjs +8 -7
  87. package/bin/lean/repro-output.test.mjs +45 -0
  88. package/bin/lean/routing.mjs +49 -0
  89. package/bin/lean/routing.test.mjs +54 -1
  90. package/bin/lean/run-issue-placement.test.mjs +30 -1
  91. package/bin/lean/sandbox-actions.mjs +121 -0
  92. package/bin/lean/sandbox-actions.test.mjs +94 -0
  93. package/bin/lean/sandbox-provider.contract.test.mjs +22 -1
  94. package/bin/lean/sandbox-remote.mjs +3 -1
  95. package/bin/lean/schedd-health.mjs +14 -2
  96. package/bin/lean/schedd-health.test.mjs +13 -0
  97. package/bin/lean/schedd.mjs +43 -17
  98. package/bin/lean/schedd.test.mjs +61 -1
  99. package/bin/lean/toolchain.mjs +16 -6
  100. package/bin/lean/toolplace.mjs +12 -0
  101. package/bin/lean/weakguard.mjs +105 -0
  102. package/bin/lean/weakguard.test.mjs +59 -0
  103. package/bin/lean/winspawn.mjs +61 -0
  104. package/bin/lean/winspawn.test.mjs +45 -0
  105. package/bin/lean/worktree.mjs +3 -1
  106. package/bin/lean/worktree.test.mjs +11 -0
  107. package/bin/pool/agent.mjs +215 -15
  108. package/bin/pool/cache-sweep.mjs +74 -0
  109. package/bin/pool/cli.mjs +11 -3
  110. package/bin/pool/docker.mjs +33 -2
  111. package/bin/pool/health.mjs +38 -0
  112. package/bin/pool/lane-tools.mjs +23 -4
  113. package/bin/pool/lane-tools.test.mjs +12 -1
  114. package/bin/pool/router.mjs +21 -3
  115. package/bin/runner.mjs +37 -0
  116. package/bin/splash-scene.mjs +356 -0
  117. package/bin/win-hide-children.mjs +114 -0
  118. package/commands/orchestrate.md +18 -27
  119. package/commands/review-pr-agents/infra.md +1 -0
  120. package/commands/review-pr-staging.md +2 -2
  121. package/docs/CONFIG.md +60 -3
  122. package/docs/OUTCOME-CODES.md +3 -0
  123. package/package.json +1 -1
  124. package/plugins/forgedock-splash/.claude-plugin/plugin.json +1 -1
  125. package/plugins/forgedock-splash/README.md +1 -1
  126. package/plugins/forgedock-splash/hooks/scene.ts +142 -8
  127. package/pool/README.md +6 -0
  128. package/pool/image/entrypoint.sh +1 -0
  129. package/scripts/acceptance-red-green.sh +8 -3
  130. package/scripts/acceptance-red-green.test.sh +8 -0
  131. package/scripts/check-spec-size.sh +3 -1
  132. package/scripts/gen-splash-scene.mjs +24 -0
  133. package/scripts/review-staging-pre.sh +8 -3
  134. package/scripts/review-staging-pre.test.sh +2 -0
package/bin/lean/lean.mjs CHANGED
@@ -5,12 +5,14 @@
5
5
  * ForgeDock registers everything on GitHub (labels, one register comment, PR, merge). No investigation, synthesis,
6
6
  * severity taxonomy, risk tiers or local CI gates. All effects are injected through `io` so it is unit-testable.
7
7
  */
8
+ import { releaseMergeHold, ledgerIoFromGh } from "./release-merge-hold.mjs";
8
9
  import { issuePrMarker, supersedeOlderPrs, openPrBlockingClose } from "./orphan-pr.mjs";
9
10
  import { resolveFindingLabel } from "./findinglabel.mjs";
10
11
  import { spawnSync } from "node:child_process";
11
12
  import { existsSync, readFileSync } from "node:fs";
12
13
  import { join, dirname, basename, delimiter } from "node:path";
13
- import { hostname as osHostname } from "node:os";
14
+ import { isAbsPath } from "./winspawn.mjs";
15
+ import { hostname as osHostname, tmpdir as osTmpdir } from "node:os";
14
16
  import { appendEvent } from "../engine/runlog.mjs";
15
17
  import { testAdequacyRows, testAdequacyFailures, testAdequacyTelemetry, adequacyCounts, regressionRan } from "./testadequacy.mjs";
16
18
  import { readSelfReview, compareSelfReview, firstReviewRecord, selfCheckFailures } from "./selfreview.mjs";
@@ -21,25 +23,28 @@ import { createHash, randomBytes } from "node:crypto";
21
23
  import { otherLaneOwner } from "./lanelock.mjs";
22
24
  import { stampText, checkStamp } from "./stagestamp.mjs";
23
25
  import { acquireBranchLock, waitPidsExit } from "./branchlock.mjs";
24
- import { contractRuleCounts, onlyTestPlanProblems, isTestPath, applyValidateRecipes, rewriteProjectDirCommand, deferChecklessPostDeploy, autoPostDeployE2e, applyRequirementDecisions, loneE2eRows, 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";
26
+ import { parseRecurrenceConfig, recurrenceFacts, recursLinks, designLaneNote } from "./recurrence.mjs"; // #5751
27
+ import { areaOf, acquireHotArea, countCounters } from "./hotarea.mjs"; // #5751
28
+ import { contractRuleCounts, onlyTestPlanProblems, isTestPath, applyValidateRecipes, rewriteProjectDirCommand, deferChecklessPostDeploy, autoPostDeployE2e, applyRequirementDecisions, dedupeAddRequirements, loneE2eRows, reproEnvMiss, resolveForgedockPaths, resolvingIo, portableForgedockPaths, FORGEDOCK_CHECKS_VAR, FORGEDOCK_ENTRY_VAR, describesUnrunnableCommand, removedPathsOf, TRACKED, normalizeKindModes, blockingFailures, unverifiedRequirements, mutationTargets, mutationFailures, runMutationCheck, MUTATION_SURVIVED, isBugIssue, scopeText, explainFailures, inIssue, validateContract, snapQuotes, cliUsageError, normalizeRunnerCommand, applyAmendments, amendmentKindProblems, precheck, alreadyFixedOnBase, READONLY_PROD_RE, EXTERNAL_NEED_RE, intakeHostWork, repoTracks, dropScopeValidates, tagOutOfBand, parseReview, decide, mergeReviewRows, reaskable, criterionLines, closePlan, followupItems, renderPendingFollowups, bucketTally, pendingTracking, unnamedEdges, structureNote, impliedDocDeliverables, convertDelivered } from "./conformance.mjs";
25
29
  import { checkAdmission, hostParallelism, ADMISSION_RETRY_SECONDS } from "./admission.mjs";
26
- import { namedPaths, isTrustedIssueComment } from "./prefilter.mjs";
30
+ import { namedPaths, isTrustedIssueComment, prodFailureSignal } from "./prefilter.mjs";
27
31
  import { writeStatus, postUpsert, isStatusPost, isUpsertPost, hasSection, clearPipelineLabels } from "./statuscomment.mjs";
28
32
  import { checksAt, mergeCheckEntries, CHECKS_FILE } from "./postdeploy-check.mjs";
29
33
  import { matchBaselines, baselineFailures, foldRegression } from "./baselines.mjs";
30
34
  import { readRollouts, detectNewOffKeys, rolloutModes, liveDeferralBlocks } from "./activation.mjs";
31
35
  import { toolMisses } from "./toolplace.mjs";
32
- import { hasRecipe, installLaneTools } from "../pool/lane-tools.mjs";
33
- import { testRunnerProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract, declaredEnv, depInstallFailures, testRunSummary, projectBinDirs, withLocalBins, manifestDepOwner } from "./preflight.mjs";
36
+ import { hasRecipe, installLaneTools, RECIPES } from "../pool/lane-tools.mjs";
37
+ import { testRunnerProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract, declaredEnv, depInstallFailures, toolMissingInstalls, testRunSummary, projectBinDirs, withLocalBins, manifestDepOwner } from "./preflight.mjs";
34
38
  import { resolveLane, isDefaultLane, isShippedLane, DEFAULT_STAGING_BRANCH } from "./lane.mjs";
35
39
  import { splitGate, rationaleLine } from "./decompose.mjs";
36
- import { ceilingFor, predictRestart, handoffFacts, NARROW_NOTE } from "./ceiling.mjs";
40
+ import { ceilingFor, predictRestart, handoffFacts, routeHandoff, buildReadsOf, NARROW_NOTE } from "./ceiling.mjs";
37
41
  import { dockerLabels, LEDGER_TTL_MS } from "./ledger.mjs";
38
42
  import { batchImageCache, envNamesOf, provisionSandboxes } from "./testsandbox.mjs";
39
43
  import { repoKey, estimateCostUsd } from "../runner.mjs";
40
44
  import { prepareToolchain } from "./toolchain.mjs";
41
45
  import { toolStats } from "./toolstats.mjs";
42
46
  import { readTestMap, readTestMapAtRef, selectCommands, mergeChecks, factsPath, TEST_MAP_FILE } from "./testmap.mjs";
47
+ import { deriveCiPrecheck, ciPrecheckOutcome, parseCiPrecheckConfig } from "./ci-precheck.mjs";
43
48
  import { runChecks, runWithTimeoutRetry, splitPrecheckResults, timedOutDetail, planPrecheck, worktreeFingerprint, selfCheckState, quietFailure, CHECK_PLAN_FILE, SELF_CHECK_FILE, CHECK_LOG_DIR } from "./precheck.mjs";
44
49
  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";
45
50
  import { renderInvestigation, renderImplementation, renderReview, renderPrBody, renderTrajectory, renderContract, renderAmendments, renderShadowReview, parseContractComment, parseAmendmentsComment, contractJson, capComment, sanitizeMd, MAX_COMMENT_CHARS, recoveryEvidence } from "./render.mjs";
@@ -59,27 +64,31 @@ export function contractSelfCorrectable(problems) {
59
64
  export function missingToolBlock(summary) { return MISSING_TOOL_RE.test(String(summary ?? "")); }
60
65
  import { reserveForBuild, revalidate } from "./seqreserve.mjs";
61
66
  import { patchEcho, mutationsOf, runReproMutations, classifyRepro } from "./reproquality.mjs";
62
- 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, docsPlanNote, pagePlanNote, 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";
67
+ 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, docsPlanNote, pagePlanNote, contextPackNote, buildOpeningNote, sequenceBuildRule, docsPrompt, ciFailurePrompt, ciUnavailablePrompt, precheckFailurePrompt, contextRestartPrompt, routeDigestPrompt, turnBudgetWrapupPrompt, syncChecks, GROUPING_SYSTEM, enumeratingPlanNote, enumeratingBuildRule, invariantsPlanNote, invariantsBuildRule, missingEntriesPrompt, sequencePrompt, sequenceSyncNote, sequenceSyncPrompt, fixSessionPrompt, postMergeFailurePrompt, duplicateExportsPrompt, migrationGeneratorPrompt, i18nCopiesPrompt, narrowFixPrompt } from "./prompts.mjs";
63
68
  import { postMergeCommands } from "./postmerge.mjs";
64
69
  import { classifyBaseRed, attribute as attributeBaseRed, runOnBase, reportBaseRed } from "./basered.mjs"; // #5239
65
70
  import { guardAfterMerge, withHistoryRows } from "./guards.mjs";
66
71
  import { parseProdParity, prodParityFailures as prodParityOf } from "./prodparity.mjs";
67
72
  import { routePathsFromFiles, routeReachabilityFailures } from "./routecheck.mjs";
68
73
  import { docsFailures } from "./docsgate.mjs";
69
- import { pageFailures, designSpecApproved, designLabelApproved } from "./pagegate.mjs"; // #5428
74
+ import { outcomeEvidenceFailures, rawChecksAt } from "./outcomeevidence.mjs";
75
+ import { ciBudgetFailures, parseCiBudget } from "./ci-gate.mjs";
76
+ import { pageFailures, designSpecApproved, designLabelApproved, specOnlyFailures, pageFiles, designOnlyFiles } from "./pagegate.mjs"; // #5428
77
+ import { changedRoutes, captureVisualCheck, publishToRef, visualMarkdown } from "./page-capture.mjs"; // #5770
70
78
  import { uiBuildRule, uiIssue, uiChanged } from "./ui-quality.mjs"; // #5330
71
79
  import { designGate, designGateNote, designFailures, specApproved as designSpecOk } from "./design-gate.mjs"; // #5330
72
80
  import { parseCoupled, coupledFailures } from "./coupled.mjs";
73
81
  import { analyzeRelaxations, relaxationFailures } from "./relaxation.mjs";
74
82
  import { startSpeculative } from "./overlap.mjs";
75
- import { loadGuards, selectGuards, runGuards, supersededIds, supersessionComment } from "./guardgate.mjs";
83
+ import { loadGuards, selectGuards, runGuards, supersededIds, supersessionComment, weakGuardNotes } from "./guardgate.mjs";
76
84
  import { freshFix, issueSummary, firstPassOf, sessionCostDelta, mergeNarrowTasks } from "./fixround.mjs";
77
- import { parseBuilderRouting, routeBuilder, shouldEscalate } from "./routing.mjs";
85
+ import { floorRoute, parseBuilderRouting, provisionalRoute, routeBuilder, shouldEscalate } from "./routing.mjs";
78
86
  import { makeTurnBudget, TURN_BUDGET_DEFAULTS, scaledExtra, laneSize, recoverySize, wrapupGrant, budgetDigest } from "./budget.mjs";
79
87
  import { pendingPitfall, pitfallRecord, foldPitfalls, selectPitfalls, failureLog } from "./pitfalls.mjs";
80
88
  import { unjustified } from "./enumerating.mjs";
81
89
  import { applyEnumerating, renameDuplicates, verifyApplied } from "./mechfix.mjs"; // #5348
82
90
  import { addLaneWorktree, DEFAULT_SPARSE_MAX_KB } from "./worktree.mjs";
91
+ import { ceilingEnv, listedWorktree } from "./laneconfine.mjs";
83
92
  import { claimWarm, refillWarm, warmTreeCount, NO_HOOKS } from "./warmtree.mjs";
84
93
  import { ciSignal, cancelDecision, eventLog } from "./ci-watch.mjs";
85
94
  import { classifyCiFailure } from "./ci-classify.mjs";
@@ -112,6 +121,7 @@ import { pickSalvage } from "./salvage-resume.mjs";
112
121
  import { makePostRun } from "./postrun.mjs";
113
122
  import { ensureSignedOff, salvageBranch, dropSalvageTracking } from "./signoff.mjs";
114
123
  import { reconcileCheckpoints } from "./checkpoint-reconcile.mjs";
124
+ import { guardStagedDeletions, deletionEvidence, maxForeignDeletions } from "./delguard.mjs";
115
125
  import { createLedger, flattenPhases } from "./phaseledger.mjs";
116
126
  import { DEFAULT_CATALOG_SOURCES, deriveCatalog, mergeRecipes, rewriteMissed, isDriftFailure, rewriteSubprojectVenv } from "./validate-catalog.mjs";
117
127
  import { runLightStep, runLightTests, lightBuildPrompt, upgradeNote, renderLiteReceipt } from "./lightlane.mjs";
@@ -146,6 +156,24 @@ export function builderFixable(failures) {
146
156
  }
147
157
  /** #5168: retry-in for a `backend.auth` deferral; the batch holds the account for it (an operator `--set-env` fix runs under a new identity). */
148
158
  const AUTH_RETRY_SECONDS = 900;
159
+ /** #5762: retry-in for a `backend.cli_failed` deferral (transient, not an account condition). */
160
+ const CLI_FAILED_RETRY_SECONDS = 120;
161
+ /** #5762: the account number (digits only) a lane used: the rotator's capture, else TOKENBATON_ACCOUNT / CLAUDE_CONFIG_DIR `.claude-<n>`; null when unknown. */
162
+ export function laneAccountNumber(env = process.env, account = null) {
163
+ if (account != null && /^\d+$/.test(String(account))) return String(account);
164
+ if (/^\d+$/.test(env?.TOKENBATON_ACCOUNT ?? "")) return env.TOKENBATON_ACCOUNT;
165
+ const m = /[\\/]\.claude-(\d+)[\\/]?$/.exec(env?.CLAUDE_CONFIG_DIR ?? "");
166
+ return m ? m[1] : null;
167
+ }
168
+ /** #5762: the CLI result/is_error text and account carried on a deferral and its RUN_TERMINAL. */
169
+ function cliDeferFacts(e, account) {
170
+ const acct = laneAccountNumber(process.env, account);
171
+ return { ...(e?.cliResult != null ? { cliResult: e.cliResult } : {}), ...(typeof e?.cliIsError === "boolean" ? { cliIsError: e.cliIsError } : {}), ...(acct ? { account: acct } : {}) };
172
+ }
173
+ function cliDetail(e, account) {
174
+ const acct = laneAccountNumber(process.env, account);
175
+ return ` [${acct ? `account ${acct}; ` : ""}is_error=${e?.cliIsError ?? "?"}; result=${e?.cliResult != null ? JSON.stringify(e.cliResult) : "none"}]`;
176
+ }
149
177
  /** #4323/#4334: precheck failure codes that are environment errors (state "environment"), never a builder resume. */
150
178
  const ENV_CODES = Object.freeze([OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, ENV_VALIDATE_TIMEOUT, OUTCOME_CODES.CONTRACT_INVALID_COMMAND]);
151
179
  export const DEFAULT_REVIEWER_MODEL = "claude-sonnet-5-5";
@@ -162,7 +190,7 @@ const SHADOW_BLOCKS = [OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, OUTCOME_CODES.CO
162
190
  * not done, an invalid amendment) or conformance.regression, the same codes a review blocks on, and unexempted growth of an
163
191
  * over-threshold file (maintenance.hotspot_growth, forge#4195). Scope creep stays recorded-only.
164
192
  */
165
- const SHADOW_PRE_BLOCKS = [...SHADOW_BLOCKS, OUTCOME_CODES.MAINTENANCE_HOTSPOT_GROWTH];
193
+ const SHADOW_PRE_BLOCKS = [...SHADOW_BLOCKS, OUTCOME_CODES.MAINTENANCE_HOTSPOT_GROWTH, OUTCOME_CODES.MAINTENANCE_COUNTER_GROWTH, OUTCOME_CODES.RECURRENCE_DESIGN_MISSING]; // #5751
166
194
  /** #4395: cap on the engine.lane_instructions file; a larger one is not slim and falls back to CLAUDE.md. */
167
195
  export const LANE_INSTRUCTIONS_MAX_BYTES = 16384;
168
196
  /** forge.yaml engine.review_incomplete (#4160): "needs-human" (default), or "degraded": in shadow, merge an incomplete review with a review-degraded label and a tracked follow-up. */
@@ -171,11 +199,24 @@ export const REVIEW_DEGRADED_LABEL = "review-degraded";
171
199
  const UNUSABLE_REVIEW_CODES = { "review.unparseable": OUTCOME_CODES.REVIEW_NO_VERDICT, "review.incomplete": OUTCOME_CODES.REVIEW_INCOMPLETE, "review.inconsistent": OUTCOME_CODES.REVIEW_INCONSISTENT };
172
200
  export const REGISTER_MARKER = "FORGE:WORK-ON"; // alias marker carried by the FORGE:TRAJECTORY comment
173
201
  const num = (v) => (Number.isFinite(v) ? v : null);
202
+ /** #5734: the needs-human text when a recorded production failure blocks an already-fixed/invalid close. */
203
+ const prodFailNote = (verdict, f) => `Builder reported "${verdict}", but a trusted comment records the fix failing in production (${f.why}${f.url ? `: ${f.url}` : ""}), so the issue is not closed automatically: a merged ancestor is no evidence for a production outcome.\n\n> ${f.excerpt}`;
174
204
  export const MAX_SUBISSUES = 8;
175
205
  /** #4266: required checks with no rollup entry this long into a CI wait on a MERGEABLE PR log CI_NOT_STARTED (once per wait). */
176
206
  export const CI_NOT_STARTED_GRACE_MS = 10 * 60 * 1000;
177
207
  /** 12-hex sha256 of the canonical contract JSON text (renderContract embeds the same text). */
178
208
  export const contractHash = (text) => createHash("sha256").update(String(text)).digest("hex").slice(0, 12);
209
+ /**
210
+ * #5811: why a frozen contract read back from the issue cannot be reused, or null. A changed issue scope (#4265) or a
211
+ * different recorded base is stale. Without a branch to resume (a recovery that ended before its first commit) only a
212
+ * contract that records both the scope and the base it was planned on is reused; a legacy one re-plans as before.
213
+ */
214
+ export function reuseStale({ fc, scopeHash, lane, resumed, gone = [] }) {
215
+ if (fc.base && fc.base !== lane) return `base ${fc.base} -> ${lane}`;
216
+ if (!resumed && !(fc.scope && fc.base)) return "no branch to resume and the contract records no issue scope or base";
217
+ if (fc.scope) return fc.scope !== scopeHash ? `issue scope ${fc.scope} -> ${scopeHash}` : null;
218
+ return fc.humanAfter ? "a human comment was posted after it" : gone.length ? `quote(s) no longer in the issue: ${gone.join(", ")}` : null;
219
+ }
179
220
 
180
221
  /**
181
222
  * #4385: siblings that declare a shared file (a barrel, union type, shared fixture, index doc) would conflict after the
@@ -298,8 +339,9 @@ const defaultCredExec = (args) => {
298
339
  */
299
340
  export async function runCore(o) {
300
341
  const armed = applyArmOverrides(o, o.issue); o = armed.options; // #5206: the arm's overrides shape the lane before any config is parsed
342
+ o = { ...o, io: resolvingIo(o.io, { exists: existsSync, checksCli: CHECKS_CLI, forgedockCli: FORGEDOCK_CLI }) }; // #5727: every executed command names this install's forgedock entry points
301
343
  const { issue, repo, lane: requestedLane = null, laneOverride = false, branches = {}, cwd, dir, io, builderModel = null, reviewerModel = DEFAULT_REVIEWER_MODEL, fixModel = null,
302
- toolchainOverride = null, testRunners = null, coupledFiles = null, validateRecipes = null, validateRegenerate = null, validateCatalogSources = null, routeReachability = null, docsConfig = null, pagesConfig = null, designConfig = null, prodParity = null, envSetup = null, ciMaxMinutes = 360, conformance = "shadow", conformanceKinds = null, conformanceMutation = "off", reviewIncomplete = "needs-human", reproTest = "prefer", reproQuality = "shadow", closeParent = false, mergeWait = "required", maxSessionLimitPauses = DEFAULT_MAX_SESSION_LIMIT_PAUSES, cliIdleMinutes = 15, cliMaxMinutes = 180, cliBusyMinutes = 45, contextCeilingTokens = 120000, contextCeilingBySize = null, turnBudgets = null, laneLimits = null, maxMergeRetries = 5, contractMaxCorrections = 3, reviewMaxResumes = 3, sessionLimitMaxWaitMs = DEFAULT_SESSION_LIMIT_WAIT_MS, contextWaitSeconds = 5, onProgress = () => {}, emitTelemetry = null, random = Math.random } = o;
344
+ toolchainOverride = null, testRunners = null, coupledFiles = null, validateRecipes = null, validateRegenerate = null, validateCatalogSources = null, routeReachability = null, docsConfig = null, outcomeEvidenceConfig = null, ciBudget = null, pagesConfig = null, designConfig = null, prodParity = null, envSetup = null, ciMaxMinutes = 360, holdMergesDuringReleaseCi = true, conformance = "shadow", conformanceKinds = null, conformanceMutation = "off", reviewIncomplete = "needs-human", reproTest = "prefer", reproQuality = "shadow", closeParent = false, mergeWait = "required", maxSessionLimitPauses = DEFAULT_MAX_SESSION_LIMIT_PAUSES, cliIdleMinutes = 15, cliMaxMinutes = 180, cliBusyMinutes = 45, contextCeilingTokens = 120000, contextCeilingBySize = null, routeHandoffTokens = 40000, turnBudgets = null, laneLimits = null, maxMergeRetries = 5, contractMaxCorrections = 3, reviewMaxResumes = 3, sessionLimitMaxWaitMs = DEFAULT_SESSION_LIMIT_WAIT_MS, contextWaitSeconds = 5, onProgress = () => {}, emitTelemetry = null, random = Math.random } = o;
303
345
  const now = io.now ?? (() => Date.now());
304
346
  const rotator = io.rotator !== undefined ? io.rotator : openRotator({ kind: o.accountRotator }); // #5094
305
347
  // #5205: a rotator with pick() relaunches a limited phase pinned to another account; lane-level rotations and limited accounts
@@ -320,8 +362,9 @@ export async function runCore(o) {
320
362
  const verifierCfg = parseVerifierConfig(o.verifier ?? {});
321
363
  const routingCfg = parseBuilderRouting(o.builderRouting ?? {});
322
364
  // #4394: the build's model tier, routed from the frozen contract; a failed validate round on the mid tier escalates once
323
- let route = null, escalated = false;
324
- const laneModel = () => (route?.tier === "mid" && !escalated ? route.model : builderModel);
365
+ // #5810: before the contract, the pre-contract sessions run on a provisional route from the issue's own signals
366
+ let route = null, escalated = false, preRoute = null;
367
+ const laneModel = () => { const r = route ?? preRoute; return r?.tier === "mid" && !escalated ? r.model : builderModel; };
325
368
  const sleep = io.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
326
369
  let lane = null, base = null, defaults = [], milestone = null; // set by lane resolution, before the lease
327
370
  // #4267: a batch recovery lane for a mechanical needs-human ({code, attempt, final}); #4302: only a final attempt relabels.
@@ -350,7 +393,28 @@ export async function runCore(o) {
350
393
  const sleepFn = io.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
351
394
  /** gh writes (comment, pr create, issue edit/close): retried for 5xx and secondary rate limits (#4114). */
352
395
  const ghw = (args) => retrying(() => ghc(args), { transient: GH_TRANSIENT_RE, attempts: 4, sleep: sleepFn, random });
353
- const git = (args, o = {}) => io.git(args, { cwd: wt, ...o });
396
+ // #5825: every lane git call is confined to the lane worktree (discovery never walks up into the checkout around it),
397
+ // and a write first asserts the lane folder is this repo's worktree; a refusal ends the lane engine-error, nothing written.
398
+ const laneGitEnv = ceilingEnv(wt) ?? {};
399
+ let confineRefusal = null;
400
+ const GIT_WRITES = new Set(["add", "commit", "push", "rm", "mv", "reset", "checkout", "switch", "restore", "merge", "rebase", "cherry-pick", "revert", "am", "apply", "clean", "stash", "tag", "notes", "update-index"]);
401
+ const confineError = () => Object.assign(new Error(confineRefusal), { engineCode: OUTCOME_CODES.ENGINE_ERROR, confined: false });
402
+ async function assertConfined(at) {
403
+ if (confineRefusal) throw confineError();
404
+ if (!io.confine?.verify) return;
405
+ if (io.fs?.exists && !(await io.fs.exists(wt))) throw new Error(`lane worktree ${wt} does not exist`); // no folder: git cannot run there at all
406
+ const v = await io.confine.verify({ wt, cwd });
407
+ if (v?.ok !== false) return;
408
+ const e = v.evidence ?? {};
409
+ confineRefusal = `Lane worktree ${wt} is not confined (${at}): ${v.why}; git toplevel ${e.toplevel ?? "(none)"}, git common dir ${e.common_dir ?? "(none)"}, repository common dir ${e.repo_common_dir ?? "(unknown)"}. Stopped before any git write (#5825).`;
410
+ ev({ event: "WORKTREE_NOT_CONFINED", at, why: v.why, ...e });
411
+ throw confineError();
412
+ }
413
+ const git = async (args, o = {}) => {
414
+ if ((o.cwd ?? wt) === wt && GIT_WRITES.has(args[0])) await assertConfined(`git ${args[0]}`);
415
+ return io.git(args, { cwd: wt, ...o, env: { ...laneGitEnv, ...o.env } });
416
+ };
417
+ let pageVisual = null; // #5770: the engine's visual capture {sha, screenshots, errors, rows}, kept for the page gate and the PR body
354
418
 
355
419
  const builderTriggers = []; // #4362: implement-attempt triggers in order, for the lane's first-pass flag
356
420
  let usageUnknown = false, inflight = null; // #5334: a killed session streamed nothing; the builder call in flight (flushed when a signal ends the run)
@@ -507,6 +571,8 @@ export async function runCore(o) {
507
571
  const heavyCfg = o.heavy ?? {}, heavyOn = Boolean(io.heavy) && heavyCfg.enabled !== false;
508
572
  let heavyEnv = null, heavyWaitsFile = null, heavyQueueMax = 0, stage = "plan", iss;
509
573
  let seqBuildNote = ""; // #5235: numbers reserved for this lane at build start (prompt paragraph)
574
+ const recCfg = parseRecurrenceConfig(o.recurrenceConfig); // #5751: forge.yaml recurrence: (absent: mode on, threshold 2, no hot areas or counters)
575
+ let recurrence = null, hotLock = null; // #5751: the recurrence detection; the hot-area locks held until teardown
510
576
  let seqLease = null; // #4386: the host sequence lease, held from the merge-gate renumber through the merge
511
577
  const waits = {};
512
578
  const followupsFiled = []; // #5078: {issue, class, count} per tracking issue this lane filed into, for the batch report
@@ -526,6 +592,7 @@ export async function runCore(o) {
526
592
  async function heavyStep(phase, fn) { const g = await heavyAcquire(phase); try { return await fn(); } finally { try { g?.release?.(); } catch { /* fail-open */ } } }
527
593
  // ---- lane resource ledger (#4179): every owned resource is registered before it is created, released after its teardown ----
528
594
  let ledger = null, deleteLocalBranch = false, laneHead = null; // #4958: laneHead = {branch, sha, pushedTo}
595
+ let deletionRefusal = null; // #5819: evidence of a checkpoint that refused tracked-file deletions; the lane ends engine-error, nothing pushed
529
596
  const ledgerDo = (fn) => { if (!ledger) return; try { fn(ledger); } catch (e) { ev({ event: "LEDGER_ERROR", error: String(e?.message ?? e).slice(0, 300) }); } };
530
597
  const protectedBranch = (b) => isProtectedLaneBranch(b, { issue, lane, branches, defaults });
531
598
  /** Teardown from the ledger (#4179), on every exit path: builder pids, checkpoint of unpushed work, run tmp, worktree, branch, docker. */
@@ -574,7 +641,7 @@ export async function runCore(o) {
574
641
  */
575
642
  async function salvage(why) {
576
643
  if (!io.fs?.exists || !(await io.fs.exists(wt))) return null;
577
- const g = (a) => io.git(a, { cwd: wt });
644
+ const g = (a) => io.git(a, { cwd: wt, env: laneGitEnv }); // #5825: a folder without its .git link fails here, never stages the checkout around it
578
645
  try {
579
646
  await g(["add", "-A"]);
580
647
  if (await io.fs.exists(join(wt, LEAN_DIR))) await g(["add", "-f", "--", LEAN_DIR]);
@@ -593,6 +660,21 @@ export async function runCore(o) {
593
660
  return null;
594
661
  }
595
662
  }
663
+ /**
664
+ * #5825: move a lane folder that is not a registered worktree of this repo aside (`<root>/.quarantine/`), kept for
665
+ * inspection and never reused. A folder that cannot be moved stops the lane engine-error before any git write.
666
+ */
667
+ async function quarantine(why, evidence = {}) {
668
+ let to = null;
669
+ try { to = await io.confine?.quarantine?.({ wt }); } catch (e) {
670
+ ev({ event: "WORKTREE_QUARANTINE_FAILED", path: wt, why, error: String(e?.message ?? e).slice(0, 200), ...evidence });
671
+ throw Object.assign(new Error(`Lane folder ${wt} is not a registered worktree (${why}) and could not be moved aside: ${String(e?.message ?? e).slice(0, 200)}. Stopped before any git write (#5825); remove the folder and rerun.`), { engineCode: OUTCOME_CODES.ENGINE_ERROR });
672
+ }
673
+ if (!to) throw Object.assign(new Error(`Lane folder ${wt} is not a registered worktree (${why}); no quarantine is available. Stopped before any git write (#5825).`), { engineCode: OUTCOME_CODES.ENGINE_ERROR });
674
+ ev({ event: "WORKTREE_QUARANTINED", path: wt, to, why, ...evidence });
675
+ T.anomalies.push(`Lane folder ${wt} was not a registered worktree (${why}); moved to \`${to}\` and a fresh worktree was added (#5825)`);
676
+ return to;
677
+ }
596
678
  /** #4162: stop processes still running inside the worktree (an orphaned runner from a dead run) before it is removed. */
597
679
  async function stopWorktreeProcs() {
598
680
  if (!io.proc) return;
@@ -613,10 +695,13 @@ export async function runCore(o) {
613
695
  }
614
696
  async function finishOnce(reason, detail = "", extra = {}, codeOverride = null) {
615
697
  await flushInflight(); // #5334: a signal mid-attempt: the session's usage so far is recorded before RUN_TERMINAL
698
+ try { io.host?.recordPeakRss?.(Math.ceil(process.resourceUsage().maxRSS / 1024)); } catch { /* fail-open (#5845): the learned lane footprint is best effort */ }
616
699
  try { seqLease?.release(); } catch { /* fail-open */ }
617
700
  seqLease = null;
618
701
  try { surfaceClaim?.release(); } catch { /* fail-open */ }
619
702
  surfaceClaim = null;
703
+ try { hotLock?.release(); } catch { /* fail-open */ }
704
+ hotLock = null;
620
705
  try { await io.sequenceLease?.undeclare?.({ repo, issue }); } catch { /* fail-open (#5340) */ }
621
706
  try { await io.sequenceLease?.unreserve?.({ repo, lane, issue }); } catch { /* fail-open (#4526) */ }
622
707
  if (heavyWaitsFile) { // #4169: builder-run heavy waits, read before teardown removes the run TMPDIR
@@ -627,10 +712,21 @@ export async function runCore(o) {
627
712
  if (!deferTail) {
628
713
  await postLaneFacts(); // #4401: before teardown removes the worktree's result.json
629
714
  await teardown(reason, extra); // first: unpushed work is pushed while this run still holds the lease
715
+ if (confineRefusal && !String(detail).includes(confineRefusal)) { // #5825: an unconfined lane folder ends the lane engine-error, with the evidence
716
+ if (reason !== "engine-error") ev({ event: "TERMINAL_OVERRIDDEN", from: reason, to: "engine-error", why: "lane folder is not a confined worktree" });
717
+ detail = `${confineRefusal}${detail ? ` (lane was ending ${reason}: ${String(detail).split("\n")[0].slice(0, 200)})` : ""}`;
718
+ reason = "engine-error"; codeOverride = OUTCOME_CODES.ENGINE_ERROR;
719
+ }
720
+ if (deletionRefusal && !String(detail).includes(deletionRefusal)) { // #5819: a refused checkpoint ends the lane engine-error, with the evidence
721
+ if (reason !== "engine-error") ev({ event: "TERMINAL_OVERRIDDEN", from: reason, to: "engine-error", why: "checkpoint refused tracked-file deletions" });
722
+ detail = `${deletionRefusal}${detail ? ` (lane was ending ${reason}: ${String(detail).split("\n")[0].slice(0, 200)})` : ` (lane was ending ${reason})`}`;
723
+ reason = "engine-error"; codeOverride = OUTCOME_CODES.ENGINE_ERROR;
724
+ }
630
725
  }
631
726
  const code = codeOverride ?? codeForTerminalReason(reason);
632
727
  // forge#4165: pr, milestone and the conformance verdict ride on the existing RUN_TERMINAL write (verdict-mix queries).
633
- const term = { event: "RUN_TERMINAL", reason, code, ...(extra.pr ? { pr: extra.pr } : {}), ...(milestone ? { milestone } : {}), ...(verifiedLane != null ? { verified: verifiedLane } : {}),
728
+ const term = { event: "RUN_TERMINAL", reason, code, ...(extra.cliResult != null ? { cli_result: extra.cliResult } : {}), ...(typeof extra.cliIsError === "boolean" ? { cli_is_error: extra.cliIsError } : {}), ...(extra.account ? { account: extra.account } : {}), // #5762
729
+ ...(extra.pr ? { pr: extra.pr } : {}), ...(milestone ? { milestone } : {}), ...(verifiedLane != null ? { verified: verifiedLane } : {}),
634
730
  ...(reproQ ? { repro_quality: reproQ } : {}), conformance_mode: conformance === "enforce" || riskEnforced ? "enforce" : "shadow", ...(shadowWould ? { shadow_would: shadowWould } : {}), ...(firstReview ? { first_review: firstReview } : {}), ...(adequacyTel ?? {}),
635
731
  ...(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() } : {}),
636
732
  ...(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
@@ -722,7 +818,7 @@ export async function runCore(o) {
722
818
  const notes = [premiseAnnotation(predicate), closedEdgeNote(closedDeps), link, askNote].filter(Boolean).join("\n");
723
819
  try { await post("FORGE:NEEDS_HUMAN", `## Needs human\n${why}${notes ? `\n\n${notes}` : ""}${recoverUnlabelled ? `\n\n${laneRecoveryEvidence("needs-human", code, "")}` : ""}\n\n_${usageLine()}_`); }
724
820
  catch (e) { labelFailed("comment", e); }
725
- // #5423: an environment gap is the engine's to recover (the batch requeues it), so a first lane leaves the issue visible; a final recovery lane still labels
821
+ // #5423/#5755: an environment gap is the engine's to recover or hold on an env issue, so a first lane leaves the issue visible; a final recovery lane (no seam) still labels
726
822
  if (!(!recover && ENV_ENGINE_OWNED_CODES.includes(code))) {
727
823
  try { await ghc(["issue", "edit", String(issue), "-R", repo, "--add-label", "needs-human"]); }
728
824
  catch (e) { labelFailed("label", e); }
@@ -828,7 +924,7 @@ export async function runCore(o) {
828
924
  async function installSignoffHook() {
829
925
  if (!runTmp || !io.fs?.list || !io.runCommand) return;
830
926
  try {
831
- const orig = String(await git(["rev-parse", "--git-path", "hooks"])).trim(), abs = orig.startsWith("/") ? orig : `${wt}/${orig}`, dir = `${runTmp}/hooks`;
927
+ const orig = String(await git(["rev-parse", "--git-path", "hooks"])).trim(), abs = isAbsPath(orig) ? orig : `${wt}/${orig}`, dir = `${runTmp}/hooks`;
832
928
  const q = (x) => `'${String(x).replace(/'/g, "'\\''")}'`, own = ((await io.fs.list(abs)) ?? []).filter((n) => n && !n.endsWith(".sample"));
833
929
  for (const n of own.filter((x) => x !== "commit-msg")) await io.fs.write(`${dir}/${n}`, `#!/bin/sh\nexec ${q(`${abs}/${n}`)} "$@"\n`);
834
930
  await io.fs.write(`${dir}/commit-msg`, `${SIGNOFF_HOOK}${own.includes("commit-msg") ? `exec ${q(`${abs}/commit-msg`)} "$@"\n` : "exit 0\n"}`);
@@ -842,11 +938,14 @@ export async function runCore(o) {
842
938
  let deps = {};
843
939
  try { deps = io.deps?.env?.() ?? {}; } catch { deps = {}; }
844
940
  const par = verifyParallelism();
845
- return { ...deps, ...(runTmp ? { TMPDIR: runTmp } : {}), ...(par ? { FORGE_HOST_PARALLELISM: par } : {}), FORGE_LANE_WORKTREE: "1", ...sandboxEnv, ...(toolchain?.env ?? {}) }; // #5333: the hook denies git stash where this is set
941
+ return { ...deps, ...(runTmp ? { TMPDIR: runTmp } : {}), ...(par ? { FORGE_HOST_PARALLELISM: par } : {}), FORGE_LANE_WORKTREE: "1", ...laneGitEnv, [FORGEDOCK_CHECKS_VAR]: CHECKS_CLI, [FORGEDOCK_ENTRY_VAR]: FORGEDOCK_CLI, ...sandboxEnv, ...(toolchain?.env ?? {}) }; // #5333: the hook denies git stash where this is set; #5825: git in a lane child never walks up out of the worktree
846
942
  }
847
943
  /** #5168: a failed claude login ends the lane `deferred` `backend.auth`, held per account by the batch (never the relaunch or the breaker). */
848
- const authDeferral = (e) => Object.assign(e, { deferCode: OUTCOME_CODES.BACKEND_AUTH, retryInSeconds: AUTH_RETRY_SECONDS, backendId: laneBackendId(process.env, rotator),
849
- deferDetail: `claude CLI authentication failed (login expired or invalid); held until the login is fixed: ${String(e?.message ?? e).split("\n")[0].slice(0, 300)}` });
944
+ const authDeferral = (e, account = null) => Object.assign(e, { deferCode: OUTCOME_CODES.BACKEND_AUTH, retryInSeconds: AUTH_RETRY_SECONDS, backendId: laneBackendId(process.env, rotator), ...cliDeferFacts(e, account),
945
+ deferDetail: `claude CLI authentication failed (login expired or invalid); held until the login is fixed${cliDetail(e, account)}: ${String(e?.message ?? e).split("\n")[0].slice(0, 300)}` });
946
+ /** #5762: a claude exit that never reached the API and was no login failure: a short capped retry, no account hold. */
947
+ const cliFailedDeferral = (e, account = null) => Object.assign(e, { deferCode: OUTCOME_CODES.BACKEND_CLI_FAILED, retryInSeconds: CLI_FAILED_RETRY_SECONDS, ...cliDeferFacts(e, account),
948
+ deferDetail: `claude CLI exited without reaching the API${cliDetail(e, account)}; retried shortly: ${String(e?.message ?? e).split("\n")[0].slice(0, 300)}` });
850
949
  /** #5236: no account has room: the lane ends deferred `quota.exhausted` (earliest reset) and emits QUOTA_EXHAUSTED, never a spawn or a far pause. */
851
950
  const exhaustedStop = (e, x, role) => { ev({ event: "QUOTA_EXHAUSTED", phase: role, earliestReset: x.earliestReset }); return exhaustedDeferral(e, { earliestReset: x.earliestReset, backendId: laneBackendId(process.env, rotator), now: now() }); };
852
951
  /** Runner call with the per-run TMPDIR and FORGE_HOST_PARALLELISM; a usage limit pauses and resumes the same step, or defers past the cap (#4101). */
@@ -871,7 +970,8 @@ export async function runCore(o) {
871
970
  catch (e) {
872
971
  watch?.stop(); watch?.refresh(); // #5268: the account the shim exec'd, read before the limited child is gone or now
873
972
  let epoch = Number.isFinite(e?.resetAtEpochMs) ? e.resetAtEpochMs : null;
874
- if (e?.authFailure === true && e.usageLimit !== true && epoch === null) { const x = smartRotator ? poolExhausted(rotator, laneLimited) : null; throw x ? exhaustedStop(e, x, args.role) : authDeferral(e); } // #5236: an auth failure with no account room is exhaustion // #5168: an account condition, never engine-error
973
+ if (e?.authFailure === true && e.usageLimit !== true && epoch === null) { const x = smartRotator ? poolExhausted(rotator, laneLimited) : null; throw x ? exhaustedStop(e, x, args.role) : authDeferral(e, account); } // #5236: an auth failure with no account room is exhaustion // #5168: an account condition, never engine-error
974
+ if (e?.cliFailed === true && e.usageLimit !== true && epoch === null) throw cliFailedDeferral(e, account); // #5762
875
975
  if (!(e?.usageLimit === true || epoch !== null)) throw e;
876
976
  if (smartRotator) { // #5205: exclude the limited account and relaunch the same args (resume kept) pinned to another, at once
877
977
  if (account !== null) { const until = epoch !== null && epoch > now() ? epoch : now() + DEFAULT_SESSION_LIMIT_WAIT_MS; laneLimited.set(account, until); try { rotator.markLimited(account, until); } catch { /* best effort */ } }
@@ -923,6 +1023,8 @@ export async function runCore(o) {
923
1023
  return r;
924
1024
  };
925
1025
  const gitPush = async (args) => {
1026
+ if (deletionRefusal && !args.includes("--delete")) throw Object.assign(new Error(deletionRefusal), { engineCode: OUTCOME_CODES.ENGINE_ERROR }); // #5819
1027
+ await assertConfined(`git ${args.join(" ").slice(0, 80)}`); // #5825
926
1028
  if (!args.includes("--delete")) { await untrackToolState({ git, base, ev, keep: await keepPaths() });
927
1029
  await reconcileLaneBranch();
928
1030
  try { await signOffUnpushed(); }
@@ -941,9 +1043,25 @@ export async function runCore(o) {
941
1043
 
942
1044
  /** After a timeout/idle kill: commit uncommitted work as a checkpoint and push the lane branch so a rerun resumes from it (#4112). */
943
1045
  async function checkpoint(reason) {
1046
+ if (deletionRefusal) { ev({ event: "CHECKPOINT_SKIPPED", reason, why: "an earlier checkpoint refused tracked-file deletions (#5819): nothing is pushed" }); return false; }
1047
+ if (confineRefusal) { ev({ event: "CHECKPOINT_SKIPPED", reason, why: "the lane folder is not a confined worktree (#5825): nothing is staged or pushed" }); return false; }
944
1048
  try {
1049
+ await assertConfined(`checkpoint after ${reason}`); // #5825: before `git status`/`add -A` touch any index
945
1050
  const dirty = String(await git(["status", "--porcelain"])).trim();
946
- if (dirty) { await git(["add", "-A"]); if (await unstageToolState(git)) await git(["commit", "--no-verify", "-m", `wip(forge): checkpoint after ${reason}`]); } // #4590: tool state is never staged
1051
+ if (dirty) {
1052
+ await git(["add", "-A"]);
1053
+ // #5819: deletions of base-tracked files outside the deliverables are never committed: unstaged, restored, and the lane ends engine-error unpushed
1054
+ let keep = []; // the contract's deliverables (read here: keepPaths is declared further down)
1055
+ try { keep = (JSON.parse(await io.fs.read(`${wt}/${CONTRACT_FILE}`))?.deliverables ?? []).map((d) => d?.path).filter((x) => typeof x === "string"); } catch { /* no contract yet: nothing is a deliverable */ }
1056
+ const dg = await guardStagedDeletions({ git, base, keep, max: o.checkpointMaxDeletions ?? maxForeignDeletions(io.env ?? process.env) });
1057
+ if (dg.refused) {
1058
+ deletionRefusal = deletionEvidence(dg, `checkpoint after ${reason}`);
1059
+ ev({ event: "CHECKPOINT_DELETIONS_REFUSED", reason, deleted: dg.deleted.length, foreign: dg.foreign.length, sample: dg.foreign.slice(0, 20), restored: Boolean(dg.restored), ...(dg.error ? { error: dg.error } : {}) });
1060
+ T.anomalies.push(deletionRefusal);
1061
+ }
1062
+ if (await unstageToolState(git)) await git(["commit", "--no-verify", "-m", `wip(forge): checkpoint after ${reason}`]); // #4590: tool state is never staged
1063
+ if (deletionRefusal) { ev({ event: "CHECKPOINT", reason, dirty: true, pushed: false, refused: true }); return false; } // committed locally, never pushed; the worktree is kept
1064
+ }
947
1065
  const ahead = String(await git(["diff", "--name-only", `${base}...HEAD`])).trim();
948
1066
  if (ahead) { laneHead = { branch, sha: String(await git(["rev-parse", "HEAD"])).trim(), pushedTo: null }; await gitPush(["push", "-u", "origin", branch]); laneHead.pushedTo = branch; }
949
1067
  ev({ event: "CHECKPOINT", reason, dirty: Boolean(dirty), pushed: Boolean(ahead) });
@@ -952,6 +1070,7 @@ export async function runCore(o) {
952
1070
  }
953
1071
  /** #4958: the normal push failed (sign-off rewrite, rejection): push HEAD as is to the lane branch, else to a salvage branch, so a torn-down remote sandbox never takes the commits with it. */
954
1072
  async function rescuePush(reason, rejected) {
1073
+ if (deletionRefusal || confineRefusal) return false; // #5819: never push past a refused checkpoint; #5825: nor from an unconfined folder
955
1074
  // #5014: gitPush untracks tool state and rewrites unpushed commits for DCO before it pushes, so HEAD may have moved since the capture
956
1075
  try { const now = String(await git(["rev-parse", "HEAD"])).trim(); if (now) laneHead.sha = now; } catch { /* keep the captured sha */ }
957
1076
  // a rejected lane-branch push (protected branch, permissions) would be rejected again: go straight to the salvage branch
@@ -1026,6 +1145,9 @@ export async function runCore(o) {
1026
1145
  /** #4390: builder calls stopped at the context ceiling restart fresh; planning (and its corrections) run uncapped. */
1027
1146
  let laneCeiling = contextCeilingTokens; // #5346: set to the lane size's ceiling once the contract is frozen
1028
1147
  const UNCEILED = ["plan", "contract_correction", "block_correction"], CONTEXT_RESTARTS_MAX = 3;
1148
+ /** #5812: the planning session's last-turn context, the files it read and its final reply, for the route hand-off. */
1149
+ let planSession = null;
1150
+ const notePlanSession = (r, trigger) => { planSession = { endTokens: num(r.endTokens), read: [...new Set([...(planSession?.read ?? []), ...handoffFacts(r.toolUses).read])], text: trigger === "plan" ? String(r.text ?? "") : planSession?.text ?? "" }; };
1029
1151
  async function builder(n, prompt, resume, live = false, restart = implementRestart, opts = {}) {
1030
1152
  let timeoutRetries = 0, contextRestarts = 0, p = prompt;
1031
1153
  opts = { ...opts };
@@ -1121,6 +1243,7 @@ export async function runCore(o) {
1121
1243
  await renew();
1122
1244
  await registerReported();
1123
1245
  if (r?.sessionId && !keepSession) sessionId = r.sessionId;
1246
+ if (r && UNCEILED.includes(trigger)) notePlanSession(r, trigger);
1124
1247
  await attempt("implement", n, profile && r ? { ...r, laneProfile: profile === "narrow" && laneProfile.name === "full" ? "full" : profile } : r, mode, trigger, restartOf, resume);
1125
1248
  onProgress({ event: "phase_exit", phase: "build", status: "committed" });
1126
1249
  return r;
@@ -1129,13 +1252,30 @@ export async function runCore(o) {
1129
1252
  /** #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. */
1130
1253
  async function takeBranchLock() {
1131
1254
  let dir = null;
1132
- 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; }
1255
+ try { const d = String(await io.git(["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: wt, env: laneGitEnv })).trim(); if (isAbsPath(d) && existsSync(d)) dir = d; } catch { dir = null; }
1133
1256
  if (!dir) return null;
1134
1257
  let lock;
1135
1258
  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; }
1136
1259
  if (lock.ok) return lock;
1137
1260
  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` });
1138
1261
  }
1262
+ /**
1263
+ * #5751: one lane at a time in each declared hot area (forge.yaml recurrence.hot_areas) the paths fall in: the branch lock
1264
+ * keyed hot-area:<name>, host-local. Waits for the holder, then defers host.busy. Fail-open when the shared git dir is unknown.
1265
+ */
1266
+ async function takeHotAreas(paths) {
1267
+ const areas = areaOf(paths, recCfg.hotAreas).filter((a) => !(hotLock?.areas ?? []).includes(a));
1268
+ if (!areas.length) return;
1269
+ let dir = null;
1270
+ try { const d = String(await io.git(["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: wt })).trim(); if (isAbsPath(d) && existsSync(d)) dir = d; } catch { dir = null; }
1271
+ if (!dir) { T.anomalies.push(`Hot area(s) ${areas.join(", ")} not locked: the shared git dir is unknown`); return; }
1272
+ const r = await acquireHotArea({ gitCommonDir: dir, areas, owner: agentId, waitMs: o.hotAreaWaitMs ?? 600000, pollMs: o.branchLockPollMs ?? 15000, sleep: async (ms) => { await renew(); await sleep(ms); } });
1273
+ if (!r.ok) throw Object.assign(new Error(`hot area ${r.area} is held by another lane`), { deferCode: OUTCOME_CODES.HOST_BUSY, retryInSeconds: 300, deferDetail: `hot area ${r.area} admits one lane at a time; another lane (pid ${r.holder?.pid ?? "?"}, ${r.holder?.owner ?? "?"}) holds it; retried later` });
1274
+ const prev = hotLock;
1275
+ hotLock = { areas: [...(prev?.areas ?? []), ...r.areas], release: () => { r.release(); prev?.release(); } };
1276
+ ev({ event: "HOT_AREA", areas: r.areas });
1277
+ T.decisions.push(`Hot area(s) ${r.areas.join(", ")} locked for this lane (one lane at a time, this host)`);
1278
+ }
1139
1279
  /** #4390: the restart summary: `git diff --stat` and hunks against the lane base, and the last `forgedock check` record. */
1140
1280
  async function restartFacts() {
1141
1281
  const ex = [".", `:!${LEAN_DIR}`];
@@ -1320,12 +1460,14 @@ export async function runCore(o) {
1320
1460
  if (io.host && o.admission?.enabled !== false) {
1321
1461
  const a = await checkAdmission({ cfg: o.admission, host: io.host });
1322
1462
  if (!a.ok) return { terminalReason: "deferred", code: OUTCOME_CODES.HOST_BUSY, detail: a.detail, retryInSeconds: ADMISSION_RETRY_SECONDS };
1463
+ try { io.host.recordAdmission?.(); } catch { /* the ramp stamp is best effort (#5845) */ }
1323
1464
  }
1324
1465
  // ---- lane (#4125): worked out from the issue before any lease, comment or worktree; fail closed ----
1325
1466
  {
1326
1467
  const laneIo = { ...io, gh: (a, opts) => refreshAuthOnce(() => io.gh(a, opts), { refresh: io.refreshAuth ?? runRefreshScript, state: authState }) }; // #4662
1327
1468
  const r = await resolveLane({ issue, repo, io: laneIo, cwd, branches, requested: requestedLane, override: laneOverride });
1328
1469
  if (!r.ok && GH_AUTH_RE.test(r.detail ?? "")) return { terminalReason: "deferred", code: OUTCOME_CODES.GH_AUTH, detail: r.detail, retryInSeconds: GH_AUTH_RETRY_SECONDS }; // #4662: a dead token is not a lane problem
1470
+ if (!r.ok && r.transient) return { terminalReason: "deferred", code: OUTCOME_CODES.LANE_UNRESOLVED, detail: r.detail, retryInSeconds: GH_AUTH_RETRY_SECONDS }; // #5846: a failed lookup is not a lane refusal; the orchestrator requeues it
1329
1471
  if (!r.ok) return { terminalReason: "lane-refused", code: r.code, detail: r.detail };
1330
1472
  lane = r.lane; base = `origin/${lane}`; defaults = r.defaults; milestone = r.milestone ?? null;
1331
1473
  if (r.overridden) T.decisions.push(`Lane override: ${lane} instead of the resolved ${r.expected}`);
@@ -1390,7 +1532,7 @@ export async function runCore(o) {
1390
1532
  try {
1391
1533
  iss = JSON.parse(await ghc(["issue", "view", String(issue), "-R", repo, "--json", "number,title,body,state,comments,labels,updatedAt"]));
1392
1534
  } catch (e) {
1393
- if (e?.deferCode) return finish("deferred", e.deferDetail ?? String(e.message), { code: e.deferCode, ...(e.retryInSeconds ? { retryInSeconds: e.retryInSeconds } : {}), ...(e.backendId ? { backendId: e.backendId } : {}) }, e.deferCode); // #4662; #5168 backendId
1535
+ if (e?.deferCode) return finish("deferred", e.deferDetail ?? String(e.message), { code: e.deferCode, ...(e.retryInSeconds ? { retryInSeconds: e.retryInSeconds } : {}), ...(e.backendId ? { backendId: e.backendId } : {}), ...(e.cliResult != null ? { cliResult: e.cliResult } : {}), ...(typeof e.cliIsError === "boolean" ? { cliIsError: e.cliIsError } : {}), ...(e.account ? { account: e.account } : {}) }, e.deferCode); // #4662; #5168 backendId
1394
1536
  return finish("engine-error", `cannot read issue: ${e.message}`);
1395
1537
  }
1396
1538
  const priorState = stateOf(iss.body); // #4400: the last run's end (the lease write keeps its terminal fields), read before this run ends
@@ -1477,6 +1619,12 @@ export async function runCore(o) {
1477
1619
  // processes and save the work before the worktree is removed; the lease above makes this run the only one doing so.
1478
1620
  await step("salvage_cleanup", async () => {
1479
1621
  await stopWorktreeProcs();
1622
+ // #5825: a leftover folder that is not this repo's worktree (no .git link, or git resolves it to another toplevel) is
1623
+ // never salvaged with git (that would stage the checkout around it) and never reused: it is moved aside first.
1624
+ if (io.confine?.verify && io.fs?.exists && (await io.fs.exists(wt))) {
1625
+ const v = await io.confine.verify({ wt, cwd });
1626
+ if (v?.ok === false) await quarantine(v.why, v.evidence);
1627
+ }
1480
1628
  salvagedRef = await salvage("an earlier run");
1481
1629
  try { await io.git(["worktree", "remove", "--force", wt], { cwd }); } catch { /* none */ }
1482
1630
  try { await io.git(["worktree", "prune"], { cwd }); } catch { /* best effort */ }
@@ -1487,9 +1635,11 @@ export async function runCore(o) {
1487
1635
  const leftoverDir = async () => {
1488
1636
  if (!io.fs.exists || !io.fs.rmdir || dirname(wt) !== wtRoot || basename(wt) !== `lean-${issue}`) return false;
1489
1637
  if (!(await io.fs.exists(wt))) return false;
1490
- const listed = String(await io.git(["worktree", "list", "--porcelain"], { cwd }).catch(() => "")).split("\n").some((l) => l === `worktree ${wt}`);
1638
+ // #5825: git prints `C:/...` on Windows; an exact string match never saw the lane listed and deleted a registered worktree's files
1639
+ const listed = listedWorktree(await io.git(["worktree", "list", "--porcelain"], { cwd }).catch(() => ""), wt);
1491
1640
  if (listed) return false;
1492
- await io.fs.rmdir(wt);
1641
+ try { await io.fs.rmdir(wt); } catch (e) { ev({ event: "WORKTREE_LEFTOVER_REMOVE_FAILED", path: wt, error: String(e?.message ?? e).slice(0, 200) }); }
1642
+ if (await io.fs.exists(wt)) { await quarantine("an unregistered leftover folder could not be removed"); return true; } // a partial delete (locked file) is never reused
1493
1643
  ev({ event: "WORKTREE_LEFTOVER_REMOVED", path: wt });
1494
1644
  return true;
1495
1645
  };
@@ -1540,8 +1690,9 @@ export async function runCore(o) {
1540
1690
  } else if (resumed) {
1541
1691
  wtInfo = await addWorktree(["worktree", "add", "-B", branch, wt, `origin/${branch}`], `origin/${branch}`);
1542
1692
  if (scratchOnly) { // from origin/<branch> so the later plain push stays fast-forward; the scratch goes out in a normal commit
1543
- await io.git(["rm", "-r", "-f", "-q", "--ignore-unmatch", "--", LEAN_DIR], { cwd: wt }).catch(() => {});
1544
- if (String(await io.git(["diff", "--cached", "--name-only"], { cwd: wt }).catch(() => "")).trim()) await io.git(["commit", "--no-verify", "-m", "chore(forge): drop stale .forge-lean scratch from the lane branch"], { cwd: wt }).catch(() => {});
1693
+ await assertConfined("lane start"); // #5825: before the first write into the new worktree
1694
+ await git(["rm", "-r", "-f", "-q", "--ignore-unmatch", "--", LEAN_DIR]).catch(() => {});
1695
+ if (String(await git(["diff", "--cached", "--name-only"]).catch(() => "")).trim()) await git(["commit", "--no-verify", "-m", "chore(forge): drop stale .forge-lean scratch from the lane branch"]).catch(() => {});
1545
1696
  resumed = null;
1546
1697
  ev({ event: "SCRATCH_BRANCH_DROPPED", branch });
1547
1698
  T.decisions.push(`Lane branch ${branch} held only ${LEAN_DIR}/ scratch: its stale checkpoint was dropped and the issue is planned fresh`);
@@ -1556,6 +1707,7 @@ export async function runCore(o) {
1556
1707
  if (!wtInfo) wtInfo = await step("worktree_add", () => addWorktree(["worktree", "add", "-B", branch, wt, base], base));
1557
1708
  if (warmN) refillWarm({ git: io.git, cwd, root: wtRootDir, ref: base, n: warmN, maxBlobBytes: sparseMaxKb * 1024, write: io.fs?.write }).catch(() => {});
1558
1709
  }
1710
+ await assertConfined("lane start"); // #5825: the new worktree is registered, its toplevel is the lane folder, its git dir the repo's
1559
1711
  wtCreated = true;
1560
1712
  if (fromSalvage) await dropSalvageTracking({ git, branch }); // #5047: the salvaged commits are unpublished: the sign-off range must include them
1561
1713
  if (wtInfo?.sparse) {
@@ -1568,7 +1720,7 @@ export async function runCore(o) {
1568
1720
  }
1569
1721
  await step("scratch_setup", async () => { // #5435: timed with the other startup steps
1570
1722
  const excl = String(await git(["rev-parse", "--git-path", "info/exclude"])).trim();
1571
- await io.fs.append(excl.startsWith("/") ? excl : `${wt}/${excl}`, `\n${LEAN_DIR}/\n`);
1723
+ await io.fs.append(isAbsPath(excl) ? excl : `${wt}/${excl}`, `\n${LEAN_DIR}/\n`);
1572
1724
  await installSignoffHook();
1573
1725
  if (!resumed && await clearLaneScratch({ git, fs: io.fs, cwd: wt })) ev({ event: "LANE_SCRATCH_CLEARED" }); // #4880: never read a previous lane's scratch
1574
1726
  });
@@ -1576,7 +1728,7 @@ export async function runCore(o) {
1576
1728
  const lanePath = typeof o.laneInstructions === "string" ? o.laneInstructions.trim() : "";
1577
1729
  if (laneProfile.name !== "full" && lanePath) {
1578
1730
  let why = null, text = "";
1579
- if (lanePath.startsWith("/") || lanePath.split(/[\\/]/).includes("..")) why = "not a repo-relative path";
1731
+ if (isAbsPath(lanePath) || lanePath.split(/[\\/]/).includes("..")) why = "not a repo-relative path";
1580
1732
  else { try { text = String(await io.fs.read(`${wt}/${lanePath}`) ?? "").trim(); } catch { why = "not readable in the lane worktree"; } }
1581
1733
  if (!why && !text) why = "empty";
1582
1734
  if (!why && Buffer.byteLength(text, "utf8") > LANE_INSTRUCTIONS_MAX_BYTES) why = `over ${LANE_INSTRUCTIONS_MAX_BYTES} bytes`;
@@ -1600,6 +1752,8 @@ export async function runCore(o) {
1600
1752
  // #5434: deps, heavy shims and env.setup overlap the plan session (read-only); gateSetup() awaits them before anything that builds or runs commands.
1601
1753
  let setupSettled = false;
1602
1754
  const setupStep = (step, t) => ev({ event: "LANE_SETUP_TIMING", step, ms: now() - t });
1755
+ let depsSettled = () => {};
1756
+ const depsP = new Promise((res) => { depsSettled = res; }); // #5804: the install result alone, read before the first session
1603
1757
  const setupP = (async () => {
1604
1758
  // #4220: link node_modules/.venv from the shared cache keyed by lock hash (or install once and publish). Never fails the run.
1605
1759
  // After 2b (#4347): installs run with the toolchain env, so a pm only its shim provides resolves; no env is the host PATH.
@@ -1611,9 +1765,14 @@ export async function runCore(o) {
1611
1765
  setupStep("deps", tD);
1612
1766
  for (const r of Array.isArray(res) ? res : []) {
1613
1767
  ev({ event: "DEPS_PREPARED", status: r?.status ?? null, eco: r?.eco ?? null, key: r?.key ?? null, ms: r?.ms ?? null, reason: r?.reason ?? null });
1768
+ if (r?.restore) { // #5819: a failed publish/materialize touched tracked files; depcache checked them out again
1769
+ ev({ event: "DEPS_WORKTREE_RESTORED", eco: r.eco ?? null, status: r.status ?? null, ...r.restore });
1770
+ T.anomalies.push(r.restore.error ? `Dependency cache (${r.eco}): restoring tracked files after a failed ${r.status} failed: ${r.restore.error}` : `Dependency cache (${r.eco}): ${r.restore.restored} tracked file(s) missing after a failed ${r.status} were restored${r.restore.missing ? ` (${r.restore.missing} still missing)` : ""} (#5819)`);
1771
+ }
1614
1772
  if (r?.eco) T.decisions.push(`Dependencies (${r.eco}${r.key ? ` ${r.key}` : ""}): ${r.status}${r.reason ? ` (${r.reason})` : ""}${Number.isFinite(r.ms) ? ` in ${Math.round(r.ms / 100) / 10}s` : ""}`);
1615
1773
  }
1616
1774
  }
1775
+ depsSettled();
1617
1776
  // ---- 2c. heavy-step shims (#4169): after the toolchain, so a heavy shim's real binary is the pinned toolchain shim ----
1618
1777
  const tH = now();
1619
1778
  if (heavyOn) {
@@ -1647,8 +1806,9 @@ export async function runCore(o) {
1647
1806
  T.decisions.push("forge.yaml env.setup ran once in the fresh worktree");
1648
1807
  }
1649
1808
  return null;
1650
- })().finally(() => { setupSettled = true; });
1809
+ })().finally(() => { setupSettled = true; depsSettled(); });
1651
1810
  setupWait = setupP;
1811
+ let depsDone = false; depsP.then(() => { depsDone = true; });
1652
1812
  const TIMED_OUT = Symbol("timed-out");
1653
1813
  /** #5434: `p` or TIMED_OUT after `ms` (0 = no bound); a rejection is null. The work keeps running. */
1654
1814
  const within = (p, ms) => new Promise((res) => { const t = ms > 0 ? setTimeout(() => res(TIMED_OUT), ms) : null; Promise.resolve(p).then((v) => { clearTimeout(t); res(v); }, () => { clearTimeout(t); res(null); }); });
@@ -1658,6 +1818,21 @@ export async function runCore(o) {
1658
1818
  if (setupFail === undefined) { const r = setupSettled ? await setupP : await phaseLedger.during("deps_install", () => setupP); setupFail = typeof r === "function" ? await r() : null; }
1659
1819
  return setupFail;
1660
1820
  };
1821
+ /** #5804: an install that could not start for a missing tool ends the lane env.tool_missing before any (further) builder session.
1822
+ * Same evidence line as the validate-time stop, so orchestrate's recovery (same tools, same host) classifies it alike. */
1823
+ let toolStopped = null;
1824
+ const toolStop = async (files = []) => {
1825
+ if (toolStopped) return toolStopped;
1826
+ const miss = toolMissingInstalls(depResults, { files });
1827
+ if (!miss.length) return null;
1828
+ const tools = [...new Set(miss.map((m) => m.tool))].join(", ");
1829
+ ev({ event: "PREFLIGHT_TOOL_MISSING", tools: miss.map((m) => m.tool), before_first_session: !firstSession });
1830
+ T.anomalies.push(`Dependency install could not start (${miss.map((m) => m.label).join("; ")}); the lane ended before ${firstSession ? "implementing" : "any builder session"}`);
1831
+ toolStopped = await needsHuman(`Environment error (not a conformance failure): the host is missing ${tools}, so validate command(s) could not run; the dependency install stopped, and the lane ended before ${firstSession ? "the builder implemented" : "any builder session"}; nothing merged:\n${miss.map((m) => `- env.tool_missing: dependency install stopped (${m.label}) (environment, not the change)`).join("\n")}\n\nInstall it on the host or run the check through the repo's own toolchain, then rerun.`, OUTCOME_CODES.ENV_TOOL_MISSING);
1832
+ return toolStopped;
1833
+ };
1834
+ /** #5804: gateSetup() plus the missing-tool stop (root install, or a sub-project `files` fall under), before a session that builds. */
1835
+ const gateBuild = async (files = []) => (await gateSetup()) ?? (await toolStop(files));
1661
1836
  const names = (out) => String(out).split("\n").map((s) => s.trim()).filter(Boolean);
1662
1837
  // #4160: files the branch touched (three-dot) whose content still differs from the base tip (two-dot); a file merged
1663
1838
  // in from the base by a base-sync equals the base and drops out of the scope check.
@@ -1709,11 +1884,12 @@ export async function runCore(o) {
1709
1884
  let words = rg?.base && rg?.head ? rg : { base: "UNRUNNABLE", head: "UNRUNNABLE" };
1710
1885
  if (words.head === "FAILED" && io.runCommand) { // #5020: a head that failed because a tool or env is missing is env.repro_unrunnable, not a red-green verdict
1711
1886
  const hr = await io.runCommand({ command: String(t.command), cwd: wt, timeoutMs: 120000, env: laneEnv() }).then((x) => x?.r ?? x).catch(() => null);
1887
+ if (hr && hr.output != null) words = { ...words, headOutput: String(hr.output) }; // #5732: the head run's output goes into the failure detail
1712
1888
  // release review BUG-1: a module the repo tracks is the change's own failure, never an env miss (same repoHas as the validate rerun)
1713
1889
  const repoHas = repoTracks(String(await git(["ls-files"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean));
1714
1890
  if (reproEnvMiss(hr, { command: String(t.command), repoHas })) words = { ...words, head: "UNRUNNABLE" };
1715
1891
  }
1716
- ev({ event: "REPRO_RED_GREEN", ...words });
1892
+ { const { headOutput: _h, baseOutput: _b, ...w } = words; ev({ event: "REPRO_RED_GREEN", ...w }); } // #5732: outputs stay out of events
1717
1893
  T.decisions.push(`repro_test ${t.path ?? ""}${t.id ? ` ${t.id}` : ""}: BASE=${words.base} HEAD=${words.head}`);
1718
1894
  if (reproQuality !== "off" && words.base === "FAILED" && words.head === "RAN") words = { ...words, ...(await reproQualityOf(t)) };
1719
1895
  return words;
@@ -1889,15 +2065,21 @@ export async function runCore(o) {
1889
2065
  for (const f of files) if (/(^|\/)(package\.json|pyproject\.toml|requirements[\w.-]*\.txt)$/.test(f) && !f.split("/").includes("node_modules")) texts.set(f, String(await io.fs.read(`${wt}/${f}`).catch(() => "")));
1890
2066
  return { files, owner: (name) => manifestDepOwner(name, files, (f) => texts.get(f) ?? "") };
1891
2067
  }
2068
+ let reproRecipe = false; // #5732: a validate recipe rewrote repro_test, so its env-provisioning steps are the repo's own
1892
2069
  function freezeRewrites(c) {
1893
2070
  const r = applyValidateRecipes(c, validateRecipes);
1894
- const pd = (id, cmd) => { const to = rewriteProjectDirCommand(cmd); if (to !== cmd) T.decisions.push(`project-dir rewrite of ${id}: \`${cmd}\` -> \`${to}\``); return to; };
2071
+ const pd = (id, cmd0) => { // #5727: a frozen command names forgedock by its portable placeholder, never an install path
2072
+ const cmd = portableForgedockPaths(cmd0);
2073
+ if (cmd !== cmd0) T.decisions.push(`forgedock install path made portable in ${id}: \`${cmd0}\` -> \`${cmd}\``);
2074
+ const to = rewriteProjectDirCommand(cmd); if (to !== cmd) T.decisions.push(`project-dir rewrite of ${id}: \`${cmd}\` -> \`${to}\``); return to;
2075
+ };
1895
2076
  if (r.contract && typeof r.contract === "object") { // #5234
1896
2077
  if (Array.isArray(r.contract.validate)) r.contract = { ...r.contract, validate: r.contract.validate.map((v) => (v && typeof v.command === "string" ? { ...v, command: pd(v.id, v.command) } : v)) };
1897
2078
  const t = r.contract.repro_test;
1898
2079
  if (t && typeof t === "object" && typeof t.command === "string") r.contract = { ...r.contract, repro_test: { ...t, command: pd("repro_test", t.command) } };
1899
2080
  }
1900
2081
  for (const x of r.applied) T.decisions.push(`validate recipe rewrote ${x.id}: \`${x.from}\` -> \`${x.to}\``);
2082
+ if (r.applied.some((x) => x.id === "repro_test")) reproRecipe = true; // #5732: recipe-authored env setup is allowed in repro_test
1901
2083
  const vr = rewriteSubprojectVenv(r.contract, freezeTracked, (rel) => existsSync(join(wt, rel))); // #5683
1902
2084
  r.contract = vr.contract;
1903
2085
  for (const x of vr.applied) T.decisions.push(`sub-project venv rewrite of ${x.id}: \`${x.from}\` -> \`${x.to}\``);
@@ -2025,6 +2207,8 @@ export async function runCore(o) {
2025
2207
  /** #4694: the engine appends guard-derived H preserve rows from the local index (one file read; the same contract when none apply). */
2026
2208
  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; };
2027
2209
  let frozen = null, hash = null, planned = false, files = [], split = null, planMisses = null; // planMisses (#5331): validate preflight misses from this run
2210
+ /** #5804: paths that place the change: the issue's named paths, then the frozen deliverables once they exist */
2211
+ const toolFiles = () => [...namedPaths(iss?.body ?? ""), ...(frozen?.deliverables ?? []).map((d) => d?.path)].filter(Boolean);
2028
2212
  const impliedDocs = []; // add-deliverable amendments for doc edits the docs-freshness rule demanded (docs round, CI fix round)
2029
2213
  /** Doc files a fix round added to satisfy the freshness rule: recorded only when the rule failed before and passes after. */
2030
2214
  async function noteFreshnessDocs(before, wasFailing) {
@@ -2062,16 +2246,18 @@ export async function runCore(o) {
2062
2246
  * the fix model with a narrow prompt; one resume of the build session follows when it made no commit. Else: a resume.
2063
2247
  */
2064
2248
  function fixRound(...a) { return phaseLedger.during("fix", () => fixRoundRaw(...a)); } // #5649: fix rounds are their own ledger phase
2249
+ // #5728: a context-ceiling restart of a fix resume carries the failure list (no diff), not the full build prompt
2250
+ const fixResumeRestart = (task) => () => fixSessionPrompt({ task, stat: "", base, contract: frozen, title: iss?.title ?? "", summary: issueSummary(iss?.body) });
2065
2251
  async function fixRoundRaw(kind, task, failures, trigger, failureText = "", narrow = null) { // #5348: `narrow` {files} = the minimal profile (no diff, no lane text)
2066
2252
  await notePitfall(trigger, failureText); await escalateOn(trigger); // #4375: learned once the same gate passes; #4394
2067
- if (!freshFix(kind, failures)) return await builder(++attemptN, task, sessionId ?? null, false, undefined, { mode: "resume", trigger });
2253
+ if (!freshFix(kind, failures)) return await builder(++attemptN, task, sessionId ?? null, false, fixResumeRestart(task), { mode: "resume", trigger });
2068
2254
  const before = String(await git(["rev-parse", "HEAD"])).trim();
2069
2255
  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(() => ""));
2070
2256
  const prompt = narrow ? narrowFixPrompt({ task, contract: frozen, files: narrow.files }) : fixSessionPrompt({ task, diff, stat, base, contract: frozen, title: iss?.title ?? "", summary: issueSummary(iss?.body) });
2071
2257
  const r = await builder(++attemptN, prompt, null, false, () => prompt, { model: escalated ? null : fixModel ?? reviewerModel, mode: "fresh", keepSession: true, ...(narrow ? { profile: "narrow" } : {}), trigger });
2072
2258
  if (!sessionId || String(await git(["rev-parse", "HEAD"])).trim() !== before) return r;
2073
2259
  T.decisions.push(`Fresh ${kind} fix session made no commit; builder session resumed once`);
2074
- return await builder(++attemptN, task, sessionId, false, undefined, { mode: "resume", trigger });
2260
+ return await builder(++attemptN, task, sessionId, false, fixResumeRestart(task), { mode: "resume", trigger });
2075
2261
  }
2076
2262
  /** #5348: commit what the engine applied without a model (only the files it wrote); the findings it fixed were named by a detector. */
2077
2263
  async function mechCommit(gate, applied, paths) {
@@ -2122,19 +2308,19 @@ export async function runCore(o) {
2122
2308
  frozen = split.contract; hash = contractHash(contractJson(frozen));
2123
2309
  files = await changedFiles();
2124
2310
  } else {
2125
- if (resumed) {
2311
+ if (resumed || recover) { // #5811: a recovery with no branch to resume (it ended before its first commit) still reuses the frozen contract
2126
2312
  const fc = await readFrozenContract();
2127
2313
  if (fc) {
2128
2314
  // #4265: a contract planned from an older issue scope is stale: re-plan and freeze a new one instead of judging against it
2129
2315
  await refreshIssue("rerun contract check");
2130
2316
  const gone = (Array.isArray(fc.contract?.requirements) ? fc.contract.requirements : []).filter((r) => r?.disposition === "deliver" && !inIssue(r.quote, issueText)).map((r) => r.id);
2131
- const stale = fc.scope ? (fc.scope !== scopeHash ? `issue scope ${fc.scope} -> ${scopeHash}` : null)
2132
- : fc.humanAfter ? "a human comment was posted after it" : gone.length ? `quote(s) no longer in the issue: ${gone.join(", ")}` : null;
2317
+ const stale = reuseStale({ fc, scopeHash, lane, resumed: Boolean(resumed), gone });
2133
2318
  if (stale) {
2134
- ev({ event: "CONTRACT_STALE", hash: fc.hash, scope: fc.scope, now: scopeHash, reason: stale });
2319
+ ev({ event: "CONTRACT_STALE", hash: fc.hash, scope: fc.scope, now: scopeHash, base: fc.base, lane, reason: stale });
2135
2320
  T.decisions.push(`Rerun: frozen contract ${fc.hash} is stale (${stale}); re-planning`);
2136
2321
  } else {
2137
2322
  frozen = fc.contract; hash = fc.hash; priorAmendments = fc.amendments ?? []; T.decisions.push(`Rerun: frozen contract ${hash} recovered from the issue`);
2323
+ ev({ event: "CONTRACT_REUSED", hash, recover: recover?.code ?? null, resumed: Boolean(resumed) }); // #5811: no pre-contract session; routing is next
2138
2324
  const ad = applyRequirementDecisions(frozen, trustedComments); // #5547: a structured operator decision amends the frozen row
2139
2325
  if (ad.applied.length) { frozen = deferChecklessPostDeploy(ad.contract).contract; T.decisions.push(`FORGE:DECISION applied to the frozen contract: ${ad.applied.join(", ")} tracked post-deploy`); }
2140
2326
  }
@@ -2151,9 +2337,24 @@ export async function runCore(o) {
2151
2337
  }
2152
2338
  decisionsNote = frozen && (resumed || salvagedRef || recover) ? decisionNote(trustedComments) : ""; // #4901
2153
2339
  if (decisionsNote) T.decisions.push("Trusted FORGE:DECISION comment(s) posted after the contract froze are binding notes for the builder");
2340
+ if (!route) { // #5810: the provisional tier of the pre-contract sessions; BUILDER_ROUTE may upgrade it after the contract
2341
+ preRoute = provisionalRoute({ title: iss.title, labels: iss.labels ?? [], namedFiles: namedPaths(iss.body ?? ""), prior: !!(resumed || salvagedRef || recover), riskPaths, cfg: routingCfg, topModel: builderModel });
2342
+ const rec = { event: "BUILDER_PREROUTE", mode: preRoute.mode, class: preRoute.class, tier: preRoute.tier, model: preRoute.model ?? "default", reason: preRoute.reason, risk: preRoute.risk };
2343
+ ev(rec); await emit(rec);
2344
+ T.decisions.push(`Pre-contract sessions provisionally routed to the ${preRoute.tier} tier (${preRoute.class}: ${preRoute.reason})`);
2345
+ }
2154
2346
  await label("building");
2155
2347
  // #4450: the light lane (lean.light mode on, eligible, fresh lane): one builder session, derived contract, or an upgrade
2156
2348
  const waitMs = Math.max(0, Number(contextWaitSeconds) || 0) * 1000, tHot = now();
2349
+ if (recCfg.mode === "on" && !recurrence && (namedPaths(iss.body ?? "").length || recursLinks(iss.body ?? "").length)) { // #5751: 0 LLM calls; an issue naming no path and no Recurs link cannot recur
2350
+ recurrence = await recurrenceFacts({ io: { gh: ghc, git: (a) => git(a) }, repo, issue, title: iss.title, body: iss.body ?? "", base, namedPaths: namedPaths(iss.body ?? ""), threshold: recCfg.threshold }).catch(() => null);
2351
+ if (recurrence?.recurs) {
2352
+ ev({ event: "RECURRENCE", count: recurrence.count, threshold: recurrence.threshold, fixes: recurrence.evidence.map((e) => e.number), reason: recurrence.reason });
2353
+ T.decisions.push(`Design lane (#5751): ${recurrence.reason}`);
2354
+ try { await post("FORGE:RECURRENCE", `Routed to a design lane: ${recurrence.reason}.\nThe contract must say why the earlier fixes did not hold, whether to delete or replace them, and a measurable outcome; it may decompose into ordinary lanes.`); } catch { /* best effort */ }
2355
+ }
2356
+ }
2357
+ await takeHotAreas(namedPaths(iss.body ?? "")); // #5751
2157
2358
  const hotR = await within(hotspotsOf({ paths: namedPaths(iss.body ?? "") }), waitMs); // #5209: churn and hotspot signals for eligibility; #5434: bounded, overlaps the install
2158
2359
  const hotLate = hotR === TIMED_OUT, namedHot = hotLate ? null : hotR;
2159
2360
  setupStep("hotspots", tHot);
@@ -2163,8 +2364,9 @@ export async function runCore(o) {
2163
2364
  lightVerdict = elig.verdict;
2164
2365
  if (elig.mode !== "off") T.decisions.push(`Light lane ${elig.mode}: ${elig.verdict}${elig.reasons.length ? ` (${elig.reasons.map((x) => x.code).join(", ")})` : ""}`);
2165
2366
  // #4451: a light try skips the hotspots and the context pack; an upgrade computes them before the plan call
2166
- const ffSource = fastForwardSource(o.light), ffFresh = ffSource === "investigation" && !frozen && !resumed && !salvagedRef && !recover; // #5426: the text verdict above is only a shadow signal then
2167
- const lightTry = ffSource === "text" && elig.light && !hotLate && !frozen && !resumed && !salvagedRef && !recover;
2367
+ const ffSource = fastForwardSource(o.light), ffFresh = ffSource === "investigation" && !frozen && !resumed && !salvagedRef && !recover && !recurrence?.recurs; // #5426: the text verdict above is only a shadow signal then
2368
+ const lightTry = ffSource === "text" && elig.light && !hotLate && !frozen && !resumed && !salvagedRef && !recover && !recurrence?.recurs; // #5751: a recurrence never takes the light lane
2369
+ if (recurrence?.recurs && elig.light) T.decisions.push("Light lane skipped: the issue recurs (design lane)");
2168
2370
  if (!lightTry) hotFacts = namedHot; // #4451: a light try still gives its builder no hotspot facts
2169
2371
  enumList = io.enumeratingTests ? ((await within(io.enumeratingTests({ cwd: wt, paths: namedPaths(iss.body ?? "") }), waitMs)) ?? []) : [];
2170
2372
  if (enumList === TIMED_OUT) enumList = [];
@@ -2174,7 +2376,12 @@ export async function runCore(o) {
2174
2376
  const tPack = now(); packP = contextPackStep(); ctxPack = await within(packP, waitMs); setupStep("context_pack", tPack);
2175
2377
  if (ctxPack === TIMED_OUT) { ctxPack = null; T.decisions.push(`Context pack not ready in ${waitMs / 1000}s: the plan starts without it`); }
2176
2378
  }
2177
- const planPrompt = () => builderPlanPrompt(issue, tcOpts()) + uiBuildRule(uiOn = uiOn || uiIssue(iss ?? {}), designConfig) + hotspotPlanNote(hotFacts) + enumeratingPlanNote(enumList) + invariantsPlanNote(vcfg.invariants) + reproPlanNote(reproOn()) + docsPlanNote(docsConfig) + pagePlanNote(pagesConfig) + unrunnableValidateNote(testRunners) + explorePlanRule(exploreCfg) + (ctxCfg.mode === "on" ? contextPackNote(ctxPack) : "");
2379
+ if (!frozen) { // #5804: an install that cannot start (tool not found) fails in seconds: read it inside the same waitMs bound (from tHot) before the first session; a longer install keeps overlapping the plan and gateBuild() stops it before implement
2380
+ const left = waitMs - (now() - tHot);
2381
+ if (!depsDone && left > 0) await within(depsP, left);
2382
+ const f = await toolStop(toolFiles()); if (f) return f;
2383
+ }
2384
+ const planPrompt = () => builderPlanPrompt(issue, tcOpts()) + uiBuildRule(uiOn = uiOn || uiIssue(iss ?? {}), designConfig) + hotspotPlanNote(hotFacts) + enumeratingPlanNote(enumList) + invariantsPlanNote(vcfg.invariants) + reproPlanNote(reproOn()) + docsPlanNote(docsConfig) + pagePlanNote(pagesConfig) + unrunnableValidateNote(testRunners) + explorePlanRule(exploreCfg) + (ctxCfg.mode === "on" || recurrence?.recurs ? contextPackNote(ctxPack) : "") + designLaneNote(recurrence); // #5751: on a recurrence the pack is an active input whatever the mode
2178
2385
  let lightDone = false, lightCommits = false;
2179
2386
  let ffPlan = "full", ffGo = false, lightElig = elig, lightPred = null, ffTriage = null; // #5426: how the plan call runs; ffGo = fast-forward to the light step
2180
2387
  const ffTriageOf = async (raw) => parseTriage(raw, await io.fs.read(`${wt}/${INVESTIGATION_FILE}`).catch(() => ""));
@@ -2193,7 +2400,7 @@ export async function runCore(o) {
2193
2400
  }
2194
2401
  }
2195
2402
  if (lightTry || ffGo) {
2196
- { const f = await gateSetup(); if (f) return f; } // #5434: the light build is an implement-class session
2403
+ { const f = await gateBuild(toolFiles()); if (f) return f; } // #5434, #5804: the light build is an implement-class session
2197
2404
  liveKeys = ["implementation"]; stage = "implement"; phaseLedger.enter("implement");
2198
2405
  tb.setSize(recoverySize(laneSize({ labels: (iss?.labels ?? []).map((l) => l?.name ?? l) }), recover)); // #4505
2199
2406
  const lightBase = pagesConfig ? String(await git(["ls-tree", "-r", "-z", "--name-only", base]).catch(() => "")).split("\0").filter(Boolean) : null; // #5648: pages already on the base are modified, not new
@@ -2207,8 +2414,8 @@ export async function runCore(o) {
2207
2414
  stage = "plan"; liveKeys = ["investigation"]; result = (await readResult()) ?? result;
2208
2415
  if (!lr.upgrade) {
2209
2416
  lightDone = true; light = true; frozen = historyRows(lr.contract); hash = contractHash(contractJson(frozen));
2210
- let body = renderContract(frozen, hash, { scope: scopeHash });
2211
- if (body.length > MAX_COMMENT_CHARS - 500) body = renderContract(frozen, hash, { compact: true, scope: scopeHash });
2417
+ let body = renderContract(frozen, hash, { scope: scopeHash, base: lane });
2418
+ if (body.length > MAX_COMMENT_CHARS - 500) body = renderContract(frozen, hash, { compact: true, scope: scopeHash, base: lane });
2212
2419
  await post(["FORGE:CONTRACT", "FORGE:PLAN"], body);
2213
2420
  await claimSurfaceSlots(frozen);
2214
2421
  ev({ event: "CONTRACT_FROZEN", hash, requirements: frozen.requirements.length, deferred: 0, derived: "light" });
@@ -2241,6 +2448,8 @@ export async function runCore(o) {
2241
2448
  if (closes || result?.status === "blocked") await flushStages(result, ["investigation"]); // the evidence comment for invalid/already-fixed
2242
2449
  T.validate = [result?.status ? String(result.status === "fixed" ? "CONFIRMED" : result.status).toUpperCase() : "CONFIRMED", `${evidence.length} evidence item(s)`];
2243
2450
  if (closes && !evidence.length) return await needsHuman(`Builder reported "${result.status}" without evidence, so the issue is not closed automatically.\n\n${result.summary ?? "(no summary)"}`, OUTCOME_CODES.BUILDER_NO_EVIDENCE);
2451
+ const prodFail = closes ? prodFailureSignal(trustedComments) : null; // #5734: a recorded prod failure overrides ancestry
2452
+ if (prodFail) return await needsHuman(prodFailNote(result.status, prodFail), OUTCOME_CODES.BUILDER_NO_EVIDENCE);
2244
2453
  if (closes) {
2245
2454
  T.plan = "skipped"; T.implement = "skipped"; T.review = "skipped"; T.pr = "none"; T.merge = "n/a";
2246
2455
  T.decisions.push(`Builder verdict: ${result.status}`);
@@ -2252,7 +2461,7 @@ export async function runCore(o) {
2252
2461
  const blocked = await endIfBlocked();
2253
2462
  if (blocked) return blocked;
2254
2463
  if (ffFresh && elig.mode === "shadow") { const tri = await ffTriageOf(null); ev(fastForwardEvent(fastForwardEligibility({ title: iss.title, body: iss.body ?? "", labels: iss.labels ?? [], triage: tri, textFiles: namedPaths(iss.body ?? ""), riskPaths, hotspots: (hotFacts?.files ?? []).filter((f) => tri.files.includes(f?.path ?? f)), cfg: o.light ?? {} }), tri, { shadow: true })); } // #5426: zero extra cost, no extra runner call
2255
- { const f = await gateSetup(); if (f) return f; } // #5434: the contract checks below run commands with the lane env
2464
+ { const f = await gateBuild(toolFiles()); if (f) return f; } // #5434, #5804: the contract checks below run commands with the lane env
2256
2465
  // #4353: the engine's scope gate is the only scope authority; a pure file-scope validate is dropped before it is checked or frozen
2257
2466
  const dropScope = (c) => {
2258
2467
  const d = dropScopeValidates(c);
@@ -2284,7 +2493,7 @@ export async function runCore(o) {
2284
2493
  const wtRead = (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } }; // #5585: noindex pages are not public
2285
2494
  const freezeBase = pagesConfig ? String(await git(["ls-tree", "-r", "-z", "--name-only", base]).catch(() => "")).split("\0").filter(Boolean) : null; // #5648
2286
2495
  const freezeCheckIds = await (async () => { try { return new Set(Object.keys(await checksAt(git, [base], wt))); } catch { return null; } })(); // first-pass: the base's registered post-deploy check ids
2287
- let vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, baseFiles: freezeBase, testPlan: reproOn(), readFile: wtRead, checkIds: freezeCheckIds });
2496
+ let vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, baseFiles: freezeBase, testPlan: reproOn(), readFile: wtRead, checkIds: freezeCheckIds, reproRecipe });
2288
2497
  const found0 = await preflightValidates(contract); // #4328: validate commands the host cannot run share the one correction
2289
2498
  let missed = found0;
2290
2499
  // #5653: an unrunnable command is rewritten from the repo catalogue (forge.yaml recipes first, then CI-derived) before any builder correction
@@ -2294,7 +2503,7 @@ export async function runCore(o) {
2294
2503
  if (rw.applied.length) {
2295
2504
  contract = snapContract(rw.contract);
2296
2505
  for (const x of rw.applied) T.decisions.push(`validate catalogue rewrote unrunnable ${x.id}: \`${x.from}\` -> \`${x.to}\``);
2297
- vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, baseFiles: freezeBase, testPlan: reproOn(), readFile: wtRead, checkIds: freezeCheckIds });
2506
+ vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, baseFiles: freezeBase, testPlan: reproOn(), readFile: wtRead, checkIds: freezeCheckIds, reproRecipe });
2298
2507
  missed = await preflightValidates(contract);
2299
2508
  }
2300
2509
  }
@@ -2306,7 +2515,7 @@ export async function runCore(o) {
2306
2515
  await persistGenChecks();
2307
2516
  await refreshIssue("contract validation");
2308
2517
  contract = snapContract(contract);
2309
- vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, baseFiles: freezeBase, testPlan: reproOn(), readFile: wtRead, checkIds: freezeCheckIds });
2518
+ vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, baseFiles: freezeBase, testPlan: reproOn(), readFile: wtRead, checkIds: freezeCheckIds, reproRecipe });
2310
2519
  };
2311
2520
  if ((!vc.ok || missed.length || testRunnerProblems(contract, testRunners).length) && sessionId) {
2312
2521
  await correctContract([...vc.problems, ...preflightProblems(missed), ...testRunnerProblems(contract, testRunners)], "resumed once");
@@ -2334,18 +2543,19 @@ export async function runCore(o) {
2334
2543
  if (!vc.ok) return await needsHuman(`The builder's contract is still invalid after ${rounds} correction(s):\n${vc.problems.slice(0, 12).map((x) => `- ${x}`).join("\n")}`, OUTCOME_CODES.CONTRACT_INVALID, { ...(issueEdited ? { issueEdited: true } : {}), ...(vc.problems.every((x) => /: quote is not verbatim/.test(x)) ? { quoteMismatch: true } : {}) });
2335
2544
  frozen = historyRows(contract); // #4694 guards
2336
2545
  frozen = withDecisionRows(frozen, readDecisionIndex(repo)); // #4695: anchored decisions on the deliverable paths; one index read
2546
+ await takeHotAreas((frozen.deliverables ?? []).map((d) => d?.path)); // #5751: the contract's paths before building
2337
2547
  const hRows = (frozen.preserve ?? []).filter((p) => p.source === "decision");
2338
2548
  if (hRows.length) T.decisions.push(`Anchored decisions bind this lane: ${hRows.map((p) => `${p.id} (${p.decision})`).join(", ")}`);
2339
2549
  hash = contractHash(contractJson(frozen));
2340
- let body = renderContract(frozen, hash, { scope: scopeHash });
2341
- if (body.length > MAX_COMMENT_CHARS - 500) body = renderContract(frozen, hash, { compact: true, scope: scopeHash }); // the JSON must survive the comment cap
2550
+ let body = renderContract(frozen, hash, { scope: scopeHash, base: lane });
2551
+ if (body.length > MAX_COMMENT_CHARS - 500) body = renderContract(frozen, hash, { compact: true, scope: scopeHash, base: lane }); // the JSON must survive the comment cap
2342
2552
  await post(["FORGE:CONTRACT", "FORGE:PLAN"], body);
2343
2553
  const deferredN = frozen.requirements.filter((r) => TRACKED.includes(r.disposition)).length;
2344
2554
  ev({ event: "CONTRACT_FROZEN", hash, requirements: frozen.requirements.length, deferred: deferredN });
2345
2555
  await emit({ event: "CONTRACT_FROZEN", hash, requirements: frozen.requirements.length, deferred: deferredN });
2346
2556
  T.decisions.push(`Contract frozen (${hash}): ${frozen.requirements.length} requirement(s), ${deferredN} deferred pending review`);
2347
2557
  } else {
2348
- T.validate = lightDone ? "light lane (no plan session)" : "resumed (existing branch)";
2558
+ T.validate = lightDone ? "light lane (no plan session)" : resumed ? "resumed (existing branch)" : "recovered (frozen contract)";
2349
2559
  }
2350
2560
  const dgFiles = (frozen?.deliverables ?? []).map((d) => d?.path).filter(Boolean);
2351
2561
  const designComments = (iss?.comments ?? []).filter(isTrustedIssueComment);
@@ -2388,7 +2598,7 @@ export async function runCore(o) {
2388
2598
  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);
2389
2599
  // #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)
2390
2600
  const remoteDeps = await depOwnerOf(); // #5683: a tool that is a tracked manifest dependency is prepared in the sandbox, never a lane_tools recipe or a host tool
2391
- const ownedDep = (t) => remoteDeps.owner(t) !== null, notOwned = (m) => ({ ...m, tools: m.tools.filter((t) => !ownedDep(t)) });
2601
+ const ownedDep = (t) => t === "forgedock" || remoteDeps.owner(t) !== null, notOwned = (m) => ({ ...m, tools: m.tools.filter((t) => !ownedDep(t)) });
2392
2602
  let tm0 = toolMisses(planMisses ?? await preflightValidates(frozen).catch(() => [])), tm = notOwned(tm0);
2393
2603
  if (tm0.tools.length && !tm.tools.length) { try { if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined }); ev({ event: "REMOTE_PROJECT_DEPS", tools: tm0.tools }); } catch { /* the install gate reports failures */ } }
2394
2604
  if (tm.tools.length) { // #5423: provision the sandbox once (nested lockfiles, pytest) and re-probe before giving the lane up
@@ -2408,7 +2618,7 @@ export async function runCore(o) {
2408
2618
  tm = notOwned(toolMisses(await preflightValidates(frozen).catch(() => [])));
2409
2619
  ev({ event: "REMOTE_PROVISIONED", remaining: tm.tools });
2410
2620
  }
2411
- if (noRecipe.length && tm.tools.some((t) => noRecipe.includes(t))) return await needsHuman(`Remote sandbox lacks ${noRecipe.join(", ")}, and no lane_tools recipe exists for ${noRecipe.length > 1 ? "them" : "it"}. Add it to \`execution.lane_tools\` in forge.yaml once a recipe exists, or add a recipe for ${noRecipe.join(", ")} in bin/pool/lane-tools.mjs (RECIPES).`, OUTCOME_CODES.ENV_TOOL_MISSING);
2621
+ if (noRecipe.length && tm.tools.some((t) => noRecipe.includes(t))) return await needsHuman(`Remote sandbox lacks ${noRecipe.join(", ")}, and no lane_tools recipe exists for ${noRecipe.length > 1 ? "them" : "it"}. Add it to \`execution.lane_tools\` in forge.yaml once a recipe exists, or add a recipe for ${noRecipe.join(", ")} in bin/pool/lane-tools.mjs (RECIPES). Known recipes: ${Object.keys(RECIPES).join(", ")}.`, OUTCOME_CODES.ENV_TOOL_MISSING, { toolNoRecipe: true }); // #5727: the orchestrator re-places it on the host without spending an attempt
2412
2622
  }
2413
2623
  if (tm.tools.length) {
2414
2624
  ev({ event: "REMOTE_TOOL_MISSING", tools: tm.tools, ids: tm.ids });
@@ -2424,9 +2634,9 @@ export async function runCore(o) {
2424
2634
  if (io.fs.write) { try { await io.fs.write(`${wt}/${CONTRACT_FILE}`, `${contractJson(frozen)}\n`); } catch { /* the prompt still names it */ } }
2425
2635
  // #4364: what `forgedock check` needs from the operator's forge.yaml (gitignored, so not in the worktree)
2426
2636
  if (io.fs.write) { try { await io.fs.write(`${wt}/${CHECK_PLAN_FILE}`, `${JSON.stringify({ v: 1, base, mode: vcfg.mode, learned: learnedCommands, invariants: vcfg.invariants ?? [], maxMinutes: Number(o.precheck?.maxMinutes) > 0 ? Number(o.precheck.maxMinutes) : null, precheckTotalSeconds: vcfg.precheckTotalSeconds, precheckTimeoutSeconds: vcfg.precheckTimeoutSeconds })}\n`); } catch { /* the CLI falls back to forge.yaml */ } }
2427
- route = routeBuilder({ contract: frozen, riskPaths, cfg: routingCfg, topModel: builderModel }); // #4394
2637
+ route = floorRoute(routeBuilder({ contract: frozen, riskPaths, cfg: routingCfg, topModel: builderModel }), preRoute, builderModel); // #4394; #5810: an issue risk signal floors it at top
2428
2638
  {
2429
- const rec = { event: "BUILDER_ROUTE", mode: route.mode, class: route.class, tier: route.tier, model: route.model ?? "default", risk: route.risk };
2639
+ const rec = { event: "BUILDER_ROUTE", mode: route.mode, class: route.class, tier: route.tier, model: route.model ?? "default", risk: route.risk, ...(route.pre ? { pre_tier: route.pre.tier, pre_class: route.pre.class, change: route.change } : {}), ...(route.floor ? { floor: route.floor } : {}) };
2430
2640
  ev(rec); await emit(rec);
2431
2641
  T.decisions.push(`Builder routed to the ${route.tier} tier (${route.class}; ${route.model ?? "CLI default"})`);
2432
2642
  }
@@ -2442,18 +2652,28 @@ export async function runCore(o) {
2442
2652
  const openMap = io.runCommand ? await readTestMapAtRef(git, base).catch(() => null) : null;
2443
2653
  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) + uiBuildRule(uiOn = uiOn || uiChanged(dgFiles).length > 0, designConfig) + designGateNote(designRoute) + generatorNote(surfaceClaim?.generated) + (planned ? "" : (fromCheckpoint ? CONTINUE_NOTE : RERUN_NOTE).replace("BASE", lane)) + (salvagedRef ? SALVAGE_NOTE.replaceAll("REF", salvagedRef) : "") + recoverNote() + (planned ? "" : resumeNote + decisionsNote);
2444
2654
  liveKeys = ["implementation"];
2445
- { const f = await gateSetup(); if (f) return f; } // #5434: resumed or frozen lanes skip the plan
2655
+ { const f = await gateBuild(toolFiles()); if (f) return f; } // #5434, #5804: resumed or frozen lanes skip the plan
2446
2656
  stage = "implement"; phaseLedger.enter("implement");
2447
- let buildPrompt = implementPrompt, noCeiling = false;
2657
+ let buildPrompt = implementPrompt, noCeiling = false, buildResume = planned ? sessionId : null;
2658
+ if (!lightDone && buildResume) { // #5812: a planning session above the hand-off bound is not resumed: the build starts fresh from a bounded digest
2659
+ const ho = routeHandoff({ planTokens: planSession?.endTokens ?? null, bound: routeHandoffTokens, ceiling: laneCeiling });
2660
+ if (ho.digest) {
2661
+ const digest = routeDigestPrompt({ contract: frozen, read: planSession?.read ?? [], buildReads: buildReadsOf(planSession?.text), planTokens: ho.planTokens, ...await restartFacts(), maxBytes: ho.digestBytes });
2662
+ buildPrompt = implementPrompt + digest; buildResume = null;
2663
+ T.decisions.push(`Route hand-off: the planning session ended at ${ho.planTokens} context tokens (bound ${ho.bound}); the build starts fresh from a ${Buffer.byteLength(digest)}-byte digest instead of resuming it`);
2664
+ }
2665
+ const rec = { event: "ROUTE_HANDOFF", mode: ho.digest ? "digest" : "resume", plan_tokens: ho.planTokens, bound: ho.bound, ...(ho.digest ? { digest_bytes: Buffer.byteLength(buildPrompt) - Buffer.byteLength(implementPrompt) } : {}), pack_bytes: ctxPack?.bytes ?? null, lane_profile: laneProfile.name };
2666
+ ev(rec); await emit(rec);
2667
+ }
2448
2668
  if (!lightDone) { // #5346: a session certain to restart is narrowed (or, when the named files alone exceed the ceiling, left uncapped) before it starts
2449
- const pred = predictRestart({ ceiling: laneCeiling, promptBytes: Buffer.byteLength(implementPrompt), fileBytes: await namedFileBytes(frozen) });
2669
+ const pred = predictRestart({ ceiling: laneCeiling, promptBytes: Buffer.byteLength(buildPrompt), fileBytes: await namedFileBytes(frozen) });
2450
2670
  if (pred.predicted) {
2451
- buildPrompt = implementPrompt.replace(exploreBuildRule(exploreCfg), "") + NARROW_NOTE;
2671
+ buildPrompt = buildPrompt.replace(exploreBuildRule(exploreCfg), "") + NARROW_NOTE;
2452
2672
  noCeiling = pred.certain;
2453
2673
  ev({ event: "CONTEXT_PREDICT", estimate_tokens: pred.estimate, ceiling: pred.ceiling, certain: pred.certain });
2454
2674
  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" : ""}`);
2455
2675
  }
2456
- await builder(++attemptN, buildPrompt, planned ? sessionId : null, true, undefined, { trigger: "build", noCeiling });
2676
+ await builder(++attemptN, buildPrompt, buildResume, true, undefined, { trigger: "build", noCeiling });
2457
2677
  }
2458
2678
  stage = "fix"; // later builder rounds fix precheck, CI, structure, docs or conformance findings
2459
2679
  result = await readResult();
@@ -2499,7 +2719,22 @@ export async function runCore(o) {
2499
2719
  // #4297: its commands run, so the map comes from the base ref (else the operator's checkout), never the lane worktree
2500
2720
  const testMap = io.runCommand ? (await readTestMapAtRef(git, base)) ?? (await readTestMap([cwd], io.fs?.read)) : null;
2501
2721
  // #4331: a learned command the map covers runs only when its globs match a changed file; unmapped ones always run (#4315)
2502
- const pickChecks = () => planPrecheck({ testMap, files, learned: learnedCommands, maxMinutes: o.precheck?.maxMinutes, verify: vcfg });
2722
+ // #5820: the PR's required CI jobs (scripts/ci-local plan, heavy jobs CI-only) join the round as derived commands
2723
+ const ciCfg = o.precheck?.ci ?? parseCiPrecheckConfig(null);
2724
+ let ciRequired, ciDerived = new Map(); // command -> {job, name, why, steps}
2725
+ const ciGaveUp = new Set(); // jobs found unrunnable in an earlier round: recorded once, not rerun
2726
+ async function ciPrecheckPlan(round) {
2727
+ ciDerived = new Map();
2728
+ if (ciCfg.mode === "off" || isSplit || !io.ciLocalPlan || !io.fs?.write) return [];
2729
+ if (ciRequired === undefined) { try { ciRequired = (await io.requiredChecks?.(lane)) ?? null; } catch { ciRequired = null; } }
2730
+ const p = await deriveCiPrecheck({ buildPlan: io.ciLocalPlan, required: ciRequired, cfg: ciCfg, wt, base, lane, files, perCommandMs: vcfg.precheckTimeoutSeconds * 1000, writeFile: (rel, text) => io.fs.write(`${wt}/${rel}`, text), skipJobs: ciGaveUp });
2731
+ for (const c of p.commands) ciDerived.set(c.command, c);
2732
+ ev({ event: "CI_PRECHECK_PLAN", round, source: p.source, ...(p.note ? { note: p.note } : {}), commands: p.commands.map(({ job, name, workflow, kind, why, steps, command }) => ({ job, name, workflow, kind, why, steps, command })), skipped: p.skipped, unrunnable: p.unrunnable });
2733
+ if (!round) T.decisions.push(`CI precheck (${p.source}): ${p.commands.length ? p.commands.map((c) => `${c.name} (${c.why})`).join(", ") : "no job to run locally"}${p.unrunnable.length ? `; unrunnable: ${p.unrunnable.map((u) => `${u.name}: ${u.reason}`).join("; ")}` : ""}`);
2734
+ return p.commands.map((c) => c.command);
2735
+ }
2736
+ let ciCommands = await ciPrecheckPlan(0);
2737
+ const pickChecks = () => planPrecheck({ testMap, files, learned: [...learnedCommands, ...ciCommands], maxMinutes: o.precheck?.maxMinutes, verify: vcfg });
2503
2738
  let picked = pickChecks();
2504
2739
  // #4270: the last result of each deterministic gate, as computed below; only reportVerify (verify.check_run) reads it
2505
2740
  const verifyFacts = { commands: null, structure: null, undeclaredEdges: [], docs: null, precheck: null, amendments: [], hotspots: false };
@@ -2508,7 +2743,7 @@ export async function runCore(o) {
2508
2743
  precheckRan = true;
2509
2744
  for (let round = 0; ; round++) {
2510
2745
  await renew();
2511
- if (round) picked = pickChecks();
2746
+ if (round) { ciCommands = await ciPrecheckPlan(round); picked = pickChecks(); }
2512
2747
  const precheckCommands = picked.commands;
2513
2748
  // #4318/#4331: one round has a total budget (lean.precheck.max_minutes, else verify.precheck_total_seconds); the
2514
2749
  // commands run concurrently up to the host worker cap; the rest are deferred to CI, not failed. #4344: one heavy
@@ -2519,7 +2754,17 @@ export async function runCore(o) {
2519
2754
  const round$ = await runChecks({ commands: precheckCommands, parallelism, budgetMs: totalMs, perCommandMs: picked.perCommandMs, now,
2520
2755
  acquire: () => heavyAcquire("precheck"),
2521
2756
  run: ({ command, timeoutMs, workers: share }) => { workers = share; const env = laneEnv(); return io.runCommand({ command, cwd: wt, timeoutMs, env: env.FORGE_HOST_PARALLELISM ? { ...env, FORGE_HOST_PARALLELISM: String(share) } : env }); } });
2522
- const { results, deferred } = round$;
2757
+ const { deferred } = round$;
2758
+ // #5820: a derived CI job that could not run (ci-local degraded, timeout, no tool) is recorded, never a fix round
2759
+ const ciRows = round$.results.filter((x) => ciDerived.has(x.command)).map((x) => ({ x, c: ciDerived.get(x.command), out: ciPrecheckOutcome(x) }));
2760
+ const ciSkip = new Set(ciRows.filter((r) => r.out.status === "unrunnable" || r.out.status === "deferred").map((r) => r.x.command));
2761
+ const results = round$.results.filter((x) => !ciSkip.has(x.command));
2762
+ if (ciDerived.size) {
2763
+ const ciDeferred = deferred.filter((c) => ciDerived.has(c)).map((c) => ({ job: ciDerived.get(c).job, name: ciDerived.get(c).name, status: "deferred-to-ci", reason: "precheck budget reached" }));
2764
+ const rows = [...ciRows.map(({ x, c, out }) => ({ job: c.job, name: c.name, status: out.status, rc: x.rc, ms: x.ms, ...(out.reason ? { reason: out.reason } : {}) })), ...ciDeferred];
2765
+ ev({ event: "CI_PRECHECK_RESULT", round, green: rows.every((r) => r.status !== "fail"), results: rows });
2766
+ for (const r of rows.filter((y) => y.status === "unrunnable" || y.status === "deferred")) { ciGaveUp.add(r.job); T.anomalies.push(`CI precheck job ${r.name} ${r.status} locally (${r.reason}); left to CI`); }
2767
+ }
2523
2768
  precheckMs += round$.ms; precheckDeferred += deferred.length;
2524
2769
  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(", ")}`);
2525
2770
  const { failed, timedOut } = splitPrecheckResults(results); // #5332: rc 124 is host load, never a failing check
@@ -2544,7 +2789,8 @@ export async function runCore(o) {
2544
2789
  const rel = `${CHECK_LOG_DIR}/precheck-${round + 1}-${i + 1}.log`;
2545
2790
  let logPath = null;
2546
2791
  if (io.fs.write) { try { await io.fs.write(`${wt}/${rel}`, String(f.output ?? "")); logPath = rel; } catch { /* tail only */ } }
2547
- return { command: f.command, rc: f.rc, output: quietFailure(f.output, { maxChars: capped[i].output.length || 500, logPath }) };
2792
+ const ci = ciDerived.get(f.command); // #5820: name the CI job and its steps, not only the ci-local invocation
2793
+ return { command: ci ? `${f.command} # CI job "${ci.name}" (${ci.why}): ${ci.steps.join(" && ").slice(0, 400)}` : f.command, rc: f.rc, output: quietFailure(f.output, { maxChars: capped[i].output.length || 500, logPath }) };
2548
2794
  }));
2549
2795
  await fixRound("precheck", precheckFailurePrompt(quiet, vcfg.mode), [], "precheck", capped.map((f) => `${f.command}\n${f.output ?? ""}`).join("\n"));
2550
2796
  await upsertStage("implementation");
@@ -2925,7 +3171,7 @@ export async function runCore(o) {
2925
3171
  let effective = frozen, review = null, lastAmend = "", resumes = 0, lastFailKey = null, verdict = null, degraded = null, triggerSkipped = false, selfReviewCompared = false;
2926
3172
  const TRIGGER_SKIP = "skipped (review.trigger enforce: no risk trigger)";
2927
3173
  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).";
2928
- let pendingDecisions = [], firstRounds = null, firstReply = null;
3174
+ let pendingDecisions = [], firstRounds = null, firstReply = null, lastDecided = "";
2929
3175
  let baseTree = null; // #4695: the base file list, read once and only when a decision amendment needs it
2930
3176
  let genPaths = null; // forge#4519: maintenance.generated_paths from hotspots.sh (plan facts; one config-only call without them, never on light lanes)
2931
3177
  async function amend() {
@@ -2935,8 +3181,16 @@ export async function runCore(o) {
2935
3181
  const addedPaths = wantsDecision ? String(await git(["diff", "--name-only", "--diff-filter=A", `${base}...HEAD`]).catch(() => "")).split("\n").filter(Boolean) : [];
2936
3182
  const own = [...(Array.isArray(result?.amendments) ? result.amendments : []), ...impliedDocs];
2937
3183
  const ownKeys = new Set(own.map((x) => JSON.stringify(x)));
2938
- const all = [...priorAmendments.filter((x) => !ownKeys.has(JSON.stringify(x))), ...own];
3184
+ const dd = dedupeAddRequirements(frozen, [...priorAmendments.filter((x) => !ownKeys.has(JSON.stringify(x))), ...own]); // #5773: a requeue does not renumber a re-added row
3185
+ const all = dd.amendments;
3186
+ if (dd.dropped.length) T.decisions.push(`add-requirement ${dd.dropped.map((x) => x.id).join(", ")} dropped: its quote is already a contract row or re-added later (#5773)`);
2939
3187
  const a = applyAmendments(frozen, all, issueText, { generatedPaths: genPaths, baseFiles: baseTree?.length ? baseTree : null, addedPaths, defaultWhy: engineWhy });
3188
+ const ad = applyRequirementDecisions(a.contract, trustedComments); // #5773: the operator's decision wins over replayed amendments and reaches amendment-added rows
3189
+ if (ad.applied.length) {
3190
+ a.contract = deferChecklessPostDeploy(ad.contract).contract;
3191
+ const k = ad.applied.join(", ");
3192
+ if (k !== lastDecided) { lastDecided = k; T.decisions.push(`FORGE:DECISION applied to the amended contract: ${k} tracked post-deploy`); }
3193
+ }
2940
3194
  const sig = JSON.stringify(a.applied);
2941
3195
  if (a.applied.length && sig !== lastAmend) {
2942
3196
  lastAmend = sig;
@@ -3025,7 +3279,7 @@ export async function runCore(o) {
3025
3279
  run.findings = parseVerifierFindings(rr?.text, { pathExists: (x) => listed.has(x) });
3026
3280
  run.cost_usd = num(rr?.costUsd) ?? 0;
3027
3281
  } catch (e) {
3028
- if (e?.deferUsageLimit || e?.deferCode === OUTCOME_CODES.BACKEND_AUTH) throw e; // #5168: a login failure (backend.auth) is not swallowed as a verifier error
3282
+ if (e?.deferUsageLimit || e?.deferCode === OUTCOME_CODES.BACKEND_AUTH || e?.deferCode === OUTCOME_CODES.BACKEND_CLI_FAILED) throw e; // #5168: a login failure (backend.auth) is not swallowed as a verifier error
3029
3283
  run.error = String(e?.code || e?.message || e).split("\n")[0].slice(0, 200);
3030
3284
  T.anomalies.push(`Independent verifier failed at ${head.slice(0, 12)}: ${run.error}`);
3031
3285
  }
@@ -3042,13 +3296,15 @@ export async function runCore(o) {
3042
3296
  /** #4323: rerun once each validate command the builder recorded as failed, with the lane env; {[id]: {rc, output}} or null. */
3043
3297
  /** #5005: a frozen forgedock entry-point path missing on this host is replaced by this install's own. */
3044
3298
  const forgedockResolved = (c) => resolveForgedockPaths(String(c), { exists: existsSync, checksCli: CHECKS_CLI, forgedockCli: FORGEDOCK_CLI });
3045
- async function rerunFailedValidatesRaw(contract) {
3299
+ async function rerunFailedValidatesRaw(contract, { ciVerified = false } = {}) {
3046
3300
  if (!io.runCommand) return null;
3047
3301
  const runs = Array.isArray(result?.validation) ? result.validation : [], out = {};
3048
3302
  const env = laneEnv();
3049
3303
  for (const v of contract.validate ?? []) {
3050
3304
  const r = runs.find((x) => x?.id === v.id);
3051
- if (!r || r.exit === undefined || r.exit === 0) continue;
3305
+ // #5728: an entry with no recorded result (or ci:true without an exit) is run by the engine unless the head is CI-verified
3306
+ const noRow = !r || (r.ci === true && r.exit === undefined);
3307
+ if (noRow ? ciVerified : r.exit === undefined || r.exit === 0) continue;
3052
3308
  let x;
3053
3309
  try { x = await heavyStep("precheck", async () => (await runWithTimeoutRetry((timeoutMs) => io.runCommand({ command: forgedockResolved(v.command), cwd: wt, timeoutMs, env }), vcfg.precheckTimeoutSeconds * 1000)).r); } catch (e) { x = { rc: 127, output: String(e?.message ?? e) }; }
3054
3310
  // #4761: a runner usage error (vitest -q) is the frozen command's defect: try the normalised command once
@@ -3079,9 +3335,11 @@ export async function runCore(o) {
3079
3335
  }
3080
3336
  } catch { /* fail-open: the original failure stands */ }
3081
3337
  }
3082
- out[v.id] = { rc: Number.isInteger(x?.rc) ? x.rc : 1, output: String(x?.output ?? "") };
3338
+ out[v.id] = { rc: Number.isInteger(x?.rc) ? x.rc : 1, output: String(x?.output ?? ""), ...(noRow ? { engine: true } : {}) };
3083
3339
  }
3084
- if (Object.keys(out).length) ev({ event: "VALIDATE_RERUN", runs: Object.entries(out).map(([id, x]) => ({ id, rc: x.rc })) });
3340
+ const engineRan = Object.entries(out).filter(([, x]) => x.engine);
3341
+ if (engineRan.length) T.decisions.push(`Validate ${engineRan.map(([id]) => id).join(", ")} had no recorded result: the engine ran ${engineRan.length > 1 ? "them" : "it"} (exit ${engineRan.map(([, x]) => x.rc).join(", ")})`);
3342
+ if (Object.keys(out).length) ev({ event: "VALIDATE_RERUN", runs: Object.entries(out).map(([id, x]) => ({ id, rc: x.rc, ...(x.engine ? { engine: true } : {}) })) });
3085
3343
  return out;
3086
3344
  }
3087
3345
  /** #4979 SPEC-2: rerun the frozen command of every substituted validate, so precheck accepts a substitute only for a command that cannot run. */
@@ -3104,7 +3362,7 @@ export async function runCore(o) {
3104
3362
  return out;
3105
3363
  }
3106
3364
  /** #4693: select the guards this diff intersects and rerun their base test files; zero cost when none is selected. Best effort: an error skips the gate. */
3107
- let guardSel = [], guardNoted = ""; let guardEv = null; // #4705: this pass's guard_run event, emitted by the caller once the added wall time is known
3365
+ let guardSel = [], guardNoted = "", laneRemoved = []; let guardEv = null; // #5752: laneRemoved: the lane's deleted paths, for mechanism-retired guards // #4705: this pass's guard_run event, emitted by the caller once the added wall time is known
3108
3366
  async function guardGate(files) {
3109
3367
  let sel = [], r = null; guardEv = null;
3110
3368
  try {
@@ -3112,12 +3370,14 @@ export async function runCore(o) {
3112
3370
  const picked = guards.length ? await selectGuards({ guards, files, git: (a) => git(a), base }) : { selected: [], mergeBase: null };
3113
3371
  sel = picked.selected; guardSel = sel;
3114
3372
  if (!sel.length) return [];
3115
- r = await runGuards({ selected: sel, mergeBase: picked.mergeBase, contract: effective, guardCommand: vcfg.guardCommand, git: (a) => git(a), runCommand: (a) => io.runCommand(a), cwd: wt, env: laneEnv(), parallelism: Number(process.env.FORGE_HOST_PARALLELISM) || 2 });
3373
+ r = await runGuards({ selected: sel, mergeBase: picked.mergeBase, contract: effective, guardCommand: vcfg.guardCommand, git: (a) => git(a), runCommand: (a) => io.runCommand(a), cwd: wt, env: laneEnv(), parallelism: Number(process.env.FORGE_HOST_PARALLELISM) || 2, ...(o.guardFs ? { fs: o.guardFs } : {}) });
3116
3374
  } catch (e) { T.anomalies.push(`Guard gate skipped: ${String(e?.message ?? e).split("\n")[0].slice(0, 160)}`); guardEv = { event: "guard_run", selected: sel.map((x) => x.guard.issue), ran: 0, broken: 0, skipped: 0, wall_ms: 0, error: true }; return []; }
3117
3375
  const note = `Guard gate selected ${sel.map((x) => `#${x.guard.issue} (${x.reason})`).join("; ")}${r.skipped.length ? `; skipped: ${r.skipped.join("; ")}` : ""}${r.failures.length && shadow ? "; shadow: would block" : ""}`;
3118
3376
  if (note !== guardNoted) { guardNoted = note; T.decisions.push(note); }
3119
- guardEv = { event: "guard_run", selected: sel.map((x) => x.guard.issue), reasons: Object.fromEntries(sel.map((x) => [x.guard.issue, x.reason])), batches: r.batches, ran: r.runs.length, broken: r.failures.length, skipped: r.skipped.length, wall_ms: r.ms };
3377
+ const weak = weakGuardNotes(r.runs); // #5752: a broken weak guard (literal-presence test) is a review note, not a park
3378
+ guardEv = { event: "guard_run", selected: sel.map((x) => x.guard.issue), reasons: Object.fromEntries(sel.map((x) => [x.guard.issue, x.reason])), batches: r.batches, ran: r.runs.length, broken: r.failures.length, weak: weak.length, skipped: r.skipped.length, wall_ms: r.ms };
3120
3379
  for (const f of r.failures) ev({ event: "guard_broken", guard: f.guard, test: f.test });
3380
+ for (const w of weak) { ev({ event: "guard_weak", guard: w.guard, test: w.test }); if (!T.decisions.includes(w.note)) T.decisions.push(w.note); }
3121
3381
  return r.failures;
3122
3382
  }
3123
3383
  /** Precheck then review, on the current result and changed files (also the base-sync re-review). */
@@ -3177,6 +3437,12 @@ export async function runCore(o) {
3177
3437
  const gateHead = String(await git(["rev-parse", "HEAD"])).trim();
3178
3438
  const ciVerified = remoteVerify && ciVerifiedHead !== null && ciVerifiedHead === gateHead;
3179
3439
  const hotspots = await hotspotsOf({ base, paths: files }); // #4502
3440
+ let counters = null; // #5751: recurrence.counters at the lane's merge base and at its head
3441
+ if (recCfg.counters.length) {
3442
+ const mb = String(await git(["merge-base", base, "HEAD"]).catch(() => "")).trim() || base;
3443
+ counters = { before: await countCounters({ git, ref: mb, counters: recCfg.counters }), after: await countCounters({ git, ref: "HEAD", counters: recCfg.counters }) };
3444
+ ev({ event: "COUNTERS", ...counters });
3445
+ }
3180
3446
  const rx = await relaxationsOf(files); // #5237
3181
3447
  relaxations = rx.relaxations;
3182
3448
  if (relaxations.length) {
@@ -3187,21 +3453,30 @@ export async function runCore(o) {
3187
3453
  // #5436: the review reads the same committed diff as guard+precheck, so its session starts now; reviewOnce adopts it, any earlier return discards it
3188
3454
  const repro = await reproOf(effective);
3189
3455
  // a precheck that already fails on facts at hand (no engine rerun) would discard the review, so it is not started then
3190
- const early = triggerMode === "enforce" || amendProblems.length ? null : precheck({ contract: effective, result, changedFiles: files, ignore: IGNORE, ciVerified, hotspots, frozen, repro, repoHas: repoTracks(String(await git(["ls-files"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean)) });
3456
+ const early = triggerMode === "enforce" || amendProblems.length ? null : precheck({ contract: effective, result, changedFiles: files, ignore: IGNORE, ciVerified, hotspots, counters, recurrence, frozen, repro, repoHas: repoTracks(String(await git(["ls-files"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean)) });
3191
3457
  specReview = !early || early.failures.length ? null : startSpeculative(async () => reviewerCall((await reviewPrep()).prompt));
3192
3458
  const gateT0 = now(); let validateMs = 0;
3193
3459
  // #4693: guards run beside the validate rerun; SPEC-11: the substituted-original rerun shares the one validate phase
3194
- const validatePhase = phaseLedger.during("validate", async () => ({ runs: await rerunFailedValidatesRaw(effective), subs: await rerunSubstitutedOriginals(effective) })).finally(() => { validateMs = now() - gateT0; });
3460
+ const validatePhase = phaseLedger.during("validate", async () => ({ runs: await rerunFailedValidatesRaw(effective, { ciVerified }), subs: await rerunSubstitutedOriginals(effective) })).finally(() => { validateMs = now() - gateT0; });
3195
3461
  const [{ runs: validateRuns, subs: substitutedRuns }, guardFailures] = await Promise.all([validatePhase, guardGate(files)]);
3196
3462
  // #5087: forge.yaml topology.route_reachability gates the route handlers this diff adds; unset = no check
3197
3463
  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 } }) : [];
3198
3464
  // #5419: forge.yaml docs: user-facing surfaces need docs, and added /docs links must resolve; unset = no check
3199
3465
  const docsFail = docsConfig ? await docsFailures({ cfg: docsConfig, files, result, diff: String(await git(["diff", "-U0", `${base}...HEAD`]).catch(() => "")), tracked: String(await git(["ls-files"]).catch(() => "")).split("\n").filter(Boolean), run: io.runCommand ? async ({ command }) => (await io.runCommand({ command, cwd: wt, timeoutMs: vcfg.precheckTimeoutSeconds * 1000, env: laneEnv() }).then((x) => x?.r ?? x)) ?? { rc: 127 } : null }) : [];
3466
+ // #5752: forge.yaml outcome_evidence: a touched declared area needs a before/after on recorded real inputs; unset = no check
3467
+ const outcomeFail = outcomeEvidenceConfig ? outcomeEvidenceFailures({ cfg: outcomeEvidenceConfig, files, result, contract: effective, exists: (p) => existsSync(join(wt, p)), checks: effective.requirements?.some((r) => r.disposition === "post-deploy") ? await rawChecksAt(git, [base, "HEAD"]) : null }) : [];
3200
3468
  // #5428: forge.yaml pages: a public page needs design, SEO and GEO briefs and passes the deterministic page checks; unset = no check
3201
3469
  const addedNow = String(await git(["diff", "--name-only", "--diff-filter=A", `${base}...HEAD`]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean); // #5648: new vs modified pages
3202
- const pageFail = pagesConfig ? await pageFailures({ cfg: pagesConfig, files, result, added: addedNow, diff: String(await git(["diff", "-U0", `${base}...HEAD`]).catch(() => "")), tracked: String(await git(["ls-files"]).catch(() => "")).split("\n").filter(Boolean), readFile: (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } }, designApproved: designLabelApproved(iss?.labels) || designSpecApproved((iss?.comments ?? []).filter(isTrustedIssueComment)), run: io.runCommand ? async ({ command }) => (await io.runCommand({ command, cwd: wt, timeoutMs: vcfg.precheckTimeoutSeconds * 1000, env: laneEnv() }).then((x) => x?.r ?? x)) ?? { rc: 127 } : null }) : [];
3470
+ // #5770: forge.yaml pages.capture: the engine renders the changed routes (no browser in the builder session) and uploads the shots; once per head
3471
+ const pageRoutes = pagesConfig?.capture && io.runCommand ? changedRoutes(files, pagesConfig, { readFile: (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } } }) : [];
3472
+ if (pageRoutes.length) {
3473
+ const headSha = String(await git(["rev-parse", "HEAD"]).catch(() => "")).trim(), capDir = join(osTmpdir(), `forge-visual-${runId}`) /* outside the worktree: the lane commits .forge-lean */, runIn = ({ command, env }) => io.runCommand({ command, cwd: wt, timeoutMs: vcfg.precheckTimeoutSeconds * 1000, env: { ...laneEnv(), ...env } });
3474
+ if (pageVisual?.sha !== headSha || pageVisual.errors.length) pageVisual = { sha: headSha, ...(await captureVisualCheck({ cfg: pagesConfig, routes: pageRoutes, dir: capDir, run: runIn, read: (p) => { try { return readFileSync(p); } catch { return null; } }, publish: (fs_) => publishToRef({ run: runIn, dir: capDir, files: fs_, slug: repo, runId }) })) };
3475
+ }
3476
+ const bugFixIssue = (iss?.labels ?? []).some((l) => /^(?:type:)?bug$|^(?:priority:)?p[01]$/i.test(typeof l === "string" ? l : l?.name ?? "")); // #5729: a bug fix is not forced through design for attribute edits
3477
+ const pageFail = pagesConfig ? await pageFailures({ cfg: pagesConfig, files, result, captures: pageVisual, exists: (p) => existsSync(join(wt, p)), added: addedNow, bugFix: bugFixIssue, remoteNoCapture: o.placement?.where === "remote" && !pagesConfig?.capture, diff: String(await git(["diff", "-U0", `${base}...HEAD`]).catch(() => "")), tracked: String(await git(["ls-files"]).catch(() => "")).split("\n").filter(Boolean), readFile: (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } }, designApproved: designLabelApproved(iss?.labels) || designSpecApproved((iss?.comments ?? []).filter(isTrustedIssueComment)), run: io.runCommand ? async ({ command }) => (await io.runCommand({ command, cwd: wt, timeoutMs: vcfg.precheckTimeoutSeconds * 1000, env: laneEnv() }).then((x) => x?.r ?? x)) ?? { rc: 127 } : null }) : [];
3203
3478
  // #5330: forge.yaml design.routes (opt-in, blocking only): a user-visible page needs an approved spec and passes the deterministic visual critique
3204
- const designFail = designFailures({ cfg: designConfig, files, added: addedNow, diff: String(await git(["diff", "-U0", `${base}...HEAD`]).catch(() => "")), specs: designSpecOk({ comments: (iss?.comments ?? []).filter(isTrustedIssueComment), labels: iss?.labels, cfg: designConfig }), readFile: (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } } });
3479
+ const designFail = designFailures({ cfg: designConfig, files, added: addedNow, bugFix: bugFixIssue, covered: pagesConfig?.require?.includes("design") ? [...pageFiles(files, pagesConfig, { readFile: (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } } }), ...designOnlyFiles(files, pagesConfig)] : [], diff: String(await git(["diff", "-U0", `${base}...HEAD`]).catch(() => "")), specs: designSpecOk({ comments: (iss?.comments ?? []).filter(isTrustedIssueComment), labels: iss?.labels, cfg: designConfig }), readFile: (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } } });
3205
3480
  // #5284: forge.yaml topology.prod_parity: declared production-only surfaces this diff touches need a check result or a justification
3206
3481
  const parityRules = parseProdParity(prodParity);
3207
3482
  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 } }) : [];
@@ -3216,7 +3491,8 @@ export async function runCore(o) {
3216
3491
  const repoHas = (validateRuns && Object.keys(validateRuns).length) || Object.keys(substitutedRuns ?? {}).length ? repoTracks(String(await git(["ls-files"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean)) : undefined;
3217
3492
  // #4626: post-deploy check ids resolve against the lane base's checks file or this PR's
3218
3493
  const checkIds = effective.requirements?.some((r) => r.disposition === "post-deploy") ? new Set(Object.keys(await checksAt(git, [base, "HEAD"], wt))) : null;
3219
- const removedPaths = (effective.validate ?? []).some((v) => v.substituted) ? await removedPathsOf(git, base) : []; // #4990
3494
+ const removedPaths = (effective.validate ?? []).some((v) => v.substituted) || effective.mechanisms?.length ? await removedPathsOf(git, base) : []; // #4990; #5752: a mechanism supersedes retires deleted guard tests
3495
+ laneRemoved = removedPaths ?? [];
3220
3496
  const subBaseFiles = (effective.validate ?? []).some((v) => v.substituted) ? String(await git(["ls-tree", "-r", "-z", "--name-only", base]).catch(() => "")).split("\0").filter(Boolean) : []; // #5003
3221
3497
  const baselineRuns = [];
3222
3498
  for (const b of matchBaselines(files, vcfg.baselines)) { // #5448: project baseline suites for the changed paths, enforced
@@ -3225,7 +3501,9 @@ export async function runCore(o) {
3225
3501
  baselineRuns.push({ ...b, rc: Number.isInteger(x?.rc) ? x.rc : 1, output: String(x?.output ?? "") });
3226
3502
  }
3227
3503
  if (baselineRuns.length) ev({ event: "BASELINES_RUN", runs: baselineRuns.map((b) => ({ run: b.run, rc: b.rc })) });
3228
- const pc = precheck({ baselineFailures: baselineFailures(baselineRuns), contract: effective, result, changedFiles: files, ignore: IGNORE, ciVerified, hotspots, repro: (adequacyIn.repro = repro), validateRuns, repoHas, frozen, checkIds, guardFailures, coupledFailures: await coupledOf(files), relaxationFailures: relaxationFailures(rx), routeFailures, docsFailures: docsFail, pageFailures: [...pageFail, ...designFail], seamFailures: seamFail, docsPaths: docsConfig ? [...(docsConfig.paths ?? []), ...(docsConfig.registries ?? [])] : null, prodParityFailures, newOffKeys: await newOffKeysOf(), uiBrowser: uiBrowserOf(files), substitutedRuns, removedPaths, baseFiles: subBaseFiles });
3504
+ // #5760: CI budget gate (always on: annotation + hygiene; max_* only when set); one git diff when no workflow changed
3505
+ const ciBudgetFail = await ciBudgetFailures({ cfg: ciBudget ?? parseCiBudget(null), base, git }).catch((e) => { ev({ event: "CI_BUDGET_GATE_ERROR", error: String(e?.message ?? e).slice(0, 200) }); return []; });
3506
+ const pc = precheck({ baselineFailures: baselineFailures(baselineRuns), contract: effective, result, changedFiles: files, ignore: IGNORE, ciVerified, hotspots, counters, recurrence, repro: (adequacyIn.repro = repro), validateRuns, repoHas, frozen, checkIds, guardFailures, coupledFailures: await coupledOf(files), relaxationFailures: relaxationFailures(rx), routeFailures, docsFailures: docsFail, outcomeEvidenceFailures: outcomeFail, ciBudgetFailures: ciBudgetFail, pageFailures: [...pageFail, ...designFail], seamFailures: seamFail, docsPaths: docsConfig ? [...(docsConfig.paths ?? []), ...(docsConfig.registries ?? [])] : null, prodParityFailures, newOffKeys: await newOffKeysOf(), uiBrowser: uiBrowserOf(files), substitutedRuns, removedPaths, baseFiles: subBaseFiles });
3229
3507
  // #5447: an install failure for a package the changed files import blocks (env.tool_missing); unrelated ones are logged
3230
3508
  const depFail = depInstallFailures({ results: depResults, changedFiles: files });
3231
3509
  for (const l of depFail.logged) if (!T.decisions.includes(l)) T.decisions.push(l);
@@ -3290,6 +3568,8 @@ export async function runCore(o) {
3290
3568
  if (pre.length) ev({ event: "PRECHECK", failures: pre.map((f) => f.code) });
3291
3569
  // #5080: the repro already passes on the base and the diff changes no source: the fix is on the base, not missing
3292
3570
  if (alreadyFixedOnBase(pre, files, IGNORE)) return { state: "already-fixed", by: "precheck", failures: pre };
3571
+ // #5729: a missing /design spec or visual evidence is not a builder fix: end design.spec_required before any resume or recovery lane
3572
+ if (pre.length && !recording() && specOnlyFailures(pre)) return { state: "spec-only", by: "precheck", failures: pre };
3293
3573
  if (pre.length && !recording()) return { state: "nonconforming", by: "precheck", failures: pre };
3294
3574
  // shadow: the builder's own failed checks block before any reviewer tokens are spent (#4160)
3295
3575
  const hard = recording() ? blockingOf(pre, SHADOW_PRE_BLOCKS).block : [];
@@ -3405,11 +3685,15 @@ export async function runCore(o) {
3405
3685
  const explained = explainFailures(outcome.failures, effective); // #4265: name the unmet requirement, not only the code
3406
3686
  const list = explained.slice(0, 15).map((f) => `- ${f.code}: ${f.detail}`).join("\n");
3407
3687
  if (outcome.state === "environment") return await envNeedsHuman(outcome.failures);
3688
+ if (outcome.state === "spec-only") return await needsHuman(`The page gate needs an approved FORGE:DESIGN_SPEC (run /design) or visual evidence a builder resume cannot produce, so no resume or recovery lane was spent:\n\n${list}`, OUTCOME_CODES.DESIGN_SPEC_REQUIRED, { ask: `Run /design for #${issue}` });
3408
3689
  // #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
3409
- if (o.placement?.where === "remote" && !recover && outcome.failures?.length && outcome.failures.every((f) => f?.kind === "validate_failed")) {
3690
+ // #5732: so is a repro head failure whose output carries no assertion text (an env error of the sandbox, not a red test)
3691
+ if (o.placement?.where === "remote" && !recover && outcome.failures?.length && outcome.failures.every((f) => f?.kind === "validate_failed" || (f?.kind === "repro_red_green" && f.head === "FAILED" && f.assertion === false))) {
3410
3692
  T.anomalies.push("Remote validate failure: rerun on the host in a local recovery lane before it is terminal");
3411
3693
  return await needsHuman(`A frozen validate command failed in the remote sandbox (exit non-zero on the engine's rerun). The sandbox is a different environment from the host, so no builder resume was spent; the branch is pushed and a local recovery lane reruns the frozen command on the host (pass: the change stands; fail: conformance.unimplemented):\n${list}`, ENV_VALIDATE_PLACEMENT);
3412
3694
  }
3695
+ const reproProdFail = outcome.state === "already-fixed" ? prodFailureSignal(trustedComments) : null; // #5734: a passing repro is no prod outcome
3696
+ if (reproProdFail) return await needsHuman(prodFailNote("already-fixed (repro passes on the base)", reproProdFail), OUTCOME_CODES.BUILDER_NO_EVIDENCE);
3413
3697
  if (outcome.state === "already-fixed") { // #5080: close as delivered, citing the base commit
3414
3698
  const sha = String(await git(["rev-parse", base]).catch(() => "")).trim().slice(0, 12) || base;
3415
3699
  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}`;
@@ -3431,7 +3715,7 @@ export async function runCore(o) {
3431
3715
  resumes++;
3432
3716
  T.decisions.push(`Not conforming (${outcome.by}${outcome.inconsistent ? ", reviewer verdict contradicted its rows" : ""}): ${[...new Set(outcome.failures.map((f) => f.code))].join(", ")} (${explained.slice(0, 5).map((f) => String(f.detail).slice(0, 160)).join("; ")}); builder resumed (round ${resumes} of ${reviewMaxResumes})`);
3433
3717
  // A failed validate may only mean the base moved on: fetch the lane so the resume can merge it (never rebase).
3434
- if (outcome.failures.some((f) => f?.kind === "validate_failed")) { try { await io.git(["fetch", "origin", lane], { cwd: wt }); } catch { /* offline: the resume uses the local ref */ } }
3718
+ if (outcome.failures.some((f) => f?.kind === "validate_failed")) { try { await io.git(["fetch", "origin", lane], { cwd: wt, env: laneGitEnv }); } catch { /* offline: the resume uses the local ref */ } }
3435
3719
  await fixRound("conformance", conformanceResumePrompt(outcome.failures, vcfg.mode, lane), outcome.failures, "conformance", failureLog(outcome.failures));
3436
3720
  await upsertStage("implementation"); // the published note follows the code after every resume
3437
3721
  }
@@ -3498,14 +3782,14 @@ export async function runCore(o) {
3498
3782
  laneGuard(lane, "open a PR");
3499
3783
  const prOut = resumed?.pr ? `/pull/${resumed.pr}` : String(await ghw(["pr", "create", "-R", repo, "--base", lane, "--head", branch,
3500
3784
  "--title", `${iss.title} (#${issue})`, "--body", withLink(isSplit ? (o.refactorModule ?? (await import("./refactor.mjs"))).renderSplitPrBody({ issue, ...split })
3501
- : renderPrBody({ issue, investigation: await readStage(STAGES[0]), contract: effective, implementation: await readStage(STAGES[1]), result, gitFiles: files, tracked: closing.tracked }))])).trim();
3785
+ : renderPrBody({ issue, investigation: await readStage(STAGES[0]), contract: effective, implementation: await readStage(STAGES[1]), result, gitFiles: files, tracked: closing.tracked, visual: visualMarkdown(pageVisual, pagesConfig?.viewports) }))])).trim();
3502
3786
  const pr = Number(/\/pull\/(\d+)/.exec(prOut)?.[1] ?? /(\d+)\s*$/.exec(prOut)?.[1]);
3503
3787
  if (!Number.isInteger(pr)) return await needsHuman(`Could not parse the PR number from: ${prOut.slice(0, 200)}`);
3504
3788
  ev({ event: "PR_OPENED", pr });
3505
3789
  await emit({ event: "PR_OPENED", pr });
3506
3790
  if (!resumed?.pr && !adoptPr) { try { const old = await supersedeOlderPrs({ repo, io: { gh: ghw }, issue, newPr: pr }); if (old.length) T.decisions.push(`Superseded older open PR(s) ${old.map((n) => `#${n}`).join(", ")} (one live PR per issue)`); } catch { /* best effort: the orphan sweep closes it later */ } } // #5505
3507
3791
  if (resumed?.pr && closing.tracked.length) { // an existing PR still has to link the tracking issues visibly
3508
- try { await ghw(["pr", "edit", String(pr), "-R", repo, "--body", withLink(renderPrBody({ issue, investigation: await readStage(STAGES[0]), contract: effective, implementation: await readStage(STAGES[1]), result, gitFiles: files, tracked: closing.tracked }))]); }
3792
+ try { await ghw(["pr", "edit", String(pr), "-R", repo, "--body", withLink(renderPrBody({ issue, investigation: await readStage(STAGES[0]), contract: effective, implementation: await readStage(STAGES[1]), result, gitFiles: files, tracked: closing.tracked, visual: visualMarkdown(pageVisual, pagesConfig?.viewports) }))]); }
3509
3793
  catch (e) { e.deferCode = OUTCOME_CODES.FOLLOWUP_UNAVAILABLE; e.deferDetail = `could not link the tracking issues on PR #${pr}; nothing merged, rerun to retry`; throw e; }
3510
3794
  }
3511
3795
  if (degraded) {
@@ -3729,7 +4013,17 @@ export async function runCore(o) {
3729
4013
  // #4708: the fix head is CI-verified before its review, as in the base-sync retry (#4527), so validates left to CI are covered
3730
4014
  if (remoteVerify) { const v = await ciVerify("merge"); if (v.done) return v.done; }
3731
4015
  const rows = Array.isArray(result?.validation) ? result.validation : [], headNow = await gitOut(["rev-parse", "HEAD"]);
3732
- const lost = (effective.validate ?? []).filter((v) => !rows.some((x) => x?.id === v.id) && !(remoteVerify && ciVerifiedHead === headNow)).map((v) => v.id);
4016
+ let lost = (effective.validate ?? []).filter((v) => !rows.some((x) => x?.id === v.id) && !(remoteVerify && ciVerifiedHead === headNow)).map((v) => v.id);
4017
+ if (lost.length && io.runCommand) { // #5768: a validate with no row is run once by the engine on the fix head before the lane parks
4018
+ const ran = await rerunFailedValidatesRaw({ ...effective, validate: (effective.validate ?? []).filter((v) => lost.includes(v.id)) });
4019
+ const fresh = (effective.validate ?? []).filter((v) => ran?.[v.id]).map((v) => ({ id: v.id, command: v.command, exit: ran[v.id].rc, rerun: true }));
4020
+ if (fresh.length) {
4021
+ result = { ...result, validation: [...rows, ...fresh] };
4022
+ try { await io.fs.write(`${wt}/${RESULT_FILE}`, `${JSON.stringify(result)}\n`); } catch { /* the gate reads what is on disk */ }
4023
+ T.decisions.push(`Validate result(s) ${fresh.map((x) => x.id).join(", ")} missing after the CI fix round: the engine re-ran ${fresh.length > 1 ? "them" : "it"} on the fix head (exit ${fresh.map((x) => x.exit).join(", ")})`);
4024
+ }
4025
+ lost = lost.filter((id) => !ran?.[id]);
4026
+ }
3733
4027
  if (lost.length) return await needsHuman(`Validate result(s) ${lost.join(", ")} missing after a CI fix round on PR #${pr}: the earlier results were lost and none could be carried forward; nothing merged.`, OUTCOME_CODES.ENGINE_VALIDATE_RESULT_LOST);
3734
4028
  const rv = await doReview(); // never merge an unreviewed head
3735
4029
  if (!rv) return await needsHuman("Reviewer returned no parseable verdict after a CI fix round.", OUTCOME_CODES.REVIEW_NO_VERDICT);
@@ -3924,6 +4218,19 @@ export async function runCore(o) {
3924
4218
  let dcoFailed = [];
3925
4219
  try { dcoFailed = ((lastStates ?? await io.checkStates?.(pr)) ?? []).filter((x) => /\bdco\b/i.test(String(x?.name ?? "")) && x.state === "failure" && (!x.head || !localHead || String(x.head).startsWith(localHead) || localHead.startsWith(String(x.head)))); } catch { dcoFailed = []; }
3926
4220
  if (dcoFailed.length) return await needsHuman(`DCO check failed on PR #${pr} (${[...new Set(dcoFailed.map((x) => x.name))].join(", ")}); a commit lacks a sign-off or has a placeholder author, which would block the release. Nothing merged.`, OUTCOME_CODES.CI_DCO);
4221
+ // #5709: a merge into the integration branch restarts CI of an open release PR (head = this branch): hold until it ends
4222
+ let heldSince = null, holdPolicy = null;
4223
+ try { const { parsePolicy, POLICY_PATH } = await import("./release-config.mjs"); const d = defaults.find(Boolean); if (d) holdPolicy = parsePolicy(String(await git(["show", `origin/${d}:${POLICY_PATH}`]))).policy ?? null; } catch { holdPolicy = null; } // no policy file: default on
4224
+ for (;;) {
4225
+ const target = String(resumed?.base ?? lane ?? "");
4226
+ const hold = await releaseMergeHold({ gh: ghc, repo, branch: target, defaults, enabled: holdMergesDuringReleaseCi, policy: holdPolicy, skipReleaseCi: (io.env ?? process.env).FORGE_RELEASE_FIX_LANE === "1", readActive: async () => { const { readActive } = await import("./release-ledger.mjs"); return readActive({ io: io.api ? io : ledgerIoFromGh(ghc), repo, credential: "driver" }); } }); // #5776: lanes have no io.api
4227
+ if (!hold.held) break;
4228
+ if (heldSince === null) { heldSince = now(); T.merge = [policyText, "merge.held_release"]; T.decisions.push(`merge.held_release: ${hold.reason}; PR #${pr} stays open and green`); ev({ event: "MERGE_HELD_RELEASE", pr, kind: hold.kind, releasePr: hold.pr ?? null }); }
4229
+ if (now() - heldSince >= ciMaxMinutes * 60000) return await finish("ci-pending", `PR #${pr} merge held ${ciMaxMinutes} min (${hold.reason}); rerun resumes the PR`, { pr });
4230
+ onProgress({ event: "phase_paused", phase: "merge", detail: `merge.held_release: ${hold.reason}` });
4231
+ await sleep(30000);
4232
+ await renew();
4233
+ }
3927
4234
  T.merge = [policyText, `merged at ${localHead.slice(0, 12)}`];
3928
4235
  laneGuard(resumed?.base ?? lane, "merge");
3929
4236
  try {
@@ -4019,10 +4326,10 @@ export async function runCore(o) {
4019
4326
  T.decisions.push(`Interface ${d.supersedes} superseded by ${d.id}: ${n.map((x) => `${x.consumer} ${x.action}${x.issue ? ` #${x.issue}` : ""}`).join(", ")}`);
4020
4327
  }
4021
4328
  } catch (e) { T.anomalies.push(`decision records not posted: ${String(e?.message ?? e).slice(0, 160)}`); }
4022
- for (const sp of supersededIds(effective, guardSel)) { // #4693: the reviewer accepted the supersedes amendment; tell the guarded issue
4329
+ for (const sp of supersededIds(effective, guardSel, laneRemoved)) { // #4693: the reviewer accepted the supersedes amendment; tell the guarded issue
4023
4330
  try { await ghw(["issue", "comment", sp.guard.slice(1), "-R", repo, "--body", supersessionComment({ guard: sp.guard, pr, why: sp.why })]); ev({ event: "supersedes_accepted", guard: sp.guard, pr }); T.decisions.push(`Guard ${sp.guard} superseded: ${sp.why}`); } catch (e) { T.anomalies.push(`supersession of ${sp.guard} not posted: ${String(e?.message ?? e).slice(0, 160)}`); }
4024
4331
  }
4025
- postRun.add("guard", async () => { try { const g = await (o.guardAfterMerge ?? guardAfterMerge)({ io, repo, issue, pr, cwd: wt, base }); if (g?.posted) T.decisions.push(`FORGE:GUARD posted: ${g.guard.tests.length} test file(s), ${g.guard.hunks.length} hunk(s)`); else if (g?.skipped) ev({ event: "GUARD_SKIPPED", reason: g.reason }); } catch { /* the guard is best effort */ } }); // #5437
4332
+ postRun.add("guard", async () => { try { const g = await (o.guardAfterMerge ?? guardAfterMerge)({ io: { ...io, git: (a, op) => io.git(a, { ...op, env: { ...laneGitEnv, ...op?.env } }) }, repo, issue, pr, cwd: wt, base }); if (g?.posted) T.decisions.push(`FORGE:GUARD posted: ${g.guard.tests.length} test file(s), ${g.guard.hunks.length} hunk(s)`); else if (g?.skipped) ev({ event: "GUARD_SKIPPED", reason: g.reason }); } catch { /* the guard is best effort */ } }); // #5437
4026
4333
  // forge#4161: the merge-time structure record and the milestone ride on the lane result for orchestrate's drift fold.
4027
4334
  await gatePassed("merge_ci", "ci_red"); // #4375: merged means the required checks are green after a CI fix round
4028
4335
  let mergedTo = null; // #4711: FORGE:STATE records the lane and merge commit, so a dependent's check needs no PR search
@@ -4033,7 +4340,7 @@ export async function runCore(o) {
4033
4340
  const when = e.resetAt || (Number.isFinite(e.resetAtEpochMs) ? new Date(e.resetAtEpochMs).toISOString() : "unknown");
4034
4341
  return finish("deferred", `usage limit hit; resets at ${when}`, { code: OUTCOME_CODES.RATE_LIMITED, resetAt: when, resetAtEpochMs: Number.isFinite(e.resetAtEpochMs) ? e.resetAtEpochMs : null, backendId: laneBackendId(process.env, rotator) }, OUTCOME_CODES.RATE_LIMITED);
4035
4342
  }
4036
- if (e?.deferCode) return finish("deferred", e.deferDetail ?? String(e.message), { code: e.deferCode, ...(e.retryInSeconds ? { retryInSeconds: e.retryInSeconds } : {}), ...(e.backendId ? { backendId: e.backendId } : {}), ...quotaFacts(e) }, e.deferCode); // #5168: backendId keys the account hold; #5236 reset
4343
+ if (e?.deferCode) return finish("deferred", e.deferDetail ?? String(e.message), { code: e.deferCode, ...(e.retryInSeconds ? { retryInSeconds: e.retryInSeconds } : {}), ...(e.backendId ? { backendId: e.backendId } : {}), ...(e.cliResult != null ? { cliResult: e.cliResult } : {}), ...(typeof e.cliIsError === "boolean" ? { cliIsError: e.cliIsError } : {}), ...(e.account ? { account: e.account } : {}), ...quotaFacts(e) }, e.deferCode); // #5168: backendId keys the account hold; #5236 reset
4037
4344
  // #4505: a turn overrun is mechanical: a non-human end the batch recovers, needs-human only once a budget recovery failed too
4038
4345
  if (e?.laneCode === OUTCOME_CODES.BUDGET_EXCEEDED && !(recover?.final && recover.code === OUTCOME_CODES.BUDGET_EXCEEDED)) {
4039
4346
  return finish("budget-exceeded", e.message, { code: OUTCOME_CODES.BUDGET_EXCEEDED, branch, ...(recover ? { recovery: true } : {}) }, OUTCOME_CODES.BUDGET_EXCEEDED);