forgedock 1.51.0 → 1.53.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 (103) hide show
  1. package/bin/engine/outcome-codes.mjs +3 -0
  2. package/bin/engine/telemetry-seam.mjs +4 -2
  3. package/bin/engine-cli.mjs +61 -17
  4. package/bin/experiment.mjs +58 -6
  5. package/bin/forge-utils.mjs +6 -2
  6. package/bin/forgedock.mjs +25 -1
  7. package/bin/lean/account-watch.mjs +28 -0
  8. package/bin/lean/account-watch.test.mjs +30 -0
  9. package/bin/lean/activation.mjs +20 -0
  10. package/bin/lean/activation.test.mjs +14 -1
  11. package/bin/lean/basered.mjs +115 -0
  12. package/bin/lean/basered.test.mjs +66 -0
  13. package/bin/lean/batch-health.mjs +40 -6
  14. package/bin/lean/batch-health.test.mjs +34 -1
  15. package/bin/lean/batch.mjs +41 -2
  16. package/bin/lean/batch.test.mjs +104 -2
  17. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  18. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  19. package/bin/lean/conformance.e2e.test.mjs +1 -1
  20. package/bin/lean/conformance.mjs +205 -23
  21. package/bin/lean/conformance.test.mjs +164 -3
  22. package/bin/lean/context.mjs +27 -17
  23. package/bin/lean/context.test.mjs +15 -0
  24. package/bin/lean/effects.mjs +11 -7
  25. package/bin/lean/execution.mjs +19 -3
  26. package/bin/lean/execution.test.mjs +39 -0
  27. package/bin/lean/findinglabel.mjs +16 -0
  28. package/bin/lean/findinglabel.test.mjs +39 -0
  29. package/bin/lean/heavy.mjs +6 -3
  30. package/bin/lean/hostload.mjs +78 -0
  31. package/bin/lean/hostload.test.mjs +117 -0
  32. package/bin/lean/hotspots-remote.e2e.test.mjs +71 -0
  33. package/bin/lean/issuewatch-release.mjs +6 -2
  34. package/bin/lean/issuewatch-release.test.mjs +16 -0
  35. package/bin/lean/issuewatch.mjs +11 -1
  36. package/bin/lean/lanelock.mjs +14 -0
  37. package/bin/lean/lean.mjs +171 -36
  38. package/bin/lean/lean.test.mjs +302 -10
  39. package/bin/lean/light.mjs +48 -7
  40. package/bin/lean/light.test.mjs +37 -3
  41. package/bin/lean/limits.test.mjs +142 -9
  42. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  43. package/bin/lean/orchestrate.mjs +110 -26
  44. package/bin/lean/postdeploy-check.test.mjs +39 -0
  45. package/bin/lean/prompts.mjs +8 -7
  46. package/bin/lean/quota.mjs +39 -0
  47. package/bin/lean/recovery.test.mjs +10 -0
  48. package/bin/lean/relaxation.mjs +73 -0
  49. package/bin/lean/relaxation.test.mjs +54 -0
  50. package/bin/lean/release-postmerge.mjs +119 -0
  51. package/bin/lean/release-rehearsal.mjs +63 -0
  52. package/bin/lean/release-rehearsal.test.mjs +93 -0
  53. package/bin/lean/release-review.e2e.test.mjs +77 -0
  54. package/bin/lean/release-review.mjs +198 -0
  55. package/bin/lean/release-review.test.mjs +180 -0
  56. package/bin/lean/release.mjs +228 -0
  57. package/bin/lean/release.test.mjs +292 -0
  58. package/bin/lean/rotator.mjs +150 -31
  59. package/bin/lean/rotator.test.mjs +105 -2
  60. package/bin/lean/sandbox-remote.mjs +9 -2
  61. package/bin/lean/schedd.mjs +56 -6
  62. package/bin/lean/schedd.test.mjs +108 -6
  63. package/bin/lean/verifier.mjs +3 -2
  64. package/bin/lean/verify.mjs +2 -1
  65. package/bin/lean/verify.test.mjs +6 -0
  66. package/bin/pool/agent.mjs +18 -4
  67. package/bin/pool/router.mjs +68 -25
  68. package/bin/review-staging.mjs +23 -0
  69. package/bin/stats/conformance-outcomes.mjs +208 -0
  70. package/bin/stats/conformance-outcomes.test.mjs +188 -0
  71. package/bin/stats/depth.mjs +218 -0
  72. package/bin/stats/depth.test.mjs +133 -0
  73. package/bin/stats/experiment.mjs +7 -5
  74. package/bin/stats/github-source.mjs +2 -2
  75. package/bin/stats/index.mjs +64 -2
  76. package/bin/stats/local-source.mjs +11 -0
  77. package/bin/stats/query.mjs +69 -0
  78. package/bin/stats/selffiled.mjs +52 -0
  79. package/bin/stats/selffiled.test.mjs +71 -0
  80. package/commands/orchestrate.md +1 -1
  81. package/commands/review-pr-agents/security.md +4 -0
  82. package/commands/review-pr-staging.md +2 -0
  83. package/commands/work-on/build.md +4 -6
  84. package/docs/CONFIG.md +66 -8
  85. package/docs/ISSUE-WATCH.md +2 -0
  86. package/docs/OUTCOME-CODES.md +3 -0
  87. package/docs/STATS.md +44 -0
  88. package/docs/TELEMETRY.md +1 -1
  89. package/package.json +1 -1
  90. package/pool/README.md +1 -1
  91. package/pool/image/cs-cred +14 -1
  92. package/pool/install/install-agent.ps1 +6 -2
  93. package/scripts/backfill-finding-labels.mjs +50 -0
  94. package/scripts/backfill-finding-labels.test.mjs +36 -0
  95. package/scripts/doctor-pipeline-state.sh +21 -6
  96. package/scripts/file-deferred-followups.sh +60 -238
  97. package/scripts/file-deferred-followups.test.sh +99 -187
  98. package/scripts/followup-route.mjs +12 -0
  99. package/scripts/hotspots.sh +12 -8
  100. package/scripts/hotspots.test.sh +22 -0
  101. package/scripts/owner-route-parity.test.sh +17 -1
  102. package/scripts/prior-attempts.test.mjs +1 -1
  103. package/scripts/review-pr-side-effects.test.sh +40 -0
package/bin/lean/lean.mjs CHANGED
@@ -5,7 +5,9 @@
5
5
  * ForgeDock registers everything on GitHub (labels, one register comment, PR, merge). No investigation, synthesis,
6
6
  * severity taxonomy, risk tiers or local CI gates. All effects are injected through `io` so it is unit-testable.
7
7
  */
8
- import { existsSync } from "node:fs";
8
+ import { resolveFindingLabel } from "./findinglabel.mjs";
9
+ import { spawnSync } from "node:child_process";
10
+ import { existsSync, readFileSync } from "node:fs";
9
11
  import { join, dirname, basename, delimiter } from "node:path";
10
12
  import { hostname as osHostname } from "node:os";
11
13
  import { appendEvent } from "../engine/runlog.mjs";
