forgedock 1.67.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 (140) hide show
  1. package/bin/config-schema.mjs +1 -0
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine-cli.mjs +99 -12
  4. package/bin/engine.mjs +10 -0
  5. package/bin/forgedock.mjs +17 -1
  6. package/bin/help-text.mjs +1 -0
  7. package/bin/lean/admission.mjs +21 -0
  8. package/bin/lean/admission.test.mjs +30 -0
  9. package/bin/lean/advisory.test.mjs +25 -10
  10. package/bin/lean/amendment-schema.mjs +3 -4
  11. package/bin/lean/attempts.mjs +34 -31
  12. package/bin/lean/attempts.test.mjs +33 -19
  13. package/bin/lean/basered.mjs +26 -0
  14. package/bin/lean/batch-health.mjs +17 -12
  15. package/bin/lean/batch-health.test.mjs +39 -11
  16. package/bin/lean/batch.test.mjs +51 -2
  17. package/bin/lean/ci-gate.mjs +2 -90
  18. package/bin/lean/ci-gate.test.mjs +1 -127
  19. package/bin/lean/ci-precheck.mjs +25 -8
  20. package/bin/lean/ci-precheck.test.mjs +24 -0
  21. package/bin/lean/clear-breaker.test.mjs +4 -3
  22. package/bin/lean/commentstate.mjs +10 -5
  23. package/bin/lean/commentstate.test.mjs +12 -1
  24. package/bin/lean/conformance.e2e.test.mjs +9 -6
  25. package/bin/lean/conformance.mjs +56 -196
  26. package/bin/lean/conformance.test.mjs +40 -376
  27. package/bin/lean/depcache.mjs +100 -10
  28. package/bin/lean/depcache.test.mjs +105 -0
  29. package/bin/lean/docsgate.mjs +0 -32
  30. package/bin/lean/docsgate.test.mjs +2 -23
  31. package/bin/lean/effects-cap.test.mjs +9 -1
  32. package/bin/lean/effects-killtree.test.mjs +35 -0
  33. package/bin/lean/effects.mjs +42 -24
  34. package/bin/lean/engine-readmit.test.mjs +35 -0
  35. package/bin/lean/envgap.mjs +93 -0
  36. package/bin/lean/envgap.test.mjs +53 -0
  37. package/bin/lean/execution.mjs +10 -4
  38. package/bin/lean/execution.test.mjs +12 -0
  39. package/bin/lean/failure-census.mjs +170 -0
  40. package/bin/lean/failure-census.test.mjs +59 -0
  41. package/bin/lean/guardgate.test.mjs +2 -3
  42. package/bin/lean/heavy.mjs +33 -4
  43. package/bin/lean/heavy.test.mjs +38 -6
  44. package/bin/lean/hotarea.mjs +0 -36
  45. package/bin/lean/hotarea.test.mjs +1 -22
  46. package/bin/lean/issuewatch-verify.mjs +19 -4
  47. package/bin/lean/issuewatch.mjs +21 -4
  48. package/bin/lean/issuewatch.test.mjs +48 -1
  49. package/bin/lean/lane-audit-gap.mjs +66 -0
  50. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  51. package/bin/lean/lane-audit-llm.mjs +5 -0
  52. package/bin/lean/lane-audit-query.mjs +47 -0
  53. package/bin/lean/lane-audit-query.test.mjs +44 -0
  54. package/bin/lean/lane-audit-signatures.mjs +33 -0
  55. package/bin/lean/lane-audit.mjs +110 -0
  56. package/bin/lean/lane-audit.test.mjs +97 -0
  57. package/bin/lean/lane-recovery.test.mjs +33 -0
  58. package/bin/lean/lanecheck.mjs +5 -3
  59. package/bin/lean/lanecheck.test.mjs +6 -0
  60. package/bin/lean/lean.mjs +206 -148
  61. package/bin/lean/lean.test.mjs +406 -190
  62. package/bin/lean/limits.mjs +17 -0
  63. package/bin/lean/limits.test.mjs +15 -1
  64. package/bin/lean/live-execution.mjs +21 -2
  65. package/bin/lean/live-execution.test.mjs +39 -0
  66. package/bin/lean/orchestrate-attempts.test.mjs +17 -9
  67. package/bin/lean/orchestrate-envhold.test.mjs +47 -0
  68. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  69. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  70. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  71. package/bin/lean/orchestrate-pause.test.mjs +53 -1
  72. package/bin/lean/orchestrate-reconcile.test.mjs +17 -0
  73. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  74. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  75. package/bin/lean/orchestrate.mjs +188 -33
  76. package/bin/lean/postdeploy-check.test.mjs +1 -3
  77. package/bin/lean/precheck.mjs +20 -0
  78. package/bin/lean/preflight.mjs +100 -11
  79. package/bin/lean/preflight.test.mjs +44 -4
  80. package/bin/lean/prompts.mjs +10 -21
  81. package/bin/lean/recurrence.mjs +6 -148
  82. package/bin/lean/recurrence.test.mjs +11 -147
  83. package/bin/lean/release-flakes.mjs +14 -2
  84. package/bin/lean/release-flakes.test.mjs +17 -1
  85. package/bin/lean/release-ledger.mjs +19 -1
  86. package/bin/lean/release-ledger.test.mjs +23 -0
  87. package/bin/lean/release-preflight.mjs +28 -0
  88. package/bin/lean/release-preflight.test.mjs +42 -1
  89. package/bin/lean/release-review.mjs +40 -5
  90. package/bin/lean/release-review.test.mjs +43 -2
  91. package/bin/lean/release.mjs +43 -14
  92. package/bin/lean/release.test.mjs +32 -0
  93. package/bin/lean/retry.mjs +1 -1
  94. package/bin/lean/retry.test.mjs +6 -1
  95. package/bin/lean/rotator.mjs +9 -0
  96. package/bin/lean/rotator.test.mjs +11 -1
  97. package/bin/lean/sandbox-remote.mjs +16 -9
  98. package/bin/lean/schedd.mjs +11 -6
  99. package/bin/lean/schedd.test.mjs +65 -5
  100. package/bin/lean/selfreview.mjs +1 -1
  101. package/bin/lean/statuscomment.mjs +4 -1
  102. package/bin/lean/validate-catalog.mjs +108 -0
  103. package/bin/lean/validate-catalog.test.mjs +46 -1
  104. package/bin/lean/verify.mjs +1 -1
  105. package/bin/pool/affinity.test.mjs +91 -0
  106. package/bin/pool/agent.mjs +143 -9
  107. package/bin/pool/cache-sweep.mjs +31 -10
  108. package/bin/pool/ci-autoscale.mjs +160 -0
  109. package/bin/pool/cli.mjs +37 -8
  110. package/bin/pool/docker.mjs +3 -0
  111. package/bin/pool/engine-placement.test.mjs +94 -0
  112. package/bin/pool/lane-target.mjs +41 -0
  113. package/bin/pool/lane-tools.mjs +7 -2
  114. package/bin/pool/lane-tools.test.mjs +9 -0
  115. package/bin/pool/mirror-seed.mjs +15 -11
  116. package/bin/pool/router.mjs +88 -32
  117. package/bin/pool/version.mjs +29 -2
  118. package/bin/review-staging.mjs +11 -3
  119. package/bin/runner.mjs +59 -11
  120. package/bin/stats/release.mjs +7 -0
  121. package/bin/stats/release.test.mjs +20 -0
  122. package/bin/stats/scorecard.mjs +187 -0
  123. package/bin/stats/scorecard.test.mjs +89 -0
  124. package/docs/CONFIG.md +41 -0
  125. package/docs/OUTCOME-CODES.md +1 -0
  126. package/docs/STATS.md +17 -0
  127. package/package.json +1 -1
  128. package/pool/image/Dockerfile +14 -2
  129. package/pool/image/manifest.json +25 -0
  130. package/pool/image/mirror.sh +11 -2
  131. package/pool/install/install-agent.ps1 +11 -4
  132. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  133. package/scripts/ci-local/cli.mjs +1 -1
  134. package/scripts/ci-local/plan.mjs +3 -2
  135. package/scripts/ci-local.test.sh +11 -0
  136. package/scripts/failure-census.mjs +67 -0
  137. package/scripts/review-finalize.sh +5 -5
  138. package/scripts/review-finalize.test.sh +8 -1
  139. package/scripts/verify-phase-trail.sh +11 -0
  140. package/scripts/verify-phase-trail.test.sh +9 -0
