forgedock 1.59.2 → 1.60.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 (94) hide show
  1. package/bin/engine/outcome-codes.mjs +3 -3
  2. package/bin/engine-cli.mjs +50 -10
  3. package/bin/labels.json +5 -0
  4. package/bin/lean/batch.mjs +21 -2
  5. package/bin/lean/batch.test.mjs +116 -1
  6. package/bin/lean/conformance.mjs +12 -5
  7. package/bin/lean/conformance.test.mjs +30 -2
  8. package/bin/lean/depcache.mjs +34 -15
  9. package/bin/lean/depcache.test.mjs +100 -1
  10. package/bin/lean/design-gate.mjs +15 -10
  11. package/bin/lean/design-gate.test.mjs +21 -0
  12. package/bin/lean/effects.mjs +18 -2
  13. package/bin/lean/execution.mjs +23 -5
  14. package/bin/lean/execution.test.mjs +81 -1
  15. package/bin/lean/gatewatch.test.mjs +5 -5
  16. package/bin/lean/issuewatch-triage.mjs +68 -0
  17. package/bin/lean/issuewatch-triage.test.mjs +98 -0
  18. package/bin/lean/issuewatch.mjs +34 -6
  19. package/bin/lean/issuewatch.test.mjs +11 -0
  20. package/bin/lean/lanelock.mjs +5 -4
  21. package/bin/lean/lean.mjs +123 -17
  22. package/bin/lean/lean.test.mjs +154 -6
  23. package/bin/lean/orchestrate-cancel.test.mjs +33 -0
  24. package/bin/lean/orchestrate-hostfallback.test.mjs +41 -0
  25. package/bin/lean/orchestrate-recovering.test.mjs +42 -0
  26. package/bin/lean/orchestrate.mjs +23 -10
  27. package/bin/lean/pagegate.mjs +50 -12
  28. package/bin/lean/pagegate.test.mjs +38 -1
  29. package/bin/lean/phaseledger.mjs +65 -2
  30. package/bin/lean/phaseledger.test.mjs +70 -2
  31. package/bin/lean/preflight.mjs +5 -2
  32. package/bin/lean/preflight.test.mjs +7 -0
  33. package/bin/lean/prompts.mjs +2 -1
  34. package/bin/lean/recovery.test.mjs +11 -6
  35. package/bin/lean/release-classify.mjs +143 -0
  36. package/bin/lean/release-classify.test.mjs +130 -0
  37. package/bin/lean/release-conductor.mjs +163 -0
  38. package/bin/lean/release-conductor.test.mjs +194 -0
  39. package/bin/lean/release-config.mjs +60 -8
  40. package/bin/lean/release-config.test.mjs +43 -1
  41. package/bin/lean/release-control.mjs +22 -5
  42. package/bin/lean/release-control.test.mjs +22 -0
  43. package/bin/lean/release-credentials.mjs +40 -0
  44. package/bin/lean/release-credentials.test.mjs +42 -0
  45. package/bin/lean/release-deploy.mjs +3 -3
  46. package/bin/lean/release-deploy.test.mjs +8 -0
  47. package/bin/lean/release-docs.test.mjs +93 -0
  48. package/bin/lean/release-fence.mjs +2 -0
  49. package/bin/lean/release-gate.mjs +88 -0
  50. package/bin/lean/release-gate.test.mjs +116 -0
  51. package/bin/lean/release-gates.mjs +5 -1
  52. package/bin/lean/release-ledger.mjs +47 -1
  53. package/bin/lean/release-ledger.test.mjs +33 -1
  54. package/bin/lean/release-mergeback.mjs +148 -0
  55. package/bin/lean/release-mergeback.test.mjs +129 -0
  56. package/bin/lean/release-p0.mjs +193 -0
  57. package/bin/lean/release-p0.test.mjs +127 -0
  58. package/bin/lean/release-plan.mjs +267 -0
  59. package/bin/lean/release-plan.test.mjs +202 -0
  60. package/bin/lean/release-preflight.mjs +16 -0
  61. package/bin/lean/release-regate.mjs +141 -0
  62. package/bin/lean/release-regate.test.mjs +149 -0
  63. package/bin/lean/release-review.mjs +5 -3
  64. package/bin/lean/release-rollback.mjs +277 -0
  65. package/bin/lean/release-rollback.test.mjs +245 -0
  66. package/bin/lean/release-snapshot.mjs +48 -9
  67. package/bin/lean/release-snapshot.test.mjs +43 -1
  68. package/bin/lean/release-start.mjs +164 -0
  69. package/bin/lean/release-start.test.mjs +171 -0
  70. package/bin/lean/release-status.mjs +6 -2
  71. package/bin/lean/release-train.mjs +159 -0
  72. package/bin/lean/release-train.test.mjs +139 -0
  73. package/bin/lean/release.mjs +127 -5
  74. package/bin/lean/release.test.mjs +80 -0
  75. package/bin/lean/sandbox-remote.mjs +2 -0
  76. package/bin/lean/schedd-load.test.mjs +82 -0
  77. package/bin/lean/schedd.mjs +67 -31
  78. package/bin/lean/schedd.test.mjs +80 -1
  79. package/bin/lean/validate-catalog.mjs +94 -0
  80. package/bin/lean/validate-catalog.test.mjs +42 -0
  81. package/bin/pool/agent.mjs +4 -1
  82. package/bin/pool/lane-tools.mjs +115 -0
  83. package/bin/pool/lane-tools.test.mjs +26 -0
  84. package/bin/pool/warm.mjs +1 -1
  85. package/docs/CONFIG.md +225 -1
  86. package/docs/ISSUE-WATCH.md +1 -0
  87. package/docs/design/visual-gate.md +10 -0
  88. package/docs/eval/adversarial-bench.md +1 -0
  89. package/package.json +1 -1
  90. package/pool/README.md +2 -0
  91. package/scripts/bench-adversarial.mjs +4 -0
  92. package/scripts/bench-lightlane.mjs +2 -1
  93. package/templates/github-actions/forge-conductor.scopes.json +7 -0
  94. package/templates/github-actions/forge-conductor.yml +57 -0
package/bin/lean/lean.mjs CHANGED
@@ -29,6 +29,7 @@ import { checksAt, mergeCheckEntries, CHECKS_FILE } from "./postdeploy-check.mjs
29
29
  import { matchBaselines, baselineFailures, foldRegression } from "./baselines.mjs";
30
30
  import { readRollouts, detectNewOffKeys, rolloutModes, liveDeferralBlocks } from "./activation.mjs";
31
31
  import { toolMisses } from "./toolplace.mjs";
32
+ import { hasRecipe, installLaneTools } from "../pool/lane-tools.mjs";
32
33
  import { testRunnerProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract, declaredEnv, depInstallFailures, testRunSummary, projectBinDirs, withLocalBins } from "./preflight.mjs";
33
34
  import { resolveLane, isDefaultLane, isShippedLane, DEFAULT_STAGING_BRANCH } from "./lane.mjs";
34
35
  import { splitGate, rationaleLine } from "./decompose.mjs";
@@ -110,6 +111,7 @@ import { makePostRun } from "./postrun.mjs";
110
111
  import { ensureSignedOff, salvageBranch, dropSalvageTracking } from "./signoff.mjs";
111
112
  import { reconcileCheckpoints } from "./checkpoint-reconcile.mjs";
112
113
  import { createLedger, flattenPhases } from "./phaseledger.mjs";
114
+ import { DEFAULT_CATALOG_SOURCES, deriveCatalog, mergeRecipes, rewriteMissed, isDriftFailure } from "./validate-catalog.mjs";
113
115
  import { runLightStep, runLightTests, lightBuildPrompt, upgradeNote, renderLiteReceipt } from "./lightlane.mjs";
114
116
 