@@ -15,11 +17,11 @@ import { ciPollDelayMs, ENGINE_VERSION, DEFAULT_MAX_SESSION_LIMIT_PAUSES, DEFAUL
15
17
  import { openDependency, laneMergedPrs, dependencyOnLane, isTrustedComment, decomposedSubissues, isDecomposedRecord, reopenRevokedDecomposition } from "../engine/phases.mjs";
16
18
  import { createHash, randomBytes } from "node:crypto";
17
19
  import { otherLaneOwner } from "./lanelock.mjs";
18
- import { applyValidateRecipes, deferChecklessPostDeploy, reproEnvMiss, resolveForgedockPaths, describesUnrunnableCommand, removedPathsOf, TRACKED, normalizeKindModes, blockingFailures, unverifiedRequirements, mutationTargets, mutationFailures, runMutationCheck, MUTATION_SURVIVED, isBugIssue, scopeText, explainFailures, inIssue, validateContract, cliUsageError, normalizeRunnerCommand, applyAmendments, amendmentKindProblems, precheck, alreadyFixedOnBase, READONLY_PROD_RE, EXTERNAL_NEED_RE, repoTracks, dropScopeValidates, tagOutOfBand, parseReview, decide, mergeReviewRows, reaskable, criterionLines, closePlan, followupItems, renderPendingFollowups, bucketTally, pendingTracking, unnamedEdges, structureNote, impliedDocDeliverables } from "./conformance.mjs";
20
+ import { applyValidateRecipes, rewriteProjectDirCommand, deferChecklessPostDeploy, reproEnvMiss, resolveForgedockPaths, describesUnrunnableCommand, removedPathsOf, TRACKED, normalizeKindModes, blockingFailures, unverifiedRequirements, mutationTargets, mutationFailures, runMutationCheck, MUTATION_SURVIVED, isBugIssue, scopeText, explainFailures, inIssue, validateContract, snapQuotes, cliUsageError, normalizeRunnerCommand, applyAmendments, amendmentKindProblems, precheck, alreadyFixedOnBase, READONLY_PROD_RE, EXTERNAL_NEED_RE, intakeHostWork, repoTracks, dropScopeValidates, tagOutOfBand, parseReview, decide, mergeReviewRows, reaskable, criterionLines, closePlan, followupItems, renderPendingFollowups, bucketTally, pendingTracking, unnamedEdges, structureNote, impliedDocDeliverables } from "./conformance.mjs";
19
21
  import { checkAdmission, hostParallelism, ADMISSION_RETRY_SECONDS } from "./admission.mjs";
20
22
  import { namedPaths, isTrustedIssueComment } from "./prefilter.mjs";
21
23
  import { checksAt } from "./postdeploy-check.mjs";
22
- import { readRollouts, detectNewOffKeys } from "./activation.mjs";
24
+ import { readRollouts, detectNewOffKeys, rolloutModes } from "./activation.mjs";
23
25
  import { testRunnerProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract } from "./preflight.mjs";
24
26
  import { resolveLane, isDefaultLane, isShippedLane, DEFAULT_STAGING_BRANCH } from "./lane.mjs";
25
27
  import { splitGate, rationaleLine } from "./decompose.mjs";
@@ -40,9 +42,11 @@ const MISSING_TOOL_RE = /command not found|not found in PATH|no such file or dir
40
42
  export function missingToolBlock(summary) { return MISSING_TOOL_RE.test(String(summary ?? "")); }
41
43
  import { CHECKS_CLI, FORGEDOCK_CLI, REVIEWER_SYSTEM, LEAN_DIR, RESULT_FILE, INVESTIGATION_FILE, IMPLEMENTATION_FILE, CONTRACT_FILE, builderPlanPrompt, builderImplementPrompt, contractCorrectionPrompt, conformanceResumePrompt, amendmentCorrectionPrompt, reviewerPrompt, investigationVerdict, decisionNote, reviewerRepairPrompt, REVIEW_DIFF_MAX_BYTES, blockCorrectionPrompt, HUMAN_BLOCK_REASONS, structurePrompt, hotspotPlanNote, hotspotBuildRule, reproPlanNote, unrunnableValidateNote, contextPackNote, docsPrompt, ciFailurePrompt, ciUnavailablePrompt, precheckFailurePrompt, contextRestartPrompt, turnBudgetWrapupPrompt, syncChecks, GROUPING_SYSTEM, enumeratingPlanNote, enumeratingBuildRule, invariantsPlanNote, invariantsBuildRule, missingEntriesPrompt, sequencePrompt, sequenceSyncNote, sequenceSyncPrompt, fixSessionPrompt, postMergeFailurePrompt, duplicateExportsPrompt, migrationGeneratorPrompt, i18nCopiesPrompt } from "./prompts.mjs";
42
44
  import { postMergeCommands } from "./postmerge.mjs";
45
+ import { classifyBaseRed, attribute as attributeBaseRed, runOnBase, reportBaseRed } from "./basered.mjs"; // #5239
43
46
  import { guardAfterMerge, withHistoryRows } from "./guards.mjs";
44
47
  import { routePathsFromFiles, routeReachabilityFailures } from "./routecheck.mjs";
45
48
  import { parseCoupled, coupledFailures } from "./coupled.mjs";
49
+ import { analyzeRelaxations, relaxationFailures } from "./relaxation.mjs";
46
50
  import { loadGuards, selectGuards, runGuards, supersededIds, supersessionComment } from "./guardgate.mjs";
47
51
  import { freshFix, issueSummary, firstPassOf, sessionCostDelta } from "./fixround.mjs";
48
52
  import { parseBuilderRouting, routeBuilder, shouldEscalate } from "./routing.mjs";
@@ -54,10 +58,12 @@ import { parseVerify, runCiVerify, collectFailedLogs, capLogs, VERIFY_MODES, VER
54
58
  import { e2eSpecs, e2eWanted, ownFailures, runE2eGate, NO_TRIGGER } from "./e2e.mjs";
55
59
  import { laneBackendId } from "./limits.mjs";
56
60
  import { openRotator, rotatorRetry } from "./rotator.mjs";
61
+ import { poolExhausted, exhaustedDeferral, quotaFacts } from "./quota.mjs"; // #5236
62
+ import { watchAccount } from "./account-watch.mjs"; // #5268
57
63
  import { SPLIT_LABEL } from "./refactor.mjs";
58
64
  import { writeHeavyShims, sumWaits, isHeavyProcess } from "./heavy.mjs";
59
65
  import { priorityFromLabels } from "./sched.mjs";
60
- import { assignArm } from "../experiment.mjs";
66
+ import { applyArmOverrides } from "../experiment.mjs";
61
67
  import { parseExploreConfig, explorerAgents, explorePlanRule, exploreBuildRule } from "./explore.mjs";
62
68
  import { normaliseFacts, renderFactsRecord, FACTS_MARKER } from "./facts.mjs";
63
69
  import { readDecisionIndex, withDecisionRows, recordDecisions } from "./decisions.mjs";
@@ -69,6 +75,7 @@ import { lightEligibility } from "./light.mjs";
69
75
  import { untrackToolState, unstageToolState, isToolState, clearLaneScratch } from "./toolstate.mjs";
70
76
  import { pickSalvage } from "./salvage-resume.mjs";
71
77
  import { ensureSignedOff, salvageBranch, dropSalvageTracking } from "./signoff.mjs";
78
+ import { reconcileCheckpoints } from "./checkpoint-reconcile.mjs";
72
79
  import { createLedger, flattenPhases } from "./phaseledger.mjs";
73
80
  import { runLightStep, runLightTests, lightBuildPrompt, upgradeNote, renderLiteReceipt } from "./lightlane.mjs";
74
81
 
@@ -88,7 +95,7 @@ export const RECOVER_HOW = Object.freeze({
88
95
  [OUTCOME_CODES.ENV_CAPABILITY_REMOTE]: "the earlier run ran in a remote sandbox that lacks a host-only capability (SOPS/age key, ops credentials, read-only prod monitor SSH); this host has it. Do the work that needed it now, with the host's own tools and credentials, and never print or commit a secret in the clear",
89
96
  [OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED]: "an earlier run's conformance check found a requirement or validate command not done after one builder resume; the branch holds its work. For each named gap deliver the requirement against the frozen contract, adding any file it needs as an `add-deliverable` amendment, and re-run the validate commands",
90
97
  [OUTCOME_CODES.CONFORMANCE_OMISSION]: "an earlier run's review found a requirement the change left out or narrowed after one builder resume; the branch holds its work. For each named gap either deliver the requirement (adding any needed file as an `add-deliverable` amendment) or, when the clause is optional, unquantified or outside the issue's acceptance criteria, record an `add-requirement` / `defer` amendment with a why so the engine files a tracked follow-up instead of stopping",
91
- [OUTCOME_CODES.CONFORMANCE_UNJUSTIFIED_DEFERRAL]: "an earlier run deferred a requirement without a sufficient why after one builder resume; the branch holds its work. For each named gap either deliver the requirement (adding any needed file as an `add-deliverable` amendment) or, when the clause is optional, unquantified or outside the issue's acceptance criteria, record a `defer` amendment with a concrete why so the engine files a tracked follow-up instead of stopping",
98
+ [OUTCOME_CODES.CONFORMANCE_UNJUSTIFIED_DEFERRAL]: "an earlier run deferred a requirement without a sufficient why after one builder resume; the branch holds its work. An in-lane engineering deferral (bucket new-issue or none) must be delivered, never deferred (#5207). For each other named gap either deliver the requirement (adding any needed file as an `add-deliverable` amendment) or, when the clause is optional, unquantified or outside the issue's acceptance criteria, record a `defer` amendment with a concrete why so the engine files a tracked follow-up instead of stopping",
92
99
  [OUTCOME_CODES.ENV_REPRO_UNRUNNABLE]: "the repro harness could not run the contract's repro_test on head (timeout, missing runner or dependencies); the change may already be correct. Do not edit the deliverables or stub dependencies for it and never install anything globally: run the repro command through the repo's own toolchain and installed dependencies, and when it cannot run in this checkout, fix the repro_test command (not the code) so it does",
93
100
  });
94
101
  /** #5168: retry-in for a `backend.auth` deferral; the batch holds the account for it (an operator `--set-env` fix runs under a new identity). */
@@ -102,7 +109,7 @@ export const CONFORMANCE_MODES = Object.freeze(["shadow", "enforce"]);
102
109
  * In shadow mode only what the previous two-question reviewer blocked on still blocks: a requirement not done, a regression
103
110
  * (precheck form: SHADOW_PRE_BLOCKS). A review without usable rows never merges either.
104
111
  */
105
- const SHADOW_BLOCKS = [OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, OUTCOME_CODES.CONFORMANCE_REGRESSION];
112
+ const SHADOW_BLOCKS = [OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, OUTCOME_CODES.CONFORMANCE_REGRESSION, OUTCOME_CODES.CONFORMANCE_UNJUSTIFIED_DEFERRAL]; // #5207: an engineering deferral is undelivered work
106
113
  /**
107
114
  * Precheck failures that block in shadow mode too (#4160): every precheck or amendment failure coded
108
115
  * conformance.unimplemented (a validate command that failed or has no recorded result, a deliver requirement reported as
@@ -184,6 +191,13 @@ export function isProtectedLaneBranch(b, { issue, lane = null, branches = {}, de
184
191
  return ["main", "master", "staging", lane, branches?.default, branches?.staging].includes(b) || /^milestone\//.test(b) || isDefaultLane(b, defaults);
185
192
  }
186
193
 
194
+ /** #5205: cap on `cs-cred claude --limited` relaunches of one phase in a sandbox. */
195
+ export const SANDBOX_CRED_RETRIES = 8;
196
+ const defaultCredExec = (args) => {
197
+ const r = spawnSync("cs-cred", args, { encoding: "utf8", timeout: 30000, windowsHide: true, stdio: ["ignore", "ignore", "pipe"] });
198
+ return { status: r.error ? null : r.status, stderr: String(r.stderr ?? "") };
199
+ };
200
+
187
201
  /**
188
202
  * @param {object} o
189
203
  * @param {number} o.issue
@@ -232,10 +246,19 @@ export function isProtectedLaneBranch(b, { issue, lane = null, branches = {}, de
232
246
  * (default true) is false when the runner may launch another attempt: the lane then never relabels (#4302)
233
247
  */
234
248
  export async function runCore(o) {
249
+ const armed = applyArmOverrides(o, o.issue); o = armed.options; // #5206: the arm's overrides shape the lane before any config is parsed
235
250
  const { issue, repo, lane: requestedLane = null, laneOverride = false, branches = {}, cwd, dir, io, builderModel = null, reviewerModel = DEFAULT_REVIEWER_MODEL, fixModel = null,
236
251
  toolchainOverride = null, testRunners = null, coupledFiles = null, validateRecipes = null, routeReachability = null, envSetup = null, ciMaxMinutes = 360, conformance = "shadow", conformanceKinds = null, conformanceMutation = "off", reviewIncomplete = "needs-human", reproTest = "prefer", closeParent = false, mergeWait = "required", maxSessionLimitPauses = DEFAULT_MAX_SESSION_LIMIT_PAUSES, cliIdleMinutes = 15, cliMaxMinutes = 180, cliBusyMinutes = 45, contextCeilingTokens = 120000, turnBudgets = null, laneLimits = null, maxMergeRetries = 5, sessionLimitMaxWaitMs = DEFAULT_SESSION_LIMIT_WAIT_MS, onProgress = () => {}, emitTelemetry = null, random = Math.random } = o;
237
252
  const now = io.now ?? (() => Date.now());
238
253
  const rotator = io.rotator !== undefined ? io.rotator : openRotator({ kind: o.accountRotator }); // #5094
254
+ // #5205: a rotator with pick() relaunches a limited phase pinned to another account; lane-level rotations and limited accounts
255
+ const smartRotator = Boolean(rotator) && typeof rotator.pick === "function";
256
+ let laneRotations = 0;
257
+ const laneLimited = new Map(); // account -> until epoch ms
258
+ const rotationFacts = () => ({ rotations: laneRotations, limited: [...laneLimited].map(([account, until]) => ({ account, until })) });
259
+ // #5205: in a sandbox (CS_CRED_BASE) a usage limit is reported with `cs-cred claude --limited`, which hands the next login
260
+ const sandboxCred = Boolean((io.env ?? process.env).CS_CRED_BASE);
261
+ const credExec = io.credExec ?? defaultCredExec;
239
262
  const vcfg = { ...parseVerify({}), ...(o.verify ?? {}) };
240
263
  const learnedCommands = (Array.isArray(o.precheck?.commands) ? o.precheck.commands : []).map((c) => String(c ?? "").trim()).filter(Boolean);
241
264
  if (!VERIFY_MODES.includes(vcfg.mode)) vcfg.mode = "local";
@@ -261,7 +284,7 @@ export async function runCore(o) {
261
284
  let sessionId = null;
262
285
 
263
286
  const ev = (e) => appendEvent(dir, issue, e, { repo }); // #4432: the run log is keyed by repo + issue
264
- const expTag = o.experiment ? { experiment: o.experiment.id, arm: assignArm(o.experiment, issue) } : {}; // #4629: same arm for the whole run
287
+ const expTag = armed.tag; // #4629: same arm for the whole run; #5206: plus the applied overrides
265
288
  const emit = async (rec) => { try { await emitTelemetry?.({ ...rec, issue }); } catch { /* never fails a run */ } };
266
289
  let ghCache = null; // #4507: the run's own gh HTTP cache (set once the run tmp dir exists)
267
290
  const authState = { refreshed: false }; // #4662: one token refresh at a time, shared by every gh call of the run
@@ -453,6 +476,7 @@ export async function runCore(o) {
453
476
  }
454
477
  function finish(...args) {
455
478
  if (done) return Promise.resolve(done);
479
+ if (laneRotations || laneLimited.size) args[2] = { ...(args[2] ?? {}), ...rotationFacts() }; // #5205: rotations + limited accounts ride on the lane result
456
480
  finishing ??= finishOnce(...args); // a signal during a normal finish waits for the same teardown
457
481
  return finishing;
458
482
  }
@@ -641,25 +665,53 @@ export async function runCore(o) {
641
665
  /** #5168: a failed claude login ends the lane `deferred` `backend.auth`, held per account by the batch (never the relaunch or the breaker). */
642
666
  const authDeferral = (e) => Object.assign(e, { deferCode: OUTCOME_CODES.BACKEND_AUTH, retryInSeconds: AUTH_RETRY_SECONDS, backendId: laneBackendId(process.env, rotator),
643
667
  deferDetail: `claude CLI authentication failed (login expired or invalid); held until the login is fixed: ${String(e?.message ?? e).split("\n")[0].slice(0, 300)}` });
668
+ /** #5236: no account has room: the lane ends deferred `quota.exhausted` (earliest reset) and emits QUOTA_EXHAUSTED, never a spawn or a far pause. */
669
+ 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() }); };
644
670
  /** 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). */
645
671
  async function callRunner(args) {
646
- let pauses = 0, rotations = 0;
672
+ let pauses = 0, rotations = 0, pinned = null, credTries = 0;
647
673
  for (;;) {
674
+ 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
648
675
  // #4181: every Docker resource the builder creates carries the lane's ownership labels (same batch/lane as the ledger).
649
676
  const labels = dockerLabels({ batch: o.batchId ?? "adhoc", lane: `lean-${issue}`, issue, expires: now() + LEDGER_TTL_MS }).join(" ");
650
677
  // #4169: heavy shims first on PATH; the phase/issue/priority label each heavy step's slot and wait record.
651
678
  const heavy = heavyEnv ? { ...heavyEnv, FORGE_LANE_PHASE: args.role === "builder" ? stage : String(args.role ?? "step"), FORGE_LANE_ISSUE: String(issue), FORGE_LANE_PRIORITY: String(lanePriority()) } : {};
652
679
  const lp = laneProfile.name, profEnv = lp === "full" ? {} : { CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1", ...(lp === "lane" ? { CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1" } : {}) };
653
680
  const system = lp === "lane" && !args.resume && !args.noTools ? [args.system, laneProfile.text].filter(Boolean).join("\n\n") : args.system;
654
- try { return await io.runner({ ...args, system, env: { ...laneEnv(), FORGE_DOCKER_LABELS: labels, ...(runTmp ? { CLAUDE_CODE_TMPDIR: runTmp } : {}), ...(toolchain?.env ?? {}), ...heavy, ...profEnv } }); }
681
+ // #5205: capture the account the run uses (the shim exports it, then execs claude) and pin a rotation relaunch.
682
+ let account = pinned?.account ?? null;
683
+ let watch = null; // #5268: the shim execs claude (same pid) after spawn, so keep reading until the account shows
684
+ 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); } } : {};
685
+ const pin = pinned ? { ...(pinned.bin ? { bin: pinned.bin } : {}) } : {};
686
+ 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; }
655
687
  catch (e) {
656
- const epoch = Number.isFinite(e?.resetAtEpochMs) ? e.resetAtEpochMs : null;
657
- if (e?.authFailure === true && e.usageLimit !== true && epoch === null) throw authDeferral(e); // #5168: an account condition, never engine-error
688
+ watch?.stop(); watch?.refresh(); // #5268: the account the shim exec'd, read before the limited child is gone or now
689
+ let epoch = Number.isFinite(e?.resetAtEpochMs) ? e.resetAtEpochMs : null;
690
+ if (e?.authFailure === true && e.usageLimit !== true && epoch === null) { const x = smartRotator ? poolExhausted(rotator, laneLimited) : null; throw x ? exhaustedStop(e, x, args.role) : authDeferral(e); } // #5236: an auth failure with no account room is exhaustion // #5168: an account condition, never engine-error
658
691
  if (!(e?.usageLimit === true || epoch !== null)) throw e;
659
- if (rotatorRetry(rotator, rotations)) { rotations++; ev({ event: "PHASE_ACCOUNT_ROTATED", phase: args.role }); continue; } // #5094: same args (resume too), next account
692
+ if (smartRotator) { // #5205: exclude the limited account and relaunch the same args (resume kept) pinned to another, at once
693
+ if (account !== null) { const until = epoch !== null && epoch > now() ? epoch : now() + DEFAULT_SESSION_LIMIT_WAIT_MS; laneLimited.set(account, until); try { rotator.markLimited(account, until); } catch { /* best effort */ } }
694
+ let next = null;
695
+ try { next = rotator.pick({ exclude: laneLimited }); } catch { next = null; }
696
+ let size = 0; try { size = rotator.accounts.length; } catch { size = 0; }
697
+ if (Number.isInteger(next?.account) && rotations < size) {
698
+ rotations++; laneRotations++;
699
+ ev({ event: "PHASE_ACCOUNT_ROTATED", phase: args.role, from: account, to: next.account });
700
+ pinned = { account: next.account, bin: rotator.realClaude() ?? null, env: { CLAUDE_CONFIG_DIR: rotator.configDir(next.account) } };
701
+ continue;
702
+ }
703
+ if (next && next.account === null) throw exhaustedStop(e, { earliestReset: Number.isFinite(next.earliestReset) ? next.earliestReset : null }, args.role); // #5236
704
+ } else if (rotatorRetry(rotator, rotations)) { rotations++; laneRotations++; ev({ event: "PHASE_ACCOUNT_ROTATED", phase: args.role }); continue; } // #5094: same args (resume too), next account
705
+ else if (!rotator && sandboxCred && credTries < SANDBOX_CRED_RETRIES) { // #5205: a sandbox reports the limit; the router hands another login
706
+ credTries++;
707
+ let ok = false;
708
+ try { ok = (await credExec(["claude", "--limited", epoch !== null ? String(Math.round(epoch / 1000)) : "unknown"]))?.status === 0; } catch { ok = false; }
709
+ if (ok) { laneRotations++; ev({ event: "PHASE_ACCOUNT_ROTATED", phase: args.role, via: "cs-cred" }); continue; }
710
+ credTries = SANDBOX_CRED_RETRIES; // the router has no login with room (429): the existing defer
711
+ }
660
712
  const waitMs = epoch !== null && epoch > now() ? epoch - now() : DEFAULT_SESSION_LIMIT_WAIT_MS;
661
713
  if (pauses >= maxSessionLimitPauses || waitMs > sessionLimitMaxWaitMs) { e.deferUsageLimit = true; throw e; }
662
- pauses++;
714
+ pauses++; pinned = null; // after the wait the shim picks again
663
715
  ev({ event: "PHASE_RATE_LIMITED", phase: args.role, resetAt: epoch, resetAtDisplay: e.resetAt ?? null, waitMs });
664
716
  onProgress({ event: "phase_paused", phase: args.role, reason: "session-limit", detail: `session limit hit; pausing until ${e.resetAt || new Date(now() + waitMs).toISOString()}` });
665
717
  await sleep(waitMs);
@@ -675,8 +727,18 @@ export async function runCore(o) {
675
727
  if (r.rewritten) { T.decisions.push(`Rewrote ${r.rewritten} unpushed commit(s) with the lane identity and a sign-off (placeholder author or no Signed-off-by, #4651)`); ev({ event: "DCO_SIGNOFF_REWRITE", count: r.rewritten, ...(r.dirty ? { dirty: r.dirty } : {}) }); }
676
728
  } catch (e) { throw Object.assign(e, e?.noIdentity === true ? { laneCode: OUTCOME_CODES.CI_DCO } : { engineCode: OUTCOME_CODES.ENGINE_DCO_REWRITE }); } // #4997: a failed rewrite is mechanical (engine-error, recoverable), only a missing identity is a human block
677
729
  };