package/bin/lean/lean.mjs CHANGED
@@ -23,13 +23,12 @@ 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, designDemanded } 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, splitAdvisory, 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 { validateAmendments } from "./attempts.mjs";
32
- import { writeStatus, postUpsert, postKeyed, isKeyedPost, isStatusPost, isUpsertPost, hasSection, clearPipelineLabels, IN_PLACE_MARKERS, commentId } from "./statuscomment.mjs";
31
+ import { writeStatus, postUpsert, postKeyed, isKeyedPost, isStatusPost, isUpsertPost, hasSection, clearPipelineLabels, IN_PLACE_MARKERS, commentId, contractKey } from "./statuscomment.mjs";
33
32
  import { decidePost } from "./commentstate.mjs"; // #5979
34
33
  import { repeatSignature, countIdentical, shouldPark, summaryComment } from "./failure-stop.mjs"; // #5979
35
34
  import { checksAt, mergeCheckEntries, CHECKS_FILE } from "./postdeploy-check.mjs";
@@ -37,7 +36,7 @@ import { matchBaselines, baselineFailures, foldRegression } from "./baselines.mj
37
36
  import { readRollouts, detectNewOffKeys, rolloutModes, liveDeferralBlocks } from "./activation.mjs";
38
37
  import { toolMisses } from "./toolplace.mjs";
39
38
  import { hasRecipe, installLaneTools, genericInstallCommands, RECIPES } from "../pool/lane-tools.mjs";
40
- import { testRunnerProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract, declaredEnv, depInstallFailures, toolMissingInstalls, testRunSummary, projectBinDirs, withLocalBins, manifestDepOwner } from "./preflight.mjs";
39
+ import { testRunnerProblems, hostOnlyProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract, declaredEnv, depInstallFailures, toolMissingInstalls, testRunSummary, projectBinDirs, withLocalBins, manifestDepOwner, collectOnlyCommand, collectImportMiss, contractCommands } from "./preflight.mjs";
41
40
  import { resolveLane, isDefaultLane, isShippedLane, DEFAULT_STAGING_BRANCH } from "./lane.mjs";
42
41
  import { splitGate, rationaleLine } from "./decompose.mjs";
43
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";
@@ -49,12 +48,13 @@ import { prepareToolchain } from "./toolchain.mjs";
49
48
  import { toolStats } from "./toolstats.mjs";
50
49
  import { readTestMap, readTestMapAtRef, selectCommands, mergeChecks, factsPath, TEST_MAP_FILE } from "./testmap.mjs";
51
50
  import { deriveCiPrecheck, ciPrecheckOutcome, parseCiPrecheckConfig } from "./ci-precheck.mjs";
52
- 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";
53
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";
54
53
  import { renderInvestigation, renderImplementation, renderReview, renderPrBody, renderTrajectory, renderContract, renderAmendments, renderShadowReview, parseContractComment, parseAmendmentsComment, contractJson, capComment, sanitizeMd, MAX_COMMENT_CHARS, recoveryEvidence } from "./render.mjs";
55
54
  import { parseVerifierConfig, pickVerifierModel, changedSymbols, callersOf, verifierBudget, verifierPrompt, parseVerifierFindings, findingsToFailures, renderVerifierNote, VERIFIER_SYSTEM } from "./verifier.mjs";
56
55
  import { computeTrigger, riskPathHits, TRIGGER_MODES, pathDomains, parseEnforceDomains } from "./review-trigger.mjs";
57
56
  import { hostCapabilityBlock, contractHostNeeds } from "./execution.mjs";
57
+ import { envGapBlockCode, toolGapFailures, packageDirsMissingDeps, failureOutsideDiff } from "./envgap.mjs"; // #6106
58
58
 
59
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;
60
60
  /** #4685: true when a builder's block summary names a missing tool or module (environment), not a credential. */