115
117
  /**
@@ -130,8 +132,16 @@ export const RECOVER_HOW = Object.freeze({
130
132
  [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",
131
133
  [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",
132
134
  [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",
135
+ [OUTCOME_CODES.CONFORMANCE_REGRESSION]: "an earlier run's review found a regression (a compile, type or test failure the diff introduced, e.g. a removed symbol still referenced) that stayed after the builder resume rounds; the branch holds its work. Re-plan from the frozen contract: fix each named failure in the code and re-run the validate commands",
136
+ [OUTCOME_CODES.CONFORMANCE_SCOPE_CREEP]: "an earlier run changed files no deliverable names after the builder resume rounds; the branch holds its work. Re-plan from the frozen contract: revert each unnamed file or add it as an `add-deliverable` amendment with a why",
133
137
  [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",
134
138
  });
139
+ /** #5644: review/conformance findings a builder can fix itself (code, test, deferral or scope gaps); an empty set is not fixable. */
140
+ const BUILDER_FIXABLE = [OUTCOME_CODES.CONFORMANCE_REGRESSION, OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, OUTCOME_CODES.CONFORMANCE_OMISSION, OUTCOME_CODES.CONFORMANCE_UNJUSTIFIED_DEFERRAL, OUTCOME_CODES.CONFORMANCE_UNTRACKED_DEFERRAL, OUTCOME_CODES.CONFORMANCE_SCOPE_CREEP, OUTCOME_CODES.CONFORMANCE_PRESERVE_VIOLATED];
141
+ export function builderFixable(failures) {
142
+ const list = Array.isArray(failures) ? failures : [];
143
+ return list.length > 0 && list.every((f) => BUILDER_FIXABLE.includes(f?.code));
144
+ }
135
145
  /** #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). */
136
146
  const AUTH_RETRY_SECONDS = 900;
137
147
  /** #4323/#4334: precheck failure codes that are environment errors (state "environment"), never a builder resume. */
