forgedock 1.66.0 → 1.68.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 (173) hide show
  1. package/bin/config-schema.mjs +3 -0
  2. package/bin/engine/outcome-codes.mjs +2 -0
  3. package/bin/engine-cli.mjs +193 -27
  4. package/bin/engine.mjs +10 -0
  5. package/bin/forgedock.mjs +24 -1
  6. package/bin/help-text.mjs +4 -3
  7. package/bin/introspect-schedule.mjs +98 -0
  8. package/bin/introspect-schedule.test.mjs +67 -0
  9. package/bin/lean/admission.mjs +21 -0
  10. package/bin/lean/admission.test.mjs +30 -0
  11. package/bin/lean/advisory.test.mjs +64 -0
  12. package/bin/lean/amendment-schema.mjs +30 -0
  13. package/bin/lean/attempts.mjs +162 -0
  14. package/bin/lean/attempts.test.mjs +141 -0
  15. package/bin/lean/basered.mjs +81 -0
  16. package/bin/lean/basered.test.mjs +68 -1
  17. package/bin/lean/batch-health.mjs +20 -12
  18. package/bin/lean/batch-health.test.mjs +55 -11
  19. package/bin/lean/batch.mjs +45 -0
  20. package/bin/lean/batch.test.mjs +105 -5
  21. package/bin/lean/capwait.mjs +14 -3
  22. package/bin/lean/capwait.test.mjs +20 -0
  23. package/bin/lean/ci-gate.mjs +2 -90
  24. package/bin/lean/ci-gate.test.mjs +1 -127
  25. package/bin/lean/ci-precheck.mjs +25 -8
  26. package/bin/lean/ci-precheck.test.mjs +24 -0
  27. package/bin/lean/clear-breaker.mjs +14 -0
  28. package/bin/lean/clear-breaker.test.mjs +4 -3
  29. package/bin/lean/commentstate.mjs +46 -0
  30. package/bin/lean/commentstate.test.mjs +43 -0
  31. package/bin/lean/concurrency.mjs +89 -0
  32. package/bin/lean/concurrency.test.mjs +113 -0
  33. package/bin/lean/conformance.e2e.test.mjs +13 -8
  34. package/bin/lean/conformance.mjs +73 -181
  35. package/bin/lean/conformance.test.mjs +61 -345
  36. package/bin/lean/depcache.mjs +100 -10
  37. package/bin/lean/depcache.test.mjs +105 -0
  38. package/bin/lean/docsgate.mjs +0 -32
  39. package/bin/lean/docsgate.test.mjs +2 -23
  40. package/bin/lean/effects-cap.test.mjs +9 -1
  41. package/bin/lean/effects-killtree.test.mjs +35 -0
  42. package/bin/lean/effects.mjs +42 -24
  43. package/bin/lean/efficiency.mjs +162 -0
  44. package/bin/lean/efficiency.test.mjs +79 -0
  45. package/bin/lean/engine-readmit.test.mjs +35 -0
  46. package/bin/lean/envgap.mjs +93 -0
  47. package/bin/lean/envgap.test.mjs +53 -0
  48. package/bin/lean/execution.mjs +41 -17
  49. package/bin/lean/execution.test.mjs +58 -0
  50. package/bin/lean/failure-census.mjs +170 -0
  51. package/bin/lean/failure-census.test.mjs +59 -0
  52. package/bin/lean/failure-stop.mjs +46 -0
  53. package/bin/lean/failure-stop.test.mjs +45 -0
  54. package/bin/lean/fixtures/capacity-storm.json +609 -0
  55. package/bin/lean/guardgate.test.mjs +2 -3
  56. package/bin/lean/heavy.mjs +33 -4
  57. package/bin/lean/heavy.test.mjs +38 -6
  58. package/bin/lean/hotarea.mjs +0 -36
  59. package/bin/lean/hotarea.test.mjs +1 -22
  60. package/bin/lean/issuewatch-verify.mjs +19 -4
  61. package/bin/lean/issuewatch.mjs +21 -4
  62. package/bin/lean/issuewatch.test.mjs +48 -1
  63. package/bin/lean/lane-audit-gap.mjs +66 -0
  64. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  65. package/bin/lean/lane-audit-llm.mjs +5 -0
  66. package/bin/lean/lane-audit-query.mjs +47 -0
  67. package/bin/lean/lane-audit-query.test.mjs +44 -0
  68. package/bin/lean/lane-audit-signatures.mjs +33 -0
  69. package/bin/lean/lane-audit.mjs +110 -0
  70. package/bin/lean/lane-audit.test.mjs +97 -0
  71. package/bin/lean/lane-recovery.test.mjs +33 -0
  72. package/bin/lean/lanecheck.mjs +5 -3
  73. package/bin/lean/lanecheck.test.mjs +6 -0
  74. package/bin/lean/lean.mjs +311 -154
  75. package/bin/lean/lean.test.mjs +530 -223
  76. package/bin/lean/limits.mjs +17 -0
  77. package/bin/lean/limits.test.mjs +15 -1
  78. package/bin/lean/live-execution.mjs +21 -2
  79. package/bin/lean/live-execution.test.mjs +39 -0
  80. package/bin/lean/liveness.mjs +37 -0
  81. package/bin/lean/liveness.test.mjs +33 -0
  82. package/bin/lean/orchestrate-attempts.test.mjs +82 -0
  83. package/bin/lean/orchestrate-envhold.test.mjs +47 -0
  84. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  85. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  86. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  87. package/bin/lean/orchestrate-pause.test.mjs +76 -1
  88. package/bin/lean/orchestrate-reconcile.test.mjs +164 -0
  89. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  90. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  91. package/bin/lean/orchestrate.mjs +344 -45
  92. package/bin/lean/phaseledger.mjs +6 -0
  93. package/bin/lean/phaseledger.test.mjs +13 -1
  94. package/bin/lean/postdeploy-check.test.mjs +1 -3
  95. package/bin/lean/precheck.mjs +20 -0
  96. package/bin/lean/preflight.mjs +100 -11
  97. package/bin/lean/preflight.test.mjs +44 -4
  98. package/bin/lean/prompts.mjs +13 -28
  99. package/bin/lean/reconcile.mjs +90 -0
  100. package/bin/lean/recurrence.mjs +6 -112
  101. package/bin/lean/recurrence.test.mjs +11 -92
  102. package/bin/lean/release-flakes.mjs +14 -2
  103. package/bin/lean/release-flakes.test.mjs +17 -1
  104. package/bin/lean/release-ledger.mjs +19 -1
  105. package/bin/lean/release-ledger.test.mjs +23 -0
  106. package/bin/lean/release-preflight.mjs +28 -0
  107. package/bin/lean/release-preflight.test.mjs +42 -1
  108. package/bin/lean/release-review.mjs +40 -5
  109. package/bin/lean/release-review.test.mjs +43 -2
  110. package/bin/lean/release.mjs +43 -14
  111. package/bin/lean/release.test.mjs +32 -0
  112. package/bin/lean/retry.mjs +1 -1
  113. package/bin/lean/retry.test.mjs +6 -1
  114. package/bin/lean/rotator.mjs +9 -0
  115. package/bin/lean/rotator.test.mjs +11 -1
  116. package/bin/lean/sandbox-remote.mjs +49 -11
  117. package/bin/lean/sched.mjs +19 -0
  118. package/bin/lean/sched.test.mjs +11 -1
  119. package/bin/lean/schedd-health.mjs +4 -4
  120. package/bin/lean/schedd-health.test.mjs +8 -4
  121. package/bin/lean/schedd.mjs +45 -8
  122. package/bin/lean/schedd.test.mjs +120 -7
  123. package/bin/lean/selfreview.mjs +1 -1
  124. package/bin/lean/slo.mjs +126 -0
  125. package/bin/lean/slo.test.mjs +112 -0
  126. package/bin/lean/statuscomment.mjs +40 -0
  127. package/bin/lean/statuscomment.test.mjs +48 -1
  128. package/bin/lean/validate-catalog.mjs +108 -0
  129. package/bin/lean/validate-catalog.test.mjs +46 -1
  130. package/bin/lean/verify.mjs +3 -2
  131. package/bin/pool/affinity.test.mjs +91 -0
  132. package/bin/pool/agent.mjs +144 -10
  133. package/bin/pool/cache-sweep.mjs +31 -10
  134. package/bin/pool/ci-autoscale.mjs +160 -0
  135. package/bin/pool/cli.mjs +53 -9
  136. package/bin/pool/docker.mjs +3 -0
  137. package/bin/pool/engine-placement.test.mjs +94 -0
  138. package/bin/pool/lane-target.mjs +41 -0
  139. package/bin/pool/lane-tools.mjs +26 -0
  140. package/bin/pool/lane-tools.test.mjs +9 -0
  141. package/bin/pool/mirror-seed.mjs +15 -11
  142. package/bin/pool/router.mjs +88 -32
  143. package/bin/pool/version.mjs +29 -2
  144. package/bin/review-staging.mjs +11 -3
  145. package/bin/runner.mjs +59 -11
  146. package/bin/stats/attempts.mjs +54 -0
  147. package/bin/stats/attempts.test.mjs +30 -0
  148. package/bin/stats/churn.mjs +49 -0
  149. package/bin/stats/churn.test.mjs +31 -0
  150. package/bin/stats/index.mjs +11 -3
  151. package/bin/stats/release.mjs +7 -0
  152. package/bin/stats/release.test.mjs +20 -0
  153. package/bin/stats/scorecard.mjs +187 -0
  154. package/bin/stats/scorecard.test.mjs +89 -0
  155. package/commands/orchestrate.md +21 -18
  156. package/docs/CONFIG.md +41 -0
  157. package/docs/OUTCOME-CODES.md +2 -0
  158. package/docs/STATS.md +17 -0
  159. package/package.json +1 -1
  160. package/pool/image/Dockerfile +14 -2
  161. package/pool/image/manifest.json +25 -0
  162. package/pool/image/mirror.sh +11 -2
  163. package/pool/install/install-agent.ps1 +11 -4
  164. package/scripts/check-devdocs-freshness.sh +1 -1
  165. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  166. package/scripts/ci-local/cli.mjs +1 -1
  167. package/scripts/ci-local/plan.mjs +3 -2
  168. package/scripts/ci-local.test.sh +11 -0
  169. package/scripts/failure-census.mjs +67 -0
  170. package/scripts/review-finalize.sh +5 -5
  171. package/scripts/review-finalize.test.sh +8 -1
  172. package/scripts/verify-phase-trail.sh +11 -0
  173. package/scripts/verify-phase-trail.test.sh +9 -0
package/bin/lean/lean.mjs CHANGED
@@ -16,25 +16,27 @@ import { hostname as osHostname, tmpdir as osTmpdir } from "node:os";
16
16
  import { appendEvent } from "../engine/runlog.mjs";
17
17
  import { testAdequacyRows, testAdequacyFailures, testAdequacyTelemetry, adequacyCounts, regressionRan } from "./testadequacy.mjs";
18
18
  import { readSelfReview, compareSelfReview, firstReviewRecord, selfCheckFailures } from "./selfreview.mjs";
19
- import { codeForTerminalReason, OUTCOME_CODES, ENV_VALIDATE_TIMEOUT, ENV_VALIDATE_PLACEMENT, ENV_ENGINE_OWNED_CODES } from "../engine/outcome-codes.mjs";
19
+ import { codeForTerminalReason, parkedLabel, OUTCOME_CODES, ENV_VALIDATE_TIMEOUT, ENV_VALIDATE_PLACEMENT, ENV_ENGINE_OWNED_CODES } from "../engine/outcome-codes.mjs";
20
20
  import { ciPollDelayMs, ENGINE_VERSION, DEFAULT_MAX_SESSION_LIMIT_PAUSES, DEFAULT_SESSION_LIMIT_WAIT_MS, parseLeaseHolder, sanitizeLeaseHost } from "../engine.mjs";
21
21
  import { openDependency, laneMergedPrs, dependencyOnLane, isTrustedComment, decomposedSubissues, isDecomposedRecord, reopenRevokedDecomposition } from "../engine/phases.mjs";
22
22
  import { createHash, randomBytes } from "node:crypto";
23
23
  import { otherLaneOwner } from "./lanelock.mjs";
24
24
  import { stampText, checkStamp } from "./stagestamp.mjs";
25
25
  import { acquireBranchLock, waitPidsExit } from "./branchlock.mjs";
26
- import { parseRecurrenceConfig, recurrenceFacts, recursLinks, designLaneNote } from "./recurrence.mjs"; // #5751
27
- import { areaOf, acquireHotArea, countCounters } from "./hotarea.mjs"; // #5751
28
- import { isEnvValidateFailure, outputTail, contractRuleCounts, onlyTestPlanProblems, isTestPath, applyValidateRecipes, rewriteProjectDirCommand, deferChecklessPostDeploy, autoPostDeployE2e, applyRequirementDecisions, dedupeAddRequirements, loneE2eRows, reproEnvMiss, resolveForgedockPaths, resolvingIo, portableForgedockPaths, FORGEDOCK_CHECKS_VAR, FORGEDOCK_ENTRY_VAR, describesUnrunnableCommand, removedPathsOf, TRACKED, normalizeKindModes, blockingFailures, unverifiedRequirements, mutationTargets, mutationFailures, runMutationCheck, MUTATION_SURVIVED, isBugIssue, scopeText, explainFailures, inIssue, validateContract, snapQuotes, cliUsageError, normalizeRunnerCommand, applyAmendments, amendmentKindProblems, precheck, alreadyFixedOnBase, READONLY_PROD_RE, EXTERNAL_NEED_RE, intakeHostWork, repoTracks, dropScopeValidates, tagOutOfBand, parseReview, decide, mergeReviewRows, reaskable, criterionLines, closePlan, followupItems, renderPendingFollowups, bucketTally, pendingTracking, unnamedEdges, structureNote, impliedDocDeliverables, convertDelivered } from "./conformance.mjs";
29
- import { checkAdmission, hostParallelism, ADMISSION_RETRY_SECONDS } from "./admission.mjs";
26
+ import { parseRecurrenceConfig } from "./recurrence.mjs"; // #5751: hot-area locks only; recurrence design routing was cut (#6083)
27
+ import { areaOf, acquireHotArea } from "./hotarea.mjs"; // #5751
28
+ import { isEnvValidateFailure, outputTail, contractRuleCounts, onlyTestPlanProblems, isTestPath, applyValidateRecipes, rewriteProjectDirCommand, deferChecklessPostDeploy, autoPostDeployE2e, applyRequirementDecisions, dedupeAddRequirements, loneE2eRows, reproEnvMiss, resolveForgedockPaths, resolvingIo, portableForgedockPaths, FORGEDOCK_CHECKS_VAR, FORGEDOCK_ENTRY_VAR, describesUnrunnableCommand, removedPathsOf, TRACKED, normalizeKindModes, blockingFailures, splitAdvisory, unverifiedRequirements, mutationTargets, mutationFailures, runMutationCheck, MUTATION_SURVIVED, isBugIssue, scopeText, explainFailures, inIssue, validateContract, snapQuotes, cliUsageError, normalizeRunnerCommand, applyAmendments, precheck, alreadyFixedOnBase, READONLY_PROD_RE, EXTERNAL_NEED_RE, intakeHostWork, repoTracks, dropScopeValidates, tagOutOfBand, parseReview, decide, mergeReviewRows, reaskable, criterionLines, closePlan, followupItems, renderPendingFollowups, bucketTally, pendingTracking, unnamedEdges, structureNote, convertDelivered } from "./conformance.mjs";
29
+ import { checkAdmission, hostParallelism, quotaCores, ADMISSION_RETRY_SECONDS } from "./admission.mjs";
30
30
  import { namedPaths, isTrustedIssueComment, prodFailureSignal } from "./prefilter.mjs";
31
- import { writeStatus, postUpsert, isStatusPost, isUpsertPost, hasSection, clearPipelineLabels } from "./statuscomment.mjs";
31
+ import { writeStatus, postUpsert, postKeyed, isKeyedPost, isStatusPost, isUpsertPost, hasSection, clearPipelineLabels, IN_PLACE_MARKERS, commentId, contractKey } from "./statuscomment.mjs";
32
+ import { decidePost } from "./commentstate.mjs"; // #5979
33
+ import { repeatSignature, countIdentical, shouldPark, summaryComment } from "./failure-stop.mjs"; // #5979
32
34
  import { checksAt, mergeCheckEntries, CHECKS_FILE } from "./postdeploy-check.mjs";