@@ -68,16 +68,14 @@ export function contractSelfCorrectable(problems) {
68
68
  export function missingToolBlock(summary) { return MISSING_TOOL_RE.test(String(summary ?? "")); }
69
69
  import { reserveForBuild, revalidate } from "./seqreserve.mjs";
70
70
  import { patchEcho, mutationsOf, runReproMutations, classifyRepro } from "./reproquality.mjs";
71
- 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";
72
72
  import { postMergeCommands } from "./postmerge.mjs";
73
- import { classifyBaseRed, attribute as attributeBaseRed, runOnBase, reportBaseRed, recordBaseVerdict, bypassesGuard } from "./basered.mjs"; // #5239
73
+ import { reportParityGaps, classifyBaseRed, diffTouchesGuard, attribute as attributeBaseRed, runOnBase, reportBaseRed, recordBaseVerdict, bypassesGuard } from "./basered.mjs"; // #5239
74
74
  import { guardAfterMerge, withHistoryRows } from "./guards.mjs";
75
75
  import { parseProdParity, prodParityFailures as prodParityOf } from "./prodparity.mjs";
76
76
  import { routePathsFromFiles, routeReachabilityFailures } from "./routecheck.mjs";
77
- import { docsFailures } from "./docsgate.mjs";
78
77
  import { outcomeEvidenceFailures, rawChecksAt } from "./outcomeevidence.mjs";
79
- import { ciBudgetFailures, parseCiBudget } from "./ci-gate.mjs";
80
- import { pageFailures, designSpecApproved, designLabelApproved, specOnlyFailures, pageFiles, designOnlyFiles } from "./pagegate.mjs"; // #5428
78
+ import { pageFailures, designSpecApproved, designLabelApproved, pageFiles, designOnlyFiles } from "./pagegate.mjs"; // #5428
81
79
  import { changedRoutes, captureVisualCheck, publishToRef, visualMarkdown } from "./page-capture.mjs"; // #5770
82
80
  import { uiBuildRule, uiIssue, uiChanged } from "./ui-quality.mjs"; // #5330
83
81
  import { designGate, designGateNote, designFailures, specApproved as designSpecOk } from "./design-gate.mjs"; // #5330
@@ -127,8 +125,11 @@ import { ensureSignedOff, salvageBranch, dropSalvageTracking } from "./signoff.m
127
125
  import { reconcileCheckpoints } from "./checkpoint-reconcile.mjs";
128
126
  import { guardStagedDeletions, deletionEvidence, maxForeignDeletions } from "./delguard.mjs";
129
127
  import { createLedger, flattenPhases, overheadStats } from "./phaseledger.mjs";
130
- import { DEFAULT_CATALOG_SOURCES, deriveCatalog, mergeRecipes, rewriteMissed, isDriftFailure, rewriteSubprojectVenv } from "./validate-catalog.mjs";
128
+ import { DEFAULT_CATALOG_SOURCES, deriveCatalog, mergeRecipes, rewriteMissed, isDriftFailure, rewriteSubprojectVenv, deriveTestEnvMap, rewriteToCiEnv } from "./validate-catalog.mjs";
131
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";
132
133
  import { planStale, stackedBaseBlock, validStackedOn, cascadeDecision, invalidatedChecks } from "./stacking.mjs";
133
134
  import { runLightStep, runLightTests, lightBuildPrompt, upgradeNote, renderLiteReceipt } from "./lightlane.mjs";
134
135
 
@@ -164,6 +165,9 @@ export function builderFixable(failures) {
164
165
  const AUTH_RETRY_SECONDS = 900;
165
166
  /** #5762: retry-in for a `backend.cli_failed` deferral (transient, not an account condition). */
166
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.";
167
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. */
168
172
  export function laneAccountNumber(env = process.env, account = null) {
169
173
  if (account != null && /^\d+$/.test(String(account))) return String(account);
@@ -196,7 +200,7 @@ const SHADOW_BLOCKS = [OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, OUTCOME_CODES.CO
196
200
  * not done, an invalid amendment) or conformance.regression, the same codes a review blocks on, and unexempted growth of an
197
201
  * over-threshold file (maintenance.hotspot_growth, forge#4195). Scope creep stays recorded-only.
198
202
  */
199
- 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];
200
204
  /** #4395: cap on the engine.lane_instructions file; a larger one is not slim and falls back to CLAUDE.md. */
201
205
  export const LANE_INSTRUCTIONS_MAX_BYTES = 16384;
202
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. */
@@ -271,7 +275,7 @@ export function classifyBlock(result, issue) {
271
275
  if (b.kind === "human") {
272
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
273
277
  if (b.why === "product-decision" && describesUnrunnableCommand(`${result?.summary ?? ""} ${b.reason ?? ""} ${b.detail ?? ""}`)) { // #4857
274
- 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" };
275
279
  }
276
280
  return HUMAN_BLOCK_REASONS.includes(b.why) ? { kind: "human", why: b.why, ...(remainder.length ? { remainder } : {}) }
277
281
  : { kind: "untyped", problem: `"${String(b.why ?? "").slice(0, 80)}" is not a human-only reason (${HUMAN_BLOCK_REASONS.join(", ")})` };
@@ -468,6 +472,7 @@ export async function runCore(o) {
468
472
  const localPosts = []; // #5979: comments this lane created, so a second post in the same run sees them
469
473
  const allComments = () => [...(iss?.comments ?? []), ...localPosts];
470
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
471
476
  const post = async (marker, body, on = issue) => {
472
477
  if (on === issue && isStatusPost(marker)) { // machine-state markers: a section of the one status comment, not a comment of their own
473
478
  try {
@@ -481,14 +486,15 @@ export async function runCore(o) {
481
486
  if (on === issue && isUpsertPost(marker)) { // one comment edited in place across requeues (the marker still leads the body)
482
487
  return postUpsert({ gh: ghw, repo, issue: on, markers: marker, body, comments: iss?.comments, cap: capComment });
483
488
  }
484
- if (on === issue && isKeyedPost(marker)) { // #5986: one comment per (kind, content hash) with a repeat counter; at 12 engine comments edit in place only
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
485
490
  return postKeyed({ gh: ghw, repo, issue: on, marker: Array.isArray(marker) ? marker[0] : marker, body, cap: capComment });
486
491
  }
487
492
  const marks = (Array.isArray(marker) ? marker : [marker]).map((m) => `<!-- ${m} -->`).join("\n");
488
- const full = capComment(`${marks}\n${body}`);
489
493
  const first = Array.isArray(marker) ? marker[0] : marker;
490
- if (on === issue && IN_PLACE_MARKERS.includes(first)) { // #5979: re-post only on a state change; FACTS and DEPENDENCY are edited in place
491
- const d = decidePost({ marker: first, body: full, comments: allComments(), trusted: (c) => c?.__mine === true || isTrustedIssueComment(c) });
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) });
492
498
  if (d.action === "skip") return d.prior.url ?? null;
493
499
  const id = d.action === "patch" ? commentId(d.prior) : null;
494
500
  if (id) {
@@ -608,6 +614,7 @@ export async function runCore(o) {
608
614
  }
609
615
  let sparse = null; // #4221: {excluded, maxKb} when the lane worktree is a sparse checkout; null leaves prompts unchanged
610
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)
611
618
  let laneProfile = { name: process.env.FORGEDOCK_FULL_SESSION === "1" ? "full" : "memory-off", text: null };
612
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
613
620
  // #4169: heavy steps take a host semaphore slot (io.heavy); LLM phases are not gated. `heavyEnv` puts the heavy shims on
@@ -616,7 +623,7 @@ export async function runCore(o) {
616
623
  let heavyEnv = null, heavyWaitsFile = null, heavyQueueMax = 0, stage = "plan";
617
624
  let seqBuildNote = ""; // #5235: numbers reserved for this lane at build start (prompt paragraph)
618
625
  const recCfg = parseRecurrenceConfig(o.recurrenceConfig); // #5751: forge.yaml recurrence: (absent: mode on, threshold 2, no hot areas or counters)
619
- 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
620
627
  let seqLease = null; // #4386: the host sequence lease, held from the merge-gate renumber through the merge
621
628
  const waits = {};
622
629
  const followupsFiled = []; // #5078: {issue, class, count} per tracking issue this lane filed into, for the batch report
@@ -772,7 +779,7 @@ export async function runCore(o) {
772
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
773
780
  ...(extra.pr ? { pr: extra.pr } : {}), ...(milestone ? { milestone } : {}), ...(verifiedLane != null ? { verified: verifiedLane } : {}),
774
781
  ...(reproQ ? { repro_quality: reproQ } : {}), conformance_mode: conformance === "enforce" || riskEnforced ? "enforce" : "shadow", ...(shadowWould ? { shadow_would: shadowWould } : {}), ...(firstReview ? { first_review: firstReview } : {}), ...(adequacyTel ?? {}),
775
- ...(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() } : {}),
776
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
777
784
  Object.assign(term, overheadStats(null, term.wall_ms, term.model_ms)); // fixed_overhead_ms + model_share for the SLO
778
785
  const phases = phaseLedger.snapshot(); // #4908: run log gets the nested ledger, FORGE:TELEMETRY the flattened scalars
@@ -788,6 +795,13 @@ export async function runCore(o) {
788
795
  await ghc(["issue", "edit", String(issue), "-R", repo, "--add-label", "needs-human"]);
789
796
  } catch { /* best effort */ }
790
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
+ }
791
805
  if (["needs-human", "engine-error", "dependency-open", "dependency-blocked", "dependency-unreadable", "decomposed", "host-task"].includes(reason)) {
792
806
  const wf = ["investigating", "building", "in-review"].map((x) => `workflow:${x}`).join(",");
793
807
  try { await ghc(["issue", "edit", String(issue), "-R", repo, "--remove-label", wf]); } catch { /* best effort */ }
@@ -805,7 +819,7 @@ export async function runCore(o) {
805
819
  if (deferTail) postRun.add("teardown", () => teardown(reason, extra)); // last: the structure delta and guard read the worktree
806
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
807
821
  await releaseLease(reason, code, extra.mergedTo ?? null);
808
- 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(),
809
823
  ...(laneHead && reason !== "merged" ? { laneHead: { ...laneHead } } : {}), light, ...(lightVerdict ? { light_eligibility: lightVerdict } : {}), ...(lightUpgrade ? { light_upgrade: lightUpgrade } : {}), // #4453
810
824
  ...(Object.keys(waits).length ? { waits: { ...waits } } : {}), ...(followupsFiled.length ? { followups: followupsFiled.map((f) => ({ ...f })) } : {}), ...(pendingRecord().length ? { pendingFollowups: pendingRecord() } : {}), ...(heavyQueueMax ? { heavyQueueMax } : {}), ...(precheckRan ? { precheckMs, precheckDeferred } : {}),
811
825
  ...(firstPassOf(builderTriggers) != null ? { firstPass: firstPassOf(builderTriggers) } : {}), ...(tb.record() ? { turns: tb.record() } : {}), context: { ...ctxStats, cost_usd: impl.cost }, // #4392, #5829
@@ -968,7 +982,7 @@ export async function runCore(o) {
968
982
  const set = String(process.env.FORGE_HOST_PARALLELISM ?? "").trim();
969
983
  if (/^\d+$/.test(set) && Number(set) > 0) return set;
970
984
  if (!io.host?.cores) return null;
971
- 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; }
972
986
  }
973
987
  /**
974
988
  * #4325: the lane env every engine-run command shares with the builder: shared package-manager stores (#4220), the run
@@ -1221,7 +1235,7 @@ export async function runCore(o) {
1221
1235
  let planSession = null;
1222
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 ?? "" }; };
1223
1237
  async function builder(n, prompt, resume, live = false, restart = implementRestart, opts = {}) {
1224
- let timeoutRetries = 0, contextRestarts = 0, p = prompt;
1238
+ let timeoutRetries = 0, contextRestarts = 0, apiResumes = 0, p = prompt;
1225
1239
  opts = { ...opts };
1226
1240
  const ceiled = laneCeiling > 0 && !opts.noCeiling && !UNCEILED.includes(opts.trigger); // #5346: per-size ceiling; noCeiling = a restart is certain
1227
1241
  for (;;) {
@@ -1241,6 +1255,20 @@ export async function runCore(o) {
1241
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);
1242
1256
  return await budgetWrapup(n, opts);
1243
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
+ }
1244
1272
  if (e?.code === "CLI_CONTEXT") {
1245
1273
  contextRestarts++; ctxStats.restarts++;
1246
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 });
@@ -1483,6 +1511,10 @@ export async function runCore(o) {
1483
1511
  // #4685: a tool the sandbox lacks (docker, promtool, a Python module) is an environment gap the host recovers, never a credential.
1484
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);
1485
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
+ }
1486
1518
  if (b.kind === "human") {
1487
1519
  // #4730: the agent-doable remainder is re-queued as its own lane; only the owner step keeps needs-human.
1488
1520
  let note = "";
@@ -2192,6 +2224,11 @@ export async function runCore(o) {
2192
2224
  const vr = rewriteSubprojectVenv(r.contract, freezeTracked, (rel) => existsSync(join(wt, rel))); // #5683
2193
2225
  r.contract = vr.contract;
2194
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}\``);
2195
2232
  r.contract = foldRegression(r.contract); // #5448: the blast-radius regression set runs as validate G# entries
2196
2233
  const e = autoPostDeployE2e(r.contract); // #5468: production-only e2e/manual rows become post-deploy with a generated check
2197
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)"}`); }
@@ -2223,6 +2260,17 @@ export async function runCore(o) {
2223
2260
  for (const v of Array.isArray(contract.validate) ? contract.validate : []) {
2224
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" });
2225
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
+ }
2226
2274
  if (io.preflightRun) {
2227
2275
  const skipIds = [...new Set(misses.flatMap((m) => m.ids))];
2228
2276
  const run = (a) => heavyStep("precheck", () => io.preflightRun({ ...a, cwd: wt }));
@@ -2241,19 +2289,20 @@ export async function runCore(o) {
2241
2289
  let out = "";
2242
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; }
2243
2291
  let found = null;
2244
- 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
2245
2293
  for (const l of out.split("\n")) {
2246
2294
  let c; try { c = JSON.parse(l); } catch { continue; }
2247
2295
  if (!isTrustedComment(c)) continue;
2248
2296
  const b = String(c?.body ?? "");
2249
2297
  const am = parseAmendmentsComment(b);
2250
2298
  if (am) amendLog.push(am);
2299
+ if (b.includes("rewrite-validate")) rewritePosted.push(b); // #5920: audit comments already posted
2251
2300
  if (!b.startsWith("<!-- FORGE:CONTRACT -->")) { if (found && b.trim() && !b.trimStart().startsWith("<!-- FORGE:")) found.humanAfter = true; continue; }
2252
2301
  const fc = parseContractComment(b);
2253
2302
  if (fc && contractHash(fc.text) === fc.hash) found = { ...fc, humanAfter: false };
2254
2303
  }
2255
2304
  if (found) {
2256
- const seen = new Set(); found.amendments = [];
2305
+ const seen = new Set(); found.amendments = []; found.rewritePosted = rewritePosted;
2257
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); } }
2258
2307
  }
2259
2308
  return found;
@@ -2318,13 +2367,6 @@ export async function runCore(o) {
2318
2367
  let frozen = null, hash = null, planned = false, files = [], split = null, planMisses = null; // planMisses (#5331): validate preflight misses from this run
2319
2368
  /** #5804: paths that place the change: the issue's named paths, then the frozen deliverables once they exist */
2320
2369
  const toolFiles = () => [...namedPaths(iss?.body ?? ""), ...(frozen?.deliverables ?? []).map((d) => d?.path)].filter(Boolean);
2321
- const impliedDocs = []; // add-deliverable amendments for doc edits the docs-freshness rule demanded (docs round, CI fix round)
2322
- /** Doc files a fix round added to satisfy the freshness rule: recorded only when the rule failed before and passes after. */
2323
- async function noteFreshnessDocs(before, wasFailing) {
2324
- if (!io.docsFreshness || !wasFailing) return;
2325
- const nowOk = (await io.docsFreshness({ cwd: wt, base }).catch(() => null))?.ok === true;
2326
- for (const a of impliedDocDeliverables({ before, after: await changedFiles(), contract: frozen, wasFailing, nowOk })) if (!impliedDocs.some((x) => x.path === a.path)) impliedDocs.push(a);
2327
- }
2328
2370
  let priorAmendments = []; // #4899: accepted amendments recovered with the frozen contract
2329
2371
  const pendingPits = []; // #4375: rework rounds whose gate has not passed again yet
2330
2372
  async function notePitfall(trigger, text) {
@@ -2408,7 +2450,7 @@ export async function runCore(o) {
2408
2450
  { const f = await gateSetup(); if (f) return f; }
2409
2451
  files = await changedFiles();
2410
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: [] };
2411
- hash = contractHash(contractJson(frozen));
2453
+ hash = contractHash(contractJson(frozen)); postContractHash = hash;
2412
2454
  T.decisions.push(`Adopted PR #${adoptPr.number}: ${files.length} changed file(s) go to review as built`);
2413
2455
  } else if (isSplit) {
2414
2456
  // ---- 3'. refactor:split (#4211): deterministic move + proof replaces the builder; no builder session exists ----
@@ -2435,7 +2477,22 @@ export async function runCore(o) {
2435
2477
  T.decisions.push(`Rerun: frozen contract ${fc.hash} is stale (${stale}); re-planning`);
2436
2478
  } else {
2437
2479
  frozen = fc.contract; hash = fc.hash; priorAmendments = fc.amendments ?? []; T.decisions.push(`Rerun: frozen contract ${hash} recovered from the issue`);
2438
- 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
+ }
2439
2496
  const ad = applyRequirementDecisions(frozen, trustedComments); // #5547: a structured operator decision amends the frozen row
2440
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`); }
2441
2498
  }
@@ -2461,15 +2518,6 @@ export async function runCore(o) {
2461
2518
  if (!planOnly) await label("building"); // #5831
2462
2519
  // #4450: the light lane (lean.light mode on, eligible, fresh lane): one builder session, derived contract, or an upgrade
2463
2520
  const waitMs = Math.max(0, Number(contextWaitSeconds) || 0) * 1000, tHot = now();
2464
- 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
2465
- 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, createdAt: iss.createdAt ?? null }).catch(() => null);
2466
- if (recurrence?.recurs) {
2467
- recurrence.demanded = designDemanded(allComments()); // #5979: the design block is demanded once
2468
- ev({ event: "RECURRENCE", count: recurrence.count, threshold: recurrence.threshold, fixes: recurrence.evidence.map((e) => e.number), reason: recurrence.reason });
2469
- T.decisions.push(`Design lane (#5751): ${recurrence.reason}`);
2470
- 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 */ }
2471
- }
2472
- }
2473
2521
  await takeHotAreas(namedPaths(iss.body ?? "")); // #5751
2474
2522
  const hotR = await within(hotspotsOf({ paths: namedPaths(iss.body ?? "") }), waitMs); // #5209: churn and hotspot signals for eligibility; #5434: bounded, overlaps the install
2475
2523
  const hotLate = hotR === TIMED_OUT, namedHot = hotLate ? null : hotR;
@@ -2480,9 +2528,8 @@ export async function runCore(o) {
2480
2528
  lightVerdict = elig.verdict;
2481
2529
  if (elig.mode !== "off") T.decisions.push(`Light lane ${elig.mode}: ${elig.verdict}${elig.reasons.length ? ` (${elig.reasons.map((x) => x.code).join(", ")})` : ""}`);
2482
2530
  // #4451: a light try skips the hotspots and the context pack; an upgrade computes them before the plan call
2483
- 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
2484
- const lightTry = !planOnly && ffSource === "text" && elig.light && !hotLate && !frozen && !resumed && !salvagedRef && !recover && !recurrence?.recurs; // #5751: a recurrence never takes the light lane
2485
- 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;
2486
2533
  if (!lightTry) hotFacts = namedHot; // #4451: a light try still gives its builder no hotspot facts
2487
2534
  enumList = io.enumeratingTests ? ((await within(io.enumeratingTests({ cwd: wt, paths: namedPaths(iss.body ?? "") }), waitMs)) ?? []) : [];
2488
2535
  if (enumList === TIMED_OUT) enumList = [];
@@ -2497,7 +2544,7 @@ export async function runCore(o) {
2497
2544
  if (!depsDone && left > 0) await within(depsP, left);
2498
2545
  const f = await toolStop(toolFiles()); if (f) return f;
2499
2546
  }
2500
- 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) : "");
2501
2548
  let lightDone = false, lightCommits = false;
2502
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
2503
2550
  const ffTriageOf = async (raw) => parseTriage(raw, await io.fs.read(`${wt}/${INVESTIGATION_FILE}`).catch(() => ""));
@@ -2530,6 +2577,7 @@ export async function runCore(o) {
2530
2577
  stage = "plan"; liveKeys = ["investigation"]; result = (await readResult()) ?? result;
2531
2578
  if (!lr.upgrade) {
2532
2579
  lightDone = true; light = true; frozen = historyRows(lr.contract); hash = contractHash(contractJson(frozen));
2580
+ postContractHash = hash;
2533
2581
  let body = renderContract(frozen, hash, { scope: scopeHash, base: lane });
2534
2582
  if (body.length > MAX_COMMENT_CHARS - 500) body = renderContract(frozen, hash, { compact: true, scope: scopeHash, base: lane });
2535
2583
  await post(["FORGE:CONTRACT", "FORGE:PLAN"], body);
@@ -2608,8 +2656,7 @@ export async function runCore(o) {
2608
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);
2609
2657
  const wtRead = (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } }; // #5585: noindex pages are not public
2610
2658
  const freezeBase = pagesConfig ? String(await git(["ls-tree", "-r", "-z", "--name-only", base]).catch(() => "")).split("\0").filter(Boolean) : null; // #5648
2611
- 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
2612
- 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 });
2613
2660
  const found0 = await preflightValidates(contract); // #4328: validate commands the host cannot run share the one correction
2614
2661
  let missed = found0;
2615
2662
  // #5653: an unrunnable command is rewritten from the repo catalogue (forge.yaml recipes first, then CI-derived) before any builder correction
@@ -2619,7 +2666,7 @@ export async function runCore(o) {
2619
2666
  if (rw.applied.length) {
2620
2667
  contract = snapContract(rw.contract);
2621
2668
  for (const x of rw.applied) T.decisions.push(`validate catalogue rewrote unrunnable ${x.id}: \`${x.from}\` -> \`${x.to}\``);
2622
- 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 });
2623
2670
  missed = await preflightValidates(contract);
2624
2671
  }
2625
2672
  }
@@ -2631,10 +2678,11 @@ export async function runCore(o) {
2631
2678
  await persistGenChecks();
2632
2679
  await refreshIssue("contract validation");
2633
2680
  contract = snapContract(contract);
2634
- 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 });
2635
2682
  };
2636
- if ((!vc.ok || missed.length || testRunnerProblems(contract, testRunners).length) && sessionId) {
2637
- 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");
2638
2686
  if (missed.length) misses = await preflightValidates(contract);
2639
2687
  }
2640
2688
  // #5623: builder-correctable contract problems get up to contractMaxCorrections rounds (default 3), each with only the
@@ -2657,6 +2705,7 @@ export async function runCore(o) {
2657
2705
  }
2658
2706
  await flushStages(result ?? { status: "fixed" }, ["investigation"]); // always posted: FORGE:INVESTIGATION/VALIDATE are read downstream
2659
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 } : {}) }); }
2660
2709
  frozen = historyRows(contract); // #4694 guards