@@ -286,7 +296,7 @@ const defaultCredExec = (args) => {
286
296
  export async function runCore(o) {
287
297
  const armed = applyArmOverrides(o, o.issue); o = armed.options; // #5206: the arm's overrides shape the lane before any config is parsed
288
298
  const { issue, repo, lane: requestedLane = null, laneOverride = false, branches = {}, cwd, dir, io, builderModel = null, reviewerModel = DEFAULT_REVIEWER_MODEL, fixModel = null,
289
- toolchainOverride = null, testRunners = null, coupledFiles = null, validateRecipes = null, routeReachability = null, docsConfig = null, pagesConfig = null, designConfig = null, prodParity = null, envSetup = null, ciMaxMinutes = 360, conformance = "shadow", conformanceKinds = null, conformanceMutation = "off", reviewIncomplete = "needs-human", reproTest = "prefer", reproQuality = "shadow", closeParent = false, mergeWait = "required", maxSessionLimitPauses = DEFAULT_MAX_SESSION_LIMIT_PAUSES, cliIdleMinutes = 15, cliMaxMinutes = 180, cliBusyMinutes = 45, contextCeilingTokens = 120000, contextCeilingBySize = null, turnBudgets = null, laneLimits = null, maxMergeRetries = 5, contractMaxCorrections = 3, sessionLimitMaxWaitMs = DEFAULT_SESSION_LIMIT_WAIT_MS, contextWaitSeconds = 5, onProgress = () => {}, emitTelemetry = null, random = Math.random } = o;
299
+ toolchainOverride = null, testRunners = null, coupledFiles = null, validateRecipes = null, validateRegenerate = null, validateCatalogSources = null, routeReachability = null, docsConfig = null, pagesConfig = null, designConfig = null, prodParity = null, envSetup = null, ciMaxMinutes = 360, conformance = "shadow", conformanceKinds = null, conformanceMutation = "off", reviewIncomplete = "needs-human", reproTest = "prefer", reproQuality = "shadow", closeParent = false, mergeWait = "required", maxSessionLimitPauses = DEFAULT_MAX_SESSION_LIMIT_PAUSES, cliIdleMinutes = 15, cliMaxMinutes = 180, cliBusyMinutes = 45, contextCeilingTokens = 120000, contextCeilingBySize = null, turnBudgets = null, laneLimits = null, maxMergeRetries = 5, contractMaxCorrections = 3, reviewMaxResumes = 3, sessionLimitMaxWaitMs = DEFAULT_SESSION_LIMIT_WAIT_MS, contextWaitSeconds = 5, onProgress = () => {}, emitTelemetry = null, random = Math.random } = o;
290
300
  const now = io.now ?? (() => Date.now());
291
301
  const rotator = io.rotator !== undefined ? io.rotator : openRotator({ kind: o.accountRotator }); // #5094
292
302
  // #5205: a rotator with pick() relaunches a limited phase pinned to another account; lane-level rotations and limited accounts
@@ -356,7 +366,8 @@ export async function runCore(o) {
356
366
  if (phase === "implement") { builderTriggers.push({ trigger, restart_of: restartOf }); impl.cost += c.delta ?? 0; if (r?.model && r.model !== "default") impl.models.add(r.model); tb.note(num(r?.turns), stage === "implement"); }
357
367
  ev(rec); await emit(rec);
358
368
  modelMs += rec.duration_ms; // #4451: model time next to the lane's wall time
359
- phaseLedger.addModel(phase === "review" ? "review" : stage === "plan" ? "plan" : "implement", rec.duration_ms, c.delta);
369
+ const ledgerNow = phaseLedger.current(); // #5649: model time of contract and fix calls lands in those phases
370
+ phaseLedger.addModel(phase === "review" ? "review" : ledgerNow === "contract" || ledgerNow === "fix" ? ledgerNow : stage === "plan" ? "plan" : "implement", rec.duration_ms, c.delta);
360
371
  const u = r?.usage ?? {};
361
372
  usage.cost_usd += c.delta ?? 0;
362
373
  usage.input += u.input_tokens ?? 0; usage.output += u.output_tokens ?? 0;
@@ -389,7 +400,7 @@ export async function runCore(o) {
389
400
  const myHost = o.hostName ?? osHostname();
390
401
  // #4920: unique per lane. A sandbox's pid is 1, so `core_<pid>` made every remote lane the same holder and the lease never refused one.
391
402
  const agentId = o.agentId ?? `core_${sanitizeLeaseHost(myHost)}_${o.pid ?? process.pid}_${randomBytes(3).toString("hex")}`;
392
- const leaseObj = () => ({ by: agentId, until: now() + leaseTtlMs, host: myHost, pid: o.pid ?? process.pid });
403
+ const leaseObj = () => ({ by: agentId, until: now() + leaseTtlMs, host: myHost, pid: o.pid ?? process.pid, ...(o.batchId ? { batch: o.batchId } : {}) }); // #5654: the batch id lets its own requeue tell this lease from a foreign one
393
404
  /** Provably dead: same host and `kill(pid, 0)` throws ESRCH. A different host keeps the TTL behaviour. */
394
405
  const holderDead = (l) => {
395
406
  const parsed = parseLeaseHolder(l?.by);
@@ -447,6 +458,43 @@ export async function runCore(o) {
447
458
  let recoverUnlabelled = false; // #4297: the recovery lane removed needs-human; a final ci-pending (or needsHuman()) puts it back
448
459
  const runId = `${issue}-${t0}`;
449
460
  let runTmp = null, sandboxEnv = {}, sandboxDown = null; // #5450: test sandboxes of this lane (testsandbox.mjs)
461
+ /** #5557: after the plan call, derive the classification record from Affected Files + the base-ref unit map, post FORGE:CLASSIFY and namespaced labels. Fail-open; a no-op without `.forge/release.yaml`. */
462
+ async function classifyStage(correct) {
463
+ try {
464
+ const { parsePolicy, validatePolicy, POLICY_PATH } = await import("./release-config.mjs");
465
+ const C = await import("./release-classify.mjs");
466
+ let text; try { text = String(await git(["show", `${base}:${POLICY_PATH}`])); } catch { return; }
467
+ const { policy } = parsePolicy(text);
468
+ if (!policy || validatePolicy(policy).length) return;
469
+ const md = await io.fs.read(`${wt}/${INVESTIGATION_FILE}`).catch(() => "");
470
+ const { affectedFilesOf } = await import("./fastforward.mjs");
471
+ const files = affectedFilesOf(md);
472
+ const texts = {};
473
+ for (const f of files.filter((x) => /migrations\//.test(x))) texts[f] = String(await io.fs.read(`${wt}/${f}`).catch(() => ""));
474
+ const facts = C.deriveFacts(policy, files, { texts });
475
+ let llm = null; try { llm = JSON.parse(await io.fs.read(`${wt}/${C.CLASSIFICATION_FILE}`)); } catch { /* text-only below */ }
476
+ let problems = llm ? C.validateClassification(llm) : ["classification.json missing or unreadable"];
477
+ if (problems.length && correct) { // one correction, as for the contract; a second failure falls back to text-only
478
+ await correct(problems);
479
+ try { llm = JSON.parse(await io.fs.read(`${wt}/${C.CLASSIFICATION_FILE}`)); problems = C.validateClassification(llm); } catch { llm = null; problems = ["classification.json missing or unreadable"]; }
480
+ }
481
+ if (problems.length) { ev({ event: "CLASSIFY_INVALID", problems }); llm = { type: "chore", severity: "P3", exists_in: "unknown", confidence: 0.3 }; }
482
+ const live = policy.branches?.release;
483
+ let liveSha = null; if (live) liveSha = String(await git(["rev-parse", `origin/${live}`]).catch(() => "")).trim() || null;
484
+ let rec = C.buildClassifyRecord(llm, policy, facts, { text: problems.length > 0 });
485
+ const run = async (command, sha) => { // repro on a detached checkout of the live sha under the run TMPDIR (#5557)
486
+ const dir = `${runTmp ?? process.env.TMPDIR ?? "/tmp"}/classify-live-${issue}`;
487
+ await git(["worktree", "add", "--detach", dir, sha]);
488
+ try { const x = await io.runCommand({ command, cwd: dir, timeoutMs: 120000, env: laneEnv() }); const r = x?.r ?? x; const c = r?.rc ?? r?.exit; return typeof c === "number" ? c : 1; /* runCommand reports rc */ }
489
+ finally { await git(["worktree", "remove", "--force", dir]).catch(() => {}); }
490
+ };
491
+ rec = await C.verifyExistsIn(rec, { git: (a) => git(a), liveSha, run: io.runCommand ? run : undefined });
492
+ if (rec.exists_in === "unknown" && rec.lane_hint === "none") rec.lane_hint = "release";
493
+ await io.fs.write?.(`${wt}/${C.CLASSIFICATION_FILE}`, JSON.stringify(rec, null, 1));
494
+ await post("FORGE:CLASSIFY", C.renderClassify(rec));
495
+ for (const l of C.labelsOf(rec)) { try { await ghc(["issue", "edit", String(issue), "-R", repo, "--add-label", l]); } catch { /* label may not exist */ } }
496
+ } catch (e) { ev({ event: "CLASSIFY_FAILED", error: String(e?.message ?? e).slice(0, 200) }); }
497
+ }
450
498
  let sparse = null; // #4221: {excluded, maxKb} when the lane worktree is a sparse checkout; null leaves prompts unchanged
451
499
  // #4395: lane profile. full (FORGEDOCK_FULL_SESSION=1): unchanged sessions; memory-off: no auto-memory; lane: also no CLAUDE.md, the lane file appended
452
500
  let laneProfile = { name: process.env.FORGEDOCK_FULL_SESSION === "1" ? "full" : "memory-off", text: null };
@@ -600,6 +648,7 @@ export async function runCore(o) {
600
648
  const wf = ["investigating", "building", "in-review"].map((x) => `workflow:${x}`).join(",");
601
649
  try { await ghc(["issue", "edit", String(issue), "-R", repo, "--remove-label", wf]); } catch { /* best effort */ }
602
650
  }
651
+ if (recover) { try { await ghc(["issue", "edit", String(issue), "-R", repo, "--remove-label", "workflow:recovering"]); } catch { /* best effort (#5647): the batch re-marks a requeued attempt */ } }
603
652
  if (["merged", "invalid", "needs-human", "budget-exceeded"].includes(reason)) {
604
653
  if (reason === "budget-exceeded") T.close = ["left open", "recoverable budget.exceeded"]; // #4505: not a human escalation
605
654
  else if (reason === "merged") T.close = [extra.keptOpen ? "left open (follow-up pending)" : extra.close === "partial" ? "issue closed (partial)" : "issue closed (completed)", "label workflow:merged"]; // #5159
@@ -1999,7 +2048,8 @@ export async function runCore(o) {
1999
2048
  * #4363: one fix round. Mechanical failures (and a conformance/review FAIL citing file:line) run in a fresh session on
2000
2049
  * the fix model with a narrow prompt; one resume of the build session follows when it made no commit. Else: a resume.
2001
2050
  */
2002
- async function fixRound(kind, task, failures, trigger, failureText = "", narrow = null) { // #5348: `narrow` {files} = the minimal profile (no diff, no lane text)
2051
+ function fixRound(...a) { return phaseLedger.during("fix", () => fixRoundRaw(...a)); } // #5649: fix rounds are their own ledger phase
2052
+ async function fixRoundRaw(kind, task, failures, trigger, failureText = "", narrow = null) { // #5348: `narrow` {files} = the minimal profile (no diff, no lane text)
2003
2053
  await notePitfall(trigger, failureText); await escalateOn(trigger); // #4375: learned once the same gate passes; #4394
2004
2054
  if (!freshFix(kind, failures)) return await builder(++attemptN, task, sessionId ?? null, false, undefined, { mode: "resume", trigger });
2005
2055
  const before = String(await git(["rev-parse", "HEAD"])).trim();
@@ -2133,7 +2183,8 @@ export async function runCore(o) {
2133
2183
  { const f = await gateSetup(); if (f) return f; } // #5434: the light build is an implement-class session
2134
2184
  liveKeys = ["implementation"]; stage = "implement"; phaseLedger.enter("implement");
2135
2185
  tb.setSize(recoverySize(laneSize({ labels: (iss?.labels ?? []).map((l) => l?.name ?? l) }), recover)); // #4505
2136
- 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() }),
2186
+ const lightBase = pagesConfig ? String(await git(["ls-tree", "-r", "-z", "--name-only", base]).catch(() => "")).split("\0").filter(Boolean) : null; // #5648: pages already on the base are modified, not new
2187
+ 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, baseFiles: lightBase, testPlan: reproOn() }),
2137
2188
  build: () => builder(++attemptN, (ffGo ? FF_BUILD_LEAD : "") + lightBuildPrompt(issue, tcOpts()) + hotspotBuildRule(hotFacts) + enumeratingBuildRule(enumList) + invariantsBuildRule(vcfg.invariants), ffGo ? sessionId : null, true, undefined, { trigger: "build" }),
2138
2189
  readResult, checkpoint: () => checkpoint("light build"), changedFiles, reproOf, numstat: () => git(["diff", "--numstat", `${base}...HEAD`]),
2139
2190
  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
@@ -2168,7 +2219,7 @@ export async function runCore(o) {
2168
2219
  }
2169
2220
  }
2170
2221
  if (!frozen) {
2171
- if (ffPlan === "contract") await builder(++attemptN, contractStepPrompt(issue, tcOpts()) + recoverNote() + decisionsNote, sessionId, true, planPrompt, { mode: "resume", trigger: "plan" }); // #5426: same session, investigation already written
2222
+ if (ffPlan === "contract") await phaseLedger.during("contract", () => builder(++attemptN, contractStepPrompt(issue, tcOpts()) + recoverNote() + decisionsNote, sessionId, true, planPrompt, { mode: "resume", trigger: "plan" })); // #5426: same session, investigation already written
2172
2223
  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" }); }
2173
2224
  planned = true;
2174
2225
  result = await readResult();
@@ -2215,10 +2266,24 @@ export async function runCore(o) {
2215
2266
  return sq.contract;
2216
2267
  };
2217
2268
  contract = snapContract(contract);
2269
+ await classifyStage(sessionId ? (problems) => builder(++attemptN, `${contractCorrectionPrompt(problems)}\nThis concerns .forge-lean/classification.json: fix only the invalid fields.`, sessionId, false, planPrompt, { trigger: "contract_correction" }) : null);
2218
2270
  const wtRead = (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } }; // #5585: noindex pages are not public
2271
+ const freezeBase = pagesConfig ? String(await git(["ls-tree", "-r", "-z", "--name-only", base]).catch(() => "")).split("\0").filter(Boolean) : null; // #5648
2219
2272
  const freezeCheckIds = await (async () => { try { return new Set(Object.keys(await checksAt(git, [base], wt))); } catch { return null; } })(); // first-pass: the base's registered post-deploy check ids
2220
- let vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, testPlan: reproOn(), readFile: wtRead, checkIds: freezeCheckIds });
2221
- const missed = await preflightValidates(contract); // #4328: validate commands the host cannot run share the one correction
2273
+ let vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, baseFiles: freezeBase, testPlan: reproOn(), readFile: wtRead, checkIds: freezeCheckIds });
2274
+ const found0 = await preflightValidates(contract); // #4328: validate commands the host cannot run share the one correction
2275
+ let missed = found0;
2276
+ // #5653: an unrunnable command is rewritten from the repo catalogue (forge.yaml recipes first, then CI-derived) before any builder correction
2277
+ if (found0.length) {
2278
+ const texts = (validateCatalogSources ?? DEFAULT_CATALOG_SOURCES).map(wtRead);
2279
+ const rw = rewriteMissed(contract, mergeRecipes(validateRecipes, deriveCatalog(texts)), found0.flatMap((m) => m.ids ?? []), applyValidateRecipes);
2280
+ if (rw.applied.length) {
2281
+ contract = snapContract(rw.contract);
2282
+ for (const x of rw.applied) T.decisions.push(`validate catalogue rewrote unrunnable ${x.id}: \`${x.from}\` -> \`${x.to}\``);
2283
+ vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, baseFiles: freezeBase, testPlan: reproOn(), readFile: wtRead, checkIds: freezeCheckIds });
2284
+ missed = await preflightValidates(contract);
2285
+ }
2286
+ }
2222
2287
  let misses = missed;
2223
2288
  const correctContract = async (problems, note) => {
2224
2289
  T.decisions.push(`Contract rejected (${problems[0]}); ${note}`);
@@ -2227,7 +2292,7 @@ export async function runCore(o) {
2227
2292
  await persistGenChecks();
2228
2293
  await refreshIssue("contract validation");
2229
2294
  contract = snapContract(contract);
2230
- vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, testPlan: reproOn(), readFile: wtRead, checkIds: freezeCheckIds });
2295
+ vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, baseFiles: freezeBase, testPlan: reproOn(), readFile: wtRead, checkIds: freezeCheckIds });
2231
2296
  };