730
+ /** #5202: the lane's own pushed checkpoints a fresh session amended are merged in (-s ours) so the push stays a fast-forward. */
731
+ const reconcileLaneBranch = async () => {
732
+ const r = await reconcileCheckpoints({ git, branch });
733
+ if (r.state === "reconciled") {
734
+ ev({ event: "CHECKPOINT_RECONCILED", count: r.commits.length, sha: r.sha });
735
+ T.decisions.push(`origin/${branch} held ${r.commits.length} pushed checkpoint commit(s) the lane had rewritten locally: merged in (-s ours, ${r.sha.slice(0, 10)}) so the push stays a fast-forward`);
736
+ } else if (r.state === "foreign" || r.state === "error") ev({ event: "CHECKPOINT_RECONCILE_SKIPPED", state: r.state, ...(r.commits ? { commits: r.commits.length } : {}), ...(r.error ? { error: r.error } : {}) });
737
+ return r;
738
+ };
678
739
  const gitPush = async (args) => {
679
740
  if (!args.includes("--delete")) { await untrackToolState({ git, base, ev, keep: await keepPaths() });
741
+ await reconcileLaneBranch();
680
742
  try { await signOffUnpushed(); }
681
743
  catch (e) { // #4905: a failed rewrite must not cost the lane's finished commits: push them as-is before reporting; #5047: to a salvage ref, never the lane branch (the sign-off range excludes origin/<branch>)
682
744
  if (!e?.noIdentity) { try { const sha = String(await git(["rev-parse", "HEAD"])).trim(), ref = salvageBranch(issue, sha); await git(["push", "origin", `${sha}:refs/heads/${ref}`]); laneHead = { branch, sha, pushedTo: ref }; ev({ event: "DCO_RESCUE_PUSH", branch: ref }); } catch (pe) { ev({ event: "DCO_RESCUE_PUSH_FAILED", error: String(pe?.message ?? pe).slice(0, 200) }); } }
@@ -725,7 +787,7 @@ export async function runCore(o) {
725
787
  T.anomalies.push(line);
726
788
  if (!["invalid", "needs-human", "budget-exceeded"].includes(reason)) { try { await post("FORGE:LANE_BRANCH", `## Lane branch\n${line}`); } catch { /* best effort */ } }
727
789
  }
728
- const CONTINUE_NOTE = "\n\nThe branch already holds work from an earlier session that was interrupted (see the latest `wip(forge): checkpoint` commit). Continue from it: read `git log` and `git diff origin/BASE...HEAD`, do not start over.";
790
+ const CONTINUE_NOTE = "\n\nThe branch already holds work from an earlier session that was interrupted (see the latest `wip(forge): checkpoint` commit). Continue from it: read `git log` and `git diff origin/BASE...HEAD`, do not start over. The checkpoint commit is already pushed: do not amend, reword, squash, reset or rebase existing commits; add new commits on top.";
729
791
  const recoverNote = () => (recover ? `\n\nRecovery pass (${recover.code}): ${(RECOVER_HOW[recover.code] ?? "an earlier run ended needs-human for a mechanical reason; resolve it").replaceAll("BASE", lane)}.` : "");
730
792
  const PLAN_RERUN_NOTE = "\n\nThis is a rerun: the branch already holds commits from an earlier run. Read `git log` and `git diff origin/BASE...HEAD` to see what exists, but plan against the issue itself. This step is still planning only: do not edit code, do not commit, and do not write the result file unless the issue is invalid, already fixed or blocked.";
731
793
  const SALVAGE_NOTE = "\n\nAn earlier run on this issue stopped with uncommitted work, saved at `REF` (not on the branch). Inspect it with `git diff HEAD REF --stat` and reuse what fits the contract (`git checkout REF -- <path>`) instead of rewriting it.";
@@ -1146,6 +1208,16 @@ export async function runCore(o) {
1146
1208
  return await needsHuman(`Open PR #${resumed.pr} targets \`${resumed.base}\`, but #${issue}'s lane is \`${lane}\`; retarget or close it before rerunning.`,
1147
1209
  isDefaultLane(resumed.base, defaults) ? OUTCOME_CODES.LANE_DEFAULT_BRANCH : OUTCOME_CODES.LANE_MISMATCH);
1148
1210
  }
1211
+ if (!resumed && !recover) { // #5250: every acceptance item needs live production measurement or a real-browser capture: host work, not a code lane
1212
+ const hw = intakeHostWork(iss.body);
1213
+ if (hw.host) {
1214
+ T.decisions.push("Intake: every acceptance criterion needs live production measurement or a real-browser capture (host-task), no code lane");
1215
+ const why = `Host-task: every acceptance criterion needs live production measurement or a real-browser capture:\n${hw.items.map((t) => `- ${t}`).join("\n")}\n\nNot a code lane: run it on the host with its read-only prod tools and real browser.`;
1216
+ try { await post("FORGE:HOST_TASK", `## Host task\n${why}\n\n_${usageLine()}_`); } catch { /* best effort */ }
1217
+ try { await ghc(["issue", "edit", String(issue), "-R", repo, "--add-label", "host-task"]); } catch { /* best effort */ }
1218
+ return await finish("host-task", why, { code: OUTCOME_CODES.ENV_CAPABILITY_REMOTE }, OUTCOME_CODES.ENV_CAPABILITY_REMOTE);
1219
+ }
1220
+ }
1149
1221
  // #4162: a run that died can leave its runner writing into this worktree, and uncommitted work in it. Stop the
1150
1222
  // processes and save the work before the worktree is removed; the lease above makes this run the only one doing so.
1151
1223
  await stopWorktreeProcs();
@@ -1304,15 +1376,26 @@ export async function runCore(o) {
1304
1376
  const addedFiles = rules.some((r) => r.addedOnly) ? names(await git(["diff", "--name-only", "--diff-filter=A", `${base}...HEAD`]).catch(() => "")) : [];
1305
1377
  return coupledFailures({ rules, changedFiles: files, addedFiles });
1306
1378
  };
1379
+ /** #5237: relaxed rules in declared review.risk_paths files ({relaxations, negatives}); empty when no glob matches or git fails */
1380
+ let relaxations = [];
1381
+ const relaxationsOf = async (files) => {
1382
+ const empty = { relaxations: [], negatives: 0 };
1383
+ if (!riskPathHits(files, riskPaths).length) return empty;
1384
+ try { return analyzeRelaxations({ diff: String(await git(["diff", "-U0", `${base}...HEAD`])), riskPaths }); } catch { return empty; }
1385
+ };
1307
1386
  /** #4364: the last `forgedock check` record vs the current tree: skipped|stale|red|green; any read or git error is skipped. */
1308
1387
  const selfCheckNow = async () => {
1309
1388
  try { return selfCheckState(JSON.parse(await io.fs.read(`${wt}/${SELF_CHECK_FILE}`)), await worktreeFingerprint({ git, base })); } catch { return "skipped"; }
1310
1389
  };
1311
1390
  /** forge#4195: scripts/hotspots.sh facts in the worktree, or null (no io.hotspots, script failure): never fails a run. */
1391
+ let hotCfgNoted = false;
1312
1392
  const hotspotsOf = async (args) => {
1313
1393
  if (!io.hotspots) return null;
1314
- const h = await io.hotspots({ cwd: wt, ...args }).catch(() => null);
1315
- return h && typeof h === "object" && Array.isArray(h.files) ? h : null;
1394
+ const config = existsSync(join(cwd, "forge.yaml")) ? join(cwd, "forge.yaml") : null; // #5163: forge.yaml is often gitignored, so the worktree has none
1395
+ const h = await io.hotspots({ cwd: wt, config, ...args }).catch(() => null);
1396
+ if (!(h && typeof h === "object" && Array.isArray(h.files))) return null;
1397
+ if (h.config_source === null && !hotCfgNoted) { hotCfgNoted = true; T.anomalies.push("hotspot_config_missing: no forge.yaml readable for the hotspot gate (exclude_globs and generated_paths not applied; defaults used)"); }
1398
+ return h;
1316
1399
  };
1317
1400
  /** #4271: a bug lane with lean.repro_test on; refactor:split lanes never set it (no plan call, no repro_test). */
1318
1401
  const reproOn = () => reproTest !== "off" && isBugIssue(iss?.labels);
@@ -1470,6 +1553,12 @@ export async function runCore(o) {
1470
1553
  /** #5020: forge.yaml validate.recipes rewrite frozen commands; a check-less post-deploy requirement becomes a defer to the orchestrator. */
1471
1554
  function freezeRewrites(c) {
1472
1555
  const r = applyValidateRecipes(c, validateRecipes);
1556
+ const pd = (id, cmd) => { const to = rewriteProjectDirCommand(cmd); if (to !== cmd) T.decisions.push(`project-dir rewrite of ${id}: \`${cmd}\` -> \`${to}\``); return to; };
1557
+ if (r.contract && typeof r.contract === "object") { // #5234
1558
+ if (Array.isArray(r.contract.validate)) r.contract = { ...r.contract, validate: r.contract.validate.map((v) => (v && typeof v.command === "string" ? { ...v, command: pd(v.id, v.command) } : v)) };
1559
+ const t = r.contract.repro_test;
1560
+ if (t && typeof t === "object" && typeof t.command === "string") r.contract = { ...r.contract, repro_test: { ...t, command: pd("repro_test", t.command) } };
1561
+ }
1473
1562
  for (const x of r.applied) T.decisions.push(`validate recipe rewrote ${x.id}: \`${x.from}\` -> \`${x.to}\``);
1474
1563
  const d = deferChecklessPostDeploy(r.contract);
1475
1564
  if (d.converted.length) T.decisions.push(`Post-deploy with no registered check deferred to the orchestrator: ${d.converted.join(", ")}`);
@@ -1669,13 +1758,14 @@ export async function runCore(o) {
1669
1758
  if (decisionsNote) T.decisions.push("Trusted FORGE:DECISION comment(s) posted after the contract froze are binding notes for the builder");
1670
1759
  await label("building");
1671
1760
  // #4450: the light lane (lean.light mode on, eligible, fresh lane): one builder session, derived contract, or an upgrade
1672
- const elig = lightEligibility({ title: iss.title, body: iss.body ?? "", labels: iss.labels ?? [], predictedFiles: namedPaths(iss.body ?? ""), riskPaths, cfg: o.light ?? {} });
1673
- ev({ event: "LIGHT_ELIGIBILITY", mode: elig.mode, verdict: elig.verdict, light: elig.light, reasons: elig.reasons });
1761
+ const namedHot = await hotspotsOf({ paths: namedPaths(iss.body ?? "") }); // #5209: churn and hotspot signals for eligibility
1762
+ const elig = lightEligibility({ title: iss.title, body: iss.body ?? "", labels: iss.labels ?? [], predictedFiles: namedPaths(iss.body ?? ""), riskPaths, hotspots: namedHot?.files ?? [], cfg: o.light ?? {} });
1763
+ ev({ event: "LIGHT_ELIGIBILITY", mode: elig.mode, verdict: elig.verdict, light: elig.light, reasons: elig.reasons, signals: elig.signals });
1674
1764
  lightVerdict = elig.verdict;
1675
1765
  if (elig.mode !== "off") T.decisions.push(`Light lane ${elig.mode}: ${elig.verdict}${elig.reasons.length ? ` (${elig.reasons.map((x) => x.code).join(", ")})` : ""}`);
1676
1766
  // #4451: a light try skips the hotspots and the context pack; an upgrade computes them before the plan call
1677
1767
  const lightTry = elig.light && !frozen && !resumed && !salvagedRef && !recover;
1678
- if (!lightTry) hotFacts = await hotspotsOf({ paths: namedPaths(iss.body ?? "") });
1768
+ if (!lightTry) hotFacts = namedHot; // #4451: a light try still gives its builder no hotspot facts
1679
1769
  enumList = io.enumeratingTests ? ((await io.enumeratingTests({ cwd: wt, paths: namedPaths(iss.body ?? "") }).catch(() => null)) ?? []) : [];
1680
1770
  facts = await factsPath([wt, cwd], io.fs?.exists);
1681
1771
  let ctxPack = frozen || lightTry ? null : await contextPackStep();
@@ -1731,6 +1821,7 @@ export async function runCore(o) {
1731
1821
  // #5152: already-fixed is delivered behaviour (`completed`); only invalid is dropped scope (`not planned`)
1732
1822
  await ghw(["issue", "close", String(issue), "-R", repo, "--reason", result.status === "already-fixed" ? "completed" : "not planned"]);
1733
1823
  await label("invalid");
1824
+ 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
1734
1825
  return await finish("invalid", result.summary ?? result.status, result.status === "already-fixed" ? { close: "already-fixed" } : {});
1735
1826
  }
1736
1827
  const blocked = await endIfBlocked();
@@ -1754,6 +1845,12 @@ export async function runCore(o) {
1754
1845
  let contract = dropScope(await readContract());
1755
1846
  contract = freezeRewrites(contract);
1756
1847
  await refreshIssue("contract validation");
1848
+ const snapContract = (c) => { // #5244: a near-verbatim quote snaps to the issue's exact sentence instead of ending needs-human
1849
+ const sq = snapQuotes(c, issueText);
1850
+ for (const x of sq.snapped) { ev({ event: "CONTRACT_QUOTE_SNAPPED", id: x.id }); T.decisions.push(`Contract quote ${x.id} snapped to the issue sentence "${x.to.slice(0, 120)}"`); }
1851
+ return sq.contract;
1852
+ };
1853
+ contract = snapContract(contract);
1757
1854
  let vc = validateContract(contract, issueText, { repro: reproOn() });
1758
1855
  const missed = await preflightValidates(contract); // #4328: validate commands the host cannot run share the one correction
1759
1856
  let misses = missed;
@@ -1763,6 +1860,7 @@ export async function runCore(o) {
1763
1860
  await builder(++attemptN, contractCorrectionPrompt(problems), sessionId, false, planPrompt, { trigger: "contract_correction" });
1764
1861
  contract = freezeRewrites(dropScope(await readContract()));
1765
1862
  await refreshIssue("contract validation");
1863
+ contract = snapContract(contract);
1766
1864
  vc = validateContract(contract, issueText, { repro: reproOn() });
1767
1865
  if (missed.length) misses = await preflightValidates(contract);
1768
1866
  }
@@ -1873,7 +1971,8 @@ export async function runCore(o) {
1873
1971
  const names = failed.map((f) => `\`${f.command}\` (exit ${f.rc})`).join(", ");
1874
1972
  if (isSplit) return await needsHuman(`Declared check command(s) fail on the refactor:split move (no builder edits a split); nothing merged: ${names}`, OUTCOME_CODES.CI_RED);
1875
1973
  checkCommandsFailing = true;
1876
- if (round >= vcfg.maxRounds || !sessionId) { if (vcfg.precheckBlock) return await needsHuman(`Declared check command(s) still failing before the PR (verify.precheck_block); nothing merged: ${names}`, OUTCOME_CODES.CI_RED); T.anomalies.push(`Declared check command(s) still failing before the PR: ${names}`); break; }
1974
+ { const red = await guardRed(failed); if (red) return red; } // #5239: a guard that also fails on the base defers the lane
1975
+ if (round >= vcfg.maxRounds || !sessionId) { if (vcfg.precheckBlock || guardFailing(failed)) return await needsHuman(`Declared check command(s) still failing before the PR (verify.precheck_block); nothing merged: ${names}`, OUTCOME_CODES.CI_RED); T.anomalies.push(`Declared check command(s) still failing before the PR: ${names}`); break; }
1877
1976
  T.decisions.push(`Declared check command(s) failed: ${names}; builder resumed (round ${round + 1}/${vcfg.maxRounds})`);
1878
1977
  const before = String(await git(["rev-parse", "HEAD"])).trim();
1879
1978
  const capped = capLogs(failed.map((f) => ({ ...f, log: f.output }))).map((f) => ({ command: f.command, rc: f.rc, output: f.log }));
@@ -1887,7 +1986,7 @@ export async function runCore(o) {
1887
1986
  await fixRound("precheck", precheckFailurePrompt(quiet, vcfg.mode), [], "precheck", capped.map((f) => `${f.command}\n${f.output ?? ""}`).join("\n"));
1888
1987
  await upsertStage("implementation");
1889
1988
  result = (await readResult()) ?? result;
1890
- if (String(await git(["rev-parse", "HEAD"])).trim() === before) { if (vcfg.precheckBlock) return await needsHuman(`Declared check command(s) failing and the builder made no new commit for them (verify.precheck_block); nothing merged: ${names}`, OUTCOME_CODES.CI_RED); T.anomalies.push(`Declared check command(s) failing and the builder made no new commit for them: ${names}`); break; }
1989
+ if (String(await git(["rev-parse", "HEAD"])).trim() === before) { if (vcfg.precheckBlock || guardFailing(failed)) return await needsHuman(`Declared check command(s) failing and the builder made no new commit for them (verify.precheck_block); nothing merged: ${names}`, OUTCOME_CODES.CI_RED); T.anomalies.push(`Declared check command(s) failing and the builder made no new commit for them: ${names}`); break; }
1891
1990
  files = await changedFiles();
1892
1991
  }
1893
1992
  }
@@ -2075,7 +2174,7 @@ export async function runCore(o) {
2075
2174
  await i18nGate("hand-off");
2076
2175
  /** #4406: verify.post_merge (else the scoped typecheck) on the merged tree before the base-sync push; fix rounds up to verify.max_rounds. */
2077
2176
  async function postMergeGate(trigger) {
2078
- const commands = io.runCommand && !isSplit ? postMergeCommands({ configured: vcfg.postMerge, scoped: (await io.postMergeChecks?.({ cwd: wt, base }).catch(() => [])) ?? [], mode: vcfg.mode }) : [];
2177
+ const commands = io.runCommand && !isSplit ? [...new Set([...postMergeCommands({ configured: vcfg.postMerge, scoped: (await io.postMergeChecks?.({ cwd: wt, base }).catch(() => [])) ?? [], mode: vcfg.mode }), ...(guardOn() ? vcfg.invariants : [])])] : []; // #5239: the guard set also runs on the merged tree
2079
2178
  let fixed = false, results = [];
2080
2179
  for (let round = 0; commands.length; round++) {
2081
2180
  await renew();
@@ -2096,7 +2195,23 @@ export async function runCore(o) {
2096
2195
  fixed = true;
2097
2196
  if ((String(await git(["rev-parse", "HEAD"])).trim()) === before) { T.anomalies.push(`Post-merge check(s) failing and the builder made no new commit for them: ${names}`); break; }
2098
2197
  }
2099
- return { fixed, ran: results.map(({ command, rc }) => `${command}: ${rc === 0 ? "pass" : `fail (exit ${rc})`}`).join("; ") };
2198
+ return { fixed, stuck: results.filter((r) => r.rc !== 0 && guardFailing([r])), ran: results.map(({ command, rc }) => `${command}: ${rc === 0 ? "pass" : `fail (exit ${rc})`}`).join("; ") };
2199
+ }
2200
+ /** #5239: verify.invariants are the pre-merge guard set; blocking unless verify.guard_block is false. */
2201
+ function guardOn() { return vcfg.guardBlock !== false && (vcfg.invariants ?? []).length > 0; }
2202
+ function guardFailing(failed) { return guardOn() && failed.some((f) => vcfg.invariants.includes(f.command)); }
2203
+ /** #5239: guard commands failing here are run once on the base; failing there too, the lane is deferred (base.red) and the introducing issue is told. null: the failure is the lane's. */
2204
+ async function guardRed(failed) {
2205
+ const g = failed.filter((f) => guardFailing([f]));
2206
+ if (!g.length || isSplit || !io.runCommand) return null;
2207
+ const baseRuns = await heavyStep("precheck", () => runOnBase({ commands: g.map((f) => f.command), git, runCommand: io.runCommand, mergeBase: base, cwd: wt, env: laneEnv(), timeoutMs: vcfg.precheckTimeoutSeconds * 1000 }));
2208
+ const { baseRed } = classifyBaseRed({ failed: g, baseRuns });
2209
+ if (!baseRed.length) return null;
2210
+ const att = await attributeBaseRed({ failed: baseRed, git, base });
2211
+ const cmds = baseRed.map((f) => f.command), n = await reportBaseRed({ ghc: ghw, repo, base, att, laneIssue: issue, commands: cmds });
2212
+ T.decisions.push(`Guard command(s) ${cmds.map((c) => `\`${c}\``).join(", ")} also fail on ${base}${att ? ` (last change ${att.sha.slice(0, 12)}${att.issue ? `, #${att.issue}` : ""})` : ""}; lane deferred behind ${n ? `#${n}` : "the base fix"}`);
2213
+ ev({ event: "BASE_RED", commands: cmds, sha: att?.sha ?? null, issue: att?.issue ?? null, tracked: n });
2214
+ return await finish("deferred", `base ${base} is red on guard command(s) ${cmds.join(", ")}; deferred behind ${n ? `#${n}` : "the base fix"}`, { code: OUTCOME_CODES.BASE_RED, retryInSeconds: 900 }, OUTCOME_CODES.BASE_RED);
2100
2215
  }
2101
2216
  const structureLine = structureNote(structure);
2102
2217
 
@@ -2113,6 +2228,7 @@ export async function runCore(o) {
2113
2228
  let fixes = 0;
2114
2229
  for (;;) {
2115
2230
  await untrackToolState({ git, base, ev, keep: await keepPaths() }); // #4621: gitPush's untrack commit would move HEAD after `head` was read; do it first so head is the pushed tip
2231
+ await reconcileLaneBranch(); // #5202: likewise the checkpoint reconcile merge
2116
2232
  await signOffUnpushed(); // #4651: likewise the sign-off rewrite
2117
2233
  const head = String(await git(["rev-parse", "HEAD"])).trim();
2118
2234
  if (head === ciVerifiedHead || ciFellBack) return { fixes };
@@ -2254,7 +2370,7 @@ export async function runCore(o) {
2254
2370
  await renew();
2255
2371
  const rr = await callRunner({ role: "reviewer", issue, cwd: wt, model: reviewerModel, resume: null, system: REVIEWER_SYSTEM, readOnly: true,
2256
2372
  prompt: repair ? reviewerRepairPrompt({ missing: d.missing ?? [], problems: d.failures.map((f) => f.detail), rows: first, criteria: (d.missing ?? []).includes("issue_coverage") ? criterionLines(issueText) : [] })
2257
- : reviewerPrompt({ issue: iss, comments: trustedComments, contract: effective, result, files, diff, stat, base, structure: structureLine, ignore: IGNORE, domains, investigationVerdict: investigationVerdict(await io.fs.read(`${wt}/.forge-lean/investigation.md`).catch(() => null)) }) });
2373
+ : 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)) }) });
2258
2374
  await renew();
2259
2375
  await attempt("review", ++reviewN, rr, null, "review");
2260
2376
  const parsed = parseReview(rr?.text);
@@ -2279,7 +2395,7 @@ export async function runCore(o) {
2279
2395
  const head = String(await git(["rev-parse", "HEAD"])).trim();
2280
2396
  if (verifiedHeads.has(head)) return verifiedHeads.get(head);
2281
2397
  const diff = String(await git(["diff", `${base}...HEAD`]));
2282
- const run = { mode: verifierCfg.mode, head, findings: [], model: null, swapped: false, cost_usd: 0 };
2398
+ const run = { mode: relaxations.length ? "enforce" : verifierCfg.mode, head, findings: [], model: null, swapped: false, cost_usd: 0 };
2283
2399
  if (!diff.trim()) run.skipped = "empty_diff";
2284
2400
  else {
2285
2401
  const bytes = Buffer.byteLength(diff, "utf-8");
@@ -2291,7 +2407,7 @@ export async function runCore(o) {
2291
2407
  try {
2292
2408
  await renew();
2293
2409
  const rr = await callRunner({ role: "verifier", issue, cwd: wt, model: run.model, resume: null, system: VERIFIER_SYSTEM, readOnly: true, maxMs, maxTurns,
2294
- prompt: verifierPrompt({ issue: iss, comments: trustedComments, contract: effective, diff, stat, base, files, callers }) });
2410
+ prompt: verifierPrompt({ issue: iss, comments: trustedComments, contract: effective, diff, stat, base, files, callers, relaxations }) });
2295
2411
  await renew();
2296
2412
  await attempt("verify", ++verifyN, rr, null, "verifier");
2297
2413
  run.findings = parseVerifierFindings(rr?.text, { pathExists: (x) => listed.has(x) });
@@ -2302,7 +2418,7 @@ export async function runCore(o) {
2302
2418
  T.anomalies.push(`Independent verifier failed at ${head.slice(0, 12)}: ${run.error}`);
2303
2419
  }
2304
2420
  }
2305
- const failures = verifierCfg.mode === "enforce" ? findingsToFailures(run.findings) : [];
2421
+ const failures = run.mode === "enforce" ? findingsToFailures(run.findings) : [];
2306
2422
  ev({ event: "VERIFIER", mode: run.mode, head, model: run.model, swapped: run.swapped, findings: run.findings.length, cost_usd: run.cost_usd, implement_cost_usd: impl.cost,
2307
2423
  ratio: impl.cost > 0 ? Math.round((run.cost_usd / impl.cost) * 1000) / 1000 : null, ...(run.skipped ? { skipped: run.skipped } : {}), ...(run.error ? { error: run.error } : {}) });
2308
2424
  if (run.findings.length) T.decisions.push(`Independent verifier (${run.mode}) found ${run.findings.length} defect(s): ${run.findings.slice(0, 3).map((f) => `${f.file}:${f.line}`).join(", ")}`);
@@ -2426,7 +2542,14 @@ export async function runCore(o) {
2426
2542
  const checkIds = effective.requirements?.some((r) => r.disposition === "post-deploy") ? new Set(Object.keys(await checksAt(git, [base, "HEAD"], wt))) : null;
2427
2543
  const removedPaths = (effective.validate ?? []).some((v) => v.substituted) ? await removedPathsOf(git, base) : []; // #4990
2428
2544
  const subBaseFiles = (effective.validate ?? []).some((v) => v.substituted) ? String(await git(["ls-tree", "-r", "-z", "--name-only", base]).catch(() => "")).split("\0").filter(Boolean) : []; // #5003
2429
- 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), routeFailures, newOffKeys: await newOffKeysOf(), substitutedRuns, removedPaths, baseFiles: subBaseFiles });
2545
+ const rx = await relaxationsOf(files); // #5237
2546
+ relaxations = rx.relaxations;
2547
+ if (relaxations.length) {
2548
+ ev({ event: "RELAXATION_DETECTED", files: [...new Set(relaxations.map((r) => r.file))], count: relaxations.length, negatives: rx.negatives });
2549
+ const note = `Relaxation in a declared risk path (${[...new Set(relaxations.map((r) => r.file))].slice(0, 5).join(", ")}): negative tests added ${rx.negatives}; independent verifier enforced`;
2550
+ if (!T.decisions.includes(note)) T.decisions.push(note);
2551
+ }
2552
+ const pc = precheck({ contract: effective, result, changedFiles: files, ignore: IGNORE, ciVerified, hotspots, repro: await reproOf(effective), validateRuns, repoHas, frozen, checkIds, guardFailures, coupledFailures: await coupledOf(files), relaxationFailures: relaxationFailures(rx), routeFailures, newOffKeys: await newOffKeysOf(), substitutedRuns, removedPaths, baseFiles: subBaseFiles });
2430
2553
  // #4350: a scope-check validate stale only by amended deliverables is judged by the engine's scope gate instead
2431
2554
  if (pc.superseded?.length) {
2432
2555
  ev({ event: "VALIDATE_SUPERSEDED", runs: pc.superseded });
@@ -2484,7 +2607,7 @@ export async function runCore(o) {
2484
2607
  }
2485
2608
  let d = await reviewOnce();
2486
2609
  // #4397: the verifier runs only on a change every gate and the reviewer passed; in enforce its findings block
2487
- if (verifierCfg.mode !== "off" && d.state === "conforms" && !pre.length) {
2610
+ if ((verifierCfg.mode !== "off" || relaxations.length) && d.state === "conforms" && !pre.length) { // #5237: a relaxation lane always gets the independent second look
2488
2611
  const vf = await runVerifier();
2489
2612
  if (vf.length) d = { state: "nonconforming", failures: vf, by: "verifier" };
2490
2613
  }
@@ -2524,7 +2647,7 @@ export async function runCore(o) {
2524
2647
  async function envNeedsHuman(failures) {
2525
2648
  if (failures.every((f) => f.code === OUTCOME_CODES.ENV_REPRO_UNRUNNABLE)) {
2526
2649
  T.anomalies.push("Environment error: the repro harness could not run the repro test on head");
2527
- return await needsHuman(`Environment error (not a conformance failure): the repro harness could not run the repro test on head; no builder resume was spent and nothing merged:\n${failures.map((f) => `- ${f.code}: ${f.detail}`).join("\n")}\n\nRun the repro command through the repo's own toolchain and installed dependencies, then rerun.`, OUTCOME_CODES.ENV_REPRO_UNRUNNABLE);
2650
+ return await needsHuman(`Environment error (not a conformance failure): the repro harness could not run the repro test on head; no builder resume was spent and nothing merged:\n${failures.map((f) => `- ${f.code}: ${f.detail}`).join("\n")}\n\nEnvironment defect: run the repro command above on the host with the project's real dependencies (its lockfile or toolchain), then rerun.`, OUTCOME_CODES.ENV_REPRO_UNRUNNABLE);
2528
2651
  }
2529
2652
  if (failures.every((f) => f.code === ENV_VALIDATE_TIMEOUT)) { // #4906: the teardown below pushes the lane's commits, so CI and recovery still see them
2530
2653
  T.anomalies.push("Environment error: a validate command timed out on the engine's rerun (infra, exit 124)");
@@ -2586,7 +2709,7 @@ export async function runCore(o) {
2586
2709
  // Deferrals the reviewer accepted are filed now, before any PR: the batched follow-up must exist and be linked.
2587
2710
  const toFile = pendingTracking(effective);
2588
2711
  if (toFile.length) await track(toFile, "accepted by the conformance review");
2589
- degradedReq = degraded ? { id: "REVIEW", quote: `conformance review ${degraded.state}: re-run the review`, disposition: "defer", why: `${REVIEW_DEGRADED_LABEL}: rows still missing for ${degraded.missing.join(", ") || "the verdict"}` } : null;
2712
+ degradedReq = degraded ? { id: "REVIEW", quote: `conformance review ${degraded.state}: re-run the review`, disposition: "defer", class: "ops", why: `${REVIEW_DEGRADED_LABEL}: rows still missing for ${degraded.missing.join(", ") || "the verdict"}` } : null;
2590
2713
  if (degradedReq) await track([degradedReq], "the conformance review stayed incomplete");
2591
2714
  if (triggerSkipped) {
2592
2715
  T.decisions.push("Conformance reviewer skipped by review.trigger enforce: no trigger reason (risk path, package edge, hotspot, failed or ambiguous gate)");
@@ -2610,11 +2733,16 @@ export async function runCore(o) {
2610
2733
  }
2611
2734
  }
2612
2735
  ev({ event: "PHASE_COMMIT", phase: "review" });
2613
- const closing = closePlan(effective, { title: iss.title, review });
2614
- if (closing.reason === "partial") { // #4398: an investigation whose question is not answered carries it forward
2736
+ const closing = closePlan(effective, { title: iss.title, review, issueText });
2737
+ // #5240: a delivered change behind a rollout that is not live (shadow/off) is inert in production: say so, never claim the outcome
2738
+ const rcfg = readRollouts(wt);
2739
+ const inert = (rcfg ? rolloutModes(rcfg, files, (f) => readFileSync(join(wt, f), "utf8")) : []).filter((m) => !m.live);
2740
+ if (inert.length) T.decisions.push(`Inert in production: the change touches rollout ${inert.map((m) => `${m.flag} (mode ${m.mode})`).join(", ")}; the issue's production outcome is not claimed (#5240)`);
2741
+ if (closing.checklist) T.decisions.push(`Unticked acceptance criteria unmet (${closing.open.map((r) => r.id).join(", ")}): issue left open as partial (#5240)`);
2742
+ if (closing.reason === "partial" && !closing.checklist) { // #4398: an investigation whose question is not answered carries it forward
2615
2743
  const untracked = closing.open.filter((r) => !r.tracked);
2616
2744
  if (untracked.length) {
2617
- const carried = untracked.map((r) => ({ ...r, disposition: "defer", why: "investigation question not answered" }));
2745
+ const carried = untracked.map((r) => ({ ...r, disposition: "defer", class: "ops", why: "investigation question not answered" })); // #5207: the batch aggregate
2618
2746
  await track(carried, "the investigation's question is not answered");
2619
2747
  for (const [i, r] of untracked.entries()) r.tracked = carried[i].tracked;
2620
2748
  }
@@ -2752,6 +2880,7 @@ export async function runCore(o) {
2752
2880
  let pm = { fixed: false, ran: "" }, dupFixed = false;
2753
2881
  if ((await gitOut(["rev-parse", "HEAD"])) !== before) { // #4406: the merged tree, before the push
2754
2882
  pm = await postMergeGate(`base-sync ${syncs}`);
2883
+ if (pm.stuck?.length) return (await guardRed(pm.stuck)) ?? await needsHuman(`Guard command(s) still fail on the merged tree after ${base} was merged in (${pm.stuck.map((f) => f.command).join(", ")}); nothing merged.`, OUTCOME_CODES.CI_RED); // #5239
2755
2884
  if (pm.ran) tests = clean ? pm.ran : `${tests}; post-merge: ${pm.ran}`;
2756
2885
  if (pm.fixed) how += "; builder fixed post-merge check failures";
2757
2886
  dupFixed = await duplicateGate(`base-sync ${syncs}`);
@@ -3070,9 +3199,12 @@ export async function runCore(o) {
3070
3199
  }
3071
3200
  }
3072
3201
  const partial = closing.reason === "partial";
3202
+ if (closing.checklist) keepOpen = true; // #5240: an unmet acceptance checkbox is not closed as completed
3073
3203
  // #5152: a merged change is `completed` even when partial: the remainder is tracked (FORGE:TRACKED), not dropped
3074
3204
  if (!keepOpen) await ghw(["issue", "close", String(issue), "-R", repo, "--reason", "completed"]).catch(() => {});
3075
- if (keepOpen) { // #5159: the issue is not closed while a follow-up is pending, so the note must not say it is
3205
+ if (closing.checklist) { // #5240: partial: left open; the unticked criteria, tracked follow-ups and any inert rollout are the record
3206
+ try { await post("FORGE:TRACKED", `## Left open: partial\nMerged by PR #${pr}, but these acceptance criteria are not met by it:\n${closing.unticked.map((u) => `- [ ] ${u}`).join("\n")}${closing.tracked.length ? `\n\nTracked in ${closing.tracked.join(", ")}.` : ""}${inert.length ? `\n\nInert in production: the change takes effect only behind ${inert.map((m) => `\`${m.flag}\` (mode: ${m.mode})`).join(", ")}; the production outcome is not claimed.` : ""}`); } catch { /* the PR body and FORGE:STATE carry them */ }
3207
+ } else if (keepOpen) { // #5159: the issue is not closed while a follow-up is pending, so the note must not say it is
3076
3208
  if (partial || closing.tracked.length) try { await post("FORGE:TRACKED", `## Left open: follow-up pending\nMerged by PR #${pr}; the issue stays open until the pending follow-up is filed (FORGE:FOLLOWUP_PENDING).${partial ? " The investigation's stated question is not answered in this change." : ""}${closing.tracked.length ? ` Already tracked in ${closing.tracked.join(", ")}.` : ""}`); } catch { /* the PR body links them too */ }
3077
3209
  } else if (partial) {
3078
3210
  try { await post("FORGE:TRACKED", `## Closed as partial\nClosed as completed by PR #${pr}; the investigation's stated question is not answered in this change and is carried forward in ${closing.tracked.join(", ")}.`); } catch { /* the PR body links them too */ }
@@ -3088,6 +3220,7 @@ export async function runCore(o) {
3088
3220
  } catch (e) { T.anomalies.push(`refactor:split chain issue not filed (the maintenance scan re-files the hotspot): ${String(e?.message ?? e).slice(0, 200)}`); }
3089
3221
  }
3090
3222
  await label("merged");
3223
+ if (!keepOpen) { const f = await resolveFindingLabel({ io, issue, labels: iss.labels, reason: "merged" }); if (f.error) T.anomalies.push(`finding label not resolved: ${f.error}`); } // #5254
3091
3224
  try { // #4695/#4737: FORGE:DECISION records and supersession are persisted only after the merge
3092
3225
  const rec = await recordDecisions(pendingDecisions, { issue, repo, post });
3093
3226
  if (rec.length) T.decisions.push(`FORGE:DECISION: ${rec.map((d) => d.id).join(", ")}`);
@@ -3106,7 +3239,7 @@ export async function runCore(o) {
3106
3239
  const when = e.resetAt || (Number.isFinite(e.resetAtEpochMs) ? new Date(e.resetAtEpochMs).toISOString() : "unknown");
3107
3240
  return finish("deferred", `usage limit hit; resets at ${when}`, { code: OUTCOME_CODES.RATE_LIMITED, resetAt: when, resetAtEpochMs: Number.isFinite(e.resetAtEpochMs) ? e.resetAtEpochMs : null, backendId: laneBackendId(process.env, rotator) }, OUTCOME_CODES.RATE_LIMITED);
3108
3241
  }
3109
- if (e?.deferCode) return finish("deferred", e.deferDetail ?? String(e.message), { code: e.deferCode, ...(e.retryInSeconds ? { retryInSeconds: e.retryInSeconds } : {}), ...(e.backendId ? { backendId: e.backendId } : {}) }, e.deferCode); // #5168: backendId keys the account hold
3242
+ if (e?.deferCode) return finish("deferred", e.deferDetail ?? String(e.message), { code: e.deferCode, ...(e.retryInSeconds ? { retryInSeconds: e.retryInSeconds } : {}), ...(e.backendId ? { backendId: e.backendId } : {}), ...quotaFacts(e) }, e.deferCode); // #5168: backendId keys the account hold; #5236 reset
3110
3243
  // #4505: a turn overrun is mechanical: a non-human end the batch recovers, needs-human only once a budget recovery failed too
3111
3244
  if (e?.laneCode === OUTCOME_CODES.BUDGET_EXCEEDED && !(recover?.final && recover.code === OUTCOME_CODES.BUDGET_EXCEEDED)) {
3112
3245
  return finish("budget-exceeded", e.message, { code: OUTCOME_CODES.BUDGET_EXCEEDED, branch, ...(recover ? { recovery: true } : {}) }, OUTCOME_CODES.BUDGET_EXCEEDED);
@@ -3120,6 +3253,8 @@ export async function runCore(o) {
3120
3253
  let owner = null;
3121
3254
  try { owner = await otherLaneOwner({ gh: (a) => ghc(a), repo, issue, branch, selfId: agentId, ownPr: Number(/#(\d+)/.exec(String(T.pr?.[0] ?? ""))?.[1]) || null }); } catch { /* fail-open */ }
3122
3255
  if (owner) return finish("deferred", `git push was rejected (non-fast-forward): ${owner.detail}; another lane owns ${branch}`, { code: OUTCOME_CODES.LEASE_HELD, branch }, OUTCOME_CODES.LEASE_HELD);
3256
+ // #5202: the lane's own history diverged from origin/<branch> (not reconcilable checkpoints): mechanical, never needs-human
3257
+ return finish("engine-error", `git push was rejected (non-fast-forward) and no other lane owns ${branch}: ${String(e?.stderr ?? e?.message ?? e).slice(0, 400)}`, { code: OUTCOME_CODES.ENGINE_PUSH_DIVERGED, branch }, OUTCOME_CODES.ENGINE_PUSH_DIVERGED);
3123
3258
  }
3124
3259
  if (e?.pushRejected) return await needsHuman(`git push was rejected (no retry): ${String(e?.stderr ?? e?.message ?? e).slice(0, 400)}`);
3125
3260
  if (e?.engineCode) return finish("engine-error", e?.message ?? String(e), { code: e.engineCode }, e.engineCode); // #4997