2661
2710
  frozen = withDecisionRows(frozen, readDecisionIndex(repo)); // #4695: anchored decisions on the deliverable paths; one index read
2662
2711
  await takeHotAreas((frozen.deliverables ?? []).map((d) => d?.path)); // #5751: the contract's paths before building
@@ -2690,8 +2739,8 @@ export async function runCore(o) {
2690
2739
  }
2691
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)
2692
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; };
2693
- 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
2694
- 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; };
2695
2744
  let envMiss = await probeEnv();
2696
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 */ } }
2697
2746
  if (envMiss.length) {
@@ -2750,6 +2799,7 @@ export async function runCore(o) {
2750
2799
  for (const command of shim ?? genericInstallCommands(miss, { root })) {
2751
2800
  const r = await io.runCommand({ command, cwd: wt, timeoutMs: 600000, env: laneEnv() }).catch((e) => ({ rc: 1, stderr: String(e?.message ?? e) }));
2752
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)
2753
2803
  }
2754
2804
  }
2755
2805
  rawMisses = await preflightValidates(frozen).catch(() => []);
@@ -2861,18 +2911,50 @@ export async function runCore(o) {
2861
2911
  // #4331: a learned command the map covers runs only when its globs match a changed file; unmapped ones always run (#4315)
2862
2912
  // #5820: the PR's required CI jobs (scripts/ci-local plan, heavy jobs CI-only) join the round as derived commands
2863
2913
  const ciCfg = o.precheck?.ci ?? parseCiPrecheckConfig(null);
2864
- let ciRequired, ciDerived = new Map(); // command -> {job, name, why, steps}
2914
+ let ciRequired, ciRelease, ciDerived = new Map(); // command -> {job, name, why, steps}
2865
2915
  const ciGaveUp = new Set(); // jobs found unrunnable in an earlier round: recorded once, not rerun
2866
2916
  async function ciPrecheckPlan(round) {
2867
2917
  ciDerived = new Map();
2868
2918
  if (ciCfg.mode === "off" || isSplit || !io.ciLocalPlan || !io.fs?.write) return [];
2869
2919
  if (ciRequired === undefined) { try { ciRequired = (await io.requiredChecks?.(lane)) ?? null; } catch { ciRequired = null; } }
2870
- 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 });
2871
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
+ }
2872
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 });
2873
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("; ")}` : ""}`);
2874
2932
  return p.commands.map((c) => c.command);