2232
2297
  if ((!vc.ok || missed.length || testRunnerProblems(contract, testRunners).length) && sessionId) {
2233
2298
  await correctContract([...vc.problems, ...preflightProblems(missed), ...testRunnerProblems(contract, testRunners)], "resumed once");
@@ -2244,8 +2309,8 @@ export async function runCore(o) {
2244
2309
  }
2245
2310
  if (!vc.ok) ev({ event: "CONTRACT_INVALID_RULES", rules: contractRuleCounts(vc.problems) }), await emit({ event: "CONTRACT_INVALID_RULES", rules: contractRuleCounts(vc.problems) }); // #5587: per-rule counts for the batch false-park rate
2246
2311
  planMisses = misses;
2247
- if (missed.length) {
2248
- ev({ event: "VALIDATE_PREFLIGHT", misses: misses.map((m) => ({ ids: m.ids, tool: m.tool, kind: m.kind, source: m.source })), found: missed.map((m) => ({ ids: m.ids, tool: m.tool, kind: m.kind, source: m.source })), corrected: misses.length === 0 });
2312
+ if (found0.length) {
2313
+ ev({ event: "VALIDATE_PREFLIGHT", misses: misses.map((m) => ({ ids: m.ids, tool: m.tool, kind: m.kind, source: m.source })), found: found0.map((m) => ({ ids: m.ids, tool: m.tool, kind: m.kind, source: m.source })), corrected: misses.length === 0 });
2249
2314
  if (misses.length) {
2250
2315
  T.anomalies.push(`Validate preflight: the host lacks ${misses.map((m) => m.tool).join(", ")} after the contract correction (advisory; a failed rerun ends env.tool_missing)`);
2251
2316
  T.decisions.push(`Validate preflight left ${misses.length} miss(es) after one correction; contract frozen anyway`);
@@ -2270,7 +2335,8 @@ export async function runCore(o) {
2270
2335
  }
2271
2336
  const dgFiles = (frozen?.deliverables ?? []).map((d) => d?.path).filter(Boolean);
2272
2337
  const designComments = (iss?.comments ?? []).filter(isTrustedIssueComment);
2273
- const designRoute = designGate({ files: dgFiles, cfg: designConfig, comments: designComments, labels: iss?.labels }); // #5330: opt-in (forge.yaml design.routes): a page without a FORGE:DESIGN_SPEC goes to /design
2338
+ const dgBase = dgFiles.length && designConfig ? String(await git(["ls-tree", "--name-only", base, "--", ...dgFiles]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean) : []; // #5648: deliverables already on the base are modified pages
2339
+ const designRoute = designGate({ files: dgFiles, cfg: designConfig, comments: designComments, labels: iss?.labels, baseFiles: dgBase }); // #5330: opt-in (forge.yaml design.routes): a page without a FORGE:DESIGN_SPEC goes to /design
2274
2340
  if (designRoute.route) {
2275
2341
  ev({ event: "DESIGN_ROUTED", pages: designRoute.pages, blocked: designRoute.blocked });
2276
2342
  T.decisions.push(`Design gate: ${designRoute.reason}${designRoute.blocked ? " (design.gate: blocking, lane stopped)" : " (advisory)"}`);
@@ -2313,6 +2379,17 @@ export async function runCore(o) {
2313
2379
  ev({ event: "REMOTE_PROVISIONED", remaining: tm.tools });
2314
2380
  } catch { /* keep the original miss */ }
2315
2381
  }
2382
+ if (tm.tools.length) { // #5652: a recipe-backed tool is installed in this sandbox and re-probed before any host re-placement
2383
+ const withRecipe = tm.tools.filter(hasRecipe), noRecipe = tm.tools.filter((t) => !hasRecipe(t));
2384
+ if (withRecipe.length && io.runCommand) {
2385
+ const ins = await installLaneTools(withRecipe, { run: (a) => io.runCommand({ command: a.command, cwd: wt, timeoutMs: a.timeoutMs, env: laneEnv() }), root: process.getuid?.() === 0 });
2386
+ ev({ event: "REMOTE_TOOLS_INSTALLED", tools: withRecipe, ok: ins.ok });
2387
+ if (!ins.ok) return await needsHuman(`Installing ${ins.tool} in the remote sandbox failed (execution.lane_tools recipe); not re-placed on the host. Install stderr tail:\n${ins.stderrTail}`, OUTCOME_CODES.ENV_TOOL_MISSING);
2388
+ tm = toolMisses(await preflightValidates(frozen).catch(() => []));
2389
+ ev({ event: "REMOTE_PROVISIONED", remaining: tm.tools });
2390
+ }
2391
+ if (noRecipe.length && tm.tools.some((t) => noRecipe.includes(t))) return await needsHuman(`Remote sandbox lacks ${noRecipe.join(", ")}, and no lane_tools recipe exists for ${noRecipe.length > 1 ? "them" : "it"}. Add it to \`execution.lane_tools\` in forge.yaml once a recipe exists, or add a recipe for ${noRecipe.join(", ")} in bin/pool/lane-tools.mjs (RECIPES).`, OUTCOME_CODES.ENV_TOOL_MISSING);
2392
+ }
2316
2393
  if (tm.tools.length) {
2317
2394
  ev({ event: "REMOTE_TOOL_MISSING", tools: tm.tools, ids: tm.ids });
2318
2395
  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);
@@ -2820,7 +2897,7 @@ export async function runCore(o) {
2820
2897
  const kindsNow = () => (riskEnforced ? null : kinds);
2821
2898
  const recording = () => shadow || (!riskEnforced && Object.keys(kinds).length > 0); // the gate records what it would have blocked
2822
2899
  const blockingOf = (fs, allow) => blockingFailures(fs, { shadow, kinds: kindsNow(), allow });
2823
- let effective = frozen, review = null, lastAmend = "", resumes = 0, verdict = null, degraded = null, triggerSkipped = false, selfReviewCompared = false;
2900
+ let effective = frozen, review = null, lastAmend = "", resumes = 0, lastFailKey = null, verdict = null, degraded = null, triggerSkipped = false, selfReviewCompared = false;
2824
2901
  const TRIGGER_SKIP = "skipped (review.trigger enforce: no risk trigger)";
2825
2902
  const triggerSkipNote = "## Conformance Review\n**Skipped by `review.trigger: enforce`:** no risk path, package edge or hotspot in the diff, and every deterministic gate passed; no reviewer ran (#4273).";
2826
2903
  let pendingDecisions = [], firstRounds = null, firstReply = null;
@@ -2956,6 +3033,27 @@ export async function runCore(o) {
2956
3033
  const note = `Validate ${v.id} hit a runner usage error; reran normalised (\`${fixed}\`): exit ${x?.rc}`;
2957
3034
  if (!T.decisions.includes(note)) T.decisions.push(note);
2958
3035
  }
3036
+ // #5653: a stale generated artifact (base drift) is mechanical: base-sync (a clean merge of the lane tip), then the repo's configured regenerate command, then one rerun
3037
+ if (x && x.rc !== 0 && x.rc !== 124 && isDriftFailure(x.output)) {
3038
+ try {
3039
+ const rerunV = async () => await heavyStep("precheck", async () => (await runWithTimeoutRetry((timeoutMs) => io.runCommand({ command: forgedockResolved(v.command), cwd: wt, timeoutMs, env }), vcfg.precheckTimeoutSeconds * 1000)).r);
3040
+ let note = "";
3041
+ if (Number(String(await git(["rev-list", "--count", `HEAD..${base}`]).catch(() => "0")).trim()) > 0) {
3042
+ try { await git(["merge", "--no-edit", base]); note = `base-synced onto ${base}`; } catch { await git(["merge", "--abort"]).catch(() => {}); }
3043
+ if (note) { const again = await rerunV(); if (again?.rc === 0) { x = again; T.decisions.push(`Validate ${v.id} failed on a stale generated artifact; ${note} and the rerun passed (base drift, not a conformance failure)`); } }
3044
+ }
3045
+ if (validateRegenerate && x.rc !== 0) {
3046
+ const status = async () => String(await git(["status", "--porcelain"]).catch(() => "")).split("\n").filter(Boolean);
3047
+ const before = new Set(await status());
3048
+ await heavyStep("precheck", () => io.runCommand({ command: forgedockResolved(validateRegenerate), cwd: wt, timeoutMs: vcfg.precheckTimeoutSeconds * 1000, env }));
3049
+ const added = (await status()).filter((l) => !before.has(l)); // regeneration must leave nothing new to commit: the lane's diff stays its own
3050
+ if (!added.length) {
3051
+ const again = await rerunV();
3052
+ if (again?.rc === 0) { x = again; T.decisions.push(`Validate ${v.id} failed on a stale generated artifact; ${note ? `${note}, ` : ""}\`${validateRegenerate}\` then a rerun passed (base drift, not a conformance failure)`); }
3053
+ } else for (const l of added.filter((l) => /^ M /.test(l))) await git(["checkout", "--", l.slice(3)]).catch(() => {}); // undo only the files regeneration modified
3054
+ }
3055
+ } catch { /* fail-open: the original failure stands */ }
3056
+ }
2959
3057
  out[v.id] = { rc: Number.isInteger(x?.rc) ? x.rc : 1, output: String(x?.output ?? "") };
2960
3058
  }
2961
3059
  if (Object.keys(out).length) ev({ event: "VALIDATE_RERUN", runs: Object.entries(out).map(([id, x]) => ({ id, rc: x.rc })) });
@@ -2971,6 +3069,11 @@ export async function runCore(o) {
2971
3069
  let x;
2972
3070
  try { x = await heavyStep("precheck", async () => (await runWithTimeoutRetry((timeoutMs) => io.runCommand({ command: forgedockResolved(v.substituted.from), cwd: wt, timeoutMs, env }), vcfg.precheckTimeoutSeconds * 1000)).r); } catch (e) { x = { rc: 127, output: String(e?.message ?? e) }; }
2973
3071
  out[v.id] = { rc: Number.isInteger(x?.rc) ? x.rc : 1, output: String(x?.output ?? "") };
3072
+ // #5653: the substitute runs too, so conformance can judge "same test ids, same result" (equivalentRuns)
3073
+ if (out[v.id].rc !== 0 && out[v.id].rc !== 124) {
3074
+ let y; try { y = await heavyStep("precheck", async () => (await runWithTimeoutRetry((timeoutMs) => io.runCommand({ command: forgedockResolved(v.command), cwd: wt, timeoutMs, env }), vcfg.precheckTimeoutSeconds * 1000)).r); } catch { y = null; }
3075
+ if (y) out[v.id].sub = { rc: Number.isInteger(y.rc) ? y.rc : 1, output: String(y.output ?? "") };
3076
+ }
2974
3077
  }
2975
3078
  if (Object.keys(out).length) ev({ event: "SUBSTITUTE_RERUN", runs: Object.entries(out).map(([id, x]) => ({ id, rc: x.rc })) });
2976
3079
  return out;
@@ -3070,9 +3173,10 @@ export async function runCore(o) {
3070
3173
  // #5419: forge.yaml docs: user-facing surfaces need docs, and added /docs links must resolve; unset = no check
3071
3174
  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 }) : [];
3072
3175
  // #5428: forge.yaml pages: a public page needs design, SEO and GEO briefs and passes the deterministic page checks; unset = no check
3073
- 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 }) : [];
3176
+ const addedNow = String(await git(["diff", "--name-only", "--diff-filter=A", `${base}...HEAD`]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean); // #5648: new vs modified pages
3177
+ const pageFail = pagesConfig ? await pageFailures({ cfg: pagesConfig, files, result, added: addedNow, diff: String(await git(["diff", "-U0", `${base}...HEAD`]).catch(() => "")), tracked: String(await git(["ls-files"]).catch(() => "")).split("\n").filter(Boolean), readFile: (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } }, designApproved: designLabelApproved(iss?.labels) || designSpecApproved((iss?.comments ?? []).filter(isTrustedIssueComment)), run: io.runCommand ? async ({ command }) => (await io.runCommand({ command, cwd: wt, timeoutMs: vcfg.precheckTimeoutSeconds * 1000, env: laneEnv() }).then((x) => x?.r ?? x)) ?? { rc: 127 } : null }) : [];
3074
3178
  // #5330: forge.yaml design.routes (opt-in, blocking only): a user-visible page needs an approved spec and passes the deterministic visual critique
3075
- const designFail = designFailures({ cfg: designConfig, files, specs: designSpecOk({ comments: (iss?.comments ?? []).filter(isTrustedIssueComment), labels: iss?.labels, cfg: designConfig }), readFile: (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } } });
3179
+ const designFail = designFailures({ cfg: designConfig, files, added: addedNow, diff: String(await git(["diff", "-U0", `${base}...HEAD`]).catch(() => "")), specs: designSpecOk({ comments: (iss?.comments ?? []).filter(isTrustedIssueComment), labels: iss?.labels, cfg: designConfig }), readFile: (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } } });
3076
3180
  // #5284: forge.yaml topology.prod_parity: declared production-only surfaces this diff touches need a check result or a justification
