forgedock 1.54.0 → 1.55.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 (114) hide show
  1. package/bin/auth/app-token.mjs +2 -0
  2. package/bin/auth/app-token.test.mjs +9 -1
  3. package/bin/engine/events.mjs +1 -0
  4. package/bin/engine/events.test.mjs +5 -1
  5. package/bin/engine/outcome-codes.mjs +3 -0
  6. package/bin/engine-cli.mjs +126 -34
  7. package/bin/forgedock.mjs +56 -4
  8. package/bin/gc-schedule.mjs +83 -0
  9. package/bin/gc.mjs +56 -8
  10. package/bin/help-text.mjs +1 -1
  11. package/bin/hooks/pre-tool-use.mjs +1 -0
  12. package/bin/init-detect.mjs +73 -2
  13. package/bin/labels.json +5 -0
  14. package/bin/lean/admission.mjs +21 -1
  15. package/bin/lean/baselines.mjs +43 -0
  16. package/bin/lean/baselines.test.mjs +33 -0
  17. package/bin/lean/batch-health.mjs +43 -6
  18. package/bin/lean/batch-health.test.mjs +41 -1
  19. package/bin/lean/batch.mjs +41 -4
  20. package/bin/lean/batch.test.mjs +106 -3
  21. package/bin/lean/conformance.mjs +131 -12
  22. package/bin/lean/conformance.test.mjs +172 -3
  23. package/bin/lean/depcache.mjs +23 -2
  24. package/bin/lean/depcache.test.mjs +22 -0
  25. package/bin/lean/docsgate.mjs +137 -0
  26. package/bin/lean/docsgate.test.mjs +78 -0
  27. package/bin/lean/effects.mjs +31 -2
  28. package/bin/lean/enumerating.mjs +39 -13
  29. package/bin/lean/enumerating.test.mjs +20 -0
  30. package/bin/lean/execution.test.mjs +3 -3
  31. package/bin/lean/fastforward.mjs +93 -0
  32. package/bin/lean/fastforward.test.mjs +73 -0
  33. package/bin/lean/guardgate.mjs +38 -7
  34. package/bin/lean/guardgate.test.mjs +39 -0
  35. package/bin/lean/issuewatch-install.mjs +92 -0
  36. package/bin/lean/issuewatch-install.test.mjs +31 -0
  37. package/bin/lean/issuewatch-parity.mjs +33 -3
  38. package/bin/lean/issuewatch-parity.test.mjs +30 -5
  39. package/bin/lean/issuewatch-reconcile.mjs +123 -0
  40. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  41. package/bin/lean/issuewatch-verify.mjs +51 -9
  42. package/bin/lean/issuewatch.mjs +153 -33
  43. package/bin/lean/issuewatch.test.mjs +243 -22
  44. package/bin/lean/lean.mjs +381 -75
  45. package/bin/lean/lean.test.mjs +437 -20
  46. package/bin/lean/light.mjs +11 -3
  47. package/bin/lean/light.test.mjs +27 -0
  48. package/bin/lean/lightlane.mjs +8 -3
  49. package/bin/lean/lightlane.test.mjs +20 -0
  50. package/bin/lean/mechfix.mjs +35 -4
  51. package/bin/lean/mechfix.test.mjs +48 -1
  52. package/bin/lean/orchestrate-children.test.mjs +10 -0
  53. package/bin/lean/orchestrate-owned.test.mjs +73 -0
  54. package/bin/lean/orchestrate.mjs +28 -4
  55. package/bin/lean/overlap.mjs +20 -0
  56. package/bin/lean/overlap.test.mjs +49 -0
  57. package/bin/lean/pagegate.mjs +152 -0
  58. package/bin/lean/pagegate.test.mjs +77 -0
  59. package/bin/lean/parked-relabel.mjs +32 -0
  60. package/bin/lean/parked-relabel.test.mjs +45 -0
  61. package/bin/lean/phaseledger.mjs +17 -2
  62. package/bin/lean/postdeploy-check.mjs +27 -0
  63. package/bin/lean/postdeploy-check.test.mjs +13 -1
  64. package/bin/lean/postrun.mjs +32 -0
  65. package/bin/lean/postrun.test.mjs +41 -0
  66. package/bin/lean/preflight.mjs +46 -0
  67. package/bin/lean/preflight.test.mjs +30 -1
  68. package/bin/lean/prompts.mjs +36 -6
  69. package/bin/lean/recovery.test.mjs +16 -0
  70. package/bin/lean/release.mjs +30 -3
  71. package/bin/lean/release.test.mjs +36 -0
  72. package/bin/lean/render.mjs +17 -6
  73. package/bin/lean/reproquality.mjs +116 -0
  74. package/bin/lean/reproquality.test.mjs +85 -0
  75. package/bin/lean/review-trigger.mjs +8 -3
  76. package/bin/lean/sandbox-budget.test.mjs +27 -0
  77. package/bin/lean/schedd.mjs +40 -11
  78. package/bin/lean/schedd.test.mjs +12 -1
  79. package/bin/lean/testadequacy.mjs +97 -0
  80. package/bin/lean/testadequacy.test.mjs +92 -0
  81. package/bin/lean/testsandbox.mjs +202 -0
  82. package/bin/lean/testsandbox.test.mjs +157 -0
  83. package/bin/lean/toolplace.mjs +5 -2
  84. package/bin/lean/toolplace.test.mjs +6 -0
  85. package/bin/lean/verify.mjs +6 -1
  86. package/bin/lean/verify.test.mjs +18 -2
  87. package/bin/lean/warmtree.mjs +77 -0
  88. package/bin/lean/warmtree.test.mjs +81 -0
  89. package/bin/runner.mjs +6 -1
  90. package/bin/stats/conformance-outcomes.mjs +12 -2
  91. package/bin/stats/depth.mjs +24 -1
  92. package/bin/stats/depth.test.mjs +21 -1
  93. package/bin/stats/index.mjs +5 -2
  94. package/bin/stats/query.mjs +2 -1
  95. package/commands/cleanup.md +18 -0
  96. package/commands/fd-introspect.md +19 -0
  97. package/commands/milestone.md +5 -1
  98. package/commands/pipeline-health/phase-2-metrics.md +4 -0
  99. package/commands/recover-orphans.md +31 -1
  100. package/commands/review-pr-staging.md +9 -0
  101. package/commands/review-pr.md +2 -0
  102. package/docs/CI.md +1 -1
  103. package/docs/CONFIG.md +26 -1
  104. package/docs/EVENTS.md +1 -0
  105. package/docs/ISSUE-WATCH.md +12 -3
  106. package/docs/eval/adversarial-bench.md +1 -1
  107. package/docs/eval/published/adversarial-2026-11-11.md +58 -0
  108. package/package.json +1 -1
  109. package/scripts/bench-lightlane.mjs +3 -2
  110. package/scripts/hotspots.sh +7 -4
  111. package/scripts/hotspots.test.sh +12 -0
  112. package/scripts/recover-orphans-stateless.test.sh +79 -0
  113. package/scripts/transition-label.sh +2 -0
  114. package/templates/workflows/forgedock-reopen-clean.yml +33 -0
package/bin/lean/lean.mjs CHANGED
@@ -11,25 +11,28 @@ import { existsSync, readFileSync } from "node:fs";
11
11
  import { join, dirname, basename, delimiter } from "node:path";
12
12
  import { hostname as osHostname } from "node:os";
13
13
  import { appendEvent } from "../engine/runlog.mjs";
14
+ import { testAdequacyRows, testAdequacyFailures, testAdequacyTelemetry, adequacyCounts, regressionRan } from "./testadequacy.mjs";
14
15
  import { readSelfReview, compareSelfReview, firstReviewRecord, selfCheckFailures } from "./selfreview.mjs";
15
- import { codeForTerminalReason, OUTCOME_CODES, ENV_VALIDATE_TIMEOUT, ENV_VALIDATE_PLACEMENT } from "../engine/outcome-codes.mjs";
16
+ import { codeForTerminalReason, OUTCOME_CODES, ENV_VALIDATE_TIMEOUT, ENV_VALIDATE_PLACEMENT, ENV_ENGINE_OWNED_CODES } from "../engine/outcome-codes.mjs";
16
17
  import { ciPollDelayMs, ENGINE_VERSION, DEFAULT_MAX_SESSION_LIMIT_PAUSES, DEFAULT_SESSION_LIMIT_WAIT_MS, parseLeaseHolder, sanitizeLeaseHost } from "../engine.mjs";
17
18
  import { openDependency, laneMergedPrs, dependencyOnLane, isTrustedComment, decomposedSubissues, isDecomposedRecord, reopenRevokedDecomposition } from "../engine/phases.mjs";
18
19
  import { createHash, randomBytes } from "node:crypto";
19
20
  import { otherLaneOwner } from "./lanelock.mjs";
20
21
  import { stampText, checkStamp } from "./stagestamp.mjs";
21
22
  import { acquireBranchLock, waitPidsExit } from "./branchlock.mjs";
22
- import { applyValidateRecipes, rewriteProjectDirCommand, deferChecklessPostDeploy, reproEnvMiss, resolveForgedockPaths, describesUnrunnableCommand, removedPathsOf, TRACKED, normalizeKindModes, blockingFailures, unverifiedRequirements, mutationTargets, mutationFailures, runMutationCheck, MUTATION_SURVIVED, isBugIssue, scopeText, explainFailures, inIssue, validateContract, snapQuotes, cliUsageError, normalizeRunnerCommand, applyAmendments, amendmentKindProblems, precheck, alreadyFixedOnBase, READONLY_PROD_RE, EXTERNAL_NEED_RE, intakeHostWork, repoTracks, dropScopeValidates, tagOutOfBand, parseReview, decide, mergeReviewRows, reaskable, criterionLines, closePlan, followupItems, renderPendingFollowups, bucketTally, pendingTracking, unnamedEdges, structureNote, impliedDocDeliverables, convertDelivered } from "./conformance.mjs";
23
+ import { isTestPath, applyValidateRecipes, rewriteProjectDirCommand, deferChecklessPostDeploy, autoPostDeployE2e, loneE2eRows, reproEnvMiss, resolveForgedockPaths, describesUnrunnableCommand, removedPathsOf, TRACKED, normalizeKindModes, blockingFailures, unverifiedRequirements, mutationTargets, mutationFailures, runMutationCheck, MUTATION_SURVIVED, isBugIssue, scopeText, explainFailures, inIssue, validateContract, snapQuotes, cliUsageError, normalizeRunnerCommand, applyAmendments, amendmentKindProblems, precheck, alreadyFixedOnBase, READONLY_PROD_RE, EXTERNAL_NEED_RE, intakeHostWork, repoTracks, dropScopeValidates, tagOutOfBand, parseReview, decide, mergeReviewRows, reaskable, criterionLines, closePlan, followupItems, renderPendingFollowups, bucketTally, pendingTracking, unnamedEdges, structureNote, impliedDocDeliverables, convertDelivered } from "./conformance.mjs";
23
24
  import { checkAdmission, hostParallelism, ADMISSION_RETRY_SECONDS } from "./admission.mjs";
24
25
  import { namedPaths, isTrustedIssueComment } from "./prefilter.mjs";
25
- import { checksAt } from "./postdeploy-check.mjs";
26
+ import { checksAt, mergeCheckEntries, CHECKS_FILE } from "./postdeploy-check.mjs";
27
+ import { matchBaselines, baselineFailures, foldRegression } from "./baselines.mjs";
26
28
  import { readRollouts, detectNewOffKeys, rolloutModes, liveDeferralBlocks } from "./activation.mjs";
27
29
  import { toolMisses } from "./toolplace.mjs";
28
- import { testRunnerProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract } from "./preflight.mjs";
30
+ import { testRunnerProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract, declaredEnv, depInstallFailures, testRunSummary } from "./preflight.mjs";
29
31
  import { resolveLane, isDefaultLane, isShippedLane, DEFAULT_STAGING_BRANCH } from "./lane.mjs";
30
32
  import { splitGate, rationaleLine } from "./decompose.mjs";
31
33
  import { ceilingFor, predictRestart, handoffFacts, NARROW_NOTE } from "./ceiling.mjs";
32
34
  import { dockerLabels, LEDGER_TTL_MS } from "./ledger.mjs";
35
+ import { batchImageCache, envNamesOf, provisionSandboxes } from "./testsandbox.mjs";
33
36
  import { repoKey, estimateCostUsd } from "../runner.mjs";
34
37
  import { prepareToolchain } from "./toolchain.mjs";
35
38
  import { toolStats } from "./toolstats.mjs";
@@ -45,22 +48,27 @@ const MISSING_TOOL_RE = /command not found|not found in PATH|no such file or dir
45
48
  /** #4685: true when a builder's block summary names a missing tool or module (environment), not a credential. */
46
49
  export function missingToolBlock(summary) { return MISSING_TOOL_RE.test(String(summary ?? "")); }
47
50
  import { reserveForBuild, revalidate } from "./seqreserve.mjs";
48
- import { CHECKS_CLI, FORGEDOCK_CLI, REVIEWER_SYSTEM, LEAN_DIR, RESULT_FILE, INVESTIGATION_FILE, IMPLEMENTATION_FILE, CONTRACT_FILE, builderPlanPrompt, builderImplementPrompt, contractCorrectionPrompt, conformanceResumePrompt, amendmentCorrectionPrompt, reviewerPrompt, investigationVerdict, decisionNote, reviewerRepairPrompt, REVIEW_DIFF_MAX_BYTES, blockCorrectionPrompt, HUMAN_BLOCK_REASONS, structurePrompt, hotspotPlanNote, hotspotBuildRule, reproPlanNote, unrunnableValidateNote, contextPackNote, buildOpeningNote, sequenceBuildRule, docsPrompt, ciFailurePrompt, ciUnavailablePrompt, precheckFailurePrompt, contextRestartPrompt, turnBudgetWrapupPrompt, syncChecks, GROUPING_SYSTEM, enumeratingPlanNote, enumeratingBuildRule, invariantsPlanNote, invariantsBuildRule, missingEntriesPrompt, sequencePrompt, sequenceSyncNote, sequenceSyncPrompt, fixSessionPrompt, postMergeFailurePrompt, duplicateExportsPrompt, migrationGeneratorPrompt, i18nCopiesPrompt, narrowFixPrompt } from "./prompts.mjs";
51
+ import { patchEcho, mutationsOf, runReproMutations, classifyRepro } from "./reproquality.mjs";
52
+ import { CHECKS_CLI, FORGEDOCK_CLI, REVIEWER_SYSTEM, LEAN_DIR, RESULT_FILE, INVESTIGATION_FILE, IMPLEMENTATION_FILE, CONTRACT_FILE, builderPlanPrompt, builderImplementPrompt, contractCorrectionPrompt, conformanceResumePrompt, amendmentCorrectionPrompt, reviewerPrompt, investigationVerdict, decisionNote, reviewerRepairPrompt, REVIEW_DIFF_MAX_BYTES, blockCorrectionPrompt, HUMAN_BLOCK_REASONS, structurePrompt, hotspotPlanNote, hotspotBuildRule, reproPlanNote, unrunnableValidateNote, docsPlanNote, pagePlanNote, contextPackNote, buildOpeningNote, sequenceBuildRule, docsPrompt, ciFailurePrompt, ciUnavailablePrompt, precheckFailurePrompt, contextRestartPrompt, turnBudgetWrapupPrompt, syncChecks, GROUPING_SYSTEM, enumeratingPlanNote, enumeratingBuildRule, invariantsPlanNote, invariantsBuildRule, missingEntriesPrompt, sequencePrompt, sequenceSyncNote, sequenceSyncPrompt, fixSessionPrompt, postMergeFailurePrompt, duplicateExportsPrompt, migrationGeneratorPrompt, i18nCopiesPrompt, narrowFixPrompt } from "./prompts.mjs";
49
53
  import { postMergeCommands } from "./postmerge.mjs";
50
54
  import { classifyBaseRed, attribute as attributeBaseRed, runOnBase, reportBaseRed } from "./basered.mjs"; // #5239