2875
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
+ }
2876
2958
  let ciCommands = await ciPrecheckPlan(0);
2877
2959
  const pickChecks = () => planPrecheck({ testMap, files, learned: [...learnedCommands, ...ciCommands], maxMinutes: o.precheck?.maxMinutes, verify: vcfg });
2878
2960
  let picked = pickChecks();
@@ -2881,6 +2963,17 @@ export async function runCore(o) {
2881
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` : ""}`);
2882
2964
  if (picked.commands.length && io.runCommand) {
2883
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(", ")}`); }
2884
2977
  for (let round = 0; ; round++) {
2885
2978
  await renew();
2886
2979
  if (round) { ciCommands = await ciPrecheckPlan(round); picked = pickChecks(); }
@@ -2917,10 +3010,30 @@ export async function runCore(o) {
2917
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);
2918
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; }
2919
3012
  const names = failed.map((f) => `\`${f.command}\` (exit ${f.rc})`).join(", ");
2920
- 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
+ }
2921
3034
  checkCommandsFailing = true;
2922
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
2923
- 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; }
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; }
2924
3037
  T.decisions.push(`Declared check command(s) failed: ${names}; builder resumed (round ${round + 1}/${vcfg.maxRounds})`);
2925
3038
  const before = String(await git(["rev-parse", "HEAD"])).trim();