33
35
  import { matchBaselines, baselineFailures, foldRegression } from "./baselines.mjs";
34
36
  import { readRollouts, detectNewOffKeys, rolloutModes, liveDeferralBlocks } from "./activation.mjs";
35
37
  import { toolMisses } from "./toolplace.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";
38
+ import { hasRecipe, installLaneTools, genericInstallCommands, RECIPES } from "../pool/lane-tools.mjs";
39
+ import { testRunnerProblems, hostOnlyProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract, declaredEnv, depInstallFailures, toolMissingInstalls, testRunSummary, projectBinDirs, withLocalBins, manifestDepOwner, collectOnlyCommand, collectImportMiss, contractCommands } from "./preflight.mjs";
38
40
  import { resolveLane, isDefaultLane, isShippedLane, DEFAULT_STAGING_BRANCH } from "./lane.mjs";
39
41
  import { splitGate, rationaleLine } from "./decompose.mjs";
40
42
  import { ceilingFor, modelInfo, restartDecision, DEFAULT_CEILING, WINDOW_SHARE, RESTART_COST_USD, CACHE_READ_USD, REAL_LIMIT_SHARE, predictRestart, handoffFacts, routeHandoff, buildReadsOf, NARROW_NOTE } from "./ceiling.mjs";
@@ -46,12 +48,13 @@ import { prepareToolchain } from "./toolchain.mjs";
46
48
  import { toolStats } from "./toolstats.mjs";
47
49
  import { readTestMap, readTestMapAtRef, selectCommands, mergeChecks, factsPath, TEST_MAP_FILE } from "./testmap.mjs";
48
50
  import { deriveCiPrecheck, ciPrecheckOutcome, parseCiPrecheckConfig } from "./ci-precheck.mjs";
49
- import { runChecks, runWithTimeoutRetry, splitPrecheckResults, timedOutDetail, planPrecheck, worktreeFingerprint, selfCheckState, quietFailure, CHECK_PLAN_FILE, SELF_CHECK_FILE, CHECK_LOG_DIR } from "./precheck.mjs";
51
+ import { runChecks, runWithTimeoutRetry, splitPrecheckResults, timedOutDetail, planPrecheck, worktreeFingerprint, selfCheckState, quietFailure, checkFailureTail, CHECK_PLAN_FILE, SELF_CHECK_FILE, CHECK_LOG_DIR } from "./precheck.mjs";
50
52
  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";
51
53
  import { renderInvestigation, renderImplementation, renderReview, renderPrBody, renderTrajectory, renderContract, renderAmendments, renderShadowReview, parseContractComment, parseAmendmentsComment, contractJson, capComment, sanitizeMd, MAX_COMMENT_CHARS, recoveryEvidence } from "./render.mjs";
52
54
  import { parseVerifierConfig, pickVerifierModel, changedSymbols, callersOf, verifierBudget, verifierPrompt, parseVerifierFindings, findingsToFailures, renderVerifierNote, VERIFIER_SYSTEM } from "./verifier.mjs";
53
55
  import { computeTrigger, riskPathHits, TRIGGER_MODES, pathDomains, parseEnforceDomains } from "./review-trigger.mjs";
54
56
  import { hostCapabilityBlock, contractHostNeeds } from "./execution.mjs";
57
+ import { envGapBlockCode, toolGapFailures, packageDirsMissingDeps, failureOutsideDiff } from "./envgap.mjs"; // #6106
55
58
 
56
59
  const MISSING_TOOL_RE = /command not found|not found in PATH|no such file or directory.*\b(?:docker|promtool)\b|\b(?:docker|promtool)\b[^\n]{0,80}(?:not (?:installed|found|available)|no such file|cannot connect|daemon)|cannot connect to the docker daemon|no docker daemon|no module named|ModuleNotFoundError|\bENOENT\b[^\n]{0,60}spawn/i;
57
60
  /** #4685: true when a builder's block summary names a missing tool or module (environment), not a credential. */