51
55
  import { guardAfterMerge, withHistoryRows } from "./guards.mjs";
52
56
  import { parseProdParity, prodParityFailures as prodParityOf } from "./prodparity.mjs";
53
57
  import { routePathsFromFiles, routeReachabilityFailures } from "./routecheck.mjs";
58
+ import { docsFailures } from "./docsgate.mjs";
59
+ import { pageFailures, designSpecApproved, designLabelApproved } from "./pagegate.mjs"; // #5428
54
60
  import { parseCoupled, coupledFailures } from "./coupled.mjs";
55
61
  import { analyzeRelaxations, relaxationFailures } from "./relaxation.mjs";
62
+ import { startSpeculative } from "./overlap.mjs";
56
63
  import { loadGuards, selectGuards, runGuards, supersededIds, supersessionComment } from "./guardgate.mjs";
57
64
  import { freshFix, issueSummary, firstPassOf, sessionCostDelta, mergeNarrowTasks } from "./fixround.mjs";
58
65
  import { parseBuilderRouting, routeBuilder, shouldEscalate } from "./routing.mjs";
59
66
  import { makeTurnBudget, TURN_BUDGET_DEFAULTS, scaledExtra, laneSize, recoverySize, wrapupGrant, budgetDigest } from "./budget.mjs";
60
67
  import { pendingPitfall, pitfallRecord, foldPitfalls, selectPitfalls, failureLog } from "./pitfalls.mjs";
61
68
  import { unjustified } from "./enumerating.mjs";
62
- import { applyEnumerating, renameDuplicates } from "./mechfix.mjs"; // #5348
69
+ import { applyEnumerating, renameDuplicates, verifyApplied } from "./mechfix.mjs"; // #5348
63
70
  import { addLaneWorktree, DEFAULT_SPARSE_MAX_KB } from "./worktree.mjs";
71
+ import { claimWarm, refillWarm, warmTreeCount, NO_HOOKS } from "./warmtree.mjs";
64
72
  import { parseVerify, runCiVerify, collectFailedLogs, capLogs, VERIFY_MODES, VERIFY_CHECK_NAME, verifyReport, ciGate, rerunFailedOnce, rerunTarget, splitFlaky } from "./verify.mjs";
65
73
  import { e2eSpecs, e2eWanted, uiInteractiveChanged, ownFailures, runE2eGate, fakedPaths, NO_TRIGGER } from "./e2e.mjs";
66
74
  import { transferToEpic } from "./acceptance.mjs";
@@ -82,8 +90,10 @@ import { isExternalKill } from "./hostkill.mjs";
82
90
  import { buildResumeDigest } from "./resume.mjs";
83
91
  import { parsePredicate, evalPredicate, premiseAnnotation, registerAsk, registryPkgVersion, closedEdgeNote, onlyAsk, fileRemainder } from "./needs-human-premise.mjs";
84
92
  import { lightEligibility } from "./light.mjs";
93
+ import { fastForwardSource, parseTriage, fastForwardEligibility, fastForwardEvent, skippedStages, skippedLine, investigationOnlyPrompt, contractStepPrompt, TRIAGE_FILE, FF_BUILD_LEAD } from "./fastforward.mjs"; // #5426
85
94
  import { untrackToolState, unstageToolState, isToolState, clearLaneScratch } from "./toolstate.mjs";
86
95
  import { pickSalvage } from "./salvage-resume.mjs";
96
+ import { makePostRun } from "./postrun.mjs";
87
97
  import { ensureSignedOff, salvageBranch, dropSalvageTracking } from "./signoff.mjs";
88
98
  import { reconcileCheckpoints } from "./checkpoint-reconcile.mjs";
89
99
  import { createLedger, flattenPhases } from "./phaseledger.mjs";