2926
3039
  const capped = capLogs(failed.map((f) => ({ ...f, log: f.output }))).map((f) => ({ command: f.command, rc: f.rc, output: f.log }));
@@ -2935,7 +3048,7 @@ export async function runCore(o) {
2935
3048
  await fixRound("precheck", precheckFailurePrompt(quiet, vcfg.mode), [], "precheck", capped.map((f) => `${f.command}\n${f.output ?? ""}`).join("\n"));
2936
3049
  await upsertStage("implementation");
2937
3050
  result = (await readResult()) ?? result;
2938
- 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; }
2939
3052
  files = await changedFiles();
2940
3053
  }
2941
3054
  }
@@ -2970,26 +3083,6 @@ export async function runCore(o) {
2970
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);
2971
3084
  }
2972
3085
  }
2973
- // ---- 3c. the target repo's devdocs freshness rule, when it has one: deterministic, before any PR, so a lane does not
2974
- // pay for a failed required check. Exit 1 resumes the builder once; still failing is needs-human docs.stale.
2975
- if (io.docsFreshness) {
2976
- let docs = await io.docsFreshness({ cwd: wt, base }).catch(() => null);
2977
- if (docs && !docs.ok && sessionId) {
2978
- ev({ event: "DOCS_STALE", round: 1 });
2979
- T.decisions.push("Docs freshness check failed; builder resumed once");
2980
- const docsBefore = await changedFiles();
2981
- await fixRound("docs", docsPrompt(docs.output), [], "docs", String(docs.output ?? ""));
2982
- await upsertStage("implementation");
2983
- result = (await readResult()) ?? result;
2984
- await noteFreshnessDocs(docsBefore, true);
2985
- docs = await io.docsFreshness({ cwd: wt, base }).catch(() => null);
2986
- }
2987
- verifyFacts.docs = docs;
2988
- if (docs?.ok) await gatePassed("docs");
2989
- if (docs && !docs.ok) {
2990
- 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);
2991
- }
2992
- }
2993
3086
  // ---- 3d. enumerating tests (#4322): new symbols that tests listing their siblings do not name; one resume, then an
2994
3087
  // anomaly (CI stays the gate). Sequence numbers the base already uses: renumbered at hand-off, still colliding = base.conflict.
2995
3088
  if (io.enumeratingMissing && !isSplit) {
@@ -3198,6 +3291,12 @@ export async function runCore(o) {
3198
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)); }
3199
3292
  }
3200
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
+ }
3201
3300
  const att = await attributeBaseRed({ failed: baseRed, git, base });
3202
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)
3203
3302
  let laneFiles = [];