3077
3181
  const parityRules = parseProdParity(prodParity);
3078
3182
  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 } }) : [];
@@ -3296,9 +3400,11 @@ export async function runCore(o) {
3296
3400
  }
3297
3401
  if (outcome.state === "review.incomplete") return await needsHuman(`The conformance review was incomplete twice (a review without complete rows cannot pass); nothing merged:\n${list}`, OUTCOME_CODES.REVIEW_INCOMPLETE);
3298
3402
  if (outcome.state === "review.inconsistent") return await needsHuman(`The conformance reviewer twice said NONCONFORMING without a failing row; nothing merged.`, OUTCOME_CODES.REVIEW_INCONSISTENT);
3299
- if (resumes >= 1 || !sessionId) return await needsHuman(`The change does not conform to the issue and its frozen contract after ${resumes ? "one builder resume" : "the build (no session to resume)"} (${outcome.by}); nothing merged:\n${list}`, outcome.failures[0].code);
3403
+ let failKey = JSON.stringify((outcome.failures ?? []).map((f) => `${f.code}|${f.detail}`).sort()); // #5644: a round that leaves the failure set unchanged ends the rounds
3404
+ if (!sessionId || resumes >= (builderFixable(outcome.failures) ? reviewMaxResumes : 1) || failKey === lastFailKey) return await needsHuman(`The change does not conform to the issue and its frozen contract after ${resumes ? (resumes === 1 ? "one builder resume" : `${resumes} builder resumes`) : "the build (no session to resume)"} (${outcome.by}); nothing merged:\n${list}`, outcome.failures?.[0]?.code);
3405
+ lastFailKey = failKey;
3300
3406
  resumes++;
3301
- T.decisions.push(`Not conforming (${outcome.by}${outcome.inconsistent ? ", reviewer verdict contradicted its rows" : ""}): ${[...new Set(outcome.failures.map((f) => f.code))].join(", ")} (${explained.slice(0, 5).map((f) => String(f.detail).slice(0, 160)).join("; ")}); builder resumed once`);
3407
+ T.decisions.push(`Not conforming (${outcome.by}${outcome.inconsistent ? ", reviewer verdict contradicted its rows" : ""}): ${[...new Set(outcome.failures.map((f) => f.code))].join(", ")} (${explained.slice(0, 5).map((f) => String(f.detail).slice(0, 160)).join("; ")}); builder resumed (round ${resumes} of ${reviewMaxResumes})`);
3302
3408
  // A failed validate may only mean the base moved on: fetch the lane so the resume can merge it (never rebase).