@@ -263,7 +273,7 @@ const defaultCredExec = (args) => {
263
273
  export async function runCore(o) {
264
274
  const armed = applyArmOverrides(o, o.issue); o = armed.options; // #5206: the arm's overrides shape the lane before any config is parsed
265
275
  const { issue, repo, lane: requestedLane = null, laneOverride = false, branches = {}, cwd, dir, io, builderModel = null, reviewerModel = DEFAULT_REVIEWER_MODEL, fixModel = null,
266
- toolchainOverride = null, testRunners = null, coupledFiles = null, validateRecipes = null, routeReachability = null, prodParity = null, envSetup = null, ciMaxMinutes = 360, conformance = "shadow", conformanceKinds = null, conformanceMutation = "off", reviewIncomplete = "needs-human", reproTest = "prefer", closeParent = false, mergeWait = "required", maxSessionLimitPauses = DEFAULT_MAX_SESSION_LIMIT_PAUSES, cliIdleMinutes = 15, cliMaxMinutes = 180, cliBusyMinutes = 45, contextCeilingTokens = 120000, contextCeilingBySize = null, turnBudgets = null, laneLimits = null, maxMergeRetries = 5, sessionLimitMaxWaitMs = DEFAULT_SESSION_LIMIT_WAIT_MS, onProgress = () => {}, emitTelemetry = null, random = Math.random } = o;
276
+ toolchainOverride = null, testRunners = null, coupledFiles = null, validateRecipes = null, routeReachability = null, docsConfig = null, pagesConfig = null, prodParity = null, envSetup = null, ciMaxMinutes = 360, conformance = "shadow", conformanceKinds = null, conformanceMutation = "off", reviewIncomplete = "needs-human", reproTest = "prefer", reproQuality = "shadow", closeParent = false, mergeWait = "required", maxSessionLimitPauses = DEFAULT_MAX_SESSION_LIMIT_PAUSES, cliIdleMinutes = 15, cliMaxMinutes = 180, cliBusyMinutes = 45, contextCeilingTokens = 120000, contextCeilingBySize = null, turnBudgets = null, laneLimits = null, maxMergeRetries = 5, sessionLimitMaxWaitMs = DEFAULT_SESSION_LIMIT_WAIT_MS, contextWaitSeconds = 5, onProgress = () => {}, emitTelemetry = null, random = Math.random } = o;
267
277
  const now = io.now ?? (() => Date.now());
268
278
  const rotator = io.rotator !== undefined ? io.rotator : openRotator({ kind: o.accountRotator }); // #5094
269
279
  // #5205: a rotator with pick() relaunches a limited phase pinned to another account; lane-level rotations and limited accounts
@@ -290,7 +300,7 @@ export async function runCore(o) {
290
300
  let lane = null, base = null, defaults = [], milestone = null; // set by lane resolution, before the lease
291
301
  // #4267: a batch recovery lane for a mechanical needs-human ({code, attempt, final}); #4302: only a final attempt relabels.
292
302
  const recover = o.recover && typeof o.recover.code === "string" ? { code: o.recover.code, attempt: Number.isInteger(o.recover.attempt) ? o.recover.attempt : 1, final: o.recover.final !== false } : null;
293
- const branch = `feat/issue-${issue}-lean`;
303
+ let branch = `feat/issue-${issue}-lean`; // #5469: an adopted PR's own head branch replaces it
294
304
  const wt = join(o.worktreeRoot ?? join(cwd, ".claude", "worktrees"), `lean-${issue}`);
295
305
  const t0 = now();
296
306
  const phaseLedger = createLedger(now, "sandbox_start", t0); // #4908: where the lane wall time goes
@@ -299,6 +309,11 @@ export async function runCore(o) {
299
309
  let sessionId = null;
300
310
 
301
311
  const ev = (e) => appendEvent(dir, issue, e, { repo }); // #4432: the run log is keyed by repo + issue
312
+ /** #5435: time one sandbox_start step (SANDBOX_STEP event + ledger sub-timing); the result and errors pass through. */
313
+ const step = async (name, fn) => {
314
+ const s0 = now();
315
+ try { return await fn(); } finally { const ms = Math.max(0, now() - s0); phaseLedger.addStep("sandbox_start", name, ms); ev({ event: "SANDBOX_STEP", step: name, ms }); }
316
+ };
302
317
  const expTag = armed.tag; // #4629: same arm for the whole run; #5206: plus the applied overrides
303
318
  const emit = async (rec) => { try { await emitTelemetry?.({ ...rec, issue }); } catch { /* never fails a run */ } };
304
319
  let ghCache = null; // #4507: the run's own gh HTTP cache (set once the run tmp dir exists)
@@ -339,6 +354,7 @@ export async function runCore(o) {
339
354
  };
340
355
  /** Best effort; `true` when the transition succeeded (#4337: the decomposed close needs to know). */
341
356
  const label = async (state) => { try { await retrying(() => io.transitionLabel(issue, state), { transient: GH_TRANSIENT_RE, attempts: 4, sleep: sleepFn, random }); return true; } catch { /* labels are best effort */ return false; } };
357
+ const postRun = makePostRun({ ev, sleep: sleepFn, now }); // #5437: bookkeeping after RUN_TERMINAL, idempotent and retried
342
358
  const usageLine = () => `cost $${usage.cost_usd.toFixed(4)}, tokens ${usage.input} in / ${usage.output} out / ${usage.cache} cache, wall ${Math.round((now() - t0) / 60000 * 10) / 10} min`;
343
359
 
344
360
  // ---- lease (same FORGE:STATE lease the full path uses) ----
@@ -368,6 +384,7 @@ export async function runCore(o) {
368
384
  }
369
385
 
370
386
  // Pipeline trajectory (posted once at the end): phase rows, decisions, anomalies.
387
+ let depResults = [], gateProvisioned = false; // #5447
371
388
  const T = { issue, validate: null, plan: null, implement: null, review: null, pr: null, merge: null, close: null, decisions: [], anomalies: [] };
372
389
  const failureClasses = new Set(); // forge#4275: conformance failure codes seen this run (gate failures, shadow would-fail)
373
390
  const ctxBase = parseContextPackConfig(o.contextPack ?? {});
@@ -392,14 +409,16 @@ export async function runCore(o) {
392
409
  let shadowWould = null; // forge#4165: the shadow gate's verdict, carried on RUN_TERMINAL (no telemetry write of its own)
393
410
  const kinds = normalizeKindModes(conformanceKinds); // engine.conformance_kinds: a failure code's own mode
394
411
  let domains = [], domainsLogged = null; // #5099: review domains the diff touches (review-roster.sh path triggers)
412
+ let reproQ = null; // #5446: repro_quality of the frozen repro_test, carried on RUN_TERMINAL
395
413
  let firstReview = null; // #5345: the first gate judgement and review.incomplete of the first reply, on RUN_TERMINAL
414
+ let adequacy = null, adequacyIn = {}, adequacyTel = null; // #5449: the Test adequacy rows of the last gate and the facts they were computed from
396
415
  let riskEnforced = null, gateRan = false; // #4398: declared risk paths that made a shadow lane enforce (sticky); the gate ran
397
416
  let done = null, finishing = null, wtCreated = false, salvagedRef = null;
398
417
  let light = false, modelMs = 0; // #4451: the light lane finished without an upgrade (the same structure/hotspot gates as the full lane, #4502); summed session time
399
418
  let lightVerdict = null, lightUpgrade = null; // #4453: the eligibility verdict and the upgrade reason codes, on the run result for the bench
400
419
  let recoverUnlabelled = false; // #4297: the recovery lane removed needs-human; a final ci-pending (or needsHuman()) puts it back
401
420
  const runId = `${issue}-${t0}`;
402
- let runTmp = null;
421
+ let runTmp = null, sandboxEnv = {}, sandboxDown = null; // #5450: test sandboxes of this lane (testsandbox.mjs)
403
422
  let sparse = null; // #4221: {excluded, maxKb} when the lane worktree is a sparse checkout; null leaves prompts unchanged
404
423
  // #4395: lane profile. full (FORGEDOCK_FULL_SESSION=1): unchanged sessions; memory-off: no auto-memory; lane: also no CLAUDE.md, the lane file appended
405
424
  let laneProfile = { name: process.env.FORGEDOCK_FULL_SESSION === "1" ? "full" : "memory-off", text: null };
@@ -423,7 +442,7 @@ export async function runCore(o) {
423
442
  /** A host heavy-step slot for an engine-side step, or null (no io.heavy, disabled, or the registry failed: ungated). */
424
443
  async function heavyAcquire(phase) {
425
444
  if (!heavyOn) return null;
426
- try { const g = await io.heavy.acquire({ issue, phase, priority: lanePriority() }, heavyCfg); addWait(phase, g?.waitMs, g?.queued); return g; } catch { return null; }
445
+ try { const g = await io.heavy.acquire({ issue, phase, priority: lanePriority() }, heavyCfg); addWait(phase, g?.waitMs, g?.queued); return g; } catch (e) { if (e?.code === "DISK_LOW") throw e; return null; } // #5421: a low disk refuses the step, any other failure is fail-open
427
446
  }
428
447
  async function heavyStep(phase, fn) { const g = await heavyAcquire(phase); try { return await fn(); } finally { try { g?.release?.(); } catch { /* fail-open */ } } }
429
448
  // ---- lane resource ledger (#4179): every owned resource is registered before it is created, released after its teardown ----
@@ -459,6 +478,7 @@ export async function runCore(o) {
459
478
  } else if (wtCreated) {
460
479
  ev({ event: "TEARDOWN_KEPT", reason: stillRunning.length ? `builder process ${stillRunning.join(",")} still running: worktree and branch kept` : "checkpoint failed: worktree and branch kept so no work is lost", worktree: wt });
461
480
  }
481
+ if (sandboxDown) { try { await sandboxDown(); } catch { /* the ledger loop below retries */ } sandboxDown = null; }
462
482
  for (const kind of ["container", "volume"]) {
463
483
  for (const r of ledger ? ledger.entries(kind) : []) {
464
484
  if (!io.docker) continue;
@@ -523,12 +543,16 @@ export async function runCore(o) {
523
543
  if (heavyWaitsFile) { // #4169: builder-run heavy waits, read before teardown removes the run TMPDIR
524
544
  try { const sw = sumWaits(await io.fs.read(heavyWaitsFile)); heavyQueueMax = Math.max(heavyQueueMax, sw.queueMax); for (const [ph, ms] of Object.entries(sw.waits)) addWait(ph, ms); } catch { /* no heavy step ran */ }
525
545
  }
526
- await postLaneFacts(); // #4401: before teardown removes the worktree's result.json
527
- await teardown(reason, extra); // first: unpushed work is pushed while this run still holds the lease
546
+ if (setupWait) await setupWait.catch(() => {}); // #5434: never remove the worktree under a running install
547
+ const deferTail = reason === "merged"; // #5437: a merged lane's facts, trajectory and teardown run after RUN_TERMINAL (postRun)
548
+ if (!deferTail) {
549
+ await postLaneFacts(); // #4401: before teardown removes the worktree's result.json
550
+ await teardown(reason, extra); // first: unpushed work is pushed while this run still holds the lease
551
+ }
528
552
  const code = codeOverride ?? codeForTerminalReason(reason);
529
553
  // forge#4165: pr, milestone and the conformance verdict ride on the existing RUN_TERMINAL write (verdict-mix queries).
530
554
  const term = { event: "RUN_TERMINAL", reason, code, ...(extra.pr ? { pr: extra.pr } : {}), ...(milestone ? { milestone } : {}), ...(verifiedLane != null ? { verified: verifiedLane } : {}),
531
- conformance_mode: conformance === "enforce" || riskEnforced ? "enforce" : "shadow", ...(shadowWould ? { shadow_would: shadowWould } : {}), ...(firstReview ? { first_review: firstReview } : {}),
555
+ ...(reproQ ? { repro_quality: reproQ } : {}), conformance_mode: conformance === "enforce" || riskEnforced ? "enforce" : "shadow", ...(shadowWould ? { shadow_would: shadowWould } : {}), ...(firstReview ? { first_review: firstReview } : {}), ...(adequacyTel ?? {}),
532
556
  ...(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() } : {}),
533
557
  ...(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
534
558
  const phases = phaseLedger.snapshot(); // #4908: run log gets the nested ledger, FORGE:TELEMETRY the flattened scalars
@@ -554,15 +578,19 @@ export async function runCore(o) {
554
578
  else if (reason === "invalid" && extra.close === "already-fixed") T.close = ["issue closed (completed)", "already fixed on the base"]; // #5080
555
579
  else if (reason === "invalid") T.close = ["issue closed (not planned)", "label workflow:invalid"];
556
580
  else { T.close = ["left open", "label needs-human"]; T.anomalies.push(`needs-human: ${String(detail).split("\n")[0].slice(0, 300)}`); }
557
- try { await post(["FORGE:TRAJECTORY", REGISTER_MARKER], renderTrajectory({ ...T, usage: usageLine() })); } catch { /* best effort */ }
581
+ const postTrajectory = async () => { try { await post(["FORGE:TRAJECTORY", REGISTER_MARKER], renderTrajectory({ ...T, usage: usageLine() })); } catch { /* best effort */ } };
582
+ if (deferTail) { postRun.add("lane-facts", postLaneFacts); postRun.add("trajectory", postTrajectory); } else await postTrajectory();
558
583
  }
584
+ if (deferTail) postRun.add("teardown", () => teardown(reason, extra)); // last: the structure delta and guard read the worktree
559
585
  await releaseLease(reason, code, extra.mergedTo ?? null);
560
586
  done = { terminalReason: reason, detail, branch, worktree: wt, 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(),
561
587
  ...(laneHead && reason !== "merged" ? { laneHead: { ...laneHead } } : {}), light, ...(lightVerdict ? { light_eligibility: lightVerdict } : {}), ...(lightUpgrade ? { light_upgrade: lightUpgrade } : {}), // #4453
562
588
  ...(Object.keys(waits).length ? { waits: { ...waits } } : {}), ...(followupsFiled.length ? { followups: followupsFiled.map((f) => ({ ...f })) } : {}), ...(pendingRecord().length ? { pendingFollowups: pendingRecord() } : {}), ...(heavyQueueMax ? { heavyQueueMax } : {}), ...(precheckRan ? { precheckMs, precheckDeferred } : {}),
563
589
  ...(firstPassOf(builderTriggers) != null ? { firstPass: firstPassOf(builderTriggers) } : {}), ...(tb.record() ? { turns: tb.record() } : {}), // #4392
564
590
  ...(route ? { builderRoute: { tier: route.tier, class: route.class, escalated, model: route.model ?? "default" } } : {}),
565
- ...(gateRan ? { conformance: { mode: conformance === "enforce" || riskEnforced ? "enforce" : "shadow", would: shadowWould, risk: Boolean(riskEnforced), ...(Object.keys(kinds).length ? { kinds: [...failureClasses] } : {}) } } : {}), ...extra };
591
+ ...(gateRan ? { conformance: { mode: conformance === "enforce" || riskEnforced ? "enforce" : "shadow", would: shadowWould, ...(adequacyCounts(adequacy) ? { test_adequacy: adequacyCounts(adequacy) } : {}), risk: Boolean(riskEnforced), ...(Object.keys(kinds).length ? { kinds: [...failureClasses] } : {}) } } : {}), ...extra };
592
+ if (deferTail && o.deferPostRun) done.postRun = () => postRun.run(); // the caller runs it once the lane slot is free
593
+ else await postRun.run();
566
594
  return done;
567
595
  }
568
596
  /** #4401: post the lane's FORGE:FACTS (result.json facts and validation, changed files, contract decisions); never fails a run. */
@@ -613,8 +641,11 @@ export async function runCore(o) {
613
641
  const notes = [premiseAnnotation(predicate), closedEdgeNote(closedDeps), link, askNote].filter(Boolean).join("\n");
614
642
  try { await post("FORGE:NEEDS_HUMAN", `## Needs human\n${why}${notes ? `\n\n${notes}` : ""}${recoverUnlabelled ? `\n\n${laneRecoveryEvidence("needs-human", code, "")}` : ""}\n\n_${usageLine()}_`); }
615
643
  catch (e) { labelFailed("comment", e); }
616
- try { await ghc(["issue", "edit", String(issue), "-R", repo, "--add-label", "needs-human"]); }
617
- catch (e) { labelFailed("label", e); }
644
+ // #5423: an environment gap is the engine's to recover (the batch requeues it), so a first lane leaves the issue visible; a final recovery lane still labels
645
+ if (!(!recover && ENV_ENGINE_OWNED_CODES.includes(code))) {
646
+ try { await ghc(["issue", "edit", String(issue), "-R", repo, "--add-label", "needs-human"]); }
647
+ catch (e) { labelFailed("label", e); }
648
+ }
618
649
  } catch { /* best effort */ }
619
650
  return finish("needs-human", why, { code, ...extra, ...(recover ? { recovery: true } : {}) }, code);
620
651
  }
@@ -710,11 +741,27 @@ export async function runCore(o) {
710
741
  * #4325: the lane env every engine-run command shares with the builder: shared package-manager stores (#4220), the run
711
742
  * TMPDIR (#4104), FORGE_HOST_PARALLELISM (#4182) and the pinned toolchain (#4163); the engine's own keys win over the stores.
712
743
  */
744
+ let signoffEnv = {};
745
+ const SIGNOFF_HOOK = '#!/bin/sh\nid=$(git var GIT_COMMITTER_IDENT 2>/dev/null | sed \'s/>.*/>/\')\ncase "$id" in ""|*@localhost\\>) ;; *) git interpret-trailers --in-place --if-exists addIfDifferent --trailer "Signed-off-by: $id" "$1" ;; esac\n';
746
+ /** #5437: builder commits are signed off when made (a worktree commit-msg hook via GIT_CONFIG_*, the repo's own hooks chained), so signOffUnpushed finds nothing to rewrite. Best effort: without it the rewrite stays the fallback. */
747
+ async function installSignoffHook() {
748
+ if (!runTmp || !io.fs?.list || !io.runCommand) return;
749
+ try {
750
+ const orig = String(await git(["rev-parse", "--git-path", "hooks"])).trim(), abs = orig.startsWith("/") ? orig : `${wt}/${orig}`, dir = `${runTmp}/hooks`;
751
+ const q = (x) => `'${String(x).replace(/'/g, "'\\''")}'`, own = ((await io.fs.list(abs)) ?? []).filter((n) => n && !n.endsWith(".sample"));
752
+ for (const n of own.filter((x) => x !== "commit-msg")) await io.fs.write(`${dir}/${n}`, `#!/bin/sh\nexec ${q(`${abs}/${n}`)} "$@"\n`);
753
+ await io.fs.write(`${dir}/commit-msg`, `${SIGNOFF_HOOK}${own.includes("commit-msg") ? `exec ${q(`${abs}/commit-msg`)} "$@"\n` : "exit 0\n"}`);
754
+ const x = await io.runCommand({ command: `chmod +x ${q(dir)}/*`, cwd: wt, timeoutMs: 10000, env: laneEnv() }), r = x?.r ?? x;
755
+ if (r?.exit) throw new Error("chmod failed");
756
+ signoffEnv = { GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "core.hooksPath", GIT_CONFIG_VALUE_0: dir };
757
+ ev({ event: "SIGNOFF_HOOK", dir });
758
+ } catch { signoffEnv = {}; }
759
+ }
713
760
  function laneEnv() {
714
761
  let deps = {};
715
762
  try { deps = io.deps?.env?.() ?? {}; } catch { deps = {}; }
716
763
  const par = verifyParallelism();
717
- return { ...deps, ...(runTmp ? { TMPDIR: runTmp } : {}), ...(par ? { FORGE_HOST_PARALLELISM: par } : {}), FORGE_LANE_WORKTREE: "1", ...(toolchain?.env ?? {}) }; // #5333: the hook denies git stash where this is set
764
+ return { ...deps, ...(runTmp ? { TMPDIR: runTmp } : {}), ...(par ? { FORGE_HOST_PARALLELISM: par } : {}), FORGE_LANE_WORKTREE: "1", ...sandboxEnv, ...(toolchain?.env ?? {}) }; // #5333: the hook denies git stash where this is set
718
765
  }
719
766
  /** #5168: a failed claude login ends the lane `deferred` `backend.auth`, held per account by the batch (never the relaunch or the breaker). */
720
767
  const authDeferral = (e) => Object.assign(e, { deferCode: OUTCOME_CODES.BACKEND_AUTH, retryInSeconds: AUTH_RETRY_SECONDS, backendId: laneBackendId(process.env, rotator),
@@ -722,8 +769,10 @@ export async function runCore(o) {
722
769
  /** #5236: no account has room: the lane ends deferred `quota.exhausted` (earliest reset) and emits QUOTA_EXHAUSTED, never a spawn or a far pause. */
723
770
  const exhaustedStop = (e, x, role) => { ev({ event: "QUOTA_EXHAUSTED", phase: role, earliestReset: x.earliestReset }); return exhaustedDeferral(e, { earliestReset: x.earliestReset, backendId: laneBackendId(process.env, rotator), now: now() }); };
724
771
  /** Runner call with the per-run TMPDIR and FORGE_HOST_PARALLELISM; a usage limit pauses and resumes the same step, or defers past the cap (#4101). */
772
+ let firstSession = false, setupWait = null, firstCallAt = null, packDoneAt = null, spawnLogged = false; // #5434
725
773
  async function callRunner(args) {
726
774
  let pauses = 0, rotations = 0, pinned = null, credTries = 0;
775
+ if (!firstSession) { firstSession = true; firstCallAt = now(); ev({ event: "FIRST_SESSION", ms: firstCallAt - t0, role: args.role ?? null, ...(packDoneAt != null ? { since_context_pack_ms: firstCallAt - packDoneAt } : {}) }); } // #5434: lane start to the first model session
727
776
  for (;;) {
728
777
  if (smartRotator && !pinned) { const x = poolExhausted(rotator, laneLimited); if (x) throw exhaustedStop(new Error("no account has capacity"), x, args.role); } // #5236: the shim would fall back to the default profile
729
778
  // #4181: every Docker resource the builder creates carries the lane's ownership labels (same batch/lane as the ledger).
@@ -737,7 +786,7 @@ export async function runCore(o) {
737
786
  let watch = null; // #5268: the shim execs claude (same pid) after spawn, so keep reading until the account shows
738
787
  const spawnHook = smartRotator ? { onSpawn: (child, ...rest) => { if (account === null && !watch) { const pid = child?.pid ?? child; watch = watchAccount(() => rotator.accountOfPid(pid), { onFound: (a) => { account = a; } }); } return args.onSpawn?.(child, ...rest); } } : {};
739
788
  const pin = pinned ? { ...(pinned.bin ? { bin: pinned.bin } : {}) } : {};
740
- try { const res = await io.runner({ ...args, ...spawnHook, ...pin, system, env: { ...laneEnv(), FORGE_DOCKER_LABELS: labels, ...(runTmp ? { CLAUDE_CODE_TMPDIR: runTmp } : {}), ...(toolchain?.env ?? {}), ...heavy, ...profEnv, ...(pinned?.env ?? {}) } }); watch?.stop(); return res; }
789
+ try { const res = await io.runner({ ...args, ...spawnHook, ...pin, system, env: { ...laneEnv(), ...signoffEnv, FORGE_DOCKER_LABELS: labels, COMPOSE_PROJECT_NAME: `forgedock-lane-${issue}`, ...(runTmp ? { CLAUDE_CODE_TMPDIR: runTmp } : {}), ...(toolchain?.env ?? {}), ...heavy, ...profEnv, ...(pinned?.env ?? {}) } }); watch?.stop(); return res; }
741
790
  catch (e) {
742
791
  watch?.stop(); watch?.refresh(); // #5268: the account the shim exec'd, read before the limited child is gone or now
743
792
  let epoch = Number.isFinite(e?.resetAtEpochMs) ? e.resetAtEpochMs : null;
@@ -963,7 +1012,8 @@ export async function runCore(o) {
963
1012
  const control = {};
964
1013
  const governor = startGovernor(control);
965
1014
  let spawned = null;
966
- const onSpawn = (child) => { if (Number.isSafeInteger(child?.pid) && !finishing) { spawned = child.pid; ledgerDo((l) => l.register("pid", child.pid, { marker: basename(String(child.spawnfile ?? "")) || null })); } };
1015
+ const onSpawn = (child) => { if (!spawnLogged && firstCallAt != null) { spawnLogged = true; ev({ event: "LANE_SETUP_TIMING", step: "cli_init", ms: now() - firstCallAt }); } // #5434: runner call to process spawn
1016
+ if (Number.isSafeInteger(child?.pid) && !finishing) { spawned = child.pid; ledgerDo((l) => l.register("pid", child.pid, { marker: basename(String(child.spawnfile ?? "")) || null })); } };
967
1017
  const session = {}, cur = inflight = { n, session, at: now(), flushed: false, opts: { model, mode, trigger, restartOf } };
968
1018
  const call = Promise.resolve(callRunner({ role: "builder", issue, cwd: wt, model: model ?? laneModel(), resume, system: "", prompt, control, ...(profile ? { profile } : {}), onSpawn, session, agents: explorerAgents(exploreCfg), rereadNudge: true,
969
1019
  idleMs: Math.round(cliIdleMinutes * 60000), maxMs: Math.round(cliMaxMinutes * 60000), laneLimits, ...(contextMax > 0 ? { contextMax } : {}), ...(turnMax > 0 ? { turnMax } : {}),
@@ -1272,6 +1322,9 @@ export async function runCore(o) {
1272
1322
 
1273
1323
  try {
1274
1324
  // ---- 1. claim ----
1325
+ // #5435: the lane fetch is independent of the claim's GitHub writes; start it now and await it before the resume probe.
1326
+ const fetchP = step("fetch", async () => { try { await io.git(["fetch", "origin", lane], { cwd }); } catch { /* offline: use the local ref */ } });
1327
+ await step("claim", async () => {
1275
1328
  await label("investigating");
1276
1329
  await post("FORGE:STARTED", `Started work on #${issue} (base \`${lane}\`).`);
1277
1330
  if (recover) {
@@ -1284,17 +1337,32 @@ export async function runCore(o) {
1284
1337
  T.decisions.push(`Recovery pass for ${recover.code} (attempt ${recover.attempt}): needs-human removed, PR resumed`);
1285
1338
  ev({ event: "RECOVERY_START", code: recover.code, attempt: recover.attempt });
1286
1339
  }
1340
+ });
1287
1341
 
1288
1342
  // ---- 2. worktree (resume an open PR / remote branch) ----
1289
- try { await io.git(["fetch", "origin", lane], { cwd }); } catch { /* offline: use the local ref */ }
1343
+ await fetchP;
1290
1344
  let resumed = null, fromSalvage = false;
1291
- try {
1292
- const prs = JSON.parse(String(await ghc(["pr", "list", "-R", repo, "--head", branch, "--state", "open", "--json", "number,headRefOid,baseRefName"])) || "[]");
1293
- const remote = String(await io.git(["ls-remote", "--heads", "origin", branch], { cwd })).trim();
1345
+ // #5469: adopt: the open PR to the lane base that references this issue and was not made by the pipeline; its head branch is the lane branch
1346
+ let adoptPr = null;
1347
+ if (o.adopt) {
1348
+ await step("adopt_probe", async () => { try {
1349
+ const prs = JSON.parse(String(await ghc(["pr", "list", "-R", repo, "--state", "open", "--base", lane, "--json", "number,headRefName,body,closingIssuesReferences"])) || "[]");
1350
+ adoptPr = prs.find((x) => x.headRefName !== branch && ((x.closingIssuesReferences ?? []).some((r) => r.number === issue) || new RegExp(`#${issue}(?!\\d)`).test(x.body ?? ""))) ?? null;
1351
+ } catch { adoptPr = null; } });
1352
+ if (!adoptPr) return await needsHuman(`--adopt: no open PR to \`${lane}\` references #${issue} from a branch other than ${branch}; nothing to adopt.`, OUTCOME_CODES.LANE_MISMATCH);
1353
+ branch = adoptPr.headRefName;
1354
+ T.decisions.push(`Adopting PR #${adoptPr.number} (${branch}): review, base-sync and merge without a rebuild`);
1355
+ }
1356
+ await step("resume_probe", async () => { try {
1357
+ const [prsRaw, remoteRaw] = await Promise.all([ // #5435: independent network reads, in parallel
1358
+ ghc(["pr", "list", "-R", repo, "--head", branch, "--state", "open", "--json", "number,headRefOid,baseRefName"]),
1359
+ io.git(["ls-remote", "--heads", "origin", branch], { cwd })]);
1360
+ const prs = JSON.parse(String(prsRaw) || "[]");
1361
+ const remote = String(remoteRaw).trim();
1294
1362
  if (prs.length || remote) resumed = { pr: prs[0]?.number ?? null, base: prs[0]?.baseRefName ?? null };
1295
1363
  const salv = (await pickSalvage({ io, cwd, issue, branch, hasBranch: Boolean(remote) }).catch((e) => { ev({ event: "SALVAGE_PICK_FAILED", error: String(e?.message ?? e).slice(0, 200) }); return null; }))?.ref; // release #5068 delta SPEC-2: never silent // #4958, #5063: the newest salvage ref that is not behind the lane branch
1296
1364
  if (salv) { await io.git(["fetch", "origin", `${salv}:refs/remotes/origin/${branch}`], { cwd }); resumed = { pr: prs[0]?.number ?? null, base: prs[0]?.baseRefName ?? null }; fromSalvage = true; ev({ event: "RESUME_FROM_SALVAGE", ref: salv }); }
1297
- } catch { /* no resume info: start fresh */ }
1365
+ } catch { /* no resume info: start fresh */ } });
1298
1366
  // An open PR on another base (a hand-retargeted PR, or one opened before lane resolution) is never merged (#4125).
1299
1367
  // #4593: a shipped milestone lane (fully merged into staging) cannot take new work; follow the open PR's live base.
1300
1368
  if (resumed?.base && resumed.base !== lane && !isDefaultLane(resumed.base, defaults)) {
@@ -1323,10 +1391,12 @@ export async function runCore(o) {
1323
1391
  }
1324
1392
  // #4162: a run that died can leave its runner writing into this worktree, and uncommitted work in it. Stop the
1325
1393
  // processes and save the work before the worktree is removed; the lease above makes this run the only one doing so.
1394
+ await step("salvage_cleanup", async () => {
1326
1395
  await stopWorktreeProcs();
1327
1396
  salvagedRef = await salvage("an earlier run");
1328
1397
  try { await io.git(["worktree", "remove", "--force", wt], { cwd }); } catch { /* none */ }
1329
1398
  try { await io.git(["worktree", "prune"], { cwd }); } catch { /* best effort */ }
1399
+ });
1330
1400
  // Concurrent lanes in one repo race on .git/config.lock / index.lock during `worktree add`; retry with jitter.
1331
1401
  // A leftover dir that git no longer lists as a worktree blocks `worktree add`. Remove ONLY this issue's lean dir under the lean root.
1332
1402
  const wtRoot = o.worktreeRoot ?? join(cwd, ".claude", "worktrees");
@@ -1343,10 +1413,17 @@ export async function runCore(o) {
1343
1413
  const LOCK_RE = /could not lock|cannot lock ref|\.lock'?: File exists|Unable to create .*\.lock|index\.lock|packed-refs\.lock/i;
1344
1414
  // #4221: tracked blobs >= sparseMaxKb stay out of the checkout (lockfiles/manifests always in); falls back to a full checkout.
1345
1415
  const sparseMaxKb = Number.isFinite(o.sparseMaxKb) && o.sparseMaxKb >= 0 ? o.sparseMaxKb : DEFAULT_SPARSE_MAX_KB;
1416
+ // #5435: attribute the cold add to its git calls: the sparse plan (ls-tree), the add + checkout (which runs any post-checkout hook), the sparse checkout
1417
+ const GIT_STEP = { "ls-tree": "sparse_plan", worktree: "git_worktree_add", "sparse-checkout": "sparse_checkout", "read-tree": "sparse_checkout" };
1418
+ // #5435 (R2): the lane's own checkout never needs the repo's post-checkout hook (husky/lfs installs); it is skipped for these calls only.
1419
+ const timedGit = async (args, opts) => {
1420
+ const name = GIT_STEP[args[0]], s0 = now();
1421
+ try { return await io.git(args, name && args[0] !== "ls-tree" ? { ...opts, env: { ...opts?.env, ...NO_HOOKS } } : opts); } finally { if (name) { const ms = Math.max(0, now() - s0); phaseLedger.addStep("sandbox_start", name, ms); ev({ event: "SANDBOX_STEP", step: name, ms }); } }
1422
+ };
1346
1423
  const addWorktree = async (args, ref) => {
1347
1424
  let cleaned = false;
1348
1425
  for (let i = 0; ; i++) {
1349
- try { return await addLaneWorktree(io.git, io.fs?.write, { cwd, wt, addArgs: args, ref, maxBlobBytes: sparseMaxKb * 1024 }); } catch (e) {
1426
+ try { return await addLaneWorktree(timedGit, io.fs?.write, { cwd, wt, addArgs: args, ref, maxBlobBytes: sparseMaxKb * 1024 }); } catch (e) {
1350
1427
  const msg = String(e?.stderr ?? e?.message ?? e);
1351
1428
  if (!cleaned && /already exists/i.test(msg) && (await leftoverDir())) { cleaned = true; continue; }
1352
1429
  if (i >= 4 || !LOCK_RE.test(msg)) throw e;
@@ -1386,7 +1463,14 @@ export async function runCore(o) {
1386
1463
  T.decisions.push(`Lane branch ${branch} held only ${LEAN_DIR}/ scratch: its stale checkpoint was dropped and the issue is planned fresh`);
1387
1464
  }
1388
1465
  } else {
1389
- wtInfo = await addWorktree(["worktree", "add", "-B", branch, wt, base], base);
1466
+ const warmN = warmTreeCount(o.warmTrees);
1467
+ const wtRootDir = o.worktreeRoot ?? join(cwd, ".claude", "worktrees");
1468
+ if (warmN) { // #5435: a pooled tree is claimed and its HEAD verified against the base sha; any failure is the cold add below
1469
+ wtInfo = await step("warm_claim", () => claimWarm({ git: io.git, cwd, root: wtRootDir, wt, branch, base, n: warmN }).catch(() => null));
1470
+ if (wtInfo) ev({ event: "WARM_TREE_CLAIMED", sha: wtInfo.sha });
1471
+ }
1472
+ if (!wtInfo) wtInfo = await step("worktree_add", () => addWorktree(["worktree", "add", "-B", branch, wt, base], base));
1473
+ if (warmN) refillWarm({ git: io.git, cwd, root: wtRootDir, ref: base, n: warmN, maxBlobBytes: sparseMaxKb * 1024, write: io.fs?.write }).catch(() => {});
1390
1474
  }
1391
1475
  wtCreated = true;
1392
1476
  if (fromSalvage) await dropSalvageTracking({ git, branch }); // #5047: the salvaged commits are unpublished: the sign-off range must include them
@@ -1398,9 +1482,12 @@ export async function runCore(o) {
1398
1482
  ev({ event: "WORKTREE_SPARSE_FALLBACK", reason: wtInfo.fallback });
1399
1483
  T.anomalies.push(`Sparse checkout failed, full checkout used: ${wtInfo.fallback}`);
1400
1484
  }
1485
+ await step("scratch_setup", async () => { // #5435: timed with the other startup steps
1401
1486
  const excl = String(await git(["rev-parse", "--git-path", "info/exclude"])).trim();
1402
1487
  await io.fs.append(excl.startsWith("/") ? excl : `${wt}/${excl}`, `\n${LEAN_DIR}/\n`);
1488
+ await installSignoffHook();
1403
1489
  if (!resumed && await clearLaneScratch({ git, fs: io.fs, cwd: wt })) ev({ event: "LANE_SCRATCH_CLEARED" }); // #4880: never read a previous lane's scratch
1490
+ });
1404
1491
  // ---- 2a. lane profile (#4395): the repo's lane instruction file replaces CLAUDE.md; a bad one falls back with an anomaly ----
1405
1492
  const lanePath = typeof o.laneInstructions === "string" ? o.laneInstructions.trim() : "";
1406
1493
  if (laneProfile.name !== "full" && lanePath) {
@@ -1416,8 +1503,8 @@ export async function runCore(o) {
1416
1503
  : laneProfile.name === "full" ? "Lane profile: full session (FORGEDOCK_FULL_SESSION=1)" : "Lane profile: auto-memory off, CLAUDE.md loaded");
1417
1504
  // ---- 2b. toolchain pins + env.setup (#4163): before the builder; zero LLM. No pins and no setup changes nothing ----
1418
1505
  try {
1419
- const tc = await (io.prepareToolchain ?? prepareToolchain)({ dir: wt, override: toolchainOverride, read: io.fs.read,
1420
- binDir: join(runTmp ?? join(wt, LEAN_DIR), "toolchain", "bin") });
1506
+ const tc = await step("toolchain", () => (io.prepareToolchain ?? prepareToolchain)({ dir: wt, override: toolchainOverride, read: io.fs.read,
1507
+ binDir: join(runTmp ?? join(wt, LEAN_DIR), "toolchain", "bin") }));
1421
1508
  if (tc?.summary) {
1422
1509
  toolchain = { env: tc.env ?? null, summary: tc.summary };
1423
1510
  ev({ event: "TOOLCHAIN_PINNED", pins: tc.summary, shims: tc.shims });
@@ -1426,18 +1513,25 @@ export async function runCore(o) {
1426
1513
  if (tc?.warning) { T.anomalies.push(tc.warning); ev({ event: "TOOLCHAIN_WARNING", warning: tc.warning }); }
1427
1514
  for (const n of tc?.notes ?? []) T.anomalies.push(n);
1428
1515
  } catch (e) { T.anomalies.push(`Toolchain detection failed (host toolchain used): ${String(e?.message ?? e).slice(0, 200)}`); }
1516
+ // #5434: deps, heavy shims and env.setup overlap the plan session (read-only); gateSetup() awaits them before anything that builds or runs commands.
1517
+ let setupSettled = false;
1518
+ const setupStep = (step, t) => ev({ event: "LANE_SETUP_TIMING", step, ms: now() - t });
1519
+ const setupP = (async () => {
1429
1520
  // #4220: link node_modules/.venv from the shared cache keyed by lock hash (or install once and publish). Never fails the run.
1430
1521
  // After 2b (#4347): installs run with the toolchain env, so a pm only its shim provides resolves; no env is the host PATH.
1431
1522
  if (io.deps?.prepare) {
1432
- phaseLedger.enter("deps_install");
1523
+ const tD = now();
1433
1524
  let res;
1434
1525
  try { res = await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined }); } catch (e) { res = [{ status: "failed", eco: null, key: null, ms: 0, reason: String(e?.message ?? e).slice(0, 300) }]; }
1526
+ depResults = Array.isArray(res) ? res : []; // #5447: classified against the changed files at the gate
1527
+ setupStep("deps", tD);
1435
1528
  for (const r of Array.isArray(res) ? res : []) {
1436
1529
  ev({ event: "DEPS_PREPARED", status: r?.status ?? null, eco: r?.eco ?? null, key: r?.key ?? null, ms: r?.ms ?? null, reason: r?.reason ?? null });
1437
1530
  if (r?.eco) T.decisions.push(`Dependencies (${r.eco}${r.key ? ` ${r.key}` : ""}): ${r.status}${r.reason ? ` (${r.reason})` : ""}${Number.isFinite(r.ms) ? ` in ${Math.round(r.ms / 100) / 10}s` : ""}`);
1438
1531
  }
1439
1532
  }
1440
1533
  // ---- 2c. heavy-step shims (#4169): after the toolchain, so a heavy shim's real binary is the pinned toolchain shim ----
1534
+ const tH = now();
1441
1535
  if (heavyOn) {
1442
1536
  try {
1443
1537
  const root = runTmp ?? join(wt, LEAN_DIR), binDir = join(root, "heavy", "bin"), path = toolchain?.env?.PATH ?? process.env.PATH ?? "";
@@ -1451,18 +1545,32 @@ export async function runCore(o) {
1451
1545
  }
1452
1546
  } catch (e) { T.anomalies.push(`Heavy-step shims not written (builder steps ungated): ${String(e?.message ?? e).slice(0, 200)}`); }
1453
1547
  }
1548
+ setupStep("heavy_shims", tH);
1454
1549
  if (typeof envSetup === "string" && envSetup.trim()) {
1550
+ const tE = now();
1455
1551
  let r;
1456
1552
  if (!io.runSetup) r = { exit: 1, stderr: "no setup effect is configured" };
1457
1553
  else { try { r = await heavyStep("setup", () => io.runSetup({ cwd: wt, command: envSetup, env: laneEnv() })); } catch (e) { r = { exit: 1, stderr: String(e?.message ?? e) }; } }
1458
- ev({ event: "ENV_SETUP", exit: r?.exit ?? 1 });
1554
+ ev({ event: "ENV_SETUP", exit: r?.exit ?? 1 }); setupStep("env_setup", tE);
1459
1555
  if (r?.exit !== 0) {
1460
1556
  const tail = String(r?.stderr || r?.stdout || "").trim().slice(-800);
1461
- T.anomalies.push(`Environment error: forge.yaml env.setup exited ${r?.exit ?? "?"}; the builder did not run`);
1462
- return await needsHuman(`Environment error (not a build failure): forge.yaml \`env.setup\` (\`${envSetup.slice(0, 200)}\`) exited ${r?.exit ?? "?"} in the fresh worktree, so the builder was not started. Fix the setup command or the environment, then rerun.${tail ? `\n\n\`\`\`\n${tail}\n\`\`\`` : ""}`, OUTCOME_CODES.ENV_SETUP_FAILED);
1557
+ T.anomalies.push(`Environment error: forge.yaml env.setup exited ${r?.exit ?? "?"}; the build did not run`);
1558
+ return () => needsHuman(`Environment error (not a build failure): forge.yaml \`env.setup\` (\`${envSetup.slice(0, 200)}\`) exited ${r?.exit ?? "?"} in the fresh worktree, so the build was not started. Fix the setup command or the environment, then rerun.${tail ? `\n\n\`\`\`\n${tail}\n\`\`\`` : ""}`, OUTCOME_CODES.ENV_SETUP_FAILED);
1463
1559
  }
1464
1560
  T.decisions.push("forge.yaml env.setup ran once in the fresh worktree");
1465
1561
  }
1562
+ return null;
1563
+ })().finally(() => { setupSettled = true; });
1564
+ setupWait = setupP;
1565
+ const TIMED_OUT = Symbol("timed-out");
1566
+ /** #5434: `p` or TIMED_OUT after `ms` (0 = no bound); a rejection is null. The work keeps running. */
1567
+ const within = (p, ms) => new Promise((res) => { const t = ms > 0 ? setTimeout(() => res(TIMED_OUT), ms) : null; Promise.resolve(p).then((v) => { clearTimeout(t); res(v); }, () => { clearTimeout(t); res(null); }); });
1568
+ /** #5434: the setup is awaited (the residual wait is the deps_install phase); a failed env.setup ends the lane needs-human. Returns the terminal or null. */
1569
+ let setupFail;
1570
+ const gateSetup = async () => {
1571
+ if (setupFail === undefined) { const r = setupSettled ? await setupP : await phaseLedger.during("deps_install", () => setupP); setupFail = typeof r === "function" ? await r() : null; }
1572
+ return setupFail;
1573
+ };
1466
1574
  const names = (out) => String(out).split("\n").map((s) => s.trim()).filter(Boolean);
1467
1575
  // #4160: files the branch touched (three-dot) whose content still differs from the base tip (two-dot); a file merged
1468
1576
  // in from the base by a base-sync equals the base and drops out of the scope check.
@@ -1520,9 +1628,27 @@ export async function runCore(o) {
1520
1628
  }
1521
1629
  ev({ event: "REPRO_RED_GREEN", ...words });
1522
1630
  T.decisions.push(`repro_test ${t.path ?? ""}${t.id ? ` ${t.id}` : ""}: BASE=${words.base} HEAD=${words.head}`);
1631
+ if (reproQuality !== "off" && words.base === "FAILED" && words.head === "RAN") words = { ...words, ...(await reproQualityOf(t)) };
1523
1632
  return words;
1524
1633
  };
1525
1634
 
1635
+ /** #5446: patch-echo + targeted mutation of the fix; {quality, enforce}. Never throws (a dirty tree after a mutation is an anomaly). */
1636
+ const reproQualityOf = async (t) => {
1637
+ try {
1638
+ const files = (await changedFiles()).filter((f) => !isTestPath(f));
1639
+ const srcDiff = files.length ? String(await git(["diff", "-U0", `${base}...HEAD`, "--", ...files])) : "";
1640
+ const tests = (await changedFiles()).filter((f) => isTestPath(f));
1641
+ const testDiff = tests.length ? String(await git(["diff", "-U0", `${base}...HEAD`, "--", ...tests])) : "";
1642
+ const echo = patchEcho({ testDiff, srcDiff });
1643
+ const m = echo ? { results: [] } : await runReproMutations({ mutations: mutationsOf(srcDiff), command: String(t.command), git, runCommand: async (a) => io.runCommand(a).then((x) => x?.r ?? x), cwd: wt, env: laneEnv(), readFile: io.fs.read, writeFile: io.fs.write });
1644
+ const quality = classifyRepro({ repro_test: t, echo, mutations: m.results });
1645
+ reproQ = quality;
1646
+ ev({ event: "REPRO_QUALITY", quality, mutations: m.results.map((x) => `${x.kind}:${x.file}:${x.line}:${x.status}`), ...(m.skipped ? { skipped: m.skipped } : {}) });
1647
+ T.decisions.push(`repro_quality: ${quality}`);
1648
+ return { quality, enforce: reproQuality === "enforce" };
1649
+ } catch (e) { T.anomalies.push(`repro_quality: ${String(e?.message ?? e).slice(0, 200)}`); return {}; }
1650
+ };
1651
+
1526
1652
  // ---- 3. builder: plan call -> frozen contract -> implement call in the same session ----
1527
1653
  phaseLedger.enter("plan");
1528
1654
  let result = null, attemptN = 0, reviewN = 0;
@@ -1545,14 +1671,19 @@ export async function runCore(o) {
1545
1671
  * io.contextFacts or any failure gives null: never fails a run. The pack never enters issueText (contract quotes).
1546
1672
  */
1547
1673
  async function contextPackStep() {
1548
- const pits = await lanePitfalls();
1674
+ const tPits = now(), pits = await lanePitfalls();
1675
+ setupStep("pack_pitfalls", tPits);
1549
1676
  if (ctxCfg.mode === "off" || !io.contextFacts) return null;
1550
1677
  try {
1678
+ const tGh = now();
1551
1679
  const headSha = String(await git(["rev-parse", base])).trim();
1552
1680
  // #4316: linked-issue states are part of the key; a failed lookup only drops them from it
1553
1681
  const links = await linkStateStamp({ gh: ghc, repo, issue, body: iss.body }).catch(() => "");
1682
+ setupStep("pack_gh_reads", tGh);
1683
+ const tCp = now();
1554
1684
  const r = await contextPackFor({ cfg: ctxCfg, issue, repo, headSha, cacheDir: dir, fs: io.fs, stamp: { scope: scopeHash, attempts: priorAttempts(iss.body, trustedComments), links, pitfalls: pits.map((x) => x.sig) },
1555
1685
  gather: () => io.contextFacts({ milestone, repo, issue, iss, comments: trustedComments, cwd: wt, checkout: cwd, base, sources: ctxCfg.sources, days: ctxCfg.days, now: now(), pitfalls: pits }) });
1686
+ setupStep("pack_compile", tCp); packDoneAt = now();
1556
1687
  const p = r.pack;
1557
1688
  const inPack = Array.isArray(p.pitfalls) ? p.pitfalls : [];
1558
1689
  pitMatched = inPack.filter((x) => x.match === "files").length;
@@ -1655,6 +1786,15 @@ export async function runCore(o) {
1655
1786
  * env leaves empty and run each remaining command once on the base worktree (io.preflightRun). The misses; [] without either hook.
1656
1787
  */
1657
1788
  /** #5020: forge.yaml validate.recipes rewrite frozen commands; a check-less post-deploy requirement becomes a defer to the orchestrator. */
1789
+ const genChecks = {}; // #5468: generated post-deploy check entries, committed with the lane
1790
+ async function persistGenChecks() {
1791
+ if (!Object.keys(genChecks).length || !io.fs?.write) return;
1792
+ try {
1793
+ const cur = await io.fs.read(`${wt}/${CHECKS_FILE}`).catch(() => "");
1794
+ await io.fs.write(`${wt}/${CHECKS_FILE}`, mergeCheckEntries(cur, genChecks));
1795
+ await git(["add", "--", CHECKS_FILE]); await git(["commit", "--no-verify", "-m", "chore(forge): generated post-deploy checks for production-only e2e requirements (#5468)"]);
1796
+ } catch (e) { T.anomalies.push(`generated post-deploy checks not committed: ${String(e?.message ?? e).slice(0, 160)}`); }
1797
+ }
1658
1798
  function freezeRewrites(c) {
1659
1799
  const r = applyValidateRecipes(c, validateRecipes);
1660
1800
  const pd = (id, cmd) => { const to = rewriteProjectDirCommand(cmd); if (to !== cmd) T.decisions.push(`project-dir rewrite of ${id}: \`${cmd}\` -> \`${to}\``); return to; };
@@ -1664,6 +1804,10 @@ export async function runCore(o) {
1664
1804
  if (t && typeof t === "object" && typeof t.command === "string") r.contract = { ...r.contract, repro_test: { ...t, command: pd("repro_test", t.command) } };
1665
1805
  }
1666
1806
  for (const x of r.applied) T.decisions.push(`validate recipe rewrote ${x.id}: \`${x.from}\` -> \`${x.to}\``);
1807
+ r.contract = foldRegression(r.contract); // #5448: the blast-radius regression set runs as validate G# entries
1808
+ const e = autoPostDeployE2e(r.contract); // #5468: production-only e2e/manual rows become post-deploy with a generated check
1809
+ for (const x of e.converted) { genChecks[x.check] = x.entry; T.decisions.push(`Production-only e2e/manual requirement ${x.id} frozen as post-deploy with generated check ${x.check}`); }
1810
+ r.contract = e.contract;
1667
1811
  const d = deferChecklessPostDeploy(r.contract);
1668
1812
  if (d.converted.length) T.decisions.push(`Post-deploy with no registered check deferred to the orchestrator: ${d.converted.join(", ")}`);
1669
1813
  return d.contract;
@@ -1838,6 +1982,17 @@ export async function runCore(o) {
1838
1982
  return applied.length;
1839
1983
  }
1840
1984
  const mech = io.mechFix ?? { applyEnumerating, renameDuplicates }; // #5348: a test seam; the engine uses mechfix.mjs
1985
+ /** #5480: apply the enumerating edits, then run each edited test; a red or unrunnable one is restored and left to a session. */
1986
+ async function enumeratingMech(missing) {
1987
+ const r = await mech.applyEnumerating({ missing, cwd: wt });
1988
+ if (!r.applied.length) return r;
1989
+ const runTest = async (t) => {
1990
+ if (!io.runCommand || !/\.[cm]?js$/.test(t)) return false;
1991
+ const x = await io.runCommand({ command: `node --test ${/^[\w./@-]+$/.test(t) ? t : `'${t.replace(/'/g, "'\\''")}'`}`, cwd: wt, timeoutMs: 120000, env: laneEnv() }).then((y) => y?.r ?? y).catch(() => null);
1992
+ return x?.rc === 0;
1993
+ };
1994
+ return io.mechFix ? r : await verifyApplied({ result: r, cwd: wt, runTest });
1995
+ }
1841
1996
  let dupMech = 0; // #5348: duplicate renames the last dupsResidual() applied
1842
1997
  /** Duplicate-export findings that still need a model: the detector, then the deterministic rename, then the detector again. */
1843
1998
  async function dupsResidual() {
@@ -1851,8 +2006,16 @@ export async function runCore(o) {
1851
2006
  }
1852
2007
  return dups;
1853
2008
  }
1854
- if (isSplit) {
2009
+ if (adoptPr) {
2010
+ // ---- 3''. #5469 adopt: the PR's diff is the change; no plan and no builder session, a location-only contract for the renderers ----
2011
+ { const f = await gateSetup(); if (f) return f; }
2012
+ files = await changedFiles();
2013
+ frozen = { requirements: [], deliverables: files.map((path, i) => ({ id: `D${i + 1}`, path, change: `adopted from PR #${adoptPr.number}: reviewed as built`, requirements: [] })), preserve: [], validate: [] };
2014
+ hash = contractHash(contractJson(frozen));
2015
+ T.decisions.push(`Adopted PR #${adoptPr.number}: ${files.length} changed file(s) go to review as built`);
2016
+ } else if (isSplit) {
1855
2017
  // ---- 3'. refactor:split (#4211): deterministic move + proof replaces the builder; no builder session exists ----
2018
+ { const f = await gateSetup(); if (f) return f; } // #5434
1856
2019
  split = await splitStep();
1857
2020
  if (split.done) return split.done;
1858
2021
  frozen = split.contract; hash = contractHash(contractJson(frozen));
@@ -1885,24 +2048,51 @@ export async function runCore(o) {
1885
2048
  if (decisionsNote) T.decisions.push("Trusted FORGE:DECISION comment(s) posted after the contract froze are binding notes for the builder");
1886
2049
  await label("building");
1887
2050
  // #4450: the light lane (lean.light mode on, eligible, fresh lane): one builder session, derived contract, or an upgrade
1888
- const namedHot = await hotspotsOf({ paths: namedPaths(iss.body ?? "") }); // #5209: churn and hotspot signals for eligibility
2051
+ const waitMs = Math.max(0, Number(contextWaitSeconds) || 0) * 1000, tHot = now();
2052
+ const hotR = await within(hotspotsOf({ paths: namedPaths(iss.body ?? "") }), waitMs); // #5209: churn and hotspot signals for eligibility; #5434: bounded, overlaps the install
2053
+ const hotLate = hotR === TIMED_OUT, namedHot = hotLate ? null : hotR;
2054
+ setupStep("hotspots", tHot);
2055
+ if (hotLate) T.decisions.push(`Hotspots not ready in ${waitMs / 1000}s: light lane skipped, plan starts without hotspot facts`);
1889
2056
  const elig = lightEligibility({ title: iss.title, body: iss.body ?? "", labels: iss.labels ?? [], predictedFiles: namedPaths(iss.body ?? ""), riskPaths, hotspots: namedHot?.files ?? [], cfg: o.light ?? {} });
1890
2057
  ev({ event: "LIGHT_ELIGIBILITY", mode: elig.mode, verdict: elig.verdict, light: elig.light, reasons: elig.reasons, signals: elig.signals });
1891
2058
  lightVerdict = elig.verdict;
1892
2059
  if (elig.mode !== "off") T.decisions.push(`Light lane ${elig.mode}: ${elig.verdict}${elig.reasons.length ? ` (${elig.reasons.map((x) => x.code).join(", ")})` : ""}`);
1893
2060
  // #4451: a light try skips the hotspots and the context pack; an upgrade computes them before the plan call
1894
- const lightTry = elig.light && !frozen && !resumed && !salvagedRef && !recover;
2061
+ const ffSource = fastForwardSource(o.light), ffFresh = ffSource === "investigation" && !frozen && !resumed && !salvagedRef && !recover; // #5426: the text verdict above is only a shadow signal then
2062
+ const lightTry = ffSource === "text" && elig.light && !hotLate && !frozen && !resumed && !salvagedRef && !recover;
1895
2063
  if (!lightTry) hotFacts = namedHot; // #4451: a light try still gives its builder no hotspot facts
1896
- enumList = io.enumeratingTests ? ((await io.enumeratingTests({ cwd: wt, paths: namedPaths(iss.body ?? "") }).catch(() => null)) ?? []) : [];
2064
+ enumList = io.enumeratingTests ? ((await within(io.enumeratingTests({ cwd: wt, paths: namedPaths(iss.body ?? "") }), waitMs)) ?? []) : [];
2065
+ if (enumList === TIMED_OUT) enumList = [];
1897
2066
  facts = await factsPath([wt, cwd], io.fs?.exists);
1898
- let ctxPack = frozen || lightTry ? null : await contextPackStep();
1899
- const planPrompt = () => builderPlanPrompt(issue, tcOpts()) + hotspotPlanNote(hotFacts) + enumeratingPlanNote(enumList) + invariantsPlanNote(vcfg.invariants) + reproPlanNote(reproOn()) + unrunnableValidateNote(testRunners) + explorePlanRule(exploreCfg) + (ctxCfg.mode === "on" ? contextPackNote(ctxPack) : "");
2067
+ let ctxPack = null, packP = null;
2068
+ if (!(frozen || lightTry)) { // #5434: the plan waits for the pack at most waitMs; a late pack still posts and is read before implement
2069
+ const tPack = now(); packP = contextPackStep(); ctxPack = await within(packP, waitMs); setupStep("context_pack", tPack);
2070
+ if (ctxPack === TIMED_OUT) { ctxPack = null; T.decisions.push(`Context pack not ready in ${waitMs / 1000}s: the plan starts without it`); }
2071
+ }
2072
+ const planPrompt = () => builderPlanPrompt(issue, tcOpts()) + hotspotPlanNote(hotFacts) + enumeratingPlanNote(enumList) + invariantsPlanNote(vcfg.invariants) + reproPlanNote(reproOn()) + docsPlanNote(docsConfig) + pagePlanNote(pagesConfig) + unrunnableValidateNote(testRunners) + explorePlanRule(exploreCfg) + (ctxCfg.mode === "on" ? contextPackNote(ctxPack) : "");
1900
2073
  let lightDone = false, lightCommits = false;
1901
- if (lightTry) {
2074
+ let ffPlan = "full", ffGo = false, lightElig = elig, lightPred = null, ffTriage = null; // #5426: how the plan call runs; ffGo = fast-forward to the light step
2075
+ const ffTriageOf = async (raw) => parseTriage(raw, await io.fs.read(`${wt}/${INVESTIGATION_FILE}`).catch(() => ""));
2076
+ if (ffFresh && elig.mode === "on") { // #5426: investigation first; its verdict, predicted files and size pick the depth
2077
+ await builder(++attemptN, investigationOnlyPrompt(issue, tcOpts()), null, true, () => investigationOnlyPrompt(issue, tcOpts()), { trigger: "plan" });
2078
+ planned = true; result = await readResult();
2079
+ if (["invalid", "already-fixed", "blocked"].includes(result?.status)) ffPlan = "none"; // the shared close/block handling below
2080
+ else {
2081
+ ffTriage = await ffTriageOf(await io.fs.read(`${wt}/${TRIAGE_FILE}`).catch(() => null));
2082
+ const fh = await hotspotsOf({ paths: ffTriage.files });
2083
+ lightElig = fastForwardEligibility({ title: iss.title, body: iss.body ?? "", labels: iss.labels ?? [], triage: ffTriage, textFiles: namedPaths(iss.body ?? ""), riskPaths, hotspots: fh?.files ?? [], cfg: o.light ?? {} });
2084
+ ev(fastForwardEvent(lightElig, ffTriage));
2085
+ T.decisions.push(`Investigation decides depth: ${lightElig.verdict}${lightElig.reasons.length ? ` (${lightElig.reasons.map((x) => x.code).join(", ")})` : ""}`);
2086
+ ffGo = lightElig.light; lightPred = ffTriage.files; hotFacts = fh ?? hotFacts;
2087
+ if (!ffGo) ffPlan = "contract";
2088
+ }
2089
+ }
2090
+ if (lightTry || ffGo) {
2091
+ { const f = await gateSetup(); if (f) return f; } // #5434: the light build is an implement-class session
1902
2092
  liveKeys = ["implementation"]; stage = "implement"; phaseLedger.enter("implement");
1903
2093
  tb.setSize(recoverySize(laneSize({ labels: (iss?.labels ?? []).map((l) => l?.name ?? l) }), recover)); // #4505
1904
- const lr = await runLightStep({ title: iss.title, issueText, riskPaths, predictedFiles: namedPaths(iss.body ?? ""), cfg: o.light ?? {}, validate: (c) => validateContract(c, issueText, { repro: reproOn() }),
1905
- build: () => builder(++attemptN, lightBuildPrompt(issue, tcOpts()) + hotspotBuildRule(hotFacts) + enumeratingBuildRule(enumList) + invariantsBuildRule(vcfg.invariants), null, true, undefined, { trigger: "build" }),
2094
+ const lr = await runLightStep({ title: iss.title, issueText, riskPaths, predictedFiles: lightPred ?? namedPaths(iss.body ?? ""), cfg: o.light ?? {}, validate: (c) => validateContract(c, issueText, { repro: reproOn(), pages: pagesConfig, testPlan: reproOn() }),
2095
+ build: () => builder(++attemptN, (ffGo ? FF_BUILD_LEAD : "") + lightBuildPrompt(issue, tcOpts()) + hotspotBuildRule(hotFacts) + enumeratingBuildRule(enumList) + invariantsBuildRule(vcfg.invariants), ffGo ? sessionId : null, true, undefined, { trigger: "build" }),
1906
2096
  readResult, checkpoint: () => checkpoint("light build"), changedFiles, reproOf, numstat: () => git(["diff", "--numstat", `${base}...HEAD`]),
1907
2097
  runTests: async (cmds) => (io.runCommand ? runLightTests({ commands: mergeChecks(vcfg.invariants ?? [], cmds).commands, parallelism: Number(verifyParallelism()) || 1, now, timeoutMs: vcfg.precheckTimeoutSeconds * 1000, acquire: () => heavyAcquire("precheck"), // #4451: host-capped
1908
2098
  run: ({ command, timeoutMs, workers }) => { const env = laneEnv(); return io.runCommand({ command, cwd: wt, timeoutMs, env: env.FORGE_HOST_PARALLELISM ? { ...env, FORGE_HOST_PARALLELISM: String(workers) } : env }); } }) : null),
@@ -1919,13 +2109,14 @@ export async function runCore(o) {
1919
2109
  await emit({ event: "CONTRACT_FROZEN", hash, requirements: frozen.requirements.length, deferred: 0, derived: "light" });
1920
2110
  ev({ event: "LIGHT_DONE", files: lr.files.length, test_failures: lr.testFailures, repro: lr.repro, cost_usd: usage.cost_usd });
1921
2111
  T.decisions.push(`Light lane: one builder session, contract ${hash} derived from the diff and the test`);
1922
- try { await post("FORGE:LITE", renderLiteReceipt({ lr, eligibility: elig, costUsd: usage.cost_usd, contractHash: hash })); } catch { /* #4452: the receipt is best effort */ }
2112
+ if (ffGo) { T.decisions.push(skippedLine(lightElig)); await flushStages({ status: "fixed" }, ["investigation"]); } // #5426: FORGE:INVESTIGATION is read downstream
2113
+ try { await post("FORGE:LITE", renderLiteReceipt({ lr, eligibility: lightElig, costUsd: usage.cost_usd, contractHash: hash, skipped: ffGo ? skippedStages(lightElig) : [] })); } catch { /* #4452: the receipt is best effort */ }
1923
2114
  } else {
1924
2115
  lightCommits = lr.files.length > 0;
1925
2116
  ev({ event: "LIGHT_UPGRADE", reasons: lr.reasons, cost_usd: usage.cost_usd });
1926
2117
  lightUpgrade = lr.reasons.map((x) => x.code);
1927
2118
  T.decisions.push(`Light lane upgraded to the full lane: ${lr.reasons.map((x) => x.code).join(", ")}`);
1928
- try { await post("FORGE:LITE", renderLiteReceipt({ lr, eligibility: elig, costUsd: usage.cost_usd })); } catch { /* #4452: the receipt is best effort */ }
2119
+ try { await post("FORGE:LITE", renderLiteReceipt({ lr, eligibility: lightElig, costUsd: usage.cost_usd })); } catch { /* #4452: the receipt is best effort */ }
1929
2120
  const d = buildResumeDigest({ state: null, comments: trustedComments, contract: null, files: lr.files, lane });
1930
2121
  resumeNote = d.text + upgradeNote(lr.reasons);
1931
2122
  result = null; // the light result.json must not read as the plan's verdict
@@ -1935,7 +2126,8 @@ export async function runCore(o) {
1935
2126
  }
1936
2127
  }
1937
2128
  if (!frozen) {
1938
- await builder(++attemptN, planPrompt() + (hasCommits || lightCommits ? PLAN_RERUN_NOTE.replace("BASE", lane) : "") + recoverNote() + resumeNote + decisionsNote, null, true, planPrompt, { trigger: "plan" });
2129
+ if (ffPlan === "contract") await builder(++attemptN, contractStepPrompt(issue, tcOpts()) + recoverNote() + decisionsNote, sessionId, true, planPrompt, { mode: "resume", trigger: "plan" }); // #5426: same session, investigation already written
2130
+ else if (ffPlan === "full") { const tPrompt = now(), planText = planPrompt(); setupStep("prompt_assembly", tPrompt); await builder(++attemptN, planText + (hasCommits || lightCommits ? PLAN_RERUN_NOTE.replace("BASE", lane) : "") + recoverNote() + resumeNote + decisionsNote, null, true, planPrompt, { trigger: "plan" }); }
1939
2131
  planned = true;
1940
2132
  result = await readResult();
1941
2133
  const evidence = (Array.isArray(result?.evidence) ? result.evidence : []).filter((x) => typeof x === "string" && x.trim());
@@ -1947,13 +2139,14 @@ export async function runCore(o) {
1947
2139
  T.plan = "skipped"; T.implement = "skipped"; T.review = "skipped"; T.pr = "none"; T.merge = "n/a";
1948
2140
  T.decisions.push(`Builder verdict: ${result.status}`);
1949
2141
  // #5152: already-fixed is delivered behaviour (`completed`); only invalid is dropped scope (`not planned`)
1950
- await ghw(["issue", "close", String(issue), "-R", repo, "--reason", result.status === "already-fixed" ? "completed" : "not planned"]);
1951
- await label("invalid");
2142
+ await Promise.all([ghw(["issue", "close", String(issue), "-R", repo, "--reason", result.status === "already-fixed" ? "completed" : "not planned"]), label("invalid")]); // #5437: independent calls
1952
2143
  if (result.status === "invalid") { const f = await resolveFindingLabel({ io, issue, labels: iss.labels, reason: "invalid" }); if (f.error) T.anomalies.push(`finding label not resolved: ${f.error}`); } // #5254
1953
2144
  return await finish("invalid", result.summary ?? result.status, result.status === "already-fixed" ? { close: "already-fixed" } : {});
1954
2145
  }
1955
2146
  const blocked = await endIfBlocked();
1956
2147
  if (blocked) return blocked;
2148
+ if (ffFresh && elig.mode === "shadow") { const tri = await ffTriageOf(null); ev(fastForwardEvent(fastForwardEligibility({ title: iss.title, body: iss.body ?? "", labels: iss.labels ?? [], triage: tri, textFiles: namedPaths(iss.body ?? ""), riskPaths, hotspots: (hotFacts?.files ?? []).filter((f) => tri.files.includes(f?.path ?? f)), cfg: o.light ?? {} }), tri, { shadow: true })); } // #5426: zero extra cost, no extra runner call
2149
+ { const f = await gateSetup(); if (f) return f; } // #5434: the contract checks below run commands with the lane env
1957
2150
  // #4353: the engine's scope gate is the only scope authority; a pure file-scope validate is dropped before it is checked or frozen
1958
2151
  const dropScope = (c) => {
1959
2152
  const d = dropScopeValidates(c);
@@ -1972,6 +2165,7 @@ export async function runCore(o) {
1972
2165
  };
1973
2166
  let contract = dropScope(await readContract());
1974
2167
  contract = freezeRewrites(contract);
2168
+ await persistGenChecks();
1975
2169
  await refreshIssue("contract validation");
1976
2170
  const snapContract = (c) => { // #5244: a near-verbatim quote snaps to the issue's exact sentence instead of ending needs-human
1977
2171
  const sq = snapQuotes(c, issueText);
@@ -1979,7 +2173,7 @@ export async function runCore(o) {
1979
2173
  return sq.contract;
1980
2174
  };
1981
2175
  contract = snapContract(contract);
1982
- let vc = validateContract(contract, issueText, { repro: reproOn() });
2176
+ let vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, testPlan: reproOn() });
1983
2177
  const missed = await preflightValidates(contract); // #4328: validate commands the host cannot run share the one correction
1984
2178
  let misses = missed;
1985
2179
  if ((!vc.ok || missed.length || testRunnerProblems(contract, testRunners).length) && sessionId) {
@@ -1987,9 +2181,10 @@ export async function runCore(o) {
1987
2181
  T.decisions.push(`Contract rejected (${problems[0]}); resumed once`);
1988
2182
  await builder(++attemptN, contractCorrectionPrompt(problems), sessionId, false, planPrompt, { trigger: "contract_correction" });
1989
2183
  contract = freezeRewrites(dropScope(await readContract()));
2184
+ await persistGenChecks();
1990
2185
  await refreshIssue("contract validation");
1991
2186
  contract = snapContract(contract);
1992
- vc = validateContract(contract, issueText, { repro: reproOn() });
2187
+ vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, testPlan: reproOn() });
1993
2188
  if (missed.length) misses = await preflightValidates(contract);
1994
2189
  }
1995
2190
  planMisses = misses;
@@ -2017,12 +2212,43 @@ export async function runCore(o) {
2017
2212
  } else {
2018
2213
  T.validate = lightDone ? "light lane (no plan session)" : "resumed (existing branch)";
2019
2214
  }
2215
+ { // #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)
2216
+ const probeEnv = async () => { const miss = []; for (const t of declaredEnv(frozen)) { const r = io.runCommand ? await io.runCommand({ command: t === "pytest" ? "python3 -m pytest --version" : `command -v ${t}`, cwd: wt, timeoutMs: 30000, env: laneEnv() }).catch(() => ({ rc: 1 })) : { rc: 0 }; if ((r?.rc ?? 0) !== 0) miss.push(t); } return miss; };
2217
+ let envMiss = await probeEnv();
2218
+ if (envMiss.length) {
2219
+ try {
2220
+ if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined });
2221
+ if (envMiss.includes("pytest") && io.runCommand) await io.runCommand({ command: "python3 -m pip install --user --quiet pytest", cwd: wt, timeoutMs: 180000, env: laneEnv() });
2222
+ envMiss = await probeEnv();
2223
+ ev({ event: "TESTPLAN_ENV_PROVISIONED", remaining: envMiss });
2224
+ } catch { /* keep the original miss */ }
2225
+ }
2226
+ if (envMiss.length) return await needsHuman(`This host lacks ${envMiss.join(", ")}, which the contract's test plan declares in env; the lane is re-placed on a host that has it before the builder implements.`, OUTCOME_CODES.ENV_TOOL_MISSING);
2227
+ }
2228
+ { // #5450: the frozen validate entries' `env` names verify.sandboxes; none declared: no provider call
2229
+ const names = envNamesOf(frozen);
2230
+ if (names.length && !sandboxDown) {
2231
+ const labels = dockerLabels({ batch: o.batchId ?? "adhoc", lane: `lean-${issue}`, issue, expires: now() + LEDGER_TTL_MS });
2232
+ const sb = await provisionSandboxes({ names, specs: vcfg.sandboxes ?? {}, lane: `lean-${issue}`, docker: (a) => io.docker(a), exec: (a) => io.runCommand({ command: a.command, cwd: wt, timeoutMs: 600000, env: { ...laneEnv(), ...a.env } }).then((x) => x?.r ?? x), ledger, labels, cwd: wt, now, cache: batchImageCache });
2233
+ if (!sb.ok) return await needsHuman(`Test sandbox unavailable (${sb.reason}): ${sb.detail}. Nothing was skipped and nothing merged.`, sb.reason === "no_docker" ? OUTCOME_CODES.ENV_TOOL_MISSING : OUTCOME_CODES.ENGINE_ERROR);
2234
+ sandboxEnv = sb.env; sandboxDown = sb.down;
2235
+ for (const l of sb.lines) T.decisions.push(l);
2236
+ }
2237
+ }
2020
2238
  if (o.placement?.where === "remote" && !recover) { // #4785: the frozen validate commands need a tool only the host has
2021
2239
  const relayed = new Set(o.relayCaps ?? []); // #4778: a relayed capability is served to the sandbox, so the lane builds there
2022
2240
  const hn = contractHostNeeds(frozen, o.hostCaps && { ...o.hostCaps, hostCapabilities: (o.hostCaps.hostCapabilities ?? []).filter((c) => !relayed.has(c)) });
2023
2241
  if (hn.caps.length) return await needsHuman(`Remote sandbox lacks host capability ${hn.caps.join(", ")}, which the frozen contract's validate command(s) ${hn.ids.join(", ")} need.\n\nThe dispatching host has it; the lane is recovered locally with the frozen contract.`, OUTCOME_CODES.ENV_CAPABILITY_REMOTE);
2024
2242
  // #5331: a tool the sandbox itself lacks (probed where the lane runs) ends the lane before the builder implements; the tool-missing recovery places it on the host (orchestrate placeOf)
2025
- const tm = toolMisses(planMisses ?? await preflightValidates(frozen).catch(() => []));
2243
+ let tm = toolMisses(planMisses ?? await preflightValidates(frozen).catch(() => []));
2244
+ if (tm.tools.length) { // #5423: provision the sandbox once (nested lockfiles, pytest) and re-probe before giving the lane up
2245
+ try {
2246
+ if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined });
2247
+ if (tm.tools.includes("pytest") && io.runCommand) await io.runCommand({ command: "python3 -m pip install --user --quiet pytest", cwd: wt, timeoutMs: 180000, env: laneEnv() });
2248
+ tm = toolMisses(await preflightValidates(frozen).catch(() => []));
2249
+ ev({ event: "REMOTE_PROVISIONED", remaining: tm.tools });
2250
+ } catch { /* keep the original miss */ }
2251
+ }
2026
2252
  if (tm.tools.length) {
2027
2253
  ev({ event: "REMOTE_TOOL_MISSING", tools: tm.tools, ids: tm.ids });
2028
2254
  return await needsHuman(`Remote sandbox lacks ${tm.tools.join(", ")}, which the frozen contract's validate command(s) ${tm.ids.join(", ")} need; the lane is re-placed on the host before the builder implements.`, OUTCOME_CODES.ENV_TOOL_MISSING);
@@ -2043,17 +2269,19 @@ export async function runCore(o) {
2043
2269
  ev(rec); await emit(rec);
2044
2270
  T.decisions.push(`Builder routed to the ${route.tier} tier (${route.class}; ${route.model ?? "CLI default"})`);
2045
2271
  }
2046
- if (!isSplit && io.sequenceReserveBuild) { // #5235: reserve numbers / versions before the builder picks them from its stale snapshot
2272
+ if (!isSplit && !adoptPr && io.sequenceReserveBuild) { // #5235: reserve numbers / versions before the builder picks them from its stale snapshot
2047
2273
  const rs = await io.sequenceReserveBuild({ cwd: wt, base, lane, repo, issue, deliverables: frozen?.deliverables ?? [], versioned: o.sequenceVersioned ?? [] }).catch(() => []);
2048
2274
  seqBuildNote = sequenceBuildRule(rs);
2049
2275
  if (rs.length) { ev({ event: "SEQUENCE_RESERVED", reservations: rs }); T.decisions.push(`Sequence numbers reserved at build start: ${rs.map((r) => `${r.cls ?? r.dir}=${r.numbers.join(",")}`).join("; ")}`); }
2050
2276
  }
2051
2277
  stampHash = hash; // #5333
2052
2278
  await claimSurfaceSlots(frozen); // #5340: the full and recovered paths reach the builder here with the contract settled
2279
+ if (!ctxPack && packP) ctxPack = await packP.catch(() => null); // #5434: a pack that missed the plan wait still reaches the build
2053
2280
  const openPaths = (frozen?.deliverables ?? []).map((d) => d?.path); // #5347: facts for the build's opening batch
2054
2281
  const openMap = io.runCommand ? await readTestMapAtRef(git, base).catch(() => null) : null;
2055
2282
  const implementPrompt = builderImplementPrompt(vcfg.mode, tcOpts()) + seqBuildNote + buildOpeningNote({ paths: openPaths, tests: selectCommands(openMap, openPaths), packFiles: ctxCfg.mode === "on" ? ctxPack?.files : [] }) + hotspotBuildRule(hotFacts) + enumeratingBuildRule(enumList) + invariantsBuildRule(vcfg.invariants) + exploreBuildRule(exploreCfg) + generatorNote(surfaceClaim?.generated) + (planned ? "" : (fromCheckpoint ? CONTINUE_NOTE : RERUN_NOTE).replace("BASE", lane)) + (salvagedRef ? SALVAGE_NOTE.replaceAll("REF", salvagedRef) : "") + recoverNote() + (planned ? "" : resumeNote + decisionsNote);
2056
2283
  liveKeys = ["implementation"];
2284
+ { const f = await gateSetup(); if (f) return f; } // #5434: resumed or frozen lanes skip the plan
2057
2285
  stage = "implement"; phaseLedger.enter("implement");
2058
2286
  let buildPrompt = implementPrompt, noCeiling = false;
2059
2287
  if (!lightDone) { // #5346: a session certain to restart is narrowed (or, when the named files alone exceed the ceiling, left uncapped) before it starts
@@ -2220,8 +2448,8 @@ export async function runCore(o) {
2220
2448
  if (io.enumeratingMissing && !isSplit) {
2221
2449
  const missingNow = async () => unjustified((await io.enumeratingMissing({ cwd: wt, base }).catch(() => null)) ?? [], result?.not_members);
2222
2450
  let missing = await missingNow();
2223
- if (missing.length) { // #5348: the detector names the list entry: write it, then re-check; a session only for the rest
2224
- const m = await mech.applyEnumerating({ missing, cwd: wt });
2451
+ if (missing.length && vcfg.enumeratingMechanical !== false) { // #5348: the detector names the list entry: write it, then re-check; a session only for the rest (#5480: forge.yaml lean.enumerating.mechanical false skips it)
2452
+ const m = await enumeratingMech(missing);
2225
2453
  if (await mechCommit("enumerating", m.applied, m.applied.map((x) => x.test))) missing = await missingNow();
2226
2454
  }
2227
2455
  if (missing.length && sessionId) {
@@ -2557,13 +2785,23 @@ export async function runCore(o) {
2557
2785
  const IGNORE = [`${LEAN_DIR}/`];
2558
2786
  /** Up to two reviewer runs; a reply without usable rows (unparseable, incomplete, inconsistent) is re-asked, never charged to the builder. */
2559
2787
  function reviewOnce() { return phaseLedger.during("review", reviewOnceRaw); }
2560
- async function reviewOnceRaw() {
2788
+ /** The reviewer's inputs and full prompt for the current head: no lane state is touched, so it can run before precheck finishes (#5436). */
2789
+ async function reviewPrep() {
2561
2790
  const diff = String(await git(["diff", `${base}...HEAD`]));
2562
2791
  const stat = Buffer.byteLength(diff, "utf-8") > REVIEW_DIFF_MAX_BYTES ? String(await git(["diff", "--stat=200", `${base}...HEAD`]).catch(() => "")) : "";
2563
2792
  const listed = new Set(String(await git(["ls-files"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean));
2564
2793
  // #5339: validate-command paths that fake the real path (mocks, fakes, stubs): they cannot verify an e2e/manual requirement
2565
2794
  const cmdPaths = [...new Set((effective.validate ?? []).flatMap((v) => String(v.command ?? "").split(/\s+/)).map((t) => t.replace(/^["']+|["']+$/g, "")).filter((t) => listed.has(t)))];
2566
- const ctx = { contract: effective, changedFiles: files, issueText, pathExists: (x) => listed.has(x), repoFiles: listed, ignore: IGNORE, e2e: { faked: fakedPaths(cmdPaths, (x) => readFileSync(join(wt, x), "utf8")), checks: vcfg.e2e?.checks ?? [], isSpec: (x) => e2eSpecs([x], vcfg.e2e).length > 0 } };
2795
+ const ctx = { contract: effective, changedFiles: files, issueText, pathExists: (x) => listed.has(x), repoFiles: listed, ignore: IGNORE, e2e: { faked: fakedPaths(cmdPaths, (x) => readFileSync(join(wt, x), "utf8")), checks: vcfg.e2e?.checks ?? [], sandboxes: Object.keys(vcfg.sandboxes ?? {}), isSpec: (x) => e2eSpecs([x], vcfg.e2e).length > 0 } };
2796
+ const prompt = reviewerPrompt({ reproFlag: reproQ, issue: iss, comments: trustedComments, contract: effective, result, files, diff, stat, base, structure: structureLine, ignore: IGNORE, domains, relaxations, investigationVerdict: investigationVerdict(await io.fs.read(`${wt}/.forge-lean/investigation.md`).catch(() => null)) });
2797
+ return { ctx, prompt };
2798
+ }
2799
+ const reviewerCall = (prompt) => callRunner({ role: "reviewer", issue, cwd: wt, model: reviewerModel, resume: null, system: REVIEWER_SYSTEM, readOnly: true, prompt });
2800
+ /** #5436: the first reviewer call, started beside guard+precheck by gate(); null when none is pending. */
2801
+ let specReview = null;
2802
+ async function reviewOnceRaw() {
2803
+ const spec = specReview; specReview = null;
2804
+ const { ctx, prompt } = await reviewPrep();
2567
2805
  let d = null, first = null;
2568
2806
  for (let t = 0; t < 3; t++) {
2569
2807
  // #4327/#5164: a third run only when the repaired reply is incomplete solely by reviewer slips (unresolved evidence paths, coverage misquotes).
@@ -2574,9 +2812,9 @@ export async function runCore(o) {
2574
2812
  // #4160: a reply with rows missing is re-asked for those ids only; an unparseable one gets the full prompt again.
2575
2813
  const repair = first && (d.state === "review.incomplete" || d.state === "review.inconsistent");
2576
2814
  await renew();
2577
- const rr = await callRunner({ role: "reviewer", issue, cwd: wt, model: reviewerModel, resume: null, system: REVIEWER_SYSTEM, readOnly: true,
2578
- prompt: repair ? reviewerRepairPrompt({ missing: d.missing ?? [], problems: d.failures.map((f) => f.detail), rows: first, criteria: (d.missing ?? []).includes("issue_coverage") ? criterionLines(issueText) : [] })
2579
- : reviewerPrompt({ issue: iss, comments: trustedComments, contract: effective, result, files, diff, stat, base, structure: structureLine, ignore: IGNORE, domains, relaxations, investigationVerdict: investigationVerdict(await io.fs.read(`${wt}/.forge-lean/investigation.md`).catch(() => null)) }) });
2815
+ let rr, got = false;
2816
+ if (t === 0 && spec) { try { rr = await spec.adopt(); got = true; T.decisions.push("Review started beside guard+precheck and adopted (#5436)"); } catch { got = false; } }
2817
+ if (!got) rr = await reviewerCall(repair ? reviewerRepairPrompt({ missing: d.missing ?? [], problems: d.failures.map((f) => f.detail), rows: first, criteria: (d.missing ?? []).includes("issue_coverage") ? criterionLines(issueText) : [] }) : prompt);
2580
2818
  await renew();
2581
2819
  await attempt("review", ++reviewN, rr, null, "review");
2582
2820
  const parsed = parseReview(rr?.text);
@@ -2686,7 +2924,7 @@ export async function runCore(o) {
2686
2924
  } catch (e) { T.anomalies.push(`Guard gate skipped: ${String(e?.message ?? e).split("\n")[0].slice(0, 160)}`); guardEv = { event: "guard_run", selected: sel.map((x) => x.guard.issue), ran: 0, broken: 0, skipped: 0, wall_ms: 0, error: true }; return []; }
2687
2925
  const note = `Guard gate selected ${sel.map((x) => `#${x.guard.issue} (${x.reason})`).join("; ")}${r.skipped.length ? `; skipped: ${r.skipped.join("; ")}` : ""}${r.failures.length && shadow ? "; shadow: would block" : ""}`;
2688
2926
  if (note !== guardNoted) { guardNoted = note; T.decisions.push(note); }
2689
- guardEv = { event: "guard_run", selected: sel.map((x) => x.guard.issue), ran: r.runs.length, broken: r.failures.length, skipped: r.skipped.length, wall_ms: r.ms };
2927
+ guardEv = { event: "guard_run", selected: sel.map((x) => x.guard.issue), reasons: Object.fromEntries(sel.map((x) => [x.guard.issue, x.reason])), batches: r.batches, ran: r.runs.length, broken: r.failures.length, skipped: r.skipped.length, wall_ms: r.ms };
2690
2928
  for (const f of r.failures) ev({ event: "guard_broken", guard: f.guard, test: f.test });
2691
2929
  return r.failures;
2692
2930
  }
@@ -2705,7 +2943,11 @@ export async function runCore(o) {
2705
2943
  return { files: ui, ran: want.run, reason: want.reason, highRisk: riskPathHits(ui, riskPaths).length > 0 };
2706
2944
  }
2707
2945
  let amendFixed = false;
2946
+ /** #5436: a review started beside guard+precheck is dropped on every return that does not reach the reviewer. */
2708
2947
  async function gate() {
2948
+ try { return await gateRun(); } finally { specReview?.discard(); specReview = null; }
2949
+ }
2950
+ async function gateRun() {
2709
2951
  await refreshIssue("conformance");
2710
2952
  result = (await readResult()) ?? result;
2711
2953
  files = await changedFiles();
@@ -2718,7 +2960,7 @@ export async function runCore(o) {
2718
2960
  T.decisions.push(`Conformance enforced (review.risk_paths): ${hits.slice(0, 10).join(", ")}${hits.length > 10 ? ` and ${hits.length - 10} more` : ""}`);
2719
2961
  }
2720
2962
  // #5099: the domains the diff touches get domain checks in the review; a review.enforce_domains hit enforces (sticky)
2721
- const pd = pathDomains(files);
2963
+ const pd = pathDomains(files, { docs: docsConfig, pages: pagesConfig });
2722
2964
  const dErr = "Review domains unavailable: scripts/review-roster.sh failed; reviewed without domain checks";
2723
2965
  if (pd === null && !T.anomalies.includes(dErr)) T.anomalies.push(dErr);
2724
2966
  domains = pd ?? [];
@@ -2743,12 +2985,28 @@ export async function runCore(o) {
2743
2985
  const gateHead = String(await git(["rev-parse", "HEAD"])).trim();
2744
2986
  const ciVerified = remoteVerify && ciVerifiedHead !== null && ciVerifiedHead === gateHead;
2745
2987
  const hotspots = await hotspotsOf({ base, paths: files }); // #4502
2988
+ const rx = await relaxationsOf(files); // #5237
2989
+ relaxations = rx.relaxations;
2990
+ if (relaxations.length) {
2991
+ ev({ event: "RELAXATION_DETECTED", files: [...new Set(relaxations.map((r) => r.file))], count: relaxations.length, negatives: rx.negatives });
2992
+ const note = `Relaxation in a declared risk path (${[...new Set(relaxations.map((r) => r.file))].slice(0, 5).join(", ")}): negative tests added ${rx.negatives}; independent verifier enforced`;
2993
+ if (!T.decisions.includes(note)) T.decisions.push(note);
2994
+ }
2995
+ // #5436: the review reads the same committed diff as guard+precheck, so its session starts now; reviewOnce adopts it, any earlier return discards it
2996
+ const repro = await reproOf(effective);
2997
+ // a precheck that already fails on facts at hand (no engine rerun) would discard the review, so it is not started then
2998
+ const early = triggerMode === "enforce" || amendProblems.length ? null : precheck({ contract: effective, result, changedFiles: files, ignore: IGNORE, ciVerified, hotspots, frozen, repro, repoHas: repoTracks(String(await git(["ls-files"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean)) });
2999
+ specReview = !early || early.failures.length ? null : startSpeculative(async () => reviewerCall((await reviewPrep()).prompt));
2746
3000
  const gateT0 = now(); let validateMs = 0;
2747
3001
  // #4693: guards run beside the validate rerun; SPEC-11: the substituted-original rerun shares the one validate phase
2748
3002
  const validatePhase = phaseLedger.during("validate", async () => ({ runs: await rerunFailedValidatesRaw(effective), subs: await rerunSubstitutedOriginals(effective) })).finally(() => { validateMs = now() - gateT0; });
2749
3003
  const [{ runs: validateRuns, subs: substitutedRuns }, guardFailures] = await Promise.all([validatePhase, guardGate(files)]);
2750
3004
  // #5087: forge.yaml topology.route_reachability gates the route handlers this diff adds; unset = no check
2751
3005
  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 } }) : [];
3006
+ // #5419: forge.yaml docs: user-facing surfaces need docs, and added /docs links must resolve; unset = no check
3007
+ 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 }) : [];
3008
+ // #5428: forge.yaml pages: a public page needs design, SEO and GEO briefs and passes the deterministic page checks; unset = no check
3009
+ const pageFail = pagesConfig ? await pageFailures({ cfg: pagesConfig, files, result, diff: String(await git(["diff", "-U0", `${base}...HEAD`]).catch(() => "")), tracked: String(await git(["ls-files"]).catch(() => "")).split("\n").filter(Boolean), readFile: (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } }, designApproved: designLabelApproved(iss?.labels) || designSpecApproved((iss?.comments ?? []).filter(isTrustedIssueComment)), run: io.runCommand ? async ({ command }) => (await io.runCommand({ command, cwd: wt, timeoutMs: vcfg.precheckTimeoutSeconds * 1000, env: laneEnv() }).then((x) => x?.r ?? x)) ?? { rc: 127 } : null }) : [];
2752
3010
  // #5284: forge.yaml topology.prod_parity: declared production-only surfaces this diff touches need a check result or a justification
2753
3011
  const parityRules = parseProdParity(prodParity);
2754
3012
  const prodParityFailures = parityRules.length && io.runCommand ? await prodParityOf({ rules: parityRules, changedFiles: files, result, run: async ({ command }) => (await io.runCommand({ command, cwd: wt, timeoutMs: vcfg.precheckTimeoutSeconds * 1000, env: laneEnv() }).then((x) => x?.r ?? x)) ?? { rc: 127 } }) : [];
@@ -2761,14 +3019,31 @@ export async function runCore(o) {
2761
3019
  const checkIds = effective.requirements?.some((r) => r.disposition === "post-deploy") ? new Set(Object.keys(await checksAt(git, [base, "HEAD"], wt))) : null;
2762
3020
  const removedPaths = (effective.validate ?? []).some((v) => v.substituted) ? await removedPathsOf(git, base) : []; // #4990
2763
3021
  const subBaseFiles = (effective.validate ?? []).some((v) => v.substituted) ? String(await git(["ls-tree", "-r", "-z", "--name-only", base]).catch(() => "")).split("\0").filter(Boolean) : []; // #5003
2764
- const rx = await relaxationsOf(files); // #5237
2765
- relaxations = rx.relaxations;
2766
- if (relaxations.length) {
2767
- ev({ event: "RELAXATION_DETECTED", files: [...new Set(relaxations.map((r) => r.file))], count: relaxations.length, negatives: rx.negatives });
2768
- const note = `Relaxation in a declared risk path (${[...new Set(relaxations.map((r) => r.file))].slice(0, 5).join(", ")}): negative tests added ${rx.negatives}; independent verifier enforced`;
2769
- if (!T.decisions.includes(note)) T.decisions.push(note);
3022
+ const baselineRuns = [];
3023
+ for (const b of matchBaselines(files, vcfg.baselines)) { // #5448: project baseline suites for the changed paths, enforced
3024
+ let x;
3025
+ try { x = await heavyStep("precheck", async () => (await runWithTimeoutRetry((timeoutMs) => io.runCommand({ command: b.run, cwd: wt, timeoutMs, env: laneEnv() }), vcfg.precheckTimeoutSeconds * 1000)).r); } catch (e) { x = { rc: 127, output: String(e?.message ?? e) }; }
3026
+ baselineRuns.push({ ...b, rc: Number.isInteger(x?.rc) ? x.rc : 1, output: String(x?.output ?? "") });
3027
+ }
3028
+ if (baselineRuns.length) ev({ event: "BASELINES_RUN", runs: baselineRuns.map((b) => ({ run: b.run, rc: b.rc })) });
3029
+ const pc = precheck({ baselineFailures: baselineFailures(baselineRuns), contract: effective, result, changedFiles: files, ignore: IGNORE, ciVerified, hotspots, repro: (adequacyIn.repro = repro), validateRuns, repoHas, frozen, checkIds, guardFailures, coupledFailures: await coupledOf(files), relaxationFailures: relaxationFailures(rx), routeFailures, docsFailures: docsFail, pageFailures: pageFail, docsPaths: docsConfig ? [...(docsConfig.paths ?? []), ...(docsConfig.registries ?? [])] : null, prodParityFailures, newOffKeys: await newOffKeysOf(), uiBrowser: uiBrowserOf(files), substitutedRuns, removedPaths, baseFiles: subBaseFiles });
3030
+ // #5447: an install failure for a package the changed files import blocks (env.tool_missing); unrelated ones are logged
3031
+ const depFail = depInstallFailures({ results: depResults, changedFiles: files });
3032
+ for (const l of depFail.logged) if (!T.decisions.includes(l)) T.decisions.push(l);
3033
+ pc.failures.push(...depFail.block);
3034
+ // #5447: a test that could not run gets one provisioning pass (dependencies, pytest) and a fresh gate before the lane is given up
3035
+ const unrun = pc.failures.filter((f) => ["validate_env", "repro_env", "dep_install"].includes(f.kind));
3036
+ const wantsPytest = unrun.some((f) => /pytest/.test(`${f.tool ?? ""} ${f.detail}`));
3037
+ if (unrun.length && !gateProvisioned && (io.deps?.prepare || (wantsPytest && io.runCommand))) {
3038
+ gateProvisioned = true;
3039
+ try {
3040
+ if (io.deps?.prepare) { const rp = await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined }); depResults = Array.isArray(rp) ? rp : []; }
3041
+ if (wantsPytest && io.runCommand) await io.runCommand({ command: "python3 -m pip install --user --quiet pytest", cwd: wt, timeoutMs: 180000, env: laneEnv() });
3042
+ } catch { /* the rerun below reports what is still missing */ }
3043
+ ev({ event: "GATE_PROVISIONED", kinds: [...new Set(unrun.map((f) => f.kind))] });
3044
+ return await gate();
2770
3045
  }
2771
- const pc = precheck({ contract: effective, result, changedFiles: files, ignore: IGNORE, ciVerified, hotspots, repro: await reproOf(effective), validateRuns, repoHas, frozen, checkIds, guardFailures, coupledFailures: await coupledOf(files), relaxationFailures: relaxationFailures(rx), routeFailures, prodParityFailures, newOffKeys: await newOffKeysOf(), uiBrowser: uiBrowserOf(files), substitutedRuns, removedPaths, baseFiles: subBaseFiles });
3046
+ T.tests = testRunSummary({ contract: effective, failures: pc.failures, repro: repro });
2772
3047
  // #4350: a scope-check validate stale only by amended deliverables is judged by the engine's scope gate instead
2773
3048
  if (pc.superseded?.length) {
2774
3049
  ev({ event: "VALIDATE_SUPERSEDED", runs: pc.superseded });
@@ -2791,6 +3066,7 @@ export async function runCore(o) {
2791
3066
  let mutBlock = [];
2792
3067
  if (conformanceMutation === "report" && io.runCommand) { // #4913: report-only unless conformance_kinds enforces the kind
2793
3068
  const m = await phaseLedger.during("validate", () => runMutationCheck({ targets: mutationTargets(effective, { runs: result?.validation, reruns: validateRuns, ciCovered: pc.ciCovered }), files, base, git: (a) => git(a), runCommand: (a) => io.runCommand(a), cwd: wt, env: laneEnv(), tmp: runTmp ?? undefined }));
3069
+ adequacyIn.mutation = m.results;
2794
3070
  const mf = mutationFailures(m.results);
2795
3071
  if (m.results.length || m.skipped) ev({ event: "REQUIREMENT_MUTATION_SURVIVED", ids: mf.map((f) => f.detail.split(" ")[0]), checked: m.results.length, skipped: m.skipped || undefined });
2796
3072
  if (mf.length) {
@@ -2799,11 +3075,19 @@ export async function runCore(o) {
2799
3075
  if (!T.decisions.includes(note)) T.decisions.push(note);
2800
3076
  }
2801
3077
  }
3078
+ // #5449: test adequacy per requirement; missing blocks a bug lane, weak gets one builder resume
3079
+ const adqEv = { runs: result?.validation, reruns: validateRuns, ciCovered: pc.ciCovered };
3080
+ // enforced on a bug lane with lean.repro_test on, unless the plan declared the bug untestable (repro_test "none" with a reason)
3081
+ Object.assign(adequacyIn, adqEv, { bug: reproOn() && effective.repro_test !== "none" });
3082
+ adequacy = testAdequacyRows(effective, { ...adqEv, mutation: adequacyIn.mutation, repro: adequacyIn.repro });
3083
+ adequacyTel = testAdequacyTelemetry(effective, adequacy, { repro: adequacyIn.repro, mutation: adequacyIn.mutation, regression: regressionRan(effective, adequacyIn) });
3084
+ // an environment or repro-verdict failure is settled first (already-fixed, env.repro_unrunnable): adequacy never mixes into it
3085
+ const adqFail = pc.failures.some((f) => ENV_CODES.includes(f.code) || String(f.kind ?? "").startsWith("repro")) ? [] : testAdequacyFailures(adequacy, { bug: adequacyIn.bug, firstRound: resumes === 0 });
2802
3086
  Object.assign(verifyFacts, { precheck: pc.failures, amendments: amendProblems, hotspots: Boolean(hotspots && hotspots.enabled !== false && Array.isArray(hotspots.files)) });
2803
3087
  // #4323/#4334: a missing host tool or module, or a repro test the harness could not run, is an environment error:
2804
3088
  // never a conformance failure, never a builder resume
2805
3089
  const envFails = pc.failures.filter((f) => ENV_CODES.includes(f.code));
2806
- const pre = [...pc.failures.filter((f) => !ENV_CODES.includes(f.code)), ...amendProblems, ...mutBlock];
3090
+ const pre = [...pc.failures.filter((f) => !ENV_CODES.includes(f.code)), ...amendProblems, ...mutBlock, ...adqFail];
2807
3091
  if (pre.length) ev({ event: "PRECHECK", failures: pre.map((f) => f.code) });
2808
3092
  // #5080: the repro already passes on the base and the diff changes no source: the fix is on the base, not missing
2809
3093
  if (alreadyFixedOnBase(pre, files, IGNORE)) return { state: "already-fixed", by: "precheck", failures: pre };
@@ -2825,6 +3109,24 @@ export async function runCore(o) {
2825
3109
  triggerSkipped = false;
2826
3110
  }
2827
3111
  let d = await reviewOnce();
3112
+ { // #5468: a lone e2e_unverified on production-only rows converts to post-deploy checks and the lane continues instead of parking
3113
+ const ids = d.state === "nonconforming" ? loneE2eRows(d.failures) : null;
3114
+ const cv = ids ? autoPostDeployE2e(effective, ids) : null;
3115
+ if (cv && cv.converted.length === ids.length) {
3116
+ for (const x of cv.converted) genChecks[x.check] = x.entry;
3117
+ effective = cv.contract;
3118
+ await persistGenChecks();
3119
+ T.decisions.push(`FORGE:DECISION e2e_unverified on ${ids.join(", ")} converted to post-deploy checks ${cv.converted.map((x) => x.check).join(", ")}: the observable is production-only`);
3120
+ d = { state: "conforms", failures: [], review: d.review ?? review, by: "review" };
3121
+ }
3122
+ }
3123
+ if (d.state === "conforms" || d.state === "nonconforming") { // #5449: the reviewer's test_adequacy judgment joins the engine's rows
3124
+ adequacy = testAdequacyRows(effective, { ...adequacyIn, mutation: adequacyIn.mutation, review });
3125
+ adequacyTel = testAdequacyTelemetry(effective, adequacy, { repro: adequacyIn.repro, mutation: adequacyIn.mutation, regression: regressionRan(effective, adequacyIn) });
3126
+ const seen = new Set(pre.map((f) => f.detail));
3127
+ const more = testAdequacyFailures(adequacy, { bug: adequacyIn.bug, firstRound: resumes === 0 }).filter((f) => !seen.has(f.detail));
3128
+ if (more.length) d = { state: "nonconforming", failures: [...(d.state === "nonconforming" ? d.failures : []), ...more], by: "review", review };
3129
+ }
2828
3130
  // #4397: the verifier runs only on a change every gate and the reviewer passed; in enforce its findings block
2829
3131
  if ((verifierCfg.mode !== "off" || relaxations.length) && d.state === "conforms" && !pre.length) { // #5237: a relaxation lane always gets the independent second look
2830
3132
  const vf = await runVerifier();
@@ -2952,10 +3254,10 @@ export async function runCore(o) {
2952
3254
  ev({ event: "CONFORMANCE_SHADOW", would: verdict.would, failures: wf.map((f) => f.code) });
2953
3255
  await emit({ event: "CONFORMANCE_SHADOW", would: verdict.would, failures: wf.map((f) => f.code) });
2954
3256
  T.review = [`shadow: would ${verdict.would === "conforms" ? "pass" : `block (${verdict.would})`}`, `${reviewN} reviewer run(s), ${resumes + 1} round(s)`];
2955
- await post("FORGE:REVIEW", renderShadowReview({ would: verdict.would, failures: wf, review: verdict.reviewState === "conforms" || verdict.reviewState === "nonconforming" ? review : null, contract: effective, degraded: degradedReq?.tracked ?? (degraded ? "untracked" : null) }) + verifierSection());
3257
+ await post("FORGE:REVIEW", renderShadowReview({ adequacy, would: verdict.would, failures: wf, review: verdict.reviewState === "conforms" || verdict.reviewState === "nonconforming" ? review : null, contract: effective, degraded: degradedReq?.tracked ?? (degraded ? "untracked" : null) }) + verifierSection());
2956
3258
  } else {
2957
3259
  T.review = ["CONFORMS", `${reviewN} reviewer run(s), ${resumes + 1} round(s)`];
2958
- await post("FORGE:REVIEW", renderReview(review, effective) + verifierSection());
3260
+ await post("FORGE:REVIEW", renderReview(review, effective, adequacy) + verifierSection());
2959
3261
  }
2960
3262
  }
2961
3263
  ev({ event: "PHASE_COMMIT", phase: "review" });
@@ -3230,7 +3532,11 @@ export async function runCore(o) {
3230
3532
  }
3231
3533
  deleteLocalBranch = true;
3232
3534
  try { await io.git(["push", "origin", "--delete", branch], { cwd }); ev({ event: "BRANCH_DELETED", branch, where: "origin" }); }
3233
- catch (e) { ev({ event: "BRANCH_DELETE_FAILED", branch, where: "origin", error: String(e?.stderr ?? e?.message ?? e).slice(0, 300) }); }
3535
+ catch (e) {
3536
+ const error = String(e?.stderr ?? e?.message ?? e).slice(0, 300);
3537
+ if (/remote ref does not exist/i.test(error)) { ev({ event: "BRANCH_DELETED", branch, where: "origin", already: true }); return; } // #5437: a retry after the first delete landed
3538
+ ev({ event: "BRANCH_DELETE_FAILED", branch, where: "origin", error }); throw e; // the post-run queue retries it
3539
+ }
3234
3540
  }
3235
3541
 
3236
3542
  /**
@@ -3258,7 +3564,7 @@ export async function runCore(o) {
3258
3564
  edges_added: s.deps_added.length, edges_removed: s.deps_removed.length, import_files_added: sum("files_added"), import_files_removed: sum("files_removed"),
3259
3565
  boundary_changed: Boolean(d.boundary_config_changed?.changed), boundary_loosened: Boolean(d.boundary_config_changed?.loosens) };
3260
3566
  ev(rec);
3261
- await emit(rec);
3567
+ postRun.add("structure-telemetry", () => emit(rec)); // #5437: the telemetry write leaves the critical path
3262
3568
  }
3263
3569
 
3264
3570
  /**
@@ -3420,7 +3726,7 @@ export async function runCore(o) {
3420
3726
  }
3421
3727
  }
3422
3728
  try { await recordStructure(pr); } catch (e) { ev({ event: "STRUCTURE_DELTA_FAILED", error: String(e?.message ?? e).slice(0, 300) }); }
3423
- await deleteMergedBranch();
3729
+ postRun.add("branch-delete", deleteMergedBranch); // #5437: sets deleteLocalBranch before the teardown job
3424
3730
  let keepOpen = false;
3425
3731
  if (pendingRecord().length) { // #5141: the close step files what the lane could not track before the PR (idempotent by the marker)
3426
3732
  const left = pendingFollowups.filter((p) => !p.req.tracked);
@@ -3470,7 +3776,7 @@ export async function runCore(o) {
3470
3776
  for (const sp of supersededIds(effective, guardSel)) { // #4693: the reviewer accepted the supersedes amendment; tell the guarded issue
3471
3777
  try { await ghw(["issue", "comment", sp.guard.slice(1), "-R", repo, "--body", supersessionComment({ guard: sp.guard, pr, why: sp.why })]); ev({ event: "supersedes_accepted", guard: sp.guard, pr }); T.decisions.push(`Guard ${sp.guard} superseded: ${sp.why}`); } catch (e) { T.anomalies.push(`supersession of ${sp.guard} not posted: ${String(e?.message ?? e).slice(0, 160)}`); }
3472
3778
  }
3473
- try { const g = await (o.guardAfterMerge ?? guardAfterMerge)({ io, repo, issue, pr, cwd: wt, base }); if (g?.posted) T.decisions.push(`FORGE:GUARD posted: ${g.guard.tests.length} test file(s), ${g.guard.hunks.length} hunk(s)`); else if (g?.skipped) ev({ event: "GUARD_SKIPPED", reason: g.reason }); } catch { /* the guard is best effort */ }
3779
+ postRun.add("guard", async () => { try { const g = await (o.guardAfterMerge ?? guardAfterMerge)({ io, repo, issue, pr, cwd: wt, base }); if (g?.posted) T.decisions.push(`FORGE:GUARD posted: ${g.guard.tests.length} test file(s), ${g.guard.hunks.length} hunk(s)`); else if (g?.skipped) ev({ event: "GUARD_SKIPPED", reason: g.reason }); } catch { /* the guard is best effort */ } }); // #5437
3474
3780
  // forge#4161: the merge-time structure record and the milestone ride on the lane result for orchestrate's drift fold.
3475
3781
  await gatePassed("merge_ci", "ci_red"); // #4375: merged means the required checks are green after a CI fix round
3476
3782
  let mergedTo = null; // #4711: FORGE:STATE records the lane and merge commit, so a dependent's check needs no PR search