@@ -3213,10 +3312,10 @@ export async function runCore(o) {
3213
3312
  try { if (att?.sha) commitDate = String(await git(["show", "-s", "--format=%cI", att.sha])).trim(); } catch { /* no reopen */ }
3214
3313
  const cmds = baseRed.map((f) => f.command), outputs = Object.fromEntries(cmds.map((c) => [c, tailOf(c)]));
3215
3314
  const n = await reportBaseRed({ ghc: ghw, repo, base, att, laneIssue: issue, commands: cmds, outputs, baseSha, commitDate });
3216
- 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`);
3217
3316
  recordBaseVerdict({ repo, base, sha: baseSha, red: true, att, commands: cmds, outputs }); // #5992: later lanes and the dispatcher's probe reuse this verdict
3218
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 });
3219
- 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);
3220
3319
  }
3221
3320
  const structureLine = structureNote(structure);
3222
3321
 
@@ -3307,12 +3406,9 @@ export async function runCore(o) {
3307
3406
  ciRounds++; fixes++;
3308
3407
  T.decisions.push(`CI verification red (${jobs}); builder resumed with the failed logs (round ${ciRounds}/${vcfg.maxRounds})`);
3309
3408
  ev({ event: "CI_FIX_ROUND", trigger, round: ciRounds, jobs: sp.own.map((f) => f.job) });
3310
- const ciBefore = io.docsFreshness ? await changedFiles() : [];
3311
- const ciDocsStale = io.docsFreshness ? (await io.docsFreshness({ cwd: wt, base }).catch(() => null))?.ok === false : false;
3312
3409
  await fixRound("ci", ciFailurePrompt(sp.own, vcfg.mode), [], "ci_red", failureLog(sp.own));
3313
3410
  await upsertStage("implementation");
3314
3411
  result = (await readResult()) ?? result;
3315
- await noteFreshnessDocs(ciBefore, ciDocsStale);
3316
3412
  if (String(await git(["rev-parse", "HEAD"])).trim() === head) {
3317
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).
3318
3414
  const rr = ciReruns.get(head)?.rr ?? { ok: false, detail: isSplit ? "refactor:split" : "no rerun seam" };
@@ -3356,7 +3452,7 @@ export async function runCore(o) {
3356
3452
  const wantsDecision = (Array.isArray(result?.amendments) ? result.amendments : []).some((x) => x?.kind === "decision");
3357
3453
  baseTree ??= wantsDecision ? String(await git(["ls-tree", "-r", "-z", "--name-only", base]).catch(() => "")).split("\0").filter(Boolean) : null;
3358
3454
  const addedPaths = wantsDecision ? String(await git(["diff", "--name-only", "--diff-filter=A", `${base}...HEAD`]).catch(() => "")).split("\n").filter(Boolean) : [];
3359
- const own = [...(Array.isArray(result?.amendments) ? result.amendments : []), ...impliedDocs];
3455
+ const own = Array.isArray(result?.amendments) ? result.amendments : [];
3360
3456
  const ownKeys = new Set(own.map((x) => JSON.stringify(x)));
3361
3457
  const dd = dedupeAddRequirements(frozen, [...priorAmendments.filter((x) => !ownKeys.has(JSON.stringify(x))), ...own]); // #5773: a requeue does not renumber a re-added row
3362
3458
  const all = dd.amendments;
@@ -3377,7 +3473,7 @@ export async function runCore(o) {
3377
3473
  }
3378
3474
  pendingDecisions = a.decisions; // #4737: persisted only once the PR merges
3379
3475
  effective = a.contract;
3380
- return a.problems.map((d) => ({ code: OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, kind: "amendment_invalid", detail: d })); // unclog: advisory, the amendment is simply not applied
3476
+ return []; // #6083: an invalid amendment is simply not applied; no amendment syntax or id-reuse gate
3381
3477
  }
3382
3478
  const IGNORE = [`${LEAN_DIR}/`];
3383
3479
  /** Up to two reviewer runs; a reply without usable rows (unparseable, incomplete, inconsistent) is re-asked, never charged to the builder. */
@@ -3519,25 +3615,6 @@ export async function runCore(o) {
3519
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 } : {}) })) });
3520
3616
  return out;
3521
3617
  }
3522
- /** #4979 SPEC-2: rerun the frozen command of every substituted validate, so precheck accepts a substitute only for a command that cannot run. */
3523
- async function rerunSubstitutedOriginals(contract) {
3524
- const out = {};
3525
- if (!io.runCommand) return out;
3526
- const env = laneEnv();
3527
- for (const v of contract.validate ?? []) {
3528
- if (!v.substituted?.from) continue;
3529
- let x;
3530
- 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) }; }
3531
- out[v.id] = { rc: Number.isInteger(x?.rc) ? x.rc : 1, output: String(x?.output ?? "") };
3532
- // #5653: the substitute runs too, so conformance can judge "same test ids, same result" (equivalentRuns)
3533
- if (out[v.id].rc !== 0 && out[v.id].rc !== 124) {
3534
- 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; }
3535
- if (y) out[v.id].sub = { rc: Number.isInteger(y.rc) ? y.rc : 1, output: String(y.output ?? "") };
3536
- }
3537
- }
3538
- if (Object.keys(out).length) ev({ event: "SUBSTITUTE_RERUN", runs: Object.entries(out).map(([id, x]) => ({ id, rc: x.rc })) });
3539
- return out;
3540
- }
3541
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. */
3542
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
3543
3620
  async function guardGate(files) {
@@ -3571,7 +3648,6 @@ export async function runCore(o) {
3571
3648
  if (!want.run) T.decisions.push(`Real-browser check skipped for interactive UI change (${ui.slice(0, 3).join(", ")}): ${want.reason} (#5285)`);
3572
3649
  return { files: ui, ran: want.run, reason: want.reason, highRisk: riskPathHits(ui, riskPaths).length > 0 };
3573
3650
  }
3574
- let amendFixed = false;
3575
3651
  /** #5436: a review started beside guard+precheck is dropped on every return that does not reach the reviewer. */
3576
3652
  async function gate() {
3577
3653
  try { return await gateRun(); } finally { specReview?.discard(); specReview = null; }
@@ -3602,26 +3678,10 @@ export async function runCore(o) {
3602
3678
  domainsLogged = domains.join(",");
3603
3679
  ev({ event: "REVIEW_DOMAINS", domains, enforced: dHits.length ? dHits : undefined, ...(pd === null ? { error: "roster.failed" } : {}) });
3604
3680
  }
3605
- const vIds = [...(frozen?.validate ?? []), ...(frozen?.regression ?? [])].map((v) => v?.id);
3606
- const amendBad = (am) => [...new Set([...validateAmendments(am), ...amendmentKindProblems(am, vIds)])]; // #5089/#5986: the shared amendment schema, plus #5979's validate-row supersedes hint
3607
- if (!amendFixed && sessionId && amendBad(result?.amendments).length) { // one in-lane correction, outside the conformance resume budget; a still-invalid shape is never posted
3608
- amendFixed = true;
3609
- const bad = amendBad(result.amendments);
3610
- T.decisions.push(`Amendment kinds invalid (${bad.length}); builder asked to correct ${RESULT_FILE} once`);
3611
- await builder(++attemptN, amendmentCorrectionPrompt(bad), sessionId, false, undefined, { mode: "resume", trigger: "contract_correction" });
3612
- result = (await readResult()) ?? result;
3613
- files = await changedFiles();
3614
- }
3615
3681
  const amendProblems = await amend();
3616
3682
  const gateHead = String(await git(["rev-parse", "HEAD"])).trim();
3617
3683
  const ciVerified = remoteVerify && ciVerifiedHead !== null && ciVerifiedHead === gateHead;
3618
3684
  const hotspots = await hotspotsOf({ base, paths: files }); // #4502
3619
- let counters = null; // #5751: recurrence.counters at the lane's merge base and at its head
3620
- if (recCfg.counters.length) {
3621
- const mb = String(await git(["merge-base", base, "HEAD"]).catch(() => "")).trim() || base;
3622
- counters = { before: await countCounters({ git, ref: mb, counters: recCfg.counters }), after: await countCounters({ git, ref: "HEAD", counters: recCfg.counters }) };
3623
- ev({ event: "COUNTERS", ...counters });
3624
- }
3625
3685
  const rx = await relaxationsOf(files); // #5237
3626
3686
  relaxations = rx.relaxations;
3627
3687
  if (relaxations.length) {
@@ -3632,16 +3692,15 @@ export async function runCore(o) {
3632
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
3633
3693
  const repro = await reproOf(effective);
3634
3694
  // a precheck that already fails on facts at hand (no engine rerun) would discard the review, so it is not started then
3635
- 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)) });
3636
3696
  specReview = !early || early.failures.length ? null : startSpeculative(async () => reviewerCall((await reviewPrep()).prompt));