@@ -65,16 +68,14 @@ export function contractSelfCorrectable(problems) {
65
68
  export function missingToolBlock(summary) { return MISSING_TOOL_RE.test(String(summary ?? "")); }
66
69
  import { reserveForBuild, revalidate } from "./seqreserve.mjs";
67
70
  import { patchEcho, mutationsOf, runReproMutations, classifyRepro } from "./reproquality.mjs";
68
- 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";
71
+ import { CHECKS_CLI, FORGEDOCK_CLI, REVIEWER_SYSTEM, LEAN_DIR, RESULT_FILE, INVESTIGATION_FILE, IMPLEMENTATION_FILE, CONTRACT_FILE, builderPlanPrompt, builderImplementPrompt, contractCorrectionPrompt, conformanceResumePrompt, reviewerPrompt, investigationVerdict, decisionNote, reviewerRepairPrompt, REVIEW_DIFF_MAX_BYTES, blockCorrectionPrompt, HUMAN_BLOCK_REASONS, structurePrompt, hotspotPlanNote, hotspotBuildRule, reproPlanNote, unrunnableValidateNote, pagePlanNote, contextPackNote, buildOpeningNote, sequenceBuildRule, 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";
69
72
  import { postMergeCommands } from "./postmerge.mjs";
70
- import { classifyBaseRed, attribute as attributeBaseRed, runOnBase, reportBaseRed } from "./basered.mjs"; // #5239
73
+ import { reportParityGaps, classifyBaseRed, diffTouchesGuard, attribute as attributeBaseRed, runOnBase, reportBaseRed, recordBaseVerdict, bypassesGuard } from "./basered.mjs"; // #5239
71
74
  import { guardAfterMerge, withHistoryRows } from "./guards.mjs";
72
75
  import { parseProdParity, prodParityFailures as prodParityOf } from "./prodparity.mjs";
73
76
  import { routePathsFromFiles, routeReachabilityFailures } from "./routecheck.mjs";
74
- import { docsFailures } from "./docsgate.mjs";
75
77
  import { outcomeEvidenceFailures, rawChecksAt } from "./outcomeevidence.mjs";
76
- import { ciBudgetFailures, parseCiBudget } from "./ci-gate.mjs";
77
- import { pageFailures, designSpecApproved, designLabelApproved, specOnlyFailures, pageFiles, designOnlyFiles } from "./pagegate.mjs"; // #5428
78
+ import { pageFailures, designSpecApproved, designLabelApproved, pageFiles, designOnlyFiles } from "./pagegate.mjs"; // #5428
78
79
  import { changedRoutes, captureVisualCheck, publishToRef, visualMarkdown } from "./page-capture.mjs"; // #5770
79
80
  import { uiBuildRule, uiIssue, uiChanged } from "./ui-quality.mjs"; // #5330
80
81
  import { designGate, designGateNote, designFailures, specApproved as designSpecOk } from "./design-gate.mjs"; // #5330
@@ -123,8 +124,12 @@ import { makePostRun } from "./postrun.mjs";
123
124
  import { ensureSignedOff, salvageBranch, dropSalvageTracking } from "./signoff.mjs";
124
125
  import { reconcileCheckpoints } from "./checkpoint-reconcile.mjs";
125
126
  import { guardStagedDeletions, deletionEvidence, maxForeignDeletions } from "./delguard.mjs";
126
- import { createLedger, flattenPhases } from "./phaseledger.mjs";
127
- import { DEFAULT_CATALOG_SOURCES, deriveCatalog, mergeRecipes, rewriteMissed, isDriftFailure, rewriteSubprojectVenv } from "./validate-catalog.mjs";
127
+ import { createLedger, flattenPhases, overheadStats } from "./phaseledger.mjs";
128
+ import { DEFAULT_CATALOG_SOURCES, deriveCatalog, mergeRecipes, rewriteMissed, isDriftFailure, rewriteSubprojectVenv, deriveTestEnvMap, rewriteToCiEnv } from "./validate-catalog.mjs";
129
+ import { holderGone } from "./liveness.mjs";
130
+ import { runLaneAudit, buildStamp, forgeYamlHash } from "./lane-audit.mjs"; // #6076
131
+ import { makeGapAuditor, parseGapConfig } from "./lane-audit-gap.mjs"; // #6078
132
+ import { parseForgeYaml } from "../forge-utils.mjs";
128
133
  import { planStale, stackedBaseBlock, validStackedOn, cascadeDecision, invalidatedChecks } from "./stacking.mjs";
129
134
  import { runLightStep, runLightTests, lightBuildPrompt, upgradeNote, renderLiteReceipt } from "./lightlane.mjs";
130
135
 
@@ -160,6 +165,9 @@ export function builderFixable(failures) {
160
165
  const AUTH_RETRY_SECONDS = 900;
161
166
  /** #5762: retry-in for a `backend.cli_failed` deferral (transient, not an account condition). */
162
167
  const CLI_FAILED_RETRY_SECONDS = 120;
168
+ /** #6105: a builder session the API cut short (terminal_reason api_error and kin) is resumed by id after these backoffs; past them the lane defers (backend.cli_failed), never the breaker. */
169
+ export const API_RESUME_BACKOFF_MS = Object.freeze([20_000, 60_000, 180_000]);
170
+ const API_RESUME_PROMPT = "Your previous turn was cut off by a transient API error (not by anything you did). Nothing you committed or wrote in the worktree was lost. Continue the task exactly where you left off; do not start over and do not redo finished work.";
163
171
  /** #5762: the account number (digits only) a lane used: the rotator's capture, else TOKENBATON_ACCOUNT / CLAUDE_CONFIG_DIR `.claude-<n>`; null when unknown. */
164
172
  export function laneAccountNumber(env = process.env, account = null) {
165
173
  if (account != null && /^\d+$/.test(String(account))) return String(account);
@@ -192,7 +200,7 @@ const SHADOW_BLOCKS = [OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, OUTCOME_CODES.CO
192
200
  * not done, an invalid amendment) or conformance.regression, the same codes a review blocks on, and unexempted growth of an
193
201
  * over-threshold file (maintenance.hotspot_growth, forge#4195). Scope creep stays recorded-only.
194
202
  */
195
- const SHADOW_PRE_BLOCKS = [...SHADOW_BLOCKS, OUTCOME_CODES.MAINTENANCE_HOTSPOT_GROWTH, OUTCOME_CODES.MAINTENANCE_COUNTER_GROWTH, OUTCOME_CODES.RECURRENCE_DESIGN_MISSING]; // #5751
203
+ const SHADOW_PRE_BLOCKS = [...SHADOW_BLOCKS];
196
204
  /** #4395: cap on the engine.lane_instructions file; a larger one is not slim and falls back to CLAUDE.md. */
197
205
  export const LANE_INSTRUCTIONS_MAX_BYTES = 16384;
198
206
  /** 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. */
@@ -267,7 +275,7 @@ export function classifyBlock(result, issue) {
267
275
  if (b.kind === "human") {
268
276
  const remainder = (Array.isArray(b.remainder) ? b.remainder : []).filter((x) => x && typeof x.title === "string" && x.title.trim() && typeof x.body === "string").slice(0, MAX_SUBISSUES).map((x) => ({ title: x.title.trim(), body: x.body })); // #4730
269
277
  if (b.why === "product-decision" && describesUnrunnableCommand(`${result?.summary ?? ""} ${b.reason ?? ""} ${b.detail ?? ""}`)) { // #4857
270
- return { kind: "untyped", problem: "an unrunnable validate command is an environment defect, never a product-decision: run an equivalent through the repo's toolchain and record it as a substitute-validate amendment" };
278
+ return { kind: "untyped", problem: "an unrunnable validate command is an environment defect, never a product-decision: run an equivalent through the repo's toolchain and record the equivalent command in the contract only if it was probed at freeze" };
271
279
  }
272
280
  return HUMAN_BLOCK_REASONS.includes(b.why) ? { kind: "human", why: b.why, ...(remainder.length ? { remainder } : {}) }
273
281
  : { kind: "untyped", problem: `"${String(b.why ?? "").slice(0, 80)}" is not a human-only reason (${HUMAN_BLOCK_REASONS.join(", ")})` };
@@ -460,7 +468,11 @@ export async function runCore(o) {
460
468
  usage.input += u.input_tokens ?? 0; usage.output += u.output_tokens ?? 0;
461
469
  usage.cache += (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0);
462
470
  }
471
+ let iss; // the issue as read at intake; declared early so the comment helpers below can see it
472
+ const localPosts = []; // #5979: comments this lane created, so a second post in the same run sees them
473
+ const allComments = () => [...(iss?.comments ?? []), ...localPosts];
463
474
  let statusCache = null; // #5592: {id, sections} of this issue's one FORGE:STATUS comment, edited in place
475
+ let postContractHash = null; // #5931: the frozen contract hash once known; in-place comments are keyed to it
464
476
  const post = async (marker, body, on = issue) => {
465
477
  if (on === issue && isStatusPost(marker)) { // machine-state markers: a section of the one status comment, not a comment of their own
466
478
  try {
@@ -474,9 +486,25 @@ export async function runCore(o) {
474
486
  if (on === issue && isUpsertPost(marker)) { // one comment edited in place across requeues (the marker still leads the body)
475
487
  return postUpsert({ gh: ghw, repo, issue: on, markers: marker, body, comments: iss?.comments, cap: capComment });
476
488
  }
489
+ if (on === issue && isKeyedPost(marker) && !(postContractHash && IN_PLACE_MARKERS.includes(Array.isArray(marker) ? marker[0] : marker))) { // #5986: one comment per (kind, content hash) with a repeat counter; at 12 engine comments edit in place only
490
+ return postKeyed({ gh: ghw, repo, issue: on, marker: Array.isArray(marker) ? marker[0] : marker, body, cap: capComment });
491
+ }
477
492
  const marks = (Array.isArray(marker) ? marker : [marker]).map((m) => `<!-- ${m} -->`).join("\n");
478
- const out = String(await ghw(["issue", "comment", String(on), "-R", repo, "--body", capComment(`${marks}\n${body}`)])).trim();
479
- return /https?:\/\/\S+/.exec(out)?.[0] ?? null;
493
+ const first = Array.isArray(marker) ? marker[0] : marker;
494
+ const keyed = on === issue && !!postContractHash && IN_PLACE_MARKERS.includes(first);
495
+ const full = capComment(`${marks}\n${body}${keyed ? `\n${contractKey(postContractHash)}` : ""}`);
496
+ if (on === issue && IN_PLACE_MARKERS.includes(first)) { // #5979: re-post only on a state change; FACTS and DEPENDENCY are edited in place; #5931: all of them per contract hash once frozen
497
+ const d = decidePost({ marker: first, body: full, contractHash: keyed ? postContractHash : null, comments: allComments(), trusted: (c) => c?.__mine === true || isTrustedIssueComment(c) });
498
+ if (d.action === "skip") return d.prior.url ?? null;
499
+ const id = d.action === "patch" ? commentId(d.prior) : null;
500
+ if (id) {
501
+ try { await ghw(["api", "-X", "PATCH", `repos/${repo}/issues/comments/${id}`, "-f", `body=${full}`]); d.prior.body = full; return d.prior.url ?? null; } catch { /* deleted or not ours: a new comment */ }
502
+ }
503
+ }
504
+ const out = String(await ghw(["issue", "comment", String(on), "-R", repo, "--body", full])).trim();
505
+ const url = /https?:\/\/\S+/.exec(out)?.[0] ?? null;
506
+ if (on === issue) localPosts.push({ body: full, url, __mine: true });
507
+ return url;
480
508
  };
481
509
  /** Best effort; `true` when the transition succeeded (#4337: the decomposed close needs to know). */
482
510
  const label = async (state) => { try { await retrying(() => io.transitionLabel(issue, state), { transient: GH_TRANSIENT_RE, attempts: 4, sleep: sleepFn, random }); return true; } catch { /* labels are best effort */ return false; } };
@@ -495,10 +523,12 @@ export async function runCore(o) {
495
523
  if (!h || !Number.isSafeInteger(pid) || pid <= 0 || sanitizeLeaseHost(h) !== sanitizeLeaseHost(myHost)) return false;
496
524
  try { (o.killFn ?? process.kill.bind(process))(pid, 0); return false; } catch (e) { return e?.code === "ESRCH"; }
497
525
  };
526
+ // #5991: a lease of a batch that no longer owns the issue (a sandbox holder is pid 1 on another host) is taken over at once
527
+ const gone = (l) => holderDead(l) || holderGone(l, { liveBatches: typeof o.liveBatches === "function" ? (() => { try { const ids = o.liveBatches(issue); return Array.isArray(ids) ? [...ids, o.batchId] : null; } catch { return null; } })() : null });
498
528
  const leaseTtlMs = o.leaseTtlMs ?? 25 * 60000; // below the projector's 30 min honour cap
499
529
  let leaseState = null, leaseTimer = null;
500
530
  const writeLease = (lease, extra = {}) => io.projector.writeState(issue, { ...leaseState, ...extra, lease });
501
- const renew = async () => { if (io.projector && leaseState && !finishing) { /* never re-take a lease a finish (or signal) released */ try { await writeLease(leaseObj()); } catch { /* best effort */ } } };
531
+ const renew = async () => { if (io.projector && leaseState && !finishing) { /* never re-take a lease a finish (or signal) released */ try { if (o.batchId && io.projector.readState && (await io.projector.readState(issue))?.suspend) return; /* #6008: the dispatcher's suspend marker stays; the lease is not renewed under it */ await writeLease(leaseObj()); } catch { /* best effort */ } } };
502
532
  async function releaseLease(reason, code = null, mergedTo = null) {
503
533
  if (leaseTimer) { clearInterval(leaseTimer); leaseTimer = null; }
504
534
  if (!io.projector || !leaseState) return;
@@ -584,15 +614,16 @@ export async function runCore(o) {
584
614
  }
585
615
  let sparse = null; // #4221: {excluded, maxKb} when the lane worktree is a sparse checkout; null leaves prompts unchanged
586
616
  // #4395: lane profile. full (FORGEDOCK_FULL_SESSION=1): unchanged sessions; memory-off: no auto-memory; lane: also no CLAUDE.md, the lane file appended
617
+ let laneApiResumes = 0; // #6105: builder sessions resumed after a transient API termination (RUN_TERMINAL api_resumes)
587
618
  let laneProfile = { name: process.env.FORGEDOCK_FULL_SESSION === "1" ? "full" : "memory-off", text: null };
588
619
  let toolchain = null; // #4163: {env, summary} when the repo pins its toolchain (env only with a pm shim); null leaves runner env and prompts unchanged
589
620
  // #4169: heavy steps take a host semaphore slot (io.heavy); LLM phases are not gated. `heavyEnv` puts the heavy shims on
590
621
  // the runner PATH; `waits` ({phase: ms}) and `heavyQueueMax` ride on the lane result for the batch report.
591
622
  const heavyCfg = o.heavy ?? {}, heavyOn = Boolean(io.heavy) && heavyCfg.enabled !== false;
592
- let heavyEnv = null, heavyWaitsFile = null, heavyQueueMax = 0, stage = "plan", iss;
623
+ let heavyEnv = null, heavyWaitsFile = null, heavyQueueMax = 0, stage = "plan";
593
624
  let seqBuildNote = ""; // #5235: numbers reserved for this lane at build start (prompt paragraph)
594
625
  const recCfg = parseRecurrenceConfig(o.recurrenceConfig); // #5751: forge.yaml recurrence: (absent: mode on, threshold 2, no hot areas or counters)
595
- let recurrence = null, hotLock = null; // #5751: the recurrence detection; the hot-area locks held until teardown
626
+ let hotLock = null; // #5751: the hot-area locks held until teardown
596
627
  let seqLease = null; // #4386: the host sequence lease, held from the merge-gate renumber through the merge
597
628
  const waits = {};
598
629
  const followupsFiled = []; // #5078: {issue, class, count} per tracking issue this lane filed into, for the batch report
@@ -748,8 +779,9 @@ export async function runCore(o) {
748
779
  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
749
780
  ...(extra.pr ? { pr: extra.pr } : {}), ...(milestone ? { milestone } : {}), ...(verifiedLane != null ? { verified: verifiedLane } : {}),
750
781
  ...(reproQ ? { repro_quality: reproQ } : {}), conformance_mode: conformance === "enforce" || riskEnforced ? "enforce" : "shadow", ...(shadowWould ? { shadow_would: shadowWould } : {}), ...(firstReview ? { first_review: firstReview } : {}), ...(adequacyTel ?? {}),
751
- ...(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() } : {}),
782
+ ...(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 } : {}), ...(laneApiResumes ? { api_resumes: laneApiResumes } : {}), ...(tb.record() ? { turns: tb.record() } : {}),
752
783
  ...(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
784
+ Object.assign(term, overheadStats(null, term.wall_ms, term.model_ms)); // fixed_overhead_ms + model_share for the SLO
753
785
  const phases = phaseLedger.snapshot(); // #4908: run log gets the nested ledger, FORGE:TELEMETRY the flattened scalars
754
786
  ev({ ...term, phases });
755
787
  await emit({ ...term, ...flattenPhases(phases) });
@@ -759,10 +791,17 @@ export async function runCore(o) {
759
791
  // either launches the next attempt or relabels in settle.
760
792
  if (recoverUnlabelled && recover.final && (reason === "ci-pending" || reason === "budget-exceeded")) { // #4505: budget-exceeded too
761
793
  try {
762
- await post("FORGE:NEEDS_HUMAN", `## Needs human\n${laneRecoveryEvidence(reason, code, detail)}\n\n_${usageLine()}_`);
794
+ await post("FORGE:NEEDS_HUMAN", `## Needs human\n${laneRecoveryEvidence(reason, code, detail)}\n\nsig=${repeatSignature(code, detail)}\n\n_${usageLine()}_`);
763
795
  await ghc(["issue", "edit", String(issue), "-R", repo, "--add-label", "needs-human"]);
764
796
  } catch { /* best effort */ }
765
797
  }
798
+ if (reason === "needs-human" || reason === "engine-error" || (recoverUnlabelled && recover.final && (reason === "ci-pending" || reason === "budget-exceeded"))) { // #6076: one version-stamped FORGE:LANE_AUDIT at the unhappy terminals; never changes how the lane ends
799
+ try {
800
+ let gapCfg; try { gapCfg = parseGapConfig(parseForgeYaml(readFileSync(join(o.cwd ?? wt, "forge.yaml"), "utf8"))); } catch { gapCfg = parseGapConfig({}); }
801
+ await runLaneAudit({ gap: makeGapAuditor({ gh: ghc, cfg: gapCfg, repo }), issue, reason, code, detail, comments: allComments(), trusted: (c) => c?.__mine === true || isTrustedIssueComment(c), phases: phaseLedger.snapshot(), post: (m, b) => post(m, b),
802
+ stamp: buildStamp({ engineVersion: ENGINE_VERSION, forgeYamlHash: forgeYamlHash(o.cwd ?? wt), batchId: o.batchId ?? null, attempt: recover?.attempt ?? o.attempt ?? 1 }) });
803
+ } catch { /* the audit is best effort */ }
804
+ }
766
805
  if (["needs-human", "engine-error", "dependency-open", "dependency-blocked", "dependency-unreadable", "decomposed", "host-task"].includes(reason)) {
767
806
  const wf = ["investigating", "building", "in-review"].map((x) => `workflow:${x}`).join(",");
768
807
  try { await ghc(["issue", "edit", String(issue), "-R", repo, "--remove-label", wf]); } catch { /* best effort */ }
@@ -780,7 +819,7 @@ export async function runCore(o) {
780
819
  if (deferTail) postRun.add("teardown", () => teardown(reason, extra)); // last: the structure delta and guard read the worktree
781
820
  if (reason === "merged" || reason === "invalid") await clearPipelineLabels({ gh: ghc, repo, issue, onFail: (n, e) => T.anomalies.push(`pipeline labels not cleared${n.length ? `: ${n.join(", ")}` : ""} (${String(e?.message ?? e).slice(0, 120)})`) }); // #5592/#5759: a merged or closed issue keeps no needs-human / parked:* / remediation-queue
782
821
  await releaseLease(reason, code, extra.mergedTo ?? null);
783
- done = { terminalReason: reason, detail, branch, worktree: wt, ...(cascadeLog.kinds.length ? { cascade: cascadeLog.kinds[cascadeLog.kinds.length - 1], cascades: [...cascadeLog.kinds], cascade_cost_usd: Math.round(cascadeLog.costUsd * 1e6) / 1e6, cascade_minutes: Math.round(cascadeLog.ms / 6000) / 10 } : {}), cost_usd: usage.cost_usd, tokens: { input: usage.input, output: usage.output, cache: usage.cache }, wall_ms: now() - t0, model_ms: modelMs, phases: phaseLedger.snapshot(),
822
+ done = { terminalReason: reason, detail, branch, worktree: wt, engineVersion: ENGINE_VERSION, ...(postContractHash ? { contractHash: postContractHash } : {}), ...(cascadeLog.kinds.length ? { cascade: cascadeLog.kinds[cascadeLog.kinds.length - 1], cascades: [...cascadeLog.kinds], cascade_cost_usd: Math.round(cascadeLog.costUsd * 1e6) / 1e6, cascade_minutes: Math.round(cascadeLog.ms / 6000) / 10 } : {}), cost_usd: usage.cost_usd, tokens: { input: usage.input, output: usage.output, cache: usage.cache }, wall_ms: now() - t0, model_ms: modelMs, phases: phaseLedger.snapshot(),
784
823
  ...(laneHead && reason !== "merged" ? { laneHead: { ...laneHead } } : {}), light, ...(lightVerdict ? { light_eligibility: lightVerdict } : {}), ...(lightUpgrade ? { light_upgrade: lightUpgrade } : {}), // #4453
785
824
  ...(Object.keys(waits).length ? { waits: { ...waits } } : {}), ...(followupsFiled.length ? { followups: followupsFiled.map((f) => ({ ...f })) } : {}), ...(pendingRecord().length ? { pendingFollowups: pendingRecord() } : {}), ...(heavyQueueMax ? { heavyQueueMax } : {}), ...(precheckRan ? { precheckMs, precheckDeferred } : {}),
786
825
  ...(firstPassOf(builderTriggers) != null ? { firstPass: firstPassOf(builderTriggers) } : {}), ...(tb.record() ? { turns: tb.record() } : {}), context: { ...ctxStats, cost_usd: impl.cost }, // #4392, #5829
@@ -836,8 +875,18 @@ export async function runCore(o) {
836
875
  if (reg.existing && (!recover || recover.final) && await duplicateAskIssue(reg.existing, [why, askText])) return finish("invalid", `only content is the owner ask of #${reg.existing}; closed as a duplicate`); // #4730
837
876
  link = reg.existing ? `Same owner ask as #${reg.existing} (one ask, linked): answering it unblocks this issue too.` : reg.entry ?? "";
838
877
  }
878
+ // #5979: the second identical failure (same code and normalised detail as an earlier NEEDS_HUMAN/PARKED of this issue) parks with one summary, no recovery
879
+ const sig = repeatSignature(code, why);
880
+ const stoppable = code !== OUTCOME_CODES.BUILDER_BLOCKED && code !== OUTCOME_CODES.FAILURE_REPEATED && !ENV_ENGINE_OWNED_CODES.includes(code);
881
+ const identical = stoppable ? countIdentical(allComments(), sig, (c) => c?.__mine === true || isTrustedIssueComment(c)) + 1 : 1;
882
+ if (shouldPark(identical)) {
883
+ try { await post("FORGE:PARKED", summaryComment({ attempts: identical, code, detail: why, sig })); } catch (e) { labelFailed("comment", e); }
884
+ try { await ghc(["issue", "edit", String(issue), "-R", repo, "--add-label", "needs-human", "--add-label", parkedLabel(OUTCOME_CODES.FAILURE_REPEATED)]); } catch (e) { labelFailed("label", e); }
885
+ T.decisions.push(`Identical failure ${code} (${sig}) seen ${identical}x: parked as ${OUTCOME_CODES.FAILURE_REPEATED}, not relaunched`);
886
+ return finish("needs-human", why, { code: OUTCOME_CODES.FAILURE_REPEATED, ...extra, ...(recover ? { recovery: true } : {}) }, OUTCOME_CODES.FAILURE_REPEATED);
887
+ }
839
888
  const notes = [premiseAnnotation(predicate), closedEdgeNote(closedDeps), link, askNote].filter(Boolean).join("\n");
840
- try { await post("FORGE:NEEDS_HUMAN", `## Needs human\n${why}${notes ? `\n\n${notes}` : ""}${recoverUnlabelled ? `\n\n${laneRecoveryEvidence("needs-human", code, "")}` : ""}\n\n_${usageLine()}_`); }
889
+ try { await post("FORGE:NEEDS_HUMAN", `## Needs human\n${why}${notes ? `\n\n${notes}` : ""}${recoverUnlabelled ? `\n\n${laneRecoveryEvidence("needs-human", code, "")}` : ""}\n\nsig=${sig}\n\n_${usageLine()}_`); }
841
890
  catch (e) { labelFailed("comment", e); }
842
891
  // #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
843
892
  if (!(!recover && ENV_ENGINE_OWNED_CODES.includes(code))) {
@@ -933,7 +982,7 @@ export async function runCore(o) {
933
982
  const set = String(process.env.FORGE_HOST_PARALLELISM ?? "").trim();
934
983
  if (/^\d+$/.test(set) && Number(set) > 0) return set;
935
984
  if (!io.host?.cores) return null;
936
- try { return String(hostParallelism({ cores: io.host.cores(), lanes: io.host.activeLanes?.() })); } catch { return null; }
985
+ try { return String(hostParallelism({ cores: quotaCores({ cores: io.host.cores(), read: (f) => readFileSync(f, "utf8"), env: process.env }), lanes: io.host.activeLanes?.() })); } catch { return null; }
937
986
  }
938
987
  /**
939
988
  * #4325: the lane env every engine-run command shares with the builder: shared package-manager stores (#4220), the run
@@ -1043,9 +1092,23 @@ export async function runCore(o) {
1043
1092
  } else if (r.state === "foreign" || r.state === "error") ev({ event: "CHECKPOINT_RECONCILE_SKIPPED", state: r.state, ...(r.commits ? { commits: r.commits.length } : {}), ...(r.error ? { error: r.error } : {}) });
1044
1093
  return r;
1045
1094
  };
1095
+ /** #6008: a batch-dispatched lane re-reads its FORGE:STATE before it pushes or merges. No current lease of its batch, or a dispatcher hold/pause marker (`suspend`), suspends it (deferred, sandbox kept for adopt). Lanes without a batch (run-issue, tests) are not guarded. */
1096
+ const suspensionGuard = async (what) => {
1097
+ if (!o.batchId || !io.projector?.readState || !leaseState) return;
1098
+ let st = null;
1099
+ try { st = await io.projector.readState(issue); } catch { return; /* unreadable: fail open like admission */ }
1100
+ if (!st) return; // no FORGE:STATE readable at all: unknown, fail open
1101
+ const l = st?.lease, mine = l && (l.by === agentId || l.batch === o.batchId);
1102
+ const why = st?.suspend ? `the issue is ${st.suspend.reason ?? "held"} by the dispatcher (${st.suspend.batch ?? "batch"})`
1103
+ : !l ? "no dispatcher lease is current" : l.until <= now() ? "the dispatcher lease expired" : !mine && !gone(l) ? `the lease belongs to ${l.batch ?? l.by}, not batch ${o.batchId}` : null;
1104
+ if (!why) return;
1105
+ ev({ event: "LANE_SUSPENDED", what, reason: why });
1106
+ throw Object.assign(new Error(`refusing to ${what}: ${why}`), { deferCode: "lane.suspended", deferDetail: `suspended before ${what}: ${why}; the sandbox is kept for adopt` });
1107
+ };
1046
1108
  const gitPush = async (args) => {
1047
1109
  if (deletionRefusal && !args.includes("--delete")) throw Object.assign(new Error(deletionRefusal), { engineCode: OUTCOME_CODES.ENGINE_ERROR }); // #5819
1048
1110
  await assertConfined(`git ${args.join(" ").slice(0, 80)}`); // #5825
1111
+ if (!args.includes("--delete")) await suspensionGuard("push"); // #6008
1049
1112
  if (!args.includes("--delete")) { await untrackToolState({ git, base, ev, keep: await keepPaths() });
1050
1113
  await reconcileLaneBranch();
1051
1114
  try { await signOffUnpushed(); }
@@ -1172,7 +1235,7 @@ export async function runCore(o) {
1172
1235
  let planSession = null;
1173
1236
  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 ?? "" }; };
1174
1237
  async function builder(n, prompt, resume, live = false, restart = implementRestart, opts = {}) {
1175
- let timeoutRetries = 0, contextRestarts = 0, p = prompt;
1238
+ let timeoutRetries = 0, contextRestarts = 0, apiResumes = 0, p = prompt;
1176
1239
  opts = { ...opts };
1177
1240
  const ceiled = laneCeiling > 0 && !opts.noCeiling && !UNCEILED.includes(opts.trigger); // #5346: per-size ceiling; noCeiling = a restart is certain
1178
1241
  for (;;) {
@@ -1192,6 +1255,20 @@ export async function runCore(o) {
1192
1255
  await attempt("implement", n, { usage: e.usage ?? null, turns: e.turns ?? null, tools: toolStats(e.toolUses), costUsd: null, model: opts.model ?? builderModel ?? null }, opts.mode, opts.trigger, opts.restartOf);
1193
1256
  return await budgetWrapup(n, opts);
1194
1257
  }
1258
+ if (e?.apiError === true) { // #6105: the API ended the session after real work: resume the same session (worktree and commits kept) with backoff, never relaunch the lane
1259
+ const sid = e.cliSessionId ?? null;
1260
+ if (!sid || apiResumes >= API_RESUME_BACKOFF_MS.length) {
1261
+ ev({ event: "API_ERROR_RESUME_EXHAUSTED", session_id: sid, terminal_reason: e.cliTerminalReason ?? null, resumes: apiResumes, trigger: opts.trigger ?? null });
1262
+ T.anomalies.push(`builder session ended ${e.cliTerminalReason ?? "api_error"} ${sid ? `after ${apiResumes} resume(s)` : "with no session id to resume"}: lane deferred`);
1263
+ throw Object.assign(cliFailedDeferral(e), { deferDetail: `builder session ended ${e.cliTerminalReason ?? "api_error"} (transient API error) ${sid ? `and ${apiResumes} resume(s) of ${sid} failed` : "with no session id to resume"}; the branch keeps its commits; retried shortly${cliDetail(e)}` });
1264
+ }
1265
+ const waitMs = API_RESUME_BACKOFF_MS[apiResumes++]; laneApiResumes++;
1266
+ ev({ event: "API_ERROR_RESUME", session_id: sid, terminal_reason: e.cliTerminalReason ?? null, attempt: apiResumes, wait_ms: waitMs, trigger: opts.trigger ?? null });
1267
+ T.decisions.push(`Builder session ${sid} ended ${e.cliTerminalReason ?? "api_error"}: resuming the same session after ${Math.round(waitMs / 1000)}s (resume ${apiResumes}/${API_RESUME_BACKOFF_MS.length}), no relaunch`);
1268
+ await renew(); await sleep(waitMs); await renew();
1269
+ p = API_RESUME_PROMPT; resume = sid; opts.restartOf ??= opts.trigger ?? null; opts.trigger = "api_error_resume";
1270
+ continue;
1271
+ }
1195
1272
  if (e?.code === "CLI_CONTEXT") {
1196
1273
  contextRestarts++; ctxStats.restarts++;
1197
1274
  ev({ event: "CONTEXT_CEILING", context_tokens: e.context ?? null, ceiling: e.contextMax ?? laneCeiling, real_limit: Boolean(continued), turns: e.turns ?? null, trigger: opts.trigger ?? null, restart: contextRestarts, last_tool: e.lastTool?.name ?? null });
@@ -1434,6 +1511,10 @@ export async function runCore(o) {
1434
1511
  // #4685: a tool the sandbox lacks (docker, promtool, a Python module) is an environment gap the host recovers, never a credential.
1435
1512
  return await needsHuman(`Remote sandbox lacks a validate tool (Builder is blocked (credentials)): ${s}\n\nNot a credential: the lane is recovered where the tool exists.`, OUTCOME_CODES.ENV_TOOL_MISSING);
1436
1513
  }
1514
+ if (b.kind === "human") { // #6106: a missing tool/interpreter/recipe/package/sandbox capability is an env gap that recovers, whatever reason the builder typed; genuine human reasons stay human
1515
+ const envCode = envGapBlockCode(b.why, s);
1516
+ if (envCode) { T.decisions.push(`Builder block (${b.why}) reclassified to ${envCode}: it names an environment gap, not a human decision`); return await needsHuman(`Environment gap, not a human decision (Builder reported blocked (${b.why})): ${s}\n\nThe lane is recovered where the tool, interpreter or capability exists.`, envCode); }
1517
+ }
1437
1518
  if (b.kind === "human") {
1438
1519
  // #4730: the agent-doable remainder is re-queued as its own lane; only the owner step keeps needs-human.
1439
1520
  let note = "";
@@ -1548,7 +1629,7 @@ export async function runCore(o) {
1548
1629
  if (io.projector) {
1549
1630
  let st = null;
1550
1631
  try { st = await io.projector.readState(issue); } catch { /* unreadable: proceed */ }
1551
- if (st?.lease && st.lease.until > now() && st.lease.by !== agentId && holderDead(st.lease)) {
1632
+ if (st?.lease && st.lease.until > now() && st.lease.by !== agentId && gone(st.lease)) {
1552
1633
  ev({ event: "LEASE_TAKEOVER", from: st.lease.by, host: st.lease.host ?? null, pid: st.lease.pid ?? null });
1553
1634
  onProgress({ event: "lease_takeover", detail: `taking over the lease of dead holder ${st.lease.by} (pid ${st.lease.pid ?? "?"} gone)` });
1554
1635
  } else if (st?.lease && st.lease.until > now() && st.lease.by !== agentId) {
@@ -1583,7 +1664,7 @@ export async function runCore(o) {
1583
1664
  ev({ event: "RUN_START", run: `core_${issue}_${t0}`, issue, lane, path: "core", version: ENGINE_VERSION, forge_version: ENGINE_VERSION, repo });
1584
1665
  await emit({ event: "RUN_START", run: `core_${issue}_${t0}`, lane, path: "core" }); // #4630: lifecycle event stream
1585
1666
  try {
1586
- iss = JSON.parse(await ghc(["issue", "view", String(issue), "-R", repo, "--json", "number,title,body,state,comments,labels,updatedAt"]));
1667
+ iss = JSON.parse(await ghc(["issue", "view", String(issue), "-R", repo, "--json", "number,title,body,state,comments,labels,updatedAt,createdAt"]));
1587
1668
  } catch (e) {
1588
1669
  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
1589
1670
  return finish("engine-error", `cannot read issue: ${e.message}`);
@@ -2032,7 +2113,7 @@ export async function runCore(o) {
2032
2113
  /** #4188: the builder reads the live issue, so quotes are checked against the current text, not the RUN_START snapshot. Best effort. */
2033
2114
  async function refreshIssue(stage) {
2034
2115
  let next;
2035
- try { next = JSON.parse(String(await ghc(["issue", "view", String(issue), "-R", repo, "--json", "number,title,body,state,comments,labels,updatedAt"]))); } catch { return; }
2116
+ try { next = JSON.parse(String(await ghc(["issue", "view", String(issue), "-R", repo, "--json", "number,title,body,state,comments,labels,updatedAt,createdAt"]))); } catch { return; }
2036
2117
  if (!next || typeof next !== "object") return;
2037
2118
  const tc = trustedOf(next), text = textOf(next, tc);
2038
2119
  if (contractHash(issueText) === contractHash(text)) return;
@@ -2143,6 +2224,11 @@ export async function runCore(o) {
2143
2224
  const vr = rewriteSubprojectVenv(r.contract, freezeTracked, (rel) => existsSync(join(wt, rel))); // #5683
2144
2225
  r.contract = vr.contract;
2145
2226
  for (const x of vr.applied) T.decisions.push(`sub-project venv rewrite of ${x.id}: \`${x.from}\` -> \`${x.to}\``);
2227
+ // #5753: a pytest path CI runs in another env (working-directory + poetry/uv run) runs there, not under a bare interpreter
2228
+ const ciTexts = (validateCatalogSources ?? DEFAULT_CATALOG_SOURCES).map((p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } });
2229
+ const ce = rewriteToCiEnv(r.contract, deriveTestEnvMap(ciTexts), freezeTracked, (rel) => existsSync(join(wt, rel)));
2230
+ r.contract = ce.contract;
2231
+ for (const x of ce.applied) T.decisions.push(`CI test-env rewrite of ${x.id}: \`${x.from}\` -> \`${x.to}\``);
2146
2232
  r.contract = foldRegression(r.contract); // #5448: the blast-radius regression set runs as validate G# entries
2147
2233
  const e = autoPostDeployE2e(r.contract); // #5468: production-only e2e/manual rows become post-deploy with a generated check
2148
2234
  for (const x of e.converted) { if (x.check) genChecks[x.check] = x.entry; T.decisions.push(`Production-only e2e/manual requirement ${x.id} frozen as post-deploy with ${x.check ? `generated check ${x.check}` : "no check (production observation window)"}`); }
@@ -2174,6 +2260,17 @@ export async function runCore(o) {
2174
2260
  for (const v of Array.isArray(contract.validate) ? contract.validate : []) {
2175
2261
  if (v?.id && typeof v.command === "string") for (const name of unsetEnvVars(v.command, fullEnv)) misses.push({ ids: [v.id], tool: name, kind: "env-var", source: "env" });
2176
2262
  }
2263
+ if (io.preflightRun) { // #5753: one collect-only run per pytest command imports its test modules before a builder is spent
2264
+ const done = new Set(misses.flatMap((m) => m.ids)), repoHas = repoTracks(files);
2265
+ for (const v of contractCommands(contract)) {
2266
+ const cmd = done.has(v.id) ? null : collectOnlyCommand(v.command);
2267
+ if (!cmd) continue;
2268
+ let r;
2269
+ try { r = await heavyStep("precheck", () => io.preflightRun({ command: cmd, timeoutMs: 60000, env, cwd: wt })); } catch (e) { r = { rc: 127, output: String(e?.message ?? e) }; }
2270
+ const miss = collectImportMiss(r, { repoHas });
2271
+ if (miss) misses.push({ ids: [v.id], ...miss, source: "collect" });
2272
+ }
2273
+ }
2177
2274
  if (io.preflightRun) {
2178
2275
  const skipIds = [...new Set(misses.flatMap((m) => m.ids))];
2179
2276
  const run = (a) => heavyStep("precheck", () => io.preflightRun({ ...a, cwd: wt }));
@@ -2192,19 +2289,20 @@ export async function runCore(o) {
2192
2289
  let out = "";
2193
2290
  try { out = String(await ghc(["api", "--paginate", `repos/${repo}/issues/${issue}/comments`, "--jq", ".[] | {body, author_association, user: {type: .user.type, login: .user.login}}"])); } catch { return null; }
2194
2291
  let found = null;
2195
- const amendLog = []; // #4899: trusted FORGE:AMENDMENT payloads in order, bound to a contract hash
2292
+ const amendLog = [], rewritePosted = []; // #4899: trusted FORGE:AMENDMENT payloads in order, bound to a contract hash
2196
2293
  for (const l of out.split("\n")) {
2197
2294
  let c; try { c = JSON.parse(l); } catch { continue; }
2198
2295
  if (!isTrustedComment(c)) continue;
2199
2296
  const b = String(c?.body ?? "");
2200
2297
  const am = parseAmendmentsComment(b);
2201
2298
  if (am) amendLog.push(am);
2299
+ if (b.includes("rewrite-validate")) rewritePosted.push(b); // #5920: audit comments already posted
2202
2300
  if (!b.startsWith("<!-- FORGE:CONTRACT -->")) { if (found && b.trim() && !b.trimStart().startsWith("<!-- FORGE:")) found.humanAfter = true; continue; }
2203
2301
  const fc = parseContractComment(b);
2204
2302
  if (fc && contractHash(fc.text) === fc.hash) found = { ...fc, humanAfter: false };
2205
2303
  }
2206
2304
  if (found) {
2207
- const seen = new Set(); found.amendments = [];
2305
+ const seen = new Set(); found.amendments = []; found.rewritePosted = rewritePosted;
2208
2306
  for (const st of amendLog) if (st.contract === found.hash) for (const a of st.amendments) { const k = JSON.stringify(a); if (!seen.has(k)) { seen.add(k); found.amendments.push(a); } }
2209
2307
  }
2210
2308
  return found;
@@ -2269,13 +2367,6 @@ export async function runCore(o) {
2269
2367
  let frozen = null, hash = null, planned = false, files = [], split = null, planMisses = null; // planMisses (#5331): validate preflight misses from this run
2270
2368
  /** #5804: paths that place the change: the issue's named paths, then the frozen deliverables once they exist */
2271
2369
  const toolFiles = () => [...namedPaths(iss?.body ?? ""), ...(frozen?.deliverables ?? []).map((d) => d?.path)].filter(Boolean);
2272
- const impliedDocs = []; // add-deliverable amendments for doc edits the docs-freshness rule demanded (docs round, CI fix round)
2273
- /** Doc files a fix round added to satisfy the freshness rule: recorded only when the rule failed before and passes after. */
2274
- async function noteFreshnessDocs(before, wasFailing) {
2275
- if (!io.docsFreshness || !wasFailing) return;
2276
- const nowOk = (await io.docsFreshness({ cwd: wt, base }).catch(() => null))?.ok === true;
2277
- for (const a of impliedDocDeliverables({ before, after: await changedFiles(), contract: frozen, wasFailing, nowOk })) if (!impliedDocs.some((x) => x.path === a.path)) impliedDocs.push(a);
2278
- }
2279
2370
  let priorAmendments = []; // #4899: accepted amendments recovered with the frozen contract
2280
2371
  const pendingPits = []; // #4375: rework rounds whose gate has not passed again yet
2281
2372
  async function notePitfall(trigger, text) {
@@ -2359,7 +2450,7 @@ export async function runCore(o) {
2359
2450
  { const f = await gateSetup(); if (f) return f; }
2360
2451
  files = await changedFiles();
2361
2452
  frozen = { requirements: [], deliverables: files.map((path, i) => ({ id: `D${i + 1}`, path, change: `adopted from PR #${adoptPr.number}: reviewed as built`, requirements: [] })), preserve: [], validate: [] };
2362
- hash = contractHash(contractJson(frozen));
2453
+ hash = contractHash(contractJson(frozen)); postContractHash = hash;
2363
2454
  T.decisions.push(`Adopted PR #${adoptPr.number}: ${files.length} changed file(s) go to review as built`);
2364
2455
  } else if (isSplit) {
2365
2456
  // ---- 3'. refactor:split (#4211): deterministic move + proof replaces the builder; no builder session exists ----
@@ -2386,7 +2477,22 @@ export async function runCore(o) {
2386
2477
  T.decisions.push(`Rerun: frozen contract ${fc.hash} is stale (${stale}); re-planning`);
2387
2478
  } else {
2388
2479
  frozen = fc.contract; hash = fc.hash; priorAmendments = fc.amendments ?? []; T.decisions.push(`Rerun: frozen contract ${hash} recovered from the issue`);
2389
- ev({ event: "CONTRACT_REUSED", hash, recover: recover?.code ?? null, resumed: Boolean(resumed) }); // #5811: no pre-contract session; routing is next
2480
+ postContractHash = hash; ev({ event: "CONTRACT_REUSED", hash, recover: recover?.code ?? null, resumed: Boolean(resumed) }); // #5811: no pre-contract session; routing is next
2481
+ freezeTracked = (await depOwnerOf()).files;
2482
+ const rw = freezeRewrites(structuredClone(frozen)); // #5920: the freeze-time rewrites (validate.recipes, venv, CI env) apply to a reused contract too; only commands are adopted
2483
+ const swaps = [];
2484
+ const swap = (id, o, n) => { if (o && typeof o.command === "string" && typeof n?.command === "string" && n.command !== o.command) { swaps.push({ id, from: o.command, to: n.command }); o.command = n.command; } };
2485
+ frozen = structuredClone(frozen);
2486
+ for (const v of Array.isArray(frozen.validate) ? frozen.validate : []) swap(v?.id, v, (rw.validate ?? []).find((x) => x?.id === v?.id));
2487
+ swap("repro_test", frozen.repro_test, rw.repro_test);
2488
+ if (swaps.length) { // audit-only comment (no AMENDMENT-STATE, so a later reuse never replays it); the rewrite is deterministic and re-derived each reuse
2489
+ const why = `rewrite of frozen contract ${hash} on reuse (#5920)`;
2490
+ const body = renderAmendments(swaps.map((x) => ({ kind: "rewrite-validate", target: x.id, why: `${why}: \`${x.from}\` -> \`${x.to}\`` })));
2491
+ T.decisions.push(`Reused contract ${hash}: ${swaps.map((x) => x.id).join(", ")} rewritten at reuse`);
2492
+ if (!(fc.rewritePosted ?? []).some((c) => c.includes(body))) {
2493
+ try { await post("FORGE:AMENDMENT", body); } catch (e) { T.anomalies.push(`FORGE:AMENDMENT comment not posted: ${String(e?.message ?? e).slice(0, 160)}`); }
2494
+ }
2495
+ }
2390
2496
  const ad = applyRequirementDecisions(frozen, trustedComments); // #5547: a structured operator decision amends the frozen row
2391
2497
  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`); }
2392
2498
  }
@@ -2412,14 +2518,6 @@ export async function runCore(o) {
2412
2518
  if (!planOnly) await label("building"); // #5831
2413
2519
  // #4450: the light lane (lean.light mode on, eligible, fresh lane): one builder session, derived contract, or an upgrade
2414
2520
  const waitMs = Math.max(0, Number(contextWaitSeconds) || 0) * 1000, tHot = now();
2415
- 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
2416
- 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);
2417
- if (recurrence?.recurs) {
2418
- ev({ event: "RECURRENCE", count: recurrence.count, threshold: recurrence.threshold, fixes: recurrence.evidence.map((e) => e.number), reason: recurrence.reason });
2419
- T.decisions.push(`Design lane (#5751): ${recurrence.reason}`);
2420
- 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 */ }
2421
- }
2422
- }
2423
2521
  await takeHotAreas(namedPaths(iss.body ?? "")); // #5751
2424
2522
  const hotR = await within(hotspotsOf({ paths: namedPaths(iss.body ?? "") }), waitMs); // #5209: churn and hotspot signals for eligibility; #5434: bounded, overlaps the install
2425
2523
  const hotLate = hotR === TIMED_OUT, namedHot = hotLate ? null : hotR;
@@ -2430,9 +2528,8 @@ export async function runCore(o) {
2430
2528
  lightVerdict = elig.verdict;
2431
2529
  if (elig.mode !== "off") T.decisions.push(`Light lane ${elig.mode}: ${elig.verdict}${elig.reasons.length ? ` (${elig.reasons.map((x) => x.code).join(", ")})` : ""}`);
2432
2530
  // #4451: a light try skips the hotspots and the context pack; an upgrade computes them before the plan call
2433
- const ffSource = fastForwardSource(o.light), ffFresh = !planOnly && ffSource === "investigation" && !frozen && !resumed && !salvagedRef && !recover && !recurrence?.recurs; // #5426: the text verdict above is only a shadow signal then
2434
- const lightTry = !planOnly && ffSource === "text" && elig.light && !hotLate && !frozen && !resumed && !salvagedRef && !recover && !recurrence?.recurs; // #5751: a recurrence never takes the light lane
2435
- if (recurrence?.recurs && elig.light) T.decisions.push("Light lane skipped: the issue recurs (design lane)");
2531
+ const ffSource = fastForwardSource(o.light), ffFresh = !planOnly && ffSource === "investigation" && !frozen && !resumed && !salvagedRef && !recover; // #5426: the text verdict above is only a shadow signal then
2532
+ const lightTry = !planOnly && ffSource === "text" && elig.light && !hotLate && !frozen && !resumed && !salvagedRef && !recover;
2436
2533
  if (!lightTry) hotFacts = namedHot; // #4451: a light try still gives its builder no hotspot facts
2437
2534
  enumList = io.enumeratingTests ? ((await within(io.enumeratingTests({ cwd: wt, paths: namedPaths(iss.body ?? "") }), waitMs)) ?? []) : [];
2438
2535
  if (enumList === TIMED_OUT) enumList = [];
@@ -2447,7 +2544,7 @@ export async function runCore(o) {
2447
2544
  if (!depsDone && left > 0) await within(depsP, left);
2448
2545
  const f = await toolStop(toolFiles()); if (f) return f;
2449
2546
  }
2450
- 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
2547
+ const planPrompt = () => builderPlanPrompt(issue, tcOpts()) + uiBuildRule(uiOn = uiOn || uiIssue(iss ?? {}), designConfig) + hotspotPlanNote(hotFacts) + enumeratingPlanNote(enumList) + invariantsPlanNote(vcfg.invariants) + reproPlanNote(reproOn()) + pagePlanNote(pagesConfig) + unrunnableValidateNote(testRunners) + explorePlanRule(exploreCfg) + (ctxCfg.mode === "on" ? contextPackNote(ctxPack) : "");
2451
2548
  let lightDone = false, lightCommits = false;
2452
2549
  let ffPlan = "full", ffGo = false, lightElig = elig, lightPred = null, ffTriage = null; // #5426: how the plan call runs; ffGo = fast-forward to the light step
2453
2550
  const ffTriageOf = async (raw) => parseTriage(raw, await io.fs.read(`${wt}/${INVESTIGATION_FILE}`).catch(() => ""));
@@ -2480,6 +2577,7 @@ export async function runCore(o) {
2480
2577
  stage = "plan"; liveKeys = ["investigation"]; result = (await readResult()) ?? result;
2481
2578
  if (!lr.upgrade) {
2482
2579
  lightDone = true; light = true; frozen = historyRows(lr.contract); hash = contractHash(contractJson(frozen));
2580
+ postContractHash = hash;
2483
2581
  let body = renderContract(frozen, hash, { scope: scopeHash, base: lane });
2484
2582
  if (body.length > MAX_COMMENT_CHARS - 500) body = renderContract(frozen, hash, { compact: true, scope: scopeHash, base: lane });
2485
2583
  await post(["FORGE:CONTRACT", "FORGE:PLAN"], body);
@@ -2558,8 +2656,7 @@ export async function runCore(o) {
2558
2656
  await classifyStage(sessionId ? (problems) => builder(++attemptN, `${contractCorrectionPrompt(problems)}\nThis concerns .forge-lean/classification.json: fix only the invalid fields.`, sessionId, false, planPrompt, { trigger: "contract_correction" }) : null);
2559
2657
  const wtRead = (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } }; // #5585: noindex pages are not public
2560
2658
  const freezeBase = pagesConfig ? String(await git(["ls-tree", "-r", "-z", "--name-only", base]).catch(() => "")).split("\0").filter(Boolean) : null; // #5648
2561
- 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
2562
- let vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, baseFiles: freezeBase, testPlan: reproOn(), readFile: wtRead, checkIds: freezeCheckIds, reproRecipe });
2659
+ let vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, baseFiles: freezeBase, testPlan: reproOn(), readFile: wtRead, reproRecipe });
2563
2660
  const found0 = await preflightValidates(contract); // #4328: validate commands the host cannot run share the one correction
2564
2661
  let missed = found0;
2565
2662
  // #5653: an unrunnable command is rewritten from the repo catalogue (forge.yaml recipes first, then CI-derived) before any builder correction
@@ -2569,7 +2666,7 @@ export async function runCore(o) {
2569
2666
  if (rw.applied.length) {
2570
2667
  contract = snapContract(rw.contract);
2571
2668
  for (const x of rw.applied) T.decisions.push(`validate catalogue rewrote unrunnable ${x.id}: \`${x.from}\` -> \`${x.to}\``);
2572
- vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, baseFiles: freezeBase, testPlan: reproOn(), readFile: wtRead, checkIds: freezeCheckIds, reproRecipe });
2669
+ vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, baseFiles: freezeBase, testPlan: reproOn(), readFile: wtRead, reproRecipe });
2573
2670
  missed = await preflightValidates(contract);
2574
2671
  }
2575
2672
  }
@@ -2581,10 +2678,11 @@ export async function runCore(o) {
2581
2678
  await persistGenChecks();
2582
2679
  await refreshIssue("contract validation");
2583
2680
  contract = snapContract(contract);
2584
- vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, baseFiles: freezeBase, testPlan: reproOn(), readFile: wtRead, checkIds: freezeCheckIds, reproRecipe });
2681
+ vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, baseFiles: freezeBase, testPlan: reproOn(), readFile: wtRead, reproRecipe });
2585
2682
  };
2586
- if ((!vc.ok || missed.length || testRunnerProblems(contract, testRunners).length) && sessionId) {
2587
- await correctContract([...vc.problems, ...preflightProblems(missed), ...testRunnerProblems(contract, testRunners)], "resumed once");
2683
+ const hostOnly = () => hostOnlyProblems(contract); // #5749: a host-only wrapper or busy loop in a frozen command is corrected at freeze
2684
+ if ((!vc.ok || missed.length || testRunnerProblems(contract, testRunners).length || hostOnly().length) && sessionId) {
2685
+ await correctContract([...vc.problems, ...preflightProblems(missed), ...testRunnerProblems(contract, testRunners), ...hostOnly()], "resumed once");
2588
2686
  if (missed.length) misses = await preflightValidates(contract);
2589
2687
  }
2590
2688
  // #5623: builder-correctable contract problems get up to contractMaxCorrections rounds (default 3), each with only the
@@ -2607,6 +2705,7 @@ export async function runCore(o) {
2607
2705
  }
2608
2706
  await flushStages(result ?? { status: "fixed" }, ["investigation"]); // always posted: FORGE:INVESTIGATION/VALIDATE are read downstream
2609
2707
  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 } : {}) });
2708
+ { const ho = hostOnly(); if (ho.length) return await needsHuman(`The builder's contract still has host-only or busy-loop commands after correction (#5749); nothing was built:\n${ho.slice(0, 12).map((x) => `- ${x}`).join("\n")}`, OUTCOME_CODES.CONTRACT_INVALID, { ...(issueEdited ? { issueEdited: true } : {}) }); }
2610
2709
  frozen = historyRows(contract); // #4694 guards
2611
2710
  frozen = withDecisionRows(frozen, readDecisionIndex(repo)); // #4695: anchored decisions on the deliverable paths; one index read
2612
2711
  await takeHotAreas((frozen.deliverables ?? []).map((d) => d?.path)); // #5751: the contract's paths before building
@@ -2640,8 +2739,8 @@ export async function runCore(o) {
2640
2739
  }
2641
2740
  { // #5447: the test plan's declared env is checked on the host the lane runs on before building; a missing runner is provisioned once, else the lane ends env.tool_missing (the orchestrator re-places it on a host that has it)
2642
2741
  const deps5683 = await depOwnerOf(), projEnv = () => { const e = laneEnv(); const d = projectBinDirs(wt, deps5683.files); if (d.length) e.PATH = withLocalBins(e.PATH ?? process.env.PATH ?? "", d); return e; };
2643
- const projDeps = declaredEnv(frozen).filter((t) => deps5683.owner(t) !== null); // #5683: a sub-project's declared dependency is prepared and resolved through its bin dirs, never a host tool
2644
- const probeEnv = async () => { const miss = []; for (const t of declaredEnv(frozen)) { if (deps5683.owner(t) !== null) continue; const r = io.runCommand ? await io.runCommand({ command: t === "pytest" ? "python3 -m pytest --version" : `command -v ${t} >/dev/null || { test -d node_modules/${t} && ! test -e node_modules/.bin/${t}; } || ls -d .venv/lib/python*/site-packages/${t} >/dev/null 2>&1`, cwd: wt, timeoutMs: 30000, env: projEnv() }).catch(() => ({ rc: 1 })) : { rc: 0 }; if ((r?.rc ?? 0) !== 0) miss.push(t); } return miss; };
2742
+ const projDeps = declaredEnv(frozen, deps5683.files).filter((t) => deps5683.owner(t) !== null); // #5683: a sub-project's declared dependency is prepared and resolved through its bin dirs, never a host tool
2743
+ const probeEnv = async () => { const miss = []; for (const t of declaredEnv(frozen, deps5683.files)) { if (deps5683.owner(t) !== null) continue; const r = io.runCommand ? await io.runCommand({ command: t === "pytest" ? "python3 -m pytest --version" : `command -v ${t} >/dev/null || { test -d node_modules/${t} && ! test -e node_modules/.bin/${t}; } || ls -d .venv/lib/python*/site-packages/${t} >/dev/null 2>&1`, cwd: wt, timeoutMs: 30000, env: projEnv() }).catch(() => ({ rc: 1 })) : { rc: 0 }; if ((r?.rc ?? 0) !== 0) miss.push(t); } return miss; };
2645
2744
  let envMiss = await probeEnv();
2646
2745
  if (projDeps.length && io.deps?.prepare) { try { await io.deps.prepare({ wt, repoKey: depcacheNamespace({ repo, fallback: repoKey(cwd) }), env: toolchain?.env ?? undefined }); ev({ event: "TESTPLAN_ENV_PROJECT_DEPS", names: projDeps }); } catch { /* the install gate reports failures */ } }
2647
2746
  if (envMiss.length) {
@@ -2671,7 +2770,8 @@ export async function runCore(o) {
2671
2770
  // #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)
2672
2771
  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
2673
2772
  const ownedDep = (t) => t === "forgedock" || remoteDeps.owner(t) !== null, notOwned = (m) => ({ ...m, tools: m.tools.filter((t) => !ownedDep(t)) });
2674
- let tm0 = toolMisses(planMisses ?? await preflightValidates(frozen).catch(() => [])), tm = notOwned(tm0);
2773
+ let rawMisses = planMisses ?? await preflightValidates(frozen).catch(() => []);
2774
+ let tm0 = toolMisses(rawMisses), tm = notOwned(tm0);
2675
2775
  if (tm0.tools.length && !tm.tools.length) { try { if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: depcacheNamespace({ repo, fallback: repoKey(cwd) }), env: toolchain?.env ?? undefined }); ev({ event: "REMOTE_PROJECT_DEPS", tools: tm0.tools }); } catch { /* the install gate reports failures */ } }
2676
2776
  if (tm.tools.length) { // #5423: provision the sandbox once (nested lockfiles, pytest) and re-probe before giving the lane up
2677
2777
  try {
@@ -2690,6 +2790,23 @@ export async function runCore(o) {
2690
2790
  tm = notOwned(toolMisses(await preflightValidates(frozen).catch(() => [])));
2691
2791
  ev({ event: "REMOTE_PROVISIONED", remaining: tm.tools });
2692
2792
  }
2793
+ if (noRecipe.length && tm.tools.some((t) => noRecipe.includes(t)) && io.runCommand) { // unclog: a generic pip/npm/apt install before any park
2794
+ const root = process.getuid?.() === 0, tried = [];
2795
+ for (const t of noRecipe.filter((x) => tm.tools.includes(x))) {
2796
+ const miss = (Array.isArray(rawMisses) ? rawMisses : []).find((m) => String(m?.tool) === t) ?? { kind: "command", tool: t };
2797
+ const shim = (o.hostCaps?.offloadWrappers ?? []).includes(t) && /^[A-Za-z0-9._-]+$/.test(t) // the sandbox is already where the wrapper sends work: run its argument directly
2798
+ ? [`${root ? "" : "sudo "}sh -c 'printf "#!/bin/sh\\nexec \\"\\$@\\"\\n" > /usr/local/bin/${t} && chmod +x /usr/local/bin/${t}'`] : null;
2799
+ for (const command of shim ?? genericInstallCommands(miss, { root })) {
2800
+ const r = await io.runCommand({ command, cwd: wt, timeoutMs: 600000, env: laneEnv() }).catch((e) => ({ rc: 1, stderr: String(e?.message ?? e) }));
2801
+ tried.push({ tool: t, kind: miss.kind, rc: r?.rc ?? 0 });
2802
+ process.stderr.write(`forgedock: generic install of ${t} (${miss.kind}) rc=${r?.rc ?? 0}${(r?.rc ?? 0) ? `: ${String(r?.output ?? r?.stderr ?? "").trim().split("\n").slice(-3).join(" | ").slice(0, 300)}` : ""}\n`); // lands in the lane log (dispatcher side)
2803
+ }
2804
+ }
2805
+ rawMisses = await preflightValidates(frozen).catch(() => []);
2806
+ tm = notOwned(toolMisses(rawMisses));
2807
+ ev({ event: "REMOTE_TOOLS_GENERIC", tried, remaining: tm.tools });
2808
+ if (tried.length) T.decisions.push(`Remote sandbox lacked ${tried.map((x) => `${x.tool} (${x.kind})`).join(", ")}: generic install ${tm.tools.length ? `left ${tm.tools.join(", ")} missing` : "provided them"}`);
2809
+ }
2693
2810
  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
2694
2811
  }
2695
2812
  if (tm.tools.length) {
@@ -2794,18 +2911,50 @@ export async function runCore(o) {
2794
2911
  // #4331: a learned command the map covers runs only when its globs match a changed file; unmapped ones always run (#4315)
2795
2912
  // #5820: the PR's required CI jobs (scripts/ci-local plan, heavy jobs CI-only) join the round as derived commands
2796
2913
  const ciCfg = o.precheck?.ci ?? parseCiPrecheckConfig(null);
2797
- let ciRequired, ciDerived = new Map(); // command -> {job, name, why, steps}
2914
+ let ciRequired, ciRelease, ciDerived = new Map(); // command -> {job, name, why, steps}
2798
2915
  const ciGaveUp = new Set(); // jobs found unrunnable in an earlier round: recorded once, not rerun
2799
2916
  async function ciPrecheckPlan(round) {
2800
2917
  ciDerived = new Map();
2801
2918
  if (ciCfg.mode === "off" || isSplit || !io.ciLocalPlan || !io.fs?.write) return [];
2802
2919
  if (ciRequired === undefined) { try { ciRequired = (await io.requiredChecks?.(lane)) ?? null; } catch { ciRequired = null; } }
2803
- 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 });
2920
+ // #6049: the release branch's required checks (the integration target's CI) join the lane's pre-PR set
2921
+ const releaseBranch = String(defaults.find(Boolean) ?? "");
2922
+ const useRelease = Boolean(releaseBranch) && releaseBranch !== lane;
2923
+ if (useRelease && ciRelease === undefined) { try { ciRelease = (await io.requiredChecks?.(releaseBranch)) ?? []; } catch { ciRelease = []; } }
2924
+ const p = await deriveCiPrecheck({ buildPlan: io.ciLocalPlan, required: ciRequired, releaseRequired: useRelease ? ciRelease : null, releaseBranch: useRelease ? releaseBranch : "", cfg: ciCfg, wt, base, lane, files, perCommandMs: vcfg.precheckTimeoutSeconds * 1000, writeFile: (rel, text) => io.fs.write(`${wt}/${rel}`, text), skipJobs: ciGaveUp });
2804
2925
  for (const c of p.commands) ciDerived.set(c.command, c);
2926
+ if (useRelease && p.parity?.length) {
2927
+ ev({ event: "CI_PRECHECK_PARITY", round, release: releaseBranch, gaps: p.parity });
2928
+ if (!round) { const issues = await reportParityGaps({ ghc, repo, release: releaseBranch, gaps: p.parity }); T.decisions.push(`Lane-check parity gap(s) vs ${releaseBranch}: ${p.parity.map((g) => g.context).join(", ")}${issues.length ? ` (filed ${issues.map((n) => `#${n}`).join(", ")})` : ""}`); }
2929
+ }
2805
2930
  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 });
2806
2931
  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("; ")}` : ""}`);
2807
2932
  return p.commands.map((c) => c.command);
2808
2933
  }
2934
+ // #6107: a ci.red recovery must not judge a stale tree: the base's current head is merged in before any check runs. A conflict
2935
+ // the engine cannot resolve deterministically ends base.conflict (recoverable), never ci.red for a branch that is only behind.
2936
+ if (recover?.code === OUTCOME_CODES.CI_RED && !isSplit && io.runCommand) {
2937
+ try { await git(["fetch", "origin", lane]); } catch { /* offline: the local ref */ }
2938
+ const behind = Number(String(await git(["rev-list", "--count", `HEAD..${base}`]).catch(() => "0")).trim()) || 0;
2939
+ if (behind > 0) {
2940
+ let merged = true, conflicted = [];
2941
+ try { await git(["merge", "--no-edit", base]); } catch { merged = false; conflicted = String(await git(["diff", "--name-only", "--diff-filter=U"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean); }
2942
+ if (!merged && conflicted.length) {
2943
+ const bm = o.baseMerge, cr = io.conflictResolve && bm && Object.values(bm).some((v) => v?.length) ? await io.conflictResolve({ cwd: wt, files: conflicted, cfg: bm }).catch(() => null) : null;
2944
+ if (cr?.resolved?.length && !(cr.remaining ?? []).length) { try { await git(["commit", "--no-edit"]); merged = true; } catch { /* abort below */ } }
2945
+ if (!merged) {
2946
+ await git(["merge", "--abort"]).catch(() => {});
2947
+ ev({ event: "RECOVERY_BASE_SYNC", base, behind, result: "conflict", files: conflicted.slice(0, 20) });
2948
+ return await needsHuman(`The branch conflicts with ${base} in ${conflicted.slice(0, 20).join(", ")}; the recovery's checks were not run on the stale tree (a conflicting base is not a check failure); nothing merged.`, OUTCOME_CODES.BASE_CONFLICT);
2949
+ }
2950
+ } else if (!merged) { await git(["merge", "--abort"]).catch(() => {}); T.anomalies.push(`Recovery base-sync could not merge ${base} (${behind} commit(s) behind, no conflict files); checks run on the branch as it is`); }
2951
+ if (merged) {
2952
+ ev({ event: "RECOVERY_BASE_SYNC", base, behind, result: "merged" });
2953
+ T.decisions.push(`Recovery: merged ${base} (${behind} commit(s) behind) before re-running the checks`);
2954
+ files = await changedFiles();
2955
+ }
2956
+ }
2957
+ }
2809
2958
  let ciCommands = await ciPrecheckPlan(0);
2810
2959
  const pickChecks = () => planPrecheck({ testMap, files, learned: [...learnedCommands, ...ciCommands], maxMinutes: o.precheck?.maxMinutes, verify: vcfg });
2811
2960
  let picked = pickChecks();
@@ -2814,6 +2963,17 @@ export async function runCore(o) {
2814
2963
  if (picked.source !== "learned") T.decisions.push(`Pre-PR checks selected from ${TEST_MAP_FILE}: ${picked.selected} of ${testMap.entries.length} entries${learnedCommands.length ? `, plus ${learnedCommands.length - picked.dropped.length} learned` : ""}${picked.dropped.length ? `; ${picked.dropped.length} mapped learned command(s) not matching the changed files left to CI` : ""}`);
2815
2964
  if (picked.commands.length && io.runCommand) {
2816
2965
  precheckRan = true;
2966
+ // #6106: dependencies for every package the checks touch are prepared before the checks run; a missing tool afterwards is env, not ci.red
2967
+ let depsReprovisioned = false;
2968
+ const flakeReran = new Set();
2969
+ const reprovisionDeps = async (why) => {
2970
+ if (depsReprovisioned || !io.deps?.prepare) return false;
2971
+ depsReprovisioned = true;
2972
+ try { const rp = await io.deps.prepare({ wt, repoKey: depcacheNamespace({ repo, fallback: repoKey(cwd) }), env: toolchain?.env ?? undefined }); depResults = Array.isArray(rp) ? rp : depResults; } catch { /* the check result below says what is still missing */ }
2973
+ ev({ event: "PRECHECK_DEPS_PREPARED", why });
2974
+ return true;
2975
+ };
2976
+ { const unprepared = packageDirsMissingDeps(picked.commands, (rel) => existsSync(join(wt, rel))); if (unprepared.length) await reprovisionDeps(`no node_modules in ${unprepared.join(", ")}`); }
2817
2977
  for (let round = 0; ; round++) {
2818
2978
  await renew();
2819
2979
  if (round) { ciCommands = await ciPrecheckPlan(round); picked = pickChecks(); }
@@ -2850,10 +3010,30 @@ export async function runCore(o) {
2850
3010
  if (!failed.length && timedOut.length && (vcfg.precheckBlock || guardFailing(timedOut))) return await needsHuman(`Environment error (not a check failure): pre-PR check command(s) timed out even after one longer retry, which is host load rather than a failing check; no builder resume was spent, the branch is pushed and nothing merged: ${timedNames}`, ENV_VALIDATE_TIMEOUT);
2851
3011
  if (!failed.length) { checkCommandsFailing = false; if (round) T.decisions.push(`Declared check commands pass after ${round} builder fix round(s)`); await gatePassed("precheck"); break; }
2852
3012
  const names = failed.map((f) => `\`${f.command}\` (exit ${f.rc})`).join(", ");
2853
- if (isSplit) return await needsHuman(`Declared check command(s) fail on the refactor:split move (no builder edits a split); nothing merged: ${names}`, OUTCOME_CODES.CI_RED);
3013
+ // #5749/#6107: the park names each failing check and carries the last ~40 lines of its output, secrets redacted (run log too)
3014
+ const failTail = (fs) => { const rows = fs.map((f) => ({ name: ciDerived.get(f.command)?.name ?? null, command: f.command, rc: f.rc, tail: checkFailureTail(f, { name: ciDerived.get(f.command)?.name }) })); ev({ event: "PRECHECK_FAILED", round, checks: rows.map(({ name, command, rc, tail }) => ({ name, command, rc, tail })) }); return rows.map((r) => r.tail).join(""); };
3015
+ if (isSplit) return await needsHuman(`Declared check command(s) fail on the refactor:split move (no builder edits a split); nothing merged: ${names}${failTail(failed)}`, OUTCOME_CODES.CI_RED);
3016
+ { // #6106: every failed check died on a missing tool/binary (not on its own assertion): prepare dependencies once and rerun, then it is env.tool_missing
3017
+ const gap = toolGapFailures(failed);
3018
+ if (gap.length && gap.length === failed.length) {
3019
+ if (await reprovisionDeps("check failed on a missing tool")) { round--; continue; }
3020
+ ev({ event: "PRECHECK_TOOL_MISSING", commands: gap.map((f) => f.command) });
3021
+ return await needsHuman(`Environment error (not a check failure): declared check command(s) could not run because a tool or binary is missing, even after the dependencies were prepared; nothing merged: ${names}${failTail(gap)}`, OUTCOME_CODES.ENV_TOOL_MISSING);
3022
+ }
3023
+ }
3024
+ { // #6094: a failure in a test the diff does not touch gets one rerun before it can be ci.red or spend a builder round
3025
+ const dirty = await changedFiles();
3026
+ const todo = failed.filter((f) => !flakeReran.has(f.command) && failureOutsideDiff(f.output, dirty));
3027
+ if (todo.length && todo.length === failed.length) {
3028
+ for (const f of todo) flakeReran.add(f.command);
3029
+ const reruns = await heavyStep("precheck", async () => { const out = []; for (const f of todo) { try { out.push(await io.runCommand({ command: f.command, cwd: wt, timeoutMs: vcfg.precheckTimeoutSeconds * 1000, env: laneEnv() })); } catch { out.push({ rc: 1 }); } } return out; });
3030
+ ev({ event: "PRECHECK_FLAKE_RERUN", round, commands: todo.map((f) => f.command), results: reruns.map((r) => r?.rc ?? null) });
3031
+ if (reruns.every((r) => r?.rc === 0)) { T.decisions.push(`Declared check(s) ${todo.map((f) => `\`${f.command}\``).join(", ")} failed in test file(s) the diff does not touch and passed on one rerun (flake); no fix round spent`); checkCommandsFailing = false; await gatePassed("precheck"); break; }
3032
+ }
3033
+ }
2854
3034
  checkCommandsFailing = true;
2855
- { const red = await guardRed(failed); if (red) return red; } // #5239: a guard that also fails on the base defers the lane
2856
- if (round >= vcfg.maxRounds || !sessionId) { if (vcfg.precheckBlock || guardFailing(failed)) return await needsHuman(`Declared check command(s) still failing before the PR (verify.precheck_block); nothing merged: ${names}`, OUTCOME_CODES.CI_RED); T.anomalies.push(`Declared check command(s) still failing before the PR: ${names}`); break; }
3035
+ { const red = await guardRed(failed, { bypass: vcfg.guardBypass === true }); if (red === "bypass") { checkCommandsFailing = false; break; } if (red) return red; } // #5239: a guard that also fails on the base defers the lane; #5992: unless the lane is clear of the guarded surface
3036
+ if (round >= vcfg.maxRounds || !sessionId) { if (vcfg.precheckBlock || guardFailing(failed)) return await needsHuman(`Declared check command(s) still failing before the PR (verify.precheck_block); nothing merged: ${names}${failTail(failed)}`, OUTCOME_CODES.CI_RED); T.anomalies.push(`Declared check command(s) still failing before the PR: ${names}`); break; }
2857
3037
  T.decisions.push(`Declared check command(s) failed: ${names}; builder resumed (round ${round + 1}/${vcfg.maxRounds})`);
2858
3038
  const before = String(await git(["rev-parse", "HEAD"])).trim();
2859
3039
  const capped = capLogs(failed.map((f) => ({ ...f, log: f.output }))).map((f) => ({ command: f.command, rc: f.rc, output: f.log }));
@@ -2868,7 +3048,7 @@ export async function runCore(o) {
2868
3048
  await fixRound("precheck", precheckFailurePrompt(quiet, vcfg.mode), [], "precheck", capped.map((f) => `${f.command}\n${f.output ?? ""}`).join("\n"));
2869
3049
  await upsertStage("implementation");
2870
3050
  result = (await readResult()) ?? result;
2871
- if (String(await git(["rev-parse", "HEAD"])).trim() === before) { if (vcfg.precheckBlock || guardFailing(failed)) return await needsHuman(`Declared check command(s) failing and the builder made no new commit for them (verify.precheck_block); nothing merged: ${names}`, OUTCOME_CODES.CI_RED); T.anomalies.push(`Declared check command(s) failing and the builder made no new commit for them: ${names}`); break; }
3051
+ if (String(await git(["rev-parse", "HEAD"])).trim() === before) { if (vcfg.precheckBlock || guardFailing(failed)) return await needsHuman(`Declared check command(s) failing and the builder made no new commit for them (verify.precheck_block); nothing merged: ${names}${failTail(failed)}`, OUTCOME_CODES.CI_RED); T.anomalies.push(`Declared check command(s) failing and the builder made no new commit for them: ${names}`); break; }
2872
3052
  files = await changedFiles();
2873
3053
  }
2874
3054
  }
@@ -2903,26 +3083,6 @@ export async function runCore(o) {
2903
3083
  return await needsHuman(`The change adds dependencies between workspace packages that the frozen contract does not name${sessionId ? ", after one builder resume" : ""}; nothing merged:\n${edges.slice(0, 15).map((e) => `- ${e.from} → ${e.to} (${e.kind}, \`${e.manifest}\`)`).join("\n")}\n\nAdd each to the contract with a reason, or remove it.`, OUTCOME_CODES.STRUCTURE_UNDECLARED_EDGE);
2904
3084
  }
2905
3085
  }
2906
- // ---- 3c. the target repo's devdocs freshness rule, when it has one: deterministic, before any PR, so a lane does not
2907
- // pay for a failed required check. Exit 1 resumes the builder once; still failing is needs-human docs.stale.
2908
- if (io.docsFreshness) {
2909
- let docs = await io.docsFreshness({ cwd: wt, base }).catch(() => null);
2910
- if (docs && !docs.ok && sessionId) {
2911
- ev({ event: "DOCS_STALE", round: 1 });
2912
- T.decisions.push("Docs freshness check failed; builder resumed once");
2913
- const docsBefore = await changedFiles();
2914
- await fixRound("docs", docsPrompt(docs.output), [], "docs", String(docs.output ?? ""));
2915
- await upsertStage("implementation");
2916
- result = (await readResult()) ?? result;
2917
- await noteFreshnessDocs(docsBefore, true);
2918
- docs = await io.docsFreshness({ cwd: wt, base }).catch(() => null);
2919
- }
2920
- verifyFacts.docs = docs;
2921
- if (docs?.ok) await gatePassed("docs");
2922
- if (docs && !docs.ok) {
2923
- return await needsHuman(`The repository's docs freshness check still fails${sessionId ? " after one builder resume" : ""}; nothing merged:\n\n${String(docs.output).slice(0, 2000)}`, OUTCOME_CODES.DOCS_STALE);
2924
- }
2925
- }
2926
3086
  // ---- 3d. enumerating tests (#4322): new symbols that tests listing their siblings do not name; one resume, then an
2927
3087
  // anomaly (CI stays the gate). Sequence numbers the base already uses: renumbered at hand-off, still colliding = base.conflict.
2928
3088
  if (io.enumeratingMissing && !isSplit) {
@@ -3114,7 +3274,7 @@ export async function runCore(o) {
3114
3274
  function guardOn() { return vcfg.guardBlock !== false && (vcfg.invariants ?? []).length > 0; }
3115
3275
  function guardFailing(failed) { return guardOn() && failed.some((f) => vcfg.invariants.includes(f.command)); }
3116
3276
  /** #5239: guard commands failing here are run once on the base; failing there too, the lane is deferred (base.red) and the introducing issue is told. null: the failure is the lane's. */
3117
- async function guardRed(failed) {
3277
+ async function guardRed(failed, { bypass = false } = {}) {
3118
3278
  const g = failed.filter((f) => guardFailing([f]));
3119
3279
  if (!g.length || isSplit || !io.runCommand) return null;
3120
3280
  const baseRuns = await heavyStep("precheck", () => runOnBase({ commands: g.map((f) => f.command), git, runCommand: io.runCommand, mergeBase: base, cwd: wt, env: laneEnv(), timeoutMs: vcfg.precheckTimeoutSeconds * 1000 }));
@@ -3131,15 +3291,31 @@ export async function runCore(o) {
3131
3291
  if (ok.length) { T.decisions.push(`env.base_probe: guard command(s) ${ok.map((f) => `\`${f.command}\``).join(", ")} pass on the bare ${base} tip at the host; the sandbox base failure is environment, no issue filed`); baseRed = baseRed.filter((f) => !ok.includes(f)); }
3132
3292
  }
3133
3293
  if (!baseRed.length) return null;
3294
+ // #5913: a lane whose own diff touches the failing guard's files may be the base fix; deferring it behind the red it repairs is circular. Skip the deferral only when the guard re-run on the lane tree passes.
3295
+ const changedNow = String(await git(["diff", "--name-only", `${base}...HEAD`]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean);
3296
+ if (diffTouchesGuard({ changed: changedNow, failed: baseRed })) {
3297
+ const reruns = await heavyStep("precheck", async () => { const out = []; for (const f of baseRed) { try { out.push(await io.runCommand({ command: f.command, cwd: wt, timeoutMs: vcfg.precheckTimeoutSeconds * 1000, env: laneEnv() })); } catch { out.push({ rc: 1 }); } } return out; });
3298
+ if (reruns.every((r) => r?.rc === 0)) { T.decisions.push(`Guard command(s) ${baseRed.map((f) => `\`${f.command}\``).join(", ")} fail on ${base} but pass on this lane's tree (the lane changes the files the failure names); not deferred (base.red)`); return null; }
3299
+ }
3134
3300
  const att = await attributeBaseRed({ failed: baseRed, git, base });
3301
+ if (bypass && baseRed.length === failed.length) { // R2: bypass only when every failed command is base-red; non-guard or lane-broken failures stay the lane's. #5992: a lane clear of the guarded surface goes on; the guard is re-run on the merged tree at merge (the base-sync post-merge gate)
3302
+ let laneFiles = [];
3303
+ try { laneFiles = String(await git(["diff", "--name-only", `${base}...HEAD`])).split("\n"); } catch { /* no diff: no bypass */ }
3304
+ if (bypassesGuard({ laneFiles, att })) {
3305
+ T.decisions.push(`Guard command(s) ${baseRed.map((f) => `\`${f.command}\``).join(", ")} are red on ${base} (last change ${att.sha.slice(0, 12)}${att.issue ? `, #${att.issue}` : ""}) but this lane touches none of the files they name; proceeding, the guard is re-run at merge`);
3306
+ ev({ event: "BASE_RED_BYPASS", commands: baseRed.map((f) => f.command), sha: att.sha, issue: att.issue ?? null });
3307
+ return "bypass";
3308
+ }
3309
+ }
3135
3310
  let baseSha = "", commitDate = "";
3136
3311
  try { baseSha = String(await git(["rev-parse", base])).trim(); } catch { /* key falls back to the attributed sha */ }
3137
3312
  try { if (att?.sha) commitDate = String(await git(["show", "-s", "--format=%cI", att.sha])).trim(); } catch { /* no reopen */ }
3138
3313
  const cmds = baseRed.map((f) => f.command), outputs = Object.fromEntries(cmds.map((c) => [c, tailOf(c)]));
3139
3314
  const n = await reportBaseRed({ ghc: ghw, repo, base, att, laneIssue: issue, commands: cmds, outputs, baseSha, commitDate });
3140
- T.decisions.push(`Guard command(s) ${cmds.map((c) => `\`${c}\``).join(", ")} also fail on ${base}${att ? ` (last change ${att.sha.slice(0, 12)}${att.issue ? `, #${att.issue}` : ""})` : ""}; lane deferred behind ${n ? `#${n}` : "the base fix"}`);
3315
+ T.decisions.push(`Guard command(s) ${cmds.map((c) => `\`${c}\``).join(", ")} also fail on ${base}${att ? ` (last change ${att.sha.slice(0, 12)}${att.issue ? `, #${att.issue}` : ""})` : ""}; lane deferred behind ${n ? `#${n}` : "the base fix"}; if this lane fixes it, change the guard's files or land it through review-finalize merge-gate --manual-pr --owner-requested`);
3316
+ recordBaseVerdict({ repo, base, sha: baseSha, red: true, att, commands: cmds, outputs }); // #5992: later lanes and the dispatcher's probe reuse this verdict
3141
3317
  ev({ event: "BASE_RED", commands: cmds, output: cmds.map((c) => tailOf(c).slice(-500)), sha: att?.sha ?? null, issue: att?.issue ?? null, tracked: n });
3142
- return await finish("deferred", `base ${base} is red on guard command(s) ${cmds.join(", ")}; deferred behind ${n ? `#${n}` : "the base fix"}`, { code: OUTCOME_CODES.BASE_RED, retryInSeconds: 900 }, OUTCOME_CODES.BASE_RED);
3318
+ return await finish("deferred", `base ${base} is red on guard command(s) ${cmds.join(", ")}; deferred behind ${n ? `#${n}` : "the base fix"} (owner escape: review-finalize merge-gate --manual-pr --owner-requested)`, { code: OUTCOME_CODES.BASE_RED, retryInSeconds: 900 }, OUTCOME_CODES.BASE_RED);
3143
3319
  }
3144
3320
  const structureLine = structureNote(structure);
3145
3321
 
@@ -3230,12 +3406,9 @@ export async function runCore(o) {
3230
3406
  ciRounds++; fixes++;
3231
3407
  T.decisions.push(`CI verification red (${jobs}); builder resumed with the failed logs (round ${ciRounds}/${vcfg.maxRounds})`);
3232
3408
  ev({ event: "CI_FIX_ROUND", trigger, round: ciRounds, jobs: sp.own.map((f) => f.job) });
3233
- const ciBefore = io.docsFreshness ? await changedFiles() : [];
3234
- const ciDocsStale = io.docsFreshness ? (await io.docsFreshness({ cwd: wt, base }).catch(() => null))?.ok === false : false;
3235
3409
  await fixRound("ci", ciFailurePrompt(sp.own, vcfg.mode), [], "ci_red", failureLog(sp.own));
3236
3410
  await upsertStage("implementation");
3237
3411
  result = (await readResult()) ?? result;
3238
- await noteFreshnessDocs(ciBefore, ciDocsStale);
3239
3412
  if (String(await git(["rev-parse", "HEAD"])).trim() === head) {
3240
3413
  // #4387/#4586: no commit says the failure is not the change's; the failed jobs were already rerun once on this head (before the round).
3241
3414
  const rr = ciReruns.get(head)?.rr ?? { ok: false, detail: isSplit ? "refactor:split" : "no rerun seam" };
@@ -3257,18 +3430,29 @@ export async function runCore(o) {
3257
3430
  const kindsNow = () => (riskEnforced ? null : kinds);
3258
3431
  const recording = () => shadow || (!riskEnforced && Object.keys(kinds).length > 0); // the gate records what it would have blocked
3259
3432
  const blockingOf = (fs, allow) => blockingFailures(fs, { shadow, kinds: kindsNow(), allow });
3433
+ const enforcedKinds = () => Object.entries(kinds ?? {}).filter(([, m]) => m === "enforce").map(([c]) => c); // unclog: an explicit enforce re-promotes an advisory code
3260
3434
  let effective = frozen, review = null, lastAmend = "", resumes = 0, lastFailKey = null, verdict = null, degraded = null, triggerSkipped = false, selfReviewCompared = false;
3261
3435
  const TRIGGER_SKIP = "skipped (review.trigger enforce: no risk trigger)";
3262
3436
  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).";
3263
3437
  let pendingDecisions = [], firstRounds = null, firstReply = null, lastDecided = "";
3264
3438
  let baseTree = null; // #4695: the base file list, read once and only when a decision amendment needs it
3265
3439
  let genPaths = null; // forge#4519: maintenance.generated_paths from hotspots.sh (plan facts; one config-only call without them, never on light lanes)
3440
+ const advisorySeen = new Set();
3441
+ /** unclog: an advisory row is recorded once per lane as a decision line (trajectory + PR), never as a failure. */
3442
+ function noteAdvisory(rows) {
3443
+ for (const f of rows ?? []) {
3444
+ const line = `Advisory (not blocking): ${f.code}${f.kind ? ` ${f.kind}` : ""}: ${String(f.detail ?? "").slice(0, 300)}`;
3445
+ if (advisorySeen.has(line)) continue;
3446
+ advisorySeen.add(line); T.decisions.push(line);
3447
+ }
3448
+ if (rows?.length) ev({ event: "ADVISORY", rows: rows.map((f) => f.kind ?? f.code) });
3449
+ }
3266
3450
  async function amend() {
3267
3451
  genPaths ??= (hotFacts ? hotFacts.generated_paths : light ? [] : (await hotspotsOf({ paths: [] }))?.generated_paths) ?? [];
3268
3452
  const wantsDecision = (Array.isArray(result?.amendments) ? result.amendments : []).some((x) => x?.kind === "decision");
3269
3453
  baseTree ??= wantsDecision ? String(await git(["ls-tree", "-r", "-z", "--name-only", base]).catch(() => "")).split("\0").filter(Boolean) : null;
3270
3454
  const addedPaths = wantsDecision ? String(await git(["diff", "--name-only", "--diff-filter=A", `${base}...HEAD`]).catch(() => "")).split("\n").filter(Boolean) : [];
3271
- const own = [...(Array.isArray(result?.amendments) ? result.amendments : []), ...impliedDocs];
3455
+ const own = Array.isArray(result?.amendments) ? result.amendments : [];
3272
3456
  const ownKeys = new Set(own.map((x) => JSON.stringify(x)));
3273
3457
  const dd = dedupeAddRequirements(frozen, [...priorAmendments.filter((x) => !ownKeys.has(JSON.stringify(x))), ...own]); // #5773: a requeue does not renumber a re-added row
3274
3458
  const all = dd.amendments;
@@ -3289,7 +3473,7 @@ export async function runCore(o) {
3289
3473
  }
3290
3474
  pendingDecisions = a.decisions; // #4737: persisted only once the PR merges
3291
3475
  effective = a.contract;
3292
- return a.problems.map((d) => ({ code: OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, detail: d }));
3476
+ return []; // #6083: an invalid amendment is simply not applied; no amendment syntax or id-reuse gate
3293
3477
  }
3294
3478
  const IGNORE = [`${LEAN_DIR}/`];
3295
3479
  /** Up to two reviewer runs; a reply without usable rows (unparseable, incomplete, inconsistent) is re-asked, never charged to the builder. */
@@ -3431,25 +3615,6 @@ export async function runCore(o) {
3431
3615
  if (Object.keys(out).length) ev({ event: "VALIDATE_RERUN", runs: Object.entries(out).map(([id, x]) => ({ id, rc: x.rc, ...(x.engine ? { engine: true } : {}) })) });
3432
3616
  return out;
3433
3617
  }
3434
- /** #4979 SPEC-2: rerun the frozen command of every substituted validate, so precheck accepts a substitute only for a command that cannot run. */
3435
- async function rerunSubstitutedOriginals(contract) {
3436
- const out = {};
3437
- if (!io.runCommand) return out;
3438
- const env = laneEnv();
3439
- for (const v of contract.validate ?? []) {
3440
- if (!v.substituted?.from) continue;
3441
- let x;
3442
- try { x = await heavyStep("precheck", async () => (await runWithTimeoutRetry((timeoutMs) => io.runCommand({ command: forgedockResolved(v.substituted.from), cwd: wt, timeoutMs, env }), vcfg.precheckTimeoutSeconds * 1000)).r); } catch (e) { x = { rc: 127, output: String(e?.message ?? e) }; }
3443
- out[v.id] = { rc: Number.isInteger(x?.rc) ? x.rc : 1, output: String(x?.output ?? "") };
3444
- // #5653: the substitute runs too, so conformance can judge "same test ids, same result" (equivalentRuns)
3445
- if (out[v.id].rc !== 0 && out[v.id].rc !== 124) {
3446
- let y; try { y = await heavyStep("precheck", async () => (await runWithTimeoutRetry((timeoutMs) => io.runCommand({ command: forgedockResolved(v.command), cwd: wt, timeoutMs, env }), vcfg.precheckTimeoutSeconds * 1000)).r); } catch { y = null; }
3447
- if (y) out[v.id].sub = { rc: Number.isInteger(y.rc) ? y.rc : 1, output: String(y.output ?? "") };
3448
- }
3449
- }
3450
- if (Object.keys(out).length) ev({ event: "SUBSTITUTE_RERUN", runs: Object.entries(out).map(([id, x]) => ({ id, rc: x.rc })) });
3451
- return out;
3452
- }
3453
3618
  /** #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. */
3454
3619
  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
3455
3620
  async function guardGate(files) {
@@ -3483,7 +3648,6 @@ export async function runCore(o) {
3483
3648
  if (!want.run) T.decisions.push(`Real-browser check skipped for interactive UI change (${ui.slice(0, 3).join(", ")}): ${want.reason} (#5285)`);
3484
3649
  return { files: ui, ran: want.run, reason: want.reason, highRisk: riskPathHits(ui, riskPaths).length > 0 };
3485
3650
  }
3486
- let amendFixed = false;
3487
3651
  /** #5436: a review started beside guard+precheck is dropped on every return that does not reach the reviewer. */
3488
3652
  async function gate() {
3489
3653
  try { return await gateRun(); } finally { specReview?.discard(); specReview = null; }
@@ -3514,24 +3678,10 @@ export async function runCore(o) {
3514
3678
  domainsLogged = domains.join(",");
3515
3679
  ev({ event: "REVIEW_DOMAINS", domains, enforced: dHits.length ? dHits : undefined, ...(pd === null ? { error: "roster.failed" } : {}) });
3516
3680
  }
3517
- if (!amendFixed && sessionId && amendmentKindProblems(result?.amendments).length) { // #5089: one in-lane correction, outside the conformance resume budget
3518
- amendFixed = true;
3519
- const bad = amendmentKindProblems(result.amendments);
3520
- T.decisions.push(`Amendment kinds invalid (${bad.length}); builder asked to correct ${RESULT_FILE} once`);
3521
- await builder(++attemptN, amendmentCorrectionPrompt(bad), sessionId, false, undefined, { mode: "resume", trigger: "contract_correction" });
3522
- result = (await readResult()) ?? result;
3523
- files = await changedFiles();
3524
- }
3525
3681
  const amendProblems = await amend();
3526
3682
  const gateHead = String(await git(["rev-parse", "HEAD"])).trim();
3527
3683
  const ciVerified = remoteVerify && ciVerifiedHead !== null && ciVerifiedHead === gateHead;
3528
3684
  const hotspots = await hotspotsOf({ base, paths: files }); // #4502
3529
- let counters = null; // #5751: recurrence.counters at the lane's merge base and at its head
3530
- if (recCfg.counters.length) {
3531
- const mb = String(await git(["merge-base", base, "HEAD"]).catch(() => "")).trim() || base;
3532
- counters = { before: await countCounters({ git, ref: mb, counters: recCfg.counters }), after: await countCounters({ git, ref: "HEAD", counters: recCfg.counters }) };
3533
- ev({ event: "COUNTERS", ...counters });
3534
- }
3535
3685
  const rx = await relaxationsOf(files); // #5237
3536
3686
  relaxations = rx.relaxations;
3537
3687
  if (relaxations.length) {
@@ -3542,16 +3692,15 @@ export async function runCore(o) {
3542
3692
  // #5436: the review reads the same committed diff as guard+precheck, so its session starts now; reviewOnce adopts it, any earlier return discards it
3543
3693
  const repro = await reproOf(effective);
3544
3694
  // a precheck that already fails on facts at hand (no engine rerun) would discard the review, so it is not started then
3545
- 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)) });
3695
+ const early = triggerMode === "enforce" ? null : precheck({ contract: effective, result, changedFiles: files, ignore: IGNORE, ciVerified, frozen, repro, repoHas: repoTracks(String(await git(["ls-files"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean)) });
3546
3696
  specReview = !early || early.failures.length ? null : startSpeculative(async () => reviewerCall((await reviewPrep()).prompt));
3547
3697
  const gateT0 = now(); let validateMs = 0;
3548
- // #4693: guards run beside the validate rerun; SPEC-11: the substituted-original rerun shares the one validate phase
3549
- const validatePhase = phaseLedger.during("validate", async () => ({ runs: await rerunFailedValidatesRaw(effective, { ciVerified }), subs: await rerunSubstitutedOriginals(effective) })).finally(() => { validateMs = now() - gateT0; });
3550
- const [{ runs: validateRuns, subs: substitutedRuns }, guardFailures] = await Promise.all([validatePhase, guardGate(files)]);
3698
+ // #4693: guards run beside the validate rerun
3699
+ const validatePhase = phaseLedger.during("validate", async () => ({ runs: await rerunFailedValidatesRaw(effective, { ciVerified }) })).finally(() => { validateMs = now() - gateT0; });
3700
+ const [{ runs: validateRuns }, guardFailures] = await Promise.all([validatePhase, guardGate(files)]);
3551
3701
  // #5087: forge.yaml topology.route_reachability gates the route handlers this diff adds; unset = no check
3552
3702
  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 } }) : [];
3553
3703
  // #5419: forge.yaml docs: user-facing surfaces need docs, and added /docs links must resolve; unset = no check
3554
- 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 }) : [];
3555
3704
  // #5752: forge.yaml outcome_evidence: a touched declared area needs a before/after on recorded real inputs; unset = no check
3556
3705
  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 }) : [];
3557
3706
  // #5428: forge.yaml pages: a public page needs design, SEO and GEO briefs and passes the deterministic page checks; unset = no check
@@ -3577,12 +3726,9 @@ export async function runCore(o) {
3577
3726
  const guardRunMs = guardEv && !guardEv.error ? Math.max(0, now() - gateT0 - validateMs) : 0;
3578
3727
  guardAddedMs += guardRunMs;
3579
3728
  if (guardEv) ev({ ...guardEv, added_wall_ms: guardRunMs });
3580
- 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;
3581
- // #4626: post-deploy check ids resolve against the lane base's checks file or this PR's
3582
- const checkIds = effective.requirements?.some((r) => r.disposition === "post-deploy") ? new Set(Object.keys(await checksAt(git, [base, "HEAD"], wt))) : null;
3583
- const removedPaths = (effective.validate ?? []).some((v) => v.substituted) || effective.mechanisms?.length ? await removedPathsOf(git, base) : []; // #4990; #5752: a mechanism supersedes retires deleted guard tests
3729
+ const repoHas = (validateRuns && Object.keys(validateRuns).length) ? repoTracks(String(await git(["ls-files"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean)) : undefined;
3730
+ const removedPaths = effective.mechanisms?.length ? await removedPathsOf(git, base) : []; // #4990; #5752: a mechanism supersedes retires deleted guard tests
3584
3731
  laneRemoved = removedPaths ?? [];
3585
- const subBaseFiles = (effective.validate ?? []).some((v) => v.substituted) ? String(await git(["ls-tree", "-r", "-z", "--name-only", base]).catch(() => "")).split("\0").filter(Boolean) : []; // #5003
3586
3732
  const baselineRuns = [];
3587
3733
  for (const b of matchBaselines(files, vcfg.baselines)) { // #5448: project baseline suites for the changed paths, enforced
3588
3734
  let x;
@@ -3590,9 +3736,7 @@ export async function runCore(o) {
3590
3736
  baselineRuns.push({ ...b, rc: Number.isInteger(x?.rc) ? x.rc : 1, output: String(x?.output ?? "") });
3591
3737
  }
3592
3738
  if (baselineRuns.length) ev({ event: "BASELINES_RUN", runs: baselineRuns.map((b) => ({ run: b.run, rc: b.rc })) });
3593
- // #5760: CI budget gate (always on: annotation + hygiene; max_* only when set); one git diff when no workflow changed
3594
- 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 []; });
3595
- 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 });
3739
+ const pc = precheck({ baselineFailures: baselineFailures(baselineRuns), contract: effective, result, changedFiles: files, ignore: IGNORE, ciVerified, repro: (adequacyIn.repro = repro), validateRuns, repoHas, frozen, guardFailures, coupledFailures: await coupledOf(files), relaxationFailures: relaxationFailures(rx), routeFailures, outcomeEvidenceFailures: outcomeFail, pageFailures: [...pageFail, ...designFail], seamFailures: seamFail, prodParityFailures, newOffKeys: await newOffKeysOf(), uiBrowser: uiBrowserOf(files), removedPaths });
3596
3740
  // #5447: an install failure for a package the changed files import blocks (env.tool_missing); unrelated ones are logged
3597
3741
  const depFail = depInstallFailures({ results: depResults, changedFiles: files });
3598
3742
  for (const l of depFail.logged) if (!T.decisions.includes(l)) T.decisions.push(l);
@@ -3649,16 +3793,17 @@ export async function runCore(o) {
3649
3793
  adequacyTel = testAdequacyTelemetry(effective, adequacy, { repro: adequacyIn.repro, mutation: adequacyIn.mutation, regression: regressionRan(effective, adequacyIn) });
3650
3794
  // an environment or repro-verdict failure is settled first (already-fixed, env.repro_unrunnable): adequacy never mixes into it
3651
3795
  const adqFail = pc.failures.some((f) => ENV_CODES.includes(f.code) || String(f.kind ?? "").startsWith("repro")) ? [] : testAdequacyFailures(adequacy, { bug: adequacyIn.bug, firstRound: resumes === 0 });
3652
- Object.assign(verifyFacts, { precheck: pc.failures, amendments: amendProblems, hotspots: Boolean(hotspots && hotspots.enabled !== false && Array.isArray(hotspots.files)) });
3796
+ Object.assign(verifyFacts, { precheck: pc.failures, amendments: [], hotspots: Boolean(hotspots && hotspots.enabled !== false && Array.isArray(hotspots.files)) });
3653
3797
  // #4323/#4334: a missing host tool or module, or a repro test the harness could not run, is an environment error:
3654
3798
  // never a conformance failure, never a builder resume
3655
- const envFails = pc.failures.filter((f) => ENV_CODES.includes(f.code));
3656
- const pre = [...pc.failures.filter((f) => !ENV_CODES.includes(f.code)), ...amendProblems, ...mutBlock, ...adqFail];
3799
+ // #6083: environment codes are advisory too (CI decides); only a repo that sets the code to enforce parks on them
3800
+ const preSplit = splitAdvisory([...pc.failures, ...mutBlock, ...adqFail], { enforce: enforcedKinds() });
3801
+ noteAdvisory(preSplit.advisory);
3802
+ const envFails = preSplit.block.filter((f) => ENV_CODES.includes(f.code));
3803
+ const pre = preSplit.block.filter((f) => !ENV_CODES.includes(f.code));
3657
3804
  if (pre.length) ev({ event: "PRECHECK", failures: pre.map((f) => f.code) });
3658
3805
  // #5080: the repro already passes on the base and the diff changes no source: the fix is on the base, not missing
3659
3806
  if (alreadyFixedOnBase(pre, files, IGNORE)) return { state: "already-fixed", by: "precheck", failures: pre };
3660
- // #5729: a missing /design spec or visual evidence is not a builder fix: end design.spec_required before any resume or recovery lane
3661
- if (pre.length && !recording() && specOnlyFailures(pre)) return { state: "spec-only", by: "precheck", failures: pre };
3662
3807
  if (pre.length && !recording()) return { state: "nonconforming", by: "precheck", failures: pre };
3663
3808
  // shadow: the builder's own failed checks block before any reviewer tokens are spent (#4160)
3664
3809
  const hard = recording() ? blockingOf(pre, SHADOW_PRE_BLOCKS).block : [];
@@ -3700,6 +3845,12 @@ export async function runCore(o) {
3700
3845
  const vf = await runVerifier();
3701
3846
  if (vf.length) d = { state: "nonconforming", failures: vf, by: "verifier" };
3702
3847
  }
3848
+ if (d.state === "nonconforming") { // unclog: advisory kinds from the reviewer/verifier never park a lane either
3849
+ const ds = splitAdvisory(d.failures, { enforce: enforcedKinds() });
3850
+ noteAdvisory(ds.advisory);
3851
+ if (!ds.block.length) d = { ...d, state: "conforms", failures: [] };
3852
+ else d = { ...d, failures: ds.block };
3853
+ }
3703
3854
  if (!recording()) return { ...d, by: d.by ?? "review" };
3704
3855
  // shadow: record what enforce would have done; block only on what the previous reviewer blocked on
3705
3856
  const would = d.state === "conforms" && !pre.length ? "conforms" : d.state.startsWith("review.") ? d.state : "nonconforming";
@@ -3774,7 +3925,6 @@ export async function runCore(o) {
3774
3925
  const explained = explainFailures(outcome.failures, effective); // #4265: name the unmet requirement, not only the code
3775
3926
  const list = explained.slice(0, 15).map((f) => `- ${f.code}: ${f.detail}`).join("\n");
3776
3927
  if (outcome.state === "environment") return await envNeedsHuman(outcome.failures);
3777
- 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}` });
3778
3928
  // #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
3779
3929
  // #5732: so is a repro head failure whose output carries no assertion text (an env error of the sandbox, not a red test)
3780
3930
  if (o.placement?.where === "remote" && !recover && outcome.failures?.length && outcome.failures.every((f) => (f?.kind === "validate_failed" && isEnvValidateFailure(f.output)) || (f?.kind === "repro_red_green" && f.head === "FAILED" && f.assertion === false))) {
@@ -3800,7 +3950,12 @@ export async function runCore(o) {
3800
3950
  if (outcome.state === "review.incomplete") return await needsHuman(`The conformance review was incomplete twice (a review without complete rows cannot pass); nothing merged:\n${list}`, OUTCOME_CODES.REVIEW_INCOMPLETE);
3801
3951
  if (outcome.state === "review.inconsistent") return await needsHuman(`The conformance reviewer twice said NONCONFORMING without a failing row; nothing merged.`, OUTCOME_CODES.REVIEW_INCONSISTENT);
3802
3952
  let failKey = JSON.stringify((outcome.failures ?? []).map((f) => `${f.code}|${f.detail}`).sort()); // #5644: a round that leaves the failure set unchanged ends the rounds
3803
- if (!sessionId || resumes >= (builderFixable(outcome.failures) ? reviewMaxResumes : 1) || failKey === lastFailKey) return await needsHuman(`The change does not conform to the issue and its frozen contract after ${resumes ? (resumes === 1 ? "one builder resume" : `${resumes} builder resumes`) : "the build (no session to resume)"} (${outcome.by}); nothing merged:\n${list}`, outcome.failures?.[0]?.code);
3953
+ if (!sessionId || resumes >= (builderFixable(outcome.failures) ? reviewMaxResumes : 1) || failKey === lastFailKey) {
3954
+ // #6058: a requirement with no status row was skipped after the targeted resume, not failed: a distinct park (kind requirement_no_status)
3955
+ const skippedIds = [...new Set((outcome.failures ?? []).filter((f) => f?.kind === "requirement_no_status" && f.reqId).map((f) => f.reqId))];
3956
+ if (skippedIds.length) return await needsHuman(`The builder did not address ${skippedIds.join(", ")}: no status row in ${RESULT_FILE}${resumes ? ` after ${resumes === 1 ? "a targeted resume" : `${resumes} targeted resumes`} naming ${skippedIds.length === 1 ? "it" : "them"}` : " (no session to resume)"} (skipped, not a failing check); nothing merged:\n${list}`, outcome.failures?.[0]?.code, { kind: "requirement_no_status", requirements: skippedIds });
3957
+ return await needsHuman(`The change does not conform to the issue and its frozen contract after ${resumes ? (resumes === 1 ? "one builder resume" : `${resumes} builder resumes`) : "the build (no session to resume)"} (${outcome.by}); nothing merged:\n${list}`, outcome.failures?.[0]?.code);
3958
+ }
3804
3959
  lastFailKey = failKey;
3805
3960
  resumes++;
3806
3961
  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})`);
@@ -4052,7 +4207,8 @@ export async function runCore(o) {
4052
4207
  await reportVerify();
4053
4208
  syncRow.push(`${trigger}: ${clean ? "clean" : "conflicts"} (${baseSha})`);
4054
4209
  T.baseSync = [`${syncs} sync(s)`, syncRow.join("; ")];
4055
- await post("FORGE:BASE_SYNC", `## Base Sync\n**Trigger:** ${trigger}\n**Base merged:** \`${base}\` at \`${baseSha}\`\n**Result:** ${clean ? "clean merge" : `conflicts in ${files.map((f) => `\`${f}\``).join(", ") || "unknown files"}`}\n**Resolution:** ${how}\n**Tests run:** ${tests}\n**Re-review:** ${rereview}\n**New head:** \`${localHead.slice(0, 12)}\``);
4210
+ try { await post("FORGE:BASE_SYNC", `## Base Sync\n**Trigger:** ${trigger}\n**Base merged:** \`${base}\` at \`${baseSha}\`\n**Result:** ${clean ? "clean merge" : `conflicts in ${files.map((f) => `\`${f}\``).join(", ") || "unknown files"}`}\n**Resolution:** ${how}\n**Tests run:** ${tests}\n**Re-review:** ${rereview}\n**New head:** \`${localHead.slice(0, 12)}\``); } // #5898: the merge is done; a failed status comment is an anomaly, never an engine-error (as #5020 for FORGE:AMENDMENT)
4211
+ catch (e) { T.anomalies.push(`FORGE:BASE_SYNC comment not posted: ${String(e?.message ?? e).slice(0, 160)}`); }
4056
4212
  return null;
4057
4213
  }
4058
4214
  const NR_TESTS = "not reported";
@@ -4114,7 +4270,7 @@ export async function runCore(o) {
4114
4270
  }
4115
4271
  lost = lost.filter((id) => !ran?.[id]);
4116
4272
  }
4117
- 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);
4273
+ if (lost.length) T.anomalies.push(`Validate result(s) ${lost.join(", ")} missing after a CI fix round on PR #${pr}: recorded, the lane continues (CI is the judge; #6083)`);
4118
4274
  const rv = await doReview(); // never merge an unreviewed head
4119
4275
  if (!rv) return await needsHuman("Reviewer returned no parseable verdict after a CI fix round.", OUTCOME_CODES.REVIEW_NO_VERDICT);
4120
4276
  if (rv.env) return await envNeedsHuman(rv.env);
@@ -4415,6 +4571,7 @@ export async function runCore(o) {
4415
4571
  }
4416
4572
  T.merge = [policyText, `merged at ${localHead.slice(0, 12)}`];
4417
4573
  laneGuard(resumed?.base ?? lane, "merge");
4574
+ await suspensionGuard("merge"); // #6008
4418
4575
  try {
4419
4576
  phaseLedger.enter("merge");
4420
4577
  await ghc(["pr", "merge", String(pr), "-R", repo, "--merge", "--match-head-commit", localHead]);