3303
3409
  if (outcome.failures.some((f) => f?.kind === "validate_failed")) { try { await io.git(["fetch", "origin", lane], { cwd: wt }); } catch { /* offline: the resume uses the local ref */ } }
3304
3410
  await fixRound("conformance", conformanceResumePrompt(outcome.failures, vcfg.mode, lane), outcome.failures, "conformance", failureLog(outcome.failures));
@@ -11,7 +11,7 @@ import { normaliseDecision, writeDecisionIndex } from "./decisions.mjs"; // #533
11
11
  import { execFileSync } from "node:child_process";
12
12
  import { writeFileSync, existsSync, readFileSync, mkdirSync, symlinkSync, readdirSync, chmodSync } from "node:fs";
13
13
  import { join } from "node:path";
14
- import { runCore, contractHash, isProtectedLaneBranch, classifyBlock } from "./lean.mjs";
14
+ import { runCore, contractHash, isProtectedLaneBranch, classifyBlock, builderFixable } from "./lean.mjs";
15
15
  import { parseFactsComment, normaliseFacts, renderFactsRecord, FACTS_MARKER } from "./facts.mjs";
16
16
  import { makeLedger } from "./ledger.mjs";
17
17
  import { writeIndex } from "./guards.mjs";
@@ -375,7 +375,7 @@ describe("core work-on", () => {
375
375
  assert.equal(w.prs.length, 1);
376
376
  assert.equal(traj(w).length, 1);
377
377
  assert.match(traj(w)[0], /2 round\(s\)/);
378
- assert.match(traj(w)[0], /Not conforming \(review\): conformance\.unimplemented \(R1 partial: .*\("foo must handle a null argument without throwing\."\)\); builder resumed once/);
378
+ assert.match(traj(w)[0], /Not conforming \(review\): conformance\.unimplemented \(R1 partial: .*\("foo must handle a null argument without throwing\."\)\); builder resumed \(round 1 of 3\)/);
379
379
  assert.equal(w.comments.filter((c) => c.includes("FORGE:IMPLEMENTATION")).length, 1, "one implementation note");
380
380
  assert.equal(w.patches.length, 1, "edited in place after the resume");
381
381
  assert.match(w.patches[0].join(" "), /-X PATCH repos\/o\/r\/issues\/comments\/\d+ -f body=<!-- FORGE:IMPLEMENTATION -->/);
@@ -384,7 +384,7 @@ describe("core work-on", () => {
384
384
 
385
385
  it("nonconforming twice -> needs-human with the specific code, no PR, issue left open", async () => {
386
386
  const w = world({ reviews: [bad(), bad("still bad")] });
387
- const r = await run(w);
387
+ const r = await run(w, { reviewMaxResumes: 1 });
388
388
  assert.equal(r.terminalReason, "needs-human");
389
389
  assert.equal(r.code, "conformance.unimplemented");
390
390
  assert.equal(w.closed.length, 0);
@@ -906,6 +906,45 @@ describe("core work-on", () => {
906
906
  assert.ok(!l.edits.some((e) => e.includes("--add-label") && e.includes("needs-human")), JSON.stringify(l.edits));
907
907
  });
908
908
 
909
+ describe("#5652 in-sandbox recipe install", () => {
910
+ const remote = { placement: { where: "remote", reason: "mode remote" } };
911
+ const withTool = (tool) => ({ ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: `${tool} check x` }] });
912
+ const probing = (w, tool, installed) => { w.io.probeCommand = async (a) => ({ rc: new RegExp(tool).test(JSON.stringify(a)) && !installed() ? 127 : 0, output: "" }); };
913
+ it("a recipe-backed tool is installed in the sandbox and re-probed: the lane continues, no needs-human", async () => {
914
+ const w = world({ contract: withTool("promtool") }); let ok = false; const cmds = [];
915
+ const base = w.io.runCommand;
916
+ w.io.runCommand = async (a) => { if (/promtool/.test(a.command) && /tar -xz/.test(a.command)) { cmds.push(a.command); ok = true; return { rc: 0 }; } return base(a); };
917
+ probing(w, "promtool", () => ok);
918
+ const r = await run(w, { dir: tmpDir("lean-5652a-"), ...remote });
919
+ assert.equal(cmds.length, 1);
920
+ assert.notEqual(r.code, "env.tool_missing");
921
+ assert.notEqual(r.terminalReason, "needs-human");
922
+ });
923
+ it("a tool with no recipe ends the lane naming it, saying no recipe exists and pointing to execution.lane_tools", async () => {
924
+ const w = world({ contract: withTool("zzcheck") }); probing(w, "zzcheck", () => false);
925
+ const r = await run(w, { dir: tmpDir("lean-5652b-"), ...remote });
926
+ assert.equal(r.code, "env.tool_missing");
927
+ const txt = w.comments.map((c) => c.body ?? c).join("\n");
928
+ assert.match(txt, /lacks zzcheck, and no lane_tools recipe exists for it/);
929
+ assert.match(txt, /execution\.lane_tools/);
930
+ });
931
+ it("a failed in-sandbox install ends the lane with the stderr tail", async () => {
932
+ const w = world({ contract: withTool("promtool") }); probing(w, "promtool", () => false);
933
+ const base = w.io.runCommand;
934
+ w.io.runCommand = async (a) => (/tar -xz/.test(a.command) ? { rc: 2, stderr: "curl: (22) 404 not found" } : base(a));
935
+ const r = await run(w, { dir: tmpDir("lean-5652c-"), ...remote });
936
+ assert.equal(r.code, "env.tool_missing");
937
+ assert.match(w.comments.map((c) => c.body ?? c).join("\n"), /Installing promtool in the remote sandbox failed[\s\S]*404 not found/);
938
+ });
939
+ it("regression: a declared host capability still ends env.capability_remote without installing", async () => {
940
+ const w = world({ contract: withTool("promtool") }); let installs = 0; const base = w.io.runCommand;
941
+ w.io.runCommand = async (a) => { if (/tar -xz/.test(a.command)) installs++; return base(a); };
942
+ const r = await run(w, { dir: tmpDir("lean-5652d-"), ...remote, hostCaps: { hostCapabilities: ["promtool"] } });
943
+ assert.equal(r.code, "env.capability_remote");
944
+ assert.equal(installs, 0);
945
+ });
946
+ });
947
+
909
948
  it("#4778 a relayed host capability does not end the remote lane before building; a failed relay still recovers locally", async () => {
910
949
  const contract = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: "promtool test rules r.yml" }] };
911
950
  const remote = { placement: { where: "remote", reason: "mode remote" }, hostCaps: { hostCapabilities: ["promtool"] } };
@@ -1275,6 +1314,7 @@ describe("in-batch recovery of mechanical needs-human (#4267)", () => {
1275
1314
  const r = await run(w, { recover: { code: "ci.red", attempt: 1 } });
1276
1315
  assert.equal(r.terminalReason, "merged");
1277
1316
  assert.ok(w.edits.some((e) => e.join(" ") === "issue edit 7 -R o/r --remove-label needs-human"));
1317
+ assert.ok(w.edits.some((e) => e.join(" ") === "issue edit 7 -R o/r --remove-label workflow:recovering"), "#5647: the recovery lane's end clears workflow:recovering");
1278
1318
  const dec = w.comments.find((c) => c.startsWith("<!-- FORGE:DECISION -->"));
1279
1319
  assert.match(dec, /recovery pass for `ci\.red`/); assert.match(dec, /\*\*Why\*\*/); assert.match(dec, /\*\*Alternative\*\*/);
1280
1320
  assert.ok(builders(w).some((b) => /Recovery pass \(ci\.red\): .*--log-failed/.test(b[4])));
@@ -2178,7 +2218,7 @@ describe("hotspot prevention (forge#4195): plan facts, build rule, unexempted gr
2178
2218
  assert.equal(hotspotBuildRule(facts([], { file_lines: 1000, growth_lines: 50 })).trim(), "Don't grow a file over 1000 lines by more than 50 lines. Put new code next to it.");
2179
2219
  assert.equal(hotspotBuildRule(null), ""); assert.equal(hotspotBuildRule(facts([], { enabled: false })), "");
2180
2220
  const plan = builderPlanPrompt(7) + hotspotPlanNote(facts([HOT, { ...HOT, path: "a/b.py" }, { ...HOT, path: "c/d.py" }]));
2181
- // 1850: #4404 (verify out_of_band) and #4396 (split size rule) grew the plan prompt to ~1803 tokens on CI paths; 1900: #4589 (check timeout is not a block, one block-rule line). 2050: #4724 (deferred-row bucket rule). 1675 (hotspot case): #5284 (rubric prod_parity clause). 2375/1825: #5345 (self-check and pitfall lines).
2221
+ // 2650: #5557 (classification record line) on top of the base's growth. 1850: #4404 (verify out_of_band) and #4396 (split size rule) grew the plan prompt to ~1803 tokens on CI paths; 1900: #4589 (check timeout is not a block, one block-rule line). 2050: #4724 (deferred-row bucket rule). 1675 (hotspot case): #5284 (rubric prod_parity clause). 2375/1825: #5345 (self-check and pitfall lines).
2182
2222
  assert.ok(approxTokens(plan) <= 2650, `plan prompt with hotspots is ${approxTokens(plan)} tokens`);
2183
2223
  assert.ok(approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([]))) <= 1875, `implement prompt with the hotspot rule is ${approxTokens(builderImplementPrompt() + hotspotBuildRule(facts([])))} of 1675 tokens`); // 1600: #4591 (never hand-name migration files) and #4596 (i18n translate rule), one line each; 1650: #4726 (e2e rule)
2184
2224
  });
@@ -2597,9 +2637,30 @@ describe("comment templates", () => {
2597
2637
  assert.match(renderTrajectory({ issue: 9, validate: ["a|b", "x\ny"] }), /\| Validate \| a\\\|b \| x y \|/);
2598
2638
  });
2599
2639
 
2640
+ it("#5644 review findings get up to 3 builder resume rounds: replay of a fixable finding that clears in round 3 merges", async () => {
2641
+ const w = world({ reviews: [bad("round 1"), bad("round 2"), conf()] });
2642
+ const r = await run(w);
2643
+ assert.equal(r.terminalReason, "merged"); assert.equal(builders(w).length, 4, "build plus two resume rounds");
2644
+ });
2645
+
2646
+ it("#5644 rounds are spent: a changing but never fixed finding ends needs-human after reviewMaxResumes rounds; an unchanged one stops early", async () => {
2647
+ const w = world({ reviews: [bad("a"), bad("b"), bad("c"), bad("d")] });
2648
+ const r = await run(w);
2649
+ assert.equal(r.terminalReason, "needs-human"); assert.equal(builders(w).length, 5);
2650
+ assert.match(traj(w)[0], /after 3 builder resumes/);
2651
+ const w2 = world({ reviews: [bad("a"), bad("b"), bad("c")] });
2652
+ assert.equal((await run(w2, { reviewMaxResumes: 1 })).terminalReason, "needs-human"); assert.equal(builders(w2).length, 3);
2653
+ });
2654
+
2655
+ it("#5644 builderFixable: regression, deferral, scope are fixable; environment and empty sets are not", () => {
2656
+ assert.equal(builderFixable([{ code: "conformance.regression" }, { code: "conformance.unjustified_deferral" }, { code: "conformance.scope_creep" }]), true);
2657
+ assert.equal(builderFixable([{ code: "conformance.regression" }, { code: "env.tool_missing" }]), false);
2658
+ assert.equal(builderFixable([]), false); assert.equal(builderFixable(null), false);
2659
+ });
2660
+
2600
2661
  it("a merged run's trajectory and a needs-human run's trajectory carry the right rows", async () => {
2601
2662
  const w = world({ reviews: [bad(), bad("still bad")] });
2602
- await run(w);
2663
+ await run(w, { reviewMaxResumes: 1 });
2603
2664
  const t = traj(w)[0];
2604
2665
  assert.match(t, /\| Validate \| CONFIRMED \|/);
2605
2666
  assert.match(t, /\| Plan \| contract [0-9a-f]{12} \| 1 requirement\(s\) \|/);
@@ -4729,6 +4790,24 @@ describe("batch robustness (#4112-#4115)", () => {
4729
4790
  assert.ok(w.comments.some((c) => c.includes("FORGE:CONTRACT") && c.includes("node --test --test-reporter=dot test/foo.test.js")));
4730
4791
  });
4731
4792
 
4793
+ it("#5653 a validate command freeze preflight finds unrunnable is rewritten from the CI-derived catalogue before any builder correction", async () => {
4794
+ const d = tmpDir("lean-5653-"); const src = join(d, "ci.yml"); writeFileSync(src, "run: uv run --with-requirements r.txt pytest tests\n");
4795
+ const contract = { ...CONTRACT, validate: [...CONTRACT.validate, { id: "V2", command: "poetry run pytest t.py" }] };
4796
+ const w = world({ contract }); w.io.probeCommand = async (a) => ({ rc: /poetry/.test(JSON.stringify(a)) ? 127 : 0, output: "" });
4797
+ const r = await run(w, { dir: d, validateCatalogSources: [`../..${src}`] });
4798
+ assert.notEqual(r.code, "env.tool_missing");
4799
+ assert.ok(w.comments.some((c) => c.includes("FORGE:CONTRACT") && c.includes("uv run --with-requirements r.txt pytest t.py")));
4800
+ assert.ok(!w.comments.some((c) => c.includes("FORGE:CONTRACT") && c.includes("poetry run pytest")));
4801
+ });
4802
+
4803
+ it("#5653 the plan prompt tells the builder to prefer CI commands, record equivalent substitutes and never narrow time or production criteria", async () => {
4804
+ const { unrunnableValidateNote } = await import("./prompts.mjs");
4805
+ const n = unrunnableValidateNote();
4806
+ assert.match(n, /CI-derived command catalogue/);
4807
+ assert.match(n, /same test ids with the same result is recorded/);
4808
+ assert.match(n, /never narrow it/);
4809
+ });
4810
+
4732
4811
  // ---- #4112 ----
4733
4812
  const fakeCli = async (name, body) => {
4734
4813
  const { writeFileSync, chmodSync } = await import("node:fs");
@@ -5773,6 +5852,12 @@ describe("shared dependency cache wiring (#4220)", () => {
5773
5852
  for (const st of ["prompt_assembly", "cli_init"]) assert.ok(steps.includes(st), `${st} timed`);
5774
5853
  });
5775
5854
 
5855
+ it("#5651 launch, re-place, recovery and gate entries all install through io.deps.prepare (and so depcache's pythonFor)", () => {
5856
+ const src = readFileSync(new URL("./lean.mjs", import.meta.url), "utf8");
5857
+ assert.ok((src.match(/io\.deps\.prepare\(/g) ?? []).length >= 4);
5858
+ assert.ok(!/pythonFor/.test(src), "lean.mjs has no second interpreter-selection path");
5859
+ });
5860
+
5776
5861
  it("#5434 a failed env.setup still ends needs-human and no implement session starts", async () => {
5777
5862
  const dir = tmpDir("deps-setupfail-");
5778
5863
  const w = world(); depsIo(w);
@@ -7090,7 +7175,7 @@ describe("#4362 attempt triggers", () => {
7090
7175
  const builderSites = at(/builder\(\+\+attemptN,/), fixSites = at(/fixRound\("/), attemptSites = at(/attempt\("(?!implement)/);
7091
7176
  assert.ok(builderSites.length >= 9 && fixSites.length >= 9 && attemptSites.length >= 2, "the call sites were found");
7092
7177
  const known = (lit, l, n) => assert.ok(lit && TRIGGERS.includes(lit), `lean.mjs:${n} passes no known trigger: ${l.trim().slice(0, 120)}`);
7093
- const fixLines = at(/async function fixRound\(/)[0][1];
7178
+ const fixLines = at(/async function fixRoundRaw\(/)[0][1];
7094
7179
  for (const [l, n] of builderSites) {
7095
7180
  if (n > fixLines && n < fixLines + 10 && /trigger \}\)/.test(l)) continue; // fixRound forwards its own trigger, checked below
7096
7181
  known(/trigger: "([a-z_]+)"/.exec(l)?.[1], l, n);
@@ -8692,6 +8777,69 @@ describe("design gate routing in the lane (#5330 R11, R13, R15)", () => {
8692
8777
  });
8693
8778
  });
8694
8779
 
8780
+ describe("classification record in the plan prompt (#5557)", () => {
8781
+ it("asks only for the judgment fields and never for units or migrations", () => {
8782
+ const p = builderPlanPrompt(7);
8783
+ assert.match(p, /classification\.json/);
8784
+ assert.doesNotMatch(p.split("classification.json")[1].split("\n")[0], /units|migrations|risk/);
8785
+ });
8786
+ });
8787
+
8788
+ describe("FORGE:CLASSIFY wiring (#5557)", () => {
8789
+ const POLICY = "schema: 1\nbranches: {default: main}\nunits:\n foo: {paths: [\"src/**\"]}\n";
8790
+ const CLS = JSON.stringify({ type: "bug", severity: "P2", exists_in: "unknown", flag: "none", confidence: 0.8, units: ["LLM-LIED"] });
8791
+ const withPolicy = (w) => { const g = w.io.git; w.io.git = async (a, o) => (a[0] === "show" && /\.forge\/release\.yaml$/.test(a.at(-1)) ? POLICY : g(a, o)); };
8792
+ it("posts FORGE:CLASSIFY with code-derived units and namespaced labels when a release policy exists", async () => {
8793
+ const w = world(); withPolicy(w); const rd = w.io.fs.read; w.io.fs.read = async (p) => (p.endsWith("/classification.json") ? CLS : rd(p));
8794
+ await run(w);
8795
+ const c = w.comments.find((x) => x.includes("FORGE:CLASSIFY"));
8796
+ assert.ok(c, "FORGE:CLASSIFY posted");
8797
+ assert.match(c, /"units": \[\s*"foo"\s*\]/); assert.doesNotMatch(c, /LLM-LIED/);
8798
+ assert.ok(w.edits.some((e) => e.includes("unit:foo")) && w.edits.some((e) => e.includes("type:bug")), "namespaced labels added");
8799
+ });
8800
+ it("a live claim without verifiable evidence is downgraded and gets the lane:release label", async () => {
8801
+ const w = world(); withPolicy(w); const rd = w.io.fs.read;
8802
+ w.io.fs.read = async (p) => (p.endsWith("/classification.json") ? JSON.stringify({ type: "bug", severity: "P2", exists_in: "live", flag: "none", confidence: 0.8 }) : rd(p));
8803
+ await run(w);
8804
+ const flat = w.edits.flat().map(String).join(" ");
8805
+ assert.ok(flat.includes("lane:release"), "lane:release label issued");
8806
+ assert.ok(flat.includes("where:unknown") && !flat.includes("where:live"), "downgraded to unknown");
8807
+ });
8808
+ it("issues every label namespace incl. priority:, and an invalid record triggers the correction loop", async () => {
8809
+ const w = world(); withPolicy(w); const rd = w.io.fs.read;
8810
+ w.io.fs.read = async (p) => (p.endsWith("/classification.json") ? JSON.stringify({ type: "bug", severity: "P2", exists_in: "unknown" }) : rd(p));
8811
+ await run(w);
8812
+ const flat = w.edits.flat().map(String).join(" ");
8813
+ for (const ns of ["type:", "priority:P2", "where:", "unit:foo", "mig:", "risk:"]) assert.ok(flat.includes(ns), ns);
8814
+ const bad = world(); withPolicy(bad); const rb = bad.io.fs.read;
8815
+ bad.io.fs.read = async (p) => (p.endsWith("/classification.json") ? JSON.stringify({ type: "nope", severity: "P2", exists_in: "unknown" }) : rb(p));
8816
+ await run(bad);
8817
+ assert.ok(builders(bad).some((c) => String(c[4]).includes("concerns .forge-lean/classification.json")), "the correction resume was issued for the invalid record");
8818
+ assert.ok(!builders(w).some((c) => String(c[4]).includes("concerns .forge-lean/classification.json")), "a valid record needs no correction");
8819
+ const c = bad.comments.find((x) => x.includes("FORGE:CLASSIFY"));
8820
+ assert.ok(c && /text-only/.test(c), "a second invalid record falls back to text-only after the one correction");
8821
+ });
8822
+ it("a repro that passes (runCommand rc 0) on the live sha downgrades exists_in: live; a failing one (rc 1) keeps it", async () => {
8823
+ const LIVE = JSON.stringify({ type: "bug", severity: "P2", exists_in: "live", flag: "none", confidence: 0.8, exists_in_evidence: { cite: "src/a.js:1", repro: { command: "node r.js", red_on_live: true, green_after: null } } });
8824
+ const go = async (rc) => {
8825
+ const w = world(); const g = w.io.git, rd = w.io.fs.read;
8826
+ w.io.git = async (a, o) => (a[0] === "show" && /\.forge\/release\.yaml$/.test(a.at(-1)) ? POLICY.replace("default: main", "default: main, release: rel") : a[0] === "rev-parse" && /origin\/rel$/.test(a.at(-1)) ? "abc123\n" : a[0] === "cat-file" ? "" : a[0] === "show" && /^abc123:/.test(a.at(-1)) ? "line1\n" : a[0] === "worktree" ? "" : g(a, o));
8827
+ w.io.fs.read = async (p) => (p.endsWith("/classification.json") ? LIVE : rd(p));
8828
+ w.io.runCommand = async () => ({ rc, output: "" });
8829
+ await run(w);
8830
+ return w.comments.find((x) => x.includes("FORGE:CLASSIFY")) ?? "";
8831
+ };
8832
+ assert.match(await go(0), /"exists_in": "unknown"/);
8833
+ assert.match(await go(1), /"exists_in": "live"/);
8834
+ });
8835
+ it("is a no-op without .forge/release.yaml", async () => {
8836
+ const w = world();
8837
+ await run(w);
8838
+ assert.ok(!w.comments.some((x) => x.includes("FORGE:CLASSIFY")));
8839
+ assert.ok(!w.edits.some((e) => e.some((x) => /^(type|unit|where|mig|risk):/.test(String(x)))));
8840
+ });
8841
+ });
8842
+
8695
8843
  describe("#5592 (8) comment and label spam", () => {
8696
8844
  const BOTC = { author: { login: "rapiercraft-forgedock" }, authorAssociation: "CONTRIBUTOR" };
8697
8845
  const SEP = "<!-- FORGE:STATUS:SEP -->";
@@ -140,4 +140,37 @@ describe("--requeue of a lease-deferred pending issue (#5241)", () => {
140
140
  assert.deepEqual(runs, [9, 9]);
141
141
  assert.equal(rows.find((r) => r.issue === 9).outcome, "merged");
142
142
  });
143
+
144
+ // #5654: an interrupted or engine-error lane releases its own lease so the requeue is not deferred as lease.held
145
+ it("releases the lease of a resumed run whose lane is gone, and re-dispatches it", async () => {
146
+ let saved = { v: 1, order: [9], running: { 9: { startedAt: 1, pid: 4242 } }, results: {}, pending: [] };
147
+ const store = { load: () => saved, save: (s) => { saved = s; }, log: () => {} };
148
+ const released = [], ran = [], order = [];
149
+ await orchestrate({ issues: [9], parallel: 1, pollMs: 5, readBody: async () => "", store, adopt: async () => null,
150
+ releaseLease: async (n) => { released.push(n); order.push("release"); },
151
+ runOne: async (n) => { ran.push(n); order.push("run"); return { terminalReason: "merged", pr: 1 }; } });
152
+ assert.deepEqual(released, [9]);
153
+ assert.deepEqual(ran, [9]);
154
+ assert.equal(order[0], "release", "the lease goes before the issue is dispatched again");
155
+ });
156
+
157
+ it("releases the lease of a lane that ends in engine-error", async () => {
158
+ const released = [];
159
+ const store = { load: () => null, save: () => {}, log: () => {} };
160
+ let calls = 0;
161
+ await orchestrate({ issues: [2], parallel: 1, pollMs: 5, readBody: async () => "", store, releaseLease: async (n) => { released.push(n); },
162
+ runOne: async () => (++calls === 1 ? { terminalReason: "engine-error", detail: "boom" } : { terminalReason: "merged", pr: 2 }) });
163
+ assert.deepEqual(released, [2]);
164
+ });
165
+
166
+ it("requeues an interrupted lane at once (no backoff) after releasing its lease", async () => {
167
+ const released = [], store = { load: () => null, save: () => {}, log: () => {} };
168
+ let calls = 0;
169
+ const t0 = Date.now();
170
+ await orchestrate({ issues: [3], parallel: 1, pollMs: 5, readBody: async () => "", store, releaseLease: async (n) => { released.push(n); },
171
+ runOne: async () => (++calls === 1 ? { terminalReason: "deferred", code: "run.interrupted", detail: "SIGTERM" } : { terminalReason: "merged", pr: 3 }) });
172
+ assert.deepEqual(released, [3]);
173
+ assert.equal(calls, 2);
174
+ assert.ok(Date.now() - t0 < 10000, "re-dispatched without the 120s deferral backoff");
175
+ });
143
176
  });