3637
3697
  const gateT0 = now(); let validateMs = 0;
3638
- // #4693: guards run beside the validate rerun; SPEC-11: the substituted-original rerun shares the one validate phase
3639
- const validatePhase = phaseLedger.during("validate", async () => ({ runs: await rerunFailedValidatesRaw(effective, { ciVerified }), subs: await rerunSubstitutedOriginals(effective) })).finally(() => { validateMs = now() - gateT0; });
3640
- 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)]);
3641
3701
  // #5087: forge.yaml topology.route_reachability gates the route handlers this diff adds; unset = no check
3642
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 } }) : [];
3643
3703
  // #5419: forge.yaml docs: user-facing surfaces need docs, and added /docs links must resolve; unset = no check
3644
- 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 }) : [];
3645
3704
  // #5752: forge.yaml outcome_evidence: a touched declared area needs a before/after on recorded real inputs; unset = no check
3646
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 }) : [];
3647
3706
  // #5428: forge.yaml pages: a public page needs design, SEO and GEO briefs and passes the deterministic page checks; unset = no check
@@ -3667,12 +3726,9 @@ export async function runCore(o) {
3667
3726
  const guardRunMs = guardEv && !guardEv.error ? Math.max(0, now() - gateT0 - validateMs) : 0;
3668
3727
  guardAddedMs += guardRunMs;
3669
3728
  if (guardEv) ev({ ...guardEv, added_wall_ms: guardRunMs });
3670
- 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;
3671
- // #4626: post-deploy check ids resolve against the lane base's checks file or this PR's
3672
- const checkIds = effective.requirements?.some((r) => r.disposition === "post-deploy") ? new Set(Object.keys(await checksAt(git, [base, "HEAD"], wt))) : null;
3673
- 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
3674
3731
  laneRemoved = removedPaths ?? [];
3675
- const subBaseFiles = (effective.validate ?? []).some((v) => v.substituted) ? String(await git(["ls-tree", "-r", "-z", "--name-only", base]).catch(() => "")).split("\0").filter(Boolean) : []; // #5003
3676
3732
  const baselineRuns = [];
3677
3733
  for (const b of matchBaselines(files, vcfg.baselines)) { // #5448: project baseline suites for the changed paths, enforced
3678
3734
  let x;
@@ -3680,9 +3736,7 @@ export async function runCore(o) {
3680
3736
  baselineRuns.push({ ...b, rc: Number.isInteger(x?.rc) ? x.rc : 1, output: String(x?.output ?? "") });
3681
3737
  }
3682
3738
  if (baselineRuns.length) ev({ event: "BASELINES_RUN", runs: baselineRuns.map((b) => ({ run: b.run, rc: b.rc })) });
3683
- // #5760: CI budget gate (always on: annotation + hygiene; max_* only when set); one git diff when no workflow changed
3684
- 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 []; });
3685
- 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 });
3686
3740
  // #5447: an install failure for a package the changed files import blocks (env.tool_missing); unrelated ones are logged
3687
3741
  const depFail = depInstallFailures({ results: depResults, changedFiles: files });
3688
3742
  for (const l of depFail.logged) if (!T.decisions.includes(l)) T.decisions.push(l);
@@ -3739,18 +3793,17 @@ export async function runCore(o) {
3739
3793
  adequacyTel = testAdequacyTelemetry(effective, adequacy, { repro: adequacyIn.repro, mutation: adequacyIn.mutation, regression: regressionRan(effective, adequacyIn) });
3740
3794
  // an environment or repro-verdict failure is settled first (already-fixed, env.repro_unrunnable): adequacy never mixes into it
3741
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 });
3742
- 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)) });
3743
3797
  // #4323/#4334: a missing host tool or module, or a repro test the harness could not run, is an environment error:
3744
3798
  // never a conformance failure, never a builder resume
3745
- const envFails = pc.failures.filter((f) => ENV_CODES.includes(f.code));
3746
- const preSplit = splitAdvisory([...pc.failures.filter((f) => !ENV_CODES.includes(f.code)), ...amendProblems, ...mutBlock, ...adqFail], { enforce: enforcedKinds() });
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() });
3747
3801
  noteAdvisory(preSplit.advisory);
3748
- const pre = preSplit.block;
3802
+ const envFails = preSplit.block.filter((f) => ENV_CODES.includes(f.code));
3803
+ const pre = preSplit.block.filter((f) => !ENV_CODES.includes(f.code));
3749
3804
  if (pre.length) ev({ event: "PRECHECK", failures: pre.map((f) => f.code) });
3750
3805
  // #5080: the repro already passes on the base and the diff changes no source: the fix is on the base, not missing
3751
3806
  if (alreadyFixedOnBase(pre, files, IGNORE)) return { state: "already-fixed", by: "precheck", failures: pre };
3752
- // #5729: a missing /design spec or visual evidence is not a builder fix: end design.spec_required before any resume or recovery lane
3753
- if (pre.length && !recording() && specOnlyFailures(pre)) return { state: "spec-only", by: "precheck", failures: pre };
3754
3807
  if (pre.length && !recording()) return { state: "nonconforming", by: "precheck", failures: pre };
3755
3808
  // shadow: the builder's own failed checks block before any reviewer tokens are spent (#4160)
3756
3809
  const hard = recording() ? blockingOf(pre, SHADOW_PRE_BLOCKS).block : [];
@@ -3872,7 +3925,6 @@ export async function runCore(o) {
3872
3925
  const explained = explainFailures(outcome.failures, effective); // #4265: name the unmet requirement, not only the code
3873
3926
  const list = explained.slice(0, 15).map((f) => `- ${f.code}: ${f.detail}`).join("\n");
3874
3927
  if (outcome.state === "environment") return await envNeedsHuman(outcome.failures);
3875
- 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}` });
3876
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
3877
3929
  // #5732: so is a repro head failure whose output carries no assertion text (an env error of the sandbox, not a red test)
3878
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))) {
@@ -3898,7 +3950,12 @@ export async function runCore(o) {
3898
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);
3899
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);
3900
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
3901
- 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
+ }
3902
3959
  lastFailKey = failKey;
3903
3960
  resumes++;
3904
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})`);
@@ -4150,7 +4207,8 @@ export async function runCore(o) {
4150
4207
  await reportVerify();
4151
4208
  syncRow.push(`${trigger}: ${clean ? "clean" : "conflicts"} (${baseSha})`);
4152
4209
  T.baseSync = [`${syncs} sync(s)`, syncRow.join("; ")];
4153
- 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)}`); }
4154
4212
  return null;
4155
4213
  }
4156
4214
  const NR_TESTS = "not reported";
@@ -4212,7 +4270,7 @@ export async function runCore(o) {
4212
4270
  }
4213
4271
  lost = lost.filter((id) => !ran?.[id]);
4214
4272
  }
4215
- 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)`);
4216
4274
  const rv = await doReview(); // never merge an unreviewed head
4217
4275
  if (!rv) return await needsHuman("Reviewer returned no parseable verdict after a CI fix round.", OUTCOME_CODES.REVIEW_NO_VERDICT);
4218
4276
  if (rv.env) return await envNeedsHuman(rv.env);