forgedock 1.55.1 → 1.57.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 (133) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine/phases.mjs +4 -3
  4. package/bin/engine-cli.mjs +58 -10
  5. package/bin/forgedock.mjs +52 -3
  6. package/bin/gc.mjs +43 -6
  7. package/bin/help-text.mjs +3 -1
  8. package/bin/lean/batch-health.mjs +5 -1
  9. package/bin/lean/batch-health.test.mjs +7 -1
  10. package/bin/lean/batch.mjs +7 -2
  11. package/bin/lean/batch.test.mjs +45 -0
  12. package/bin/lean/conformance.e2e.test.mjs +3 -2
  13. package/bin/lean/conformance.mjs +88 -17
  14. package/bin/lean/conformance.test.mjs +98 -3
  15. package/bin/lean/decisions.mjs +86 -1
  16. package/bin/lean/decisions.test.mjs +21 -1
  17. package/bin/lean/depcache.mjs +124 -13
  18. package/bin/lean/depcache.test.mjs +121 -3
  19. package/bin/lean/design-gate.mjs +144 -0
  20. package/bin/lean/design-gate.test.mjs +169 -0
  21. package/bin/lean/effects-cap.test.mjs +17 -0
  22. package/bin/lean/effects.mjs +58 -13
  23. package/bin/lean/heavy.mjs +25 -8
  24. package/bin/lean/hostload.test.mjs +28 -0
  25. package/bin/lean/intake.mjs +97 -0
  26. package/bin/lean/intake.test.mjs +105 -0
  27. package/bin/lean/interfaces.mjs +181 -0
  28. package/bin/lean/interfaces.test.mjs +192 -0
  29. package/bin/lean/issuewatch-install.mjs +52 -12
  30. package/bin/lean/issuewatch-install.test.mjs +50 -0
  31. package/bin/lean/issuewatch-parity.mjs +12 -2
  32. package/bin/lean/issuewatch-parity.test.mjs +26 -0
  33. package/bin/lean/issuewatch-reconcile.mjs +29 -1
  34. package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
  35. package/bin/lean/issuewatch.mjs +34 -3
  36. package/bin/lean/issuewatch.test.mjs +49 -1
  37. package/bin/lean/lanecheck.test.mjs +15 -4
  38. package/bin/lean/lean.mjs +80 -25
  39. package/bin/lean/lean.test.mjs +149 -3
  40. package/bin/lean/orchestrate-blocked.test.mjs +18 -2
  41. package/bin/lean/orchestrate-owned.test.mjs +14 -5
  42. package/bin/lean/orchestrate.mjs +26 -4
  43. package/bin/lean/orphan-pr.mjs +125 -0
  44. package/bin/lean/orphan-pr.test.mjs +145 -0
  45. package/bin/lean/pagegate.mjs +35 -12
  46. package/bin/lean/pagegate.test.mjs +39 -1
  47. package/bin/lean/preflight.mjs +35 -1
  48. package/bin/lean/preflight.test.mjs +27 -1
  49. package/bin/lean/prompts.mjs +2 -1
  50. package/bin/lean/reap.test.mjs +39 -0
  51. package/bin/lean/recovery.test.mjs +25 -0
  52. package/bin/lean/release-config.mjs +158 -0
  53. package/bin/lean/release-config.test.mjs +109 -0
  54. package/bin/lean/release-control.mjs +148 -0
  55. package/bin/lean/release-control.test.mjs +143 -0
  56. package/bin/lean/release-fence.mjs +50 -0
  57. package/bin/lean/release-fence.test.mjs +105 -0
  58. package/bin/lean/release-flakes.mjs +139 -0
  59. package/bin/lean/release-flakes.test.mjs +116 -0
  60. package/bin/lean/release-ledger.mjs +160 -0
  61. package/bin/lean/release-ledger.test.mjs +226 -0
  62. package/bin/lean/release-minutes.mjs +92 -0
  63. package/bin/lean/release-minutes.test.mjs +99 -0
  64. package/bin/lean/release-nightly.mjs +75 -0
  65. package/bin/lean/release-nightly.test.mjs +48 -0
  66. package/bin/lean/release-postmerge.mjs +45 -21
  67. package/bin/lean/release-review.e2e.test.mjs +1 -0
  68. package/bin/lean/release-review.mjs +54 -7
  69. package/bin/lean/release-review.test.mjs +76 -7
  70. package/bin/lean/release-unitmap.mjs +35 -0
  71. package/bin/lean/release-unitmap.test.mjs +41 -0
  72. package/bin/lean/release.mjs +177 -19
  73. package/bin/lean/release.test.mjs +80 -16
  74. package/bin/lean/render.mjs +3 -1
  75. package/bin/lean/run-issue-placement.test.mjs +82 -0
  76. package/bin/lean/sandbox-remote.mjs +16 -0
  77. package/bin/lean/schedd.mjs +1 -1
  78. package/bin/lean/seam.mjs +115 -0
  79. package/bin/lean/seam.test.mjs +118 -0
  80. package/bin/lean/selftest-journey.mjs +40 -2
  81. package/bin/lean/selftest-journey.test.mjs +43 -3
  82. package/bin/lean/statuscomment.mjs +168 -0
  83. package/bin/lean/statuscomment.test.mjs +133 -0
  84. package/bin/lean/ui-quality.mjs +57 -0
  85. package/bin/lean/ui-quality.test.mjs +55 -0
  86. package/bin/lean/visual-gate.test.mjs +63 -0
  87. package/bin/pool/agent.mjs +16 -2
  88. package/bin/pool/router.mjs +5 -1
  89. package/bin/review-staging.mjs +8 -5
  90. package/bin/stats/card.mjs +117 -0
  91. package/bin/stats/card.test.mjs +109 -0
  92. package/bin/stats/conformance-outcomes.test.mjs +2 -1
  93. package/bin/stats/depth.mjs +1 -1
  94. package/bin/stats/gh-retry.test.mjs +152 -0
  95. package/bin/stats/github-source.mjs +147 -14
  96. package/bin/stats/index.mjs +35 -2
  97. package/bin/stats/stats.test.mjs +31 -3
  98. package/bin/vendor/js-yaml/LICENSE +21 -0
  99. package/bin/vendor/js-yaml/PIN.md +7 -0
  100. package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
  101. package/commands/design-render-critique-loop.md +2 -0
  102. package/commands/design.md +2 -0
  103. package/commands/incident-response.md +4 -0
  104. package/commands/issue.md +1 -1
  105. package/commands/milestone.md +1 -1
  106. package/commands/pipeline-status.md +13 -0
  107. package/commands/review-pr-agents/frontend.md +1 -0
  108. package/commands/review-pr-staging.md +5 -0
  109. package/docs/CONFIG.md +75 -1
  110. package/docs/ISSUE-WATCH.md +7 -0
  111. package/docs/OUTCOME-CODES.md +1 -0
  112. package/docs/STATS.md +10 -0
  113. package/docs/design/visual-gate.md +25 -0
  114. package/docs/eval/adversarial-bench.md +2 -2
  115. package/docs/eval/corpus/adversarial-v1.json +3 -3
  116. package/docs/site/start-a-new-project.md +7 -0
  117. package/docs/spec/forge-protocol-v1.md +31 -0
  118. package/package.json +1 -1
  119. package/pool/README.md +2 -0
  120. package/scripts/acceptance-red-green.sh +15 -1
  121. package/scripts/acceptance-red-green.test.sh +12 -0
  122. package/scripts/bench-adversarial.mjs +4 -0
  123. package/scripts/bench-lightlane.mjs +4 -1
  124. package/scripts/bootstrap-create.mjs +8 -2
  125. package/scripts/ci-local.test.sh +3 -3
  126. package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
  127. package/scripts/plan-validate-live.mjs +9 -6
  128. package/scripts/review-prepare.sh +7 -1
  129. package/scripts/review-roster.sh +5 -2
  130. package/scripts/review-roster.test.sh +9 -0
  131. package/scripts/visual-gate.mjs +64 -0
  132. package/templates/bootstrap/technical-spike.md +17 -0
  133. package/templates/contracts/seam-check.mjs +236 -0
@@ -26,7 +26,35 @@ export function classifyClaim(row) {
26
26
  return code && classifyNeedsHuman(row) !== "human" && code !== "unclassified" ? { kind: "parked", code } : { kind: "needs-human", code };
27
27
  }
28
28
  if (outcome === "" || outcome === "pending" || outcome === "running") return { kind: "running", code: null };
29
- return { kind: "stranded", code: outcome };
29
+ // #5529: a lane that could not start its CLI (unit without the lane PATH) is environmental: retried once the watcher resolves it
30
+ const why = String(row.detail ?? row.reason ?? row.error ?? "");
31
+ return MISSING_EXECUTABLE.test(why) ? { kind: "stranded", code: outcome, reason: "missing-executable" } : { kind: "stranded", code: outcome };
32
+ }
33
+
34
+ /** #5529: the lane's error text when its CLI was not on PATH ("Failed to find executable claude", spawn ENOENT, sh "not found"). */
35
+ export const MISSING_EXECUTABLE = /Failed to find executable|spawn \S+ ENOENT|command not found|claude: not found/i;
36
+ /** #5529: re-drives per stranded claim before it stays failed. */
37
+ export const REDRIVES = 2;
38
+
39
+ /**
40
+ * #5529: a stranded claim is re-driven, not only counted: `redrive(n)` (requeue into the batch, or release the claim) at most `max`
41
+ * times per issue; a `missing-executable` one only once `resolved()` says the watcher can find the CLI again. A re-driven claim's
42
+ * outcome is cleared so `claimCounts` stops counting it. @returns {number[]} the issues re-driven.
43
+ */
44
+ export function redriveStep({ state, now, resolved, redrive, max = REDRIVES }) {
45
+ state.redriven ??= {};
46
+ const out = [];
47
+ for (const [n, o] of Object.entries(state.outcomes ?? {})) {
48
+ if (o.kind !== "stranded") continue;
49
+ const r = state.redriven[n] ?? { count: 0 };
50
+ if (r.count >= max) continue;
51
+ if (o.reason === "missing-executable" && !resolved()) continue;
52
+ if (!redrive(Number(n), o)) continue;
53
+ state.redriven[n] = { count: r.count + 1, at: now, reason: o.reason ?? o.code };
54
+ delete state.outcomes[n];
55
+ out.push(Number(n));
56
+ }
57
+ return out;
30
58
  }
31
59
 
32
60
  /**
@@ -28,3 +28,24 @@ test("stuckClaims lists only old unmerged claims with the reason", () => {
28
28
  assert.deepEqual(rows.map((r) => r.issue), [1]);
29
29
  assert.match(formatStuck(rows), /#1 claimed 100h ago, no merged PR: running in its lane/);
30
30
  });
31
+
32
+ test("#5529 classifyClaim marks a lane that could not find its CLI as missing-executable; other engine-errors unchanged", () => {
33
+ const row = { outcome: "engine-error", detail: "claude CLI exited with status 1. Output: Failed to find executable claude: No such file or directory" };
34
+ assert.deepEqual(classifyClaim(row), { kind: "stranded", code: "engine-error", reason: "missing-executable" });
35
+ assert.deepEqual(classifyClaim({ outcome: "engine-error", detail: "lane pid 4 exited without a result" }), { kind: "stranded", code: "engine-error" });
36
+ });
37
+
38
+ test("#5529 redriveStep waits for claude on a missing-executable claim, re-drives others, and respects the budget", async () => {
39
+ const { redriveStep } = await import("./issuewatch-reconcile.mjs");
40
+ const state = { outcomes: { 1: { kind: "stranded", code: "engine-error", reason: "missing-executable" }, 2: { kind: "stranded", code: "engine-error" }, 3: { kind: "parked", code: "ci.red" } } };
41
+ const driven = [];
42
+ let ok = false;
43
+ assert.deepEqual(redriveStep({ state, now: 1, resolved: () => ok, redrive: (n) => (driven.push(n), true) }), [2]);
44
+ assert.equal(claimCounts({ ...state, inflight: [] }).stranded, 1);
45
+ ok = true;
46
+ assert.deepEqual(redriveStep({ state, now: 2, resolved: () => ok, redrive: (n) => (driven.push(n), true) }), [1]);
47
+ assert.equal(claimCounts({ ...state, inflight: [] }).stranded, 0);
48
+ for (let i = 0; i < 3; i++) { state.outcomes[2] = { kind: "stranded", code: "engine-error" }; redriveStep({ state, now: 3 + i, resolved: () => true, redrive: (n) => (driven.push(n), true) }); }
49
+ assert.equal(driven.filter((n) => n === 2).length, 2, "budget of 2 re-drives");
50
+ assert.equal(state.outcomes[3].kind, "parked");
51
+ });
@@ -22,12 +22,12 @@ import { releaseTick, formatDryRun } from "./issuewatch-release.mjs";
22
22
  import { releaseRoot } from "./release.mjs";
23
23
  import { loadPolicy } from "./decision-engine.mjs";
24
24
  import { decisionContext, decisionsActive, decisionStep, decisionCounts, formatDecisionDryRun, claimsUsed } from "./issuewatch-decisions.mjs";
25
- import { reconcileClaims, remediateStep, reclaimStep, claimCounts, stuckClaims, formatStuck } from "./issuewatch-reconcile.mjs";
25
+ import { reconcileClaims, remediateStep, reclaimStep, redriveStep, claimCounts, stuckClaims, formatStuck } from "./issuewatch-reconcile.mjs";
26
26
  import { APP_SLUG } from "../init-repo.mjs";
27
27
  import { noComments } from "./render.mjs";
28
28
  import { listAssociations } from "./gh-assoc.mjs";
29
29
  import { verifyMerge, verifyComment } from "./issuewatch-verify.mjs";
30
- import { DEFAULT_SKIP_LABELS, isPullRequest, searchesPullRequests, skipLabelHit, closingPrIssues, releaseInFlight, watchLiveness, alertDeadWatches } from "./issuewatch-parity.mjs";
30
+ import { DEFAULT_SKIP_LABELS, isPullRequest, searchesPullRequests, skipLabelHit, closingPrIssues, releaseInFlight, watchLiveness, alertDeadWatches, resolveOnPath } from "./issuewatch-parity.mjs";
31
31
 
32
32
  const WATCH_KEYS = ["milestone", "labels", "exclude_labels", "search", "title_regex", "since", "version", "lane", "max_issues", "max_inflight", "until", "mode", "parallel", "include_followups", "postdeploy_rollup", "threshold", "immediate", "max_release_issues", "theme_map", "tracker", "sweep_needs_human", "max_launches", "trust_app", "trust_app_labels", "skip_labels", "release_pause", "max_remediations"];
33
33
  export const TRUSTED = new Set(["OWNER", "MEMBER", "COLLABORATOR"]);
@@ -362,6 +362,16 @@ export async function tick({ watch, repo, io, state, dir, branches = {}, default
362
362
  if (watch.mode === "batch") {
363
363
  await remediateStep({ watch, repo, io, state, handles, now, settle, fail });
364
364
  await reclaimStep({ repo, io, state, trusted: (c) => TRUSTED.has(c?.authorAssociation), release: (n) => { releaseClaims(repoDir(repo, io.env), [n], watch.name); state.claimed = state.claimed.filter((x) => x !== n); delete state.lanes[n]; unsettle(state, n); } });
365
+ // #5529: stranded claims are re-driven (budgeted); a missing-executable one once this watcher, whose env its lanes inherit, finds claude
366
+ redriveStep({ state, now, resolved: () => resolveOnPath("claude", (io.env ?? process.env).PATH) !== null, redrive: (n) => {
367
+ if (state.batch) {
368
+ if (!io.batch?.requeue?.(state.batch, n, "issue-watch: re-drive stranded claim")) return false;
369
+ unsettle(state, n); if (!state.inflight.includes(n)) state.inflight.push(n);
370
+ return true;
371
+ }
372
+ releaseClaims(repoDir(repo, io.env), [n], watch.name); state.claimed = state.claimed.filter((x) => x !== n); delete state.lanes[n]; unsettle(state, n);
373
+ return true;
374
+ } });
365
375
  }
366
376
  for (const n of [...(state.pendingVerify ?? [])]) if (await closed(n)) await verify(n);
367
377
  if (watch.mode === "batch" && state.batch && io.batch.reported(state.batch)) { state.inflight.forEach(fail); state.batch = null; }
@@ -497,7 +507,8 @@ export function formatStatus(s, watch, now = Date.now()) {
497
507
  const left = watch.until ? `${Math.max(0, Math.round((Date.parse(watch.until) - now) / 60000))}m` : "forever";
498
508
  const live = s.heartbeat || s.paused || s.phase === "exited" ? watchLiveness(s, now) : null;
499
509
  return [`watch ${s.name} (${s.repo}) [${s.phase}, ${watch.mode}]`, ...(live ? [` state: ${live.state === "dead" ? "DEAD" : live.state}${["paused", "dead", "exited"].includes(live.state) ? ` (${live.reason})` : ""} last heartbeat: ${s.heartbeat ?? "never"}${live.ageMs != null ? ` (${Math.round(live.ageMs / 1000)}s ago)` : ""}`] : []), ` selector: ${sel}`,
500
- ` reconciled: ${Object.entries(claimCounts(s)).map(([k, v]) => `${k} ${v}`).join(" ")}`,
510
+ ...(s.claude === null ? [" WARNING: this watcher cannot resolve claude on its PATH; its lanes fail 'Failed to find executable claude' (reinstall: forgedock issue-watch install)"] : []), // #5529
511
+ ` reconciled: ${Object.entries(claimCounts(s)).map(([k, v]) => `${k} ${v}`).join(" ")}${s.redriven && Object.keys(s.redriven).length ? ` re-driven ${Object.keys(s.redriven).length}` : ""}`,
501
512
  ` claims: ${s.claimed.length}/${watch.max_issues ?? "∞"} inflight: ${s.inflight.length} merged: ${s.merged.length} verified: ${s.verified.length} unverified: ${(s.unverified ?? []).length} closed unmerged: ${(s.closed ?? []).length} failed: ${s.failed.length}`, ` time remaining: ${left}`,
502
513
  ...(s.decisions ? [(({ decided, evidence, folded, external_kept: kept }) => ` needs-human decisions: decided ${decided} evidence-gathered ${evidence} folded ${folded} external-kept ${kept}`)(decisionCounts(s))] : []),
503
514
  ...(s.passError ? [` last pass failed: ${s.passError}`] : []), // #5425
@@ -554,7 +565,11 @@ export async function runWatch({ watch, repo, io, dir, branches, defaults, once
554
565
  try {
555
566
  do {
556
567
  state.heartbeat = new Date(io.now()).toISOString(); state.heartbeatEveryMs = intervalMs; // #5313: liveness lives in the state, not a process grep
568
+ state.claude = resolveOnPath("claude", (io.env ?? process.env).PATH); // #5529: what this watcher's lanes inherit; status/doctor warn on null
557
569
  let rel = null; try { rel = watch.release_pause && state.phase === "running" ? (io.releaseInFlight ?? releaseInFlight)({ root: releaseRoot(io.env), repo, now: io.now() }) : null; } catch { /* unreadable release state: not paused */ }
570
+ let gp = null; // #5555 (I18): GitHub truth, every host; only for a managed release repo, so defaults make no call
571
+ if (!rel && watch.release_pause && state.phase === "running") { try { gp = await githubIntake({ io, repo, cwd, state }); } catch (e) { state.pauseError = String(e?.message ?? e).slice(0, 200); } }
572
+ if (gp) { state.paused = { reason: gp.reason, source: gp.source, since: state.paused?.since ?? state.heartbeat }; writeAtomic(join(dir, "status.json"), JSON.stringify(state) + "\n"); if (once) break; await io.sleep(intervalMs); continue; }
558
573
  if (rel) { // a release job holds staging: no claims, retries or decisions until it ends; the next pass resumes by itself
559
574
  state.paused = { reason: `release ${rel.id} in flight${rel.step ? ` (${rel.step})` : ""}`, release: rel.id, since: state.paused?.since ?? state.heartbeat };
560
575
  writeAtomic(join(dir, "status.json"), JSON.stringify(state) + "\n");
@@ -671,6 +686,22 @@ export function ghRunner(exec, warn = () => {}, { retries = GH_RETRIES, sleep =
671
686
  };
672
687
  }
673
688
 
689
+ /** #5555: `{reason, source}` when GitHub says intake is paused (null otherwise); auto-resumes a pause whose release ended. */
690
+ async function githubIntake({ io, repo, cwd, state }) {
691
+ const { readReleaseConfig } = await import("./release.mjs"), { githubPause, ghGet, setIntake } = await import("./intake.mjs");
692
+ let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* defaults */ }
693
+ const cfg = readReleaseConfig(raw);
694
+ if (!cfg.managed) return null;
695
+ const g = await githubPause({ get: ghGet(io.gh), repo, autoResume: !!cfg.intakeAutoResume });
696
+ state.pauseError = null;
697
+ if (g.resume) {
698
+ const api = io.api ?? (await import("./release.mjs")).realReleaseIo({ env: io.env, cwd }).api;
699
+ await setIntake({ io: { api }, repo, paused: false, by: "issue-watch", tracker: cfg.tracker ?? null, now: io.now() });
700
+ return null;
701
+ }
702
+ return g.paused ? g : null;
703
+ }
704
+
674
705
  const flag = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
675
706
 
676
707
  /** `forgedock issue-watch run [--name w] [--repo o/r] [--once] [--interval s] | status [--name w] [--repo o/r]`; `--dry-run` writes nothing: mode release prints the would-cut set, per-issue/batch the would-claim/fold/skip plan (#5088) and the needs-human classification. */
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { test } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { mkdirSync, writeFileSync, existsSync, readFileSync } from "node:fs";
5
+ import { mkdirSync, writeFileSync, existsSync, readFileSync, chmodSync } from "node:fs";
6
6
  import { tmpDir } from "../tests/_tmp.mjs";
7
7
  import { join } from "node:path";
8
8
  import { unclaimedOrOwn, parseWatches, validateWatch, loadWatches, matchesSelectors, issueVersion, hasUnresolvedDefer, classifyIssue, laneFor, dagOrder, claimIssue, acquireLock, tick, runWatch, formatStatus, repoDir, watchDir, issueWatchFromCli, isOwnApp, selectorMiss, planClaims, ghFailureEffect, ghRunner, isTransientGhError } from "./issuewatch.mjs";
@@ -763,3 +763,51 @@ test("a needs-human issue a person cleared with a new comment is re-claimed; stu
763
763
  await tick({ watch: w, repo: "o/r", io, state });
764
764
  assert.ok(!state.outcomes?.[1]); // released, then re-selected is up to planClaims
765
765
  });
766
+
767
+ // #5529: real tick/reconcile/redrive over a real batch state.json (openBatch) and the real claims.json registry; the
768
+ // orchestrate --requeue spawn and gh are the external seams (calls recorded); claude is resolved on a real temp PATH
769
+ const stageClaude = (d) => { mkdirSync(d, { recursive: true }); writeFileSync(join(d, "claude"), "#!/bin/sh\n"); chmodSync(join(d, "claude"), 0o755); return d; };
770
+
771
+ test("#5529 a missing-executable engine-error is requeued once claude resolves, not before; other stranded claims are re-driven within budget", async () => {
772
+ const dir = tmp(), root = tmp(), noClaude = tmp(), bin = join(tmp(), "bin");
773
+ const b = openBatch(root, "b1");
774
+ mkdirSync(b.dir, { recursive: true });
775
+ b.store.save({ order: [1, 2], results: { 1: { outcome: "engine-error", detail: "claude CLI exited with status 1. Output: Failed to find executable claude: No such file or directory" }, 2: { outcome: "engine-error", detail: "lane pid 9 exited without a result" } } });
776
+ const io = fakeIo(dir, []), requeued = [];
777
+ io.env.PATH = noClaude;
778
+ io.batch.results = (id) => openBatch(root, id).store.load()?.results ?? null;
779
+ io.batch.requeue = (id, n) => { requeued.push(n); const st = b.store.load(); delete st.results[n]; b.store.save(st); return true; }; // what orchestrate --requeue does to the row
780
+ for (const n of [1, 2]) assert.equal(claimIssue(repoDir("o/r", io.env), n, "w"), true);
781
+ const state = batchState({ claimed: [1, 2], inflight: [1, 2], lanes: { 1: "staging", 2: "staging" } });
782
+ const watch = W({ mode: "batch" });
783
+ await tick({ watch, repo: "o/r", io, state });
784
+ assert.deepEqual(requeued, [2], "claude still missing: only the generic stranded claim is re-driven");
785
+ assert.match(formatStatus(state, watch, io.now()), /stranded 1/);
786
+ await tick({ watch, repo: "o/r", io, state });
787
+ assert.deepEqual(requeued, [2], "still not resolvable: no requeue");
788
+ io.env.PATH = `${noClaude}:${stageClaude(bin)}`;
789
+ await tick({ watch, repo: "o/r", io, state });
790
+ assert.deepEqual(requeued, [2, 1]);
791
+ assert.ok(state.inflight.includes(1) && !state.failed.includes(1));
792
+ assert.match(formatStatus(state, watch, io.now()), /stranded 0.*re-driven 2/);
793
+ assert.equal(claimIssue(repoDir("o/r", io.env), 1, "other"), false, "the claim stays with this watch while it is requeued");
794
+ // budget: issue 2 keeps failing; it is requeued at most twice in total
795
+ for (let i = 0; i < 3; i++) { const st = b.store.load(); st.results[2] = { outcome: "engine-error", detail: "boom" }; b.store.save(st); await tick({ watch, repo: "o/r", io, state }); }
796
+ assert.equal(requeued.filter((n) => n === 2).length, 2);
797
+ assert.match(formatStatus(state, watch, io.now()), /stranded 1/);
798
+ });
799
+
800
+ test("#5529 the running watcher records whether it resolves claude and status warns when it cannot", async () => {
801
+ const dir = tmp(), bin = join(tmp(), "bin"), watch = W({ mode: "batch" });
802
+ const io = fakeIo(dir, []);
803
+ io.env.PATH = tmp();
804
+ const wd = watchDir("o/r", "w", io.env);
805
+ let state = await runWatch({ watch, repo: "o/r", io, dir: wd, once: true });
806
+ assert.equal(state.claude, null);
807
+ assert.equal(JSON.parse(readFileSync(join(wd, "status.json"), "utf8")).claude, null);
808
+ assert.match(formatStatus(state, watch, io.now()), /WARNING: this watcher cannot resolve claude/);
809
+ io.env.PATH = stageClaude(bin);
810
+ state = await runWatch({ watch, repo: "o/r", io, dir: wd, once: true });
811
+ assert.equal(state.claude, join(bin, "claude"));
812
+ assert.doesNotMatch(formatStatus(state, watch, io.now()), /cannot resolve claude/);
813
+ });
@@ -7,7 +7,7 @@ import { mkdirSync, writeFileSync, chmodSync } from "node:fs";
7
7
  import { join } from "node:path";
8
8
  import { tmpDir } from "../tests/_tmp.mjs";
9
9
  import { checkPoolAuth, checkPoolVersion, checkPathLoop, checkGhFields, availableFields, runLaneChecks, formatLaneChecks, UPGRADE_COMMAND } from "./lanecheck.mjs";
10
- import { findShimLoops } from "./heavy.mjs";
10
+ import { findShimLoops, heavyShimScript } from "./heavy.mjs";
11
11
  import { orchestrate, deferPolicy } from "./orchestrate.mjs";
12
12
  import { providerLanes, isCloneFailure } from "./execution.mjs";
13
13
 
@@ -66,10 +66,21 @@ describe("pool_version", () => {
66
66
  describe("path_loop", () => {
67
67
  const wrapper = "#!/bin/sh\nexec \"$(command -v docker)\" \"$@\"\n";
68
68
  const mk = () => { const d = tmpDir("lc-"); const w = join(d, "wrap"); mkdirSync(w); writeFileSync(join(w, "docker"), wrapper); chmodSync(join(w, "docker"), 0o755); return { d, w }; };
69
- it("names the wrapper dir when no real binary sits behind it", () => {
69
+ it("names the shim dir when a heavy shim execs a pass-through wrapper", () => {
70
+ const { d, w } = mk(); const sh = join(d, "shim"); mkdirSync(sh);
71
+ writeFileSync(join(sh, "docker"), heavyShimScript("docker", join(w, "docker"))); chmodSync(join(sh, "docker"), 0o755);
72
+ const c = checkPathLoop({ env: { PATH: `${sh}:${w}` } });
73
+ assert.equal(c.ok, false); assert.equal(c.code, "preflight.path_loop"); assert.ok(c.detail.includes(sh));
74
+ });
75
+ it("#5592: a batch-level wrapper with no real binary behind it does not trip (no shim is written over it)", () => {
70
76
  const { w } = mk();
71
- const c = checkPathLoop({ env: { PATH: w } });
72
- assert.equal(c.ok, false); assert.equal(c.code, "preflight.path_loop"); assert.ok(c.detail.includes(w));
77
+ assert.equal(checkPathLoop({ env: { PATH: w } }).ok, true);
78
+ });
79
+ it("#5592: a wrapper our own shim already covers (shim points at the real binary) passes", () => {
80
+ const { d, w } = mk(); const real = join(d, "real"), sh = join(d, "shim"); mkdirSync(real); mkdirSync(sh);
81
+ writeFileSync(join(real, "docker"), "#!/bin/sh\necho hi\n"); chmodSync(join(real, "docker"), 0o755);
82
+ writeFileSync(join(sh, "docker"), heavyShimScript("docker", join(real, "docker"))); chmodSync(join(sh, "docker"), 0o755);
83
+ assert.equal(checkPathLoop({ env: { PATH: `${sh}:${w}:${real}` } }).ok, true);
73
84
  });
74
85
  it("passes when a real binary is behind the wrapper", () => {
75
86
  const { d, w } = mk(); const real = join(d, "real"); mkdirSync(real); writeFileSync(join(real, "docker"), "#!/bin/sh\necho hi\n"); chmodSync(join(real, "docker"), 0o755);
package/bin/lean/lean.mjs CHANGED
@@ -5,6 +5,7 @@
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 { issuePrMarker, supersedeOlderPrs, openPrBlockingClose } from "./orphan-pr.mjs";
8
9
  import { resolveFindingLabel } from "./findinglabel.mjs";
9
10
  import { spawnSync } from "node:child_process";
10
11
  import { existsSync, readFileSync } from "node:fs";
@@ -20,14 +21,15 @@ import { createHash, randomBytes } from "node:crypto";
20
21
  import { otherLaneOwner } from "./lanelock.mjs";
21
22
  import { stampText, checkStamp } from "./stagestamp.mjs";
22
23
  import { acquireBranchLock, waitPidsExit } from "./branchlock.mjs";
23
- import { isTestPath, applyValidateRecipes, rewriteProjectDirCommand, deferChecklessPostDeploy, autoPostDeployE2e, loneE2eRows, reproEnvMiss, resolveForgedockPaths, describesUnrunnableCommand, removedPathsOf, TRACKED, normalizeKindModes, blockingFailures, unverifiedRequirements, mutationTargets, mutationFailures, runMutationCheck, MUTATION_SURVIVED, isBugIssue, scopeText, explainFailures, inIssue, validateContract, snapQuotes, cliUsageError, normalizeRunnerCommand, applyAmendments, amendmentKindProblems, precheck, alreadyFixedOnBase, READONLY_PROD_RE, EXTERNAL_NEED_RE, intakeHostWork, repoTracks, dropScopeValidates, tagOutOfBand, parseReview, decide, mergeReviewRows, reaskable, criterionLines, closePlan, followupItems, renderPendingFollowups, bucketTally, pendingTracking, unnamedEdges, structureNote, impliedDocDeliverables, convertDelivered } from "./conformance.mjs";
24
+ import { contractRuleCounts, onlyTestPlanProblems, isTestPath, applyValidateRecipes, rewriteProjectDirCommand, deferChecklessPostDeploy, autoPostDeployE2e, loneE2eRows, reproEnvMiss, resolveForgedockPaths, describesUnrunnableCommand, removedPathsOf, TRACKED, normalizeKindModes, blockingFailures, unverifiedRequirements, mutationTargets, mutationFailures, runMutationCheck, MUTATION_SURVIVED, isBugIssue, scopeText, explainFailures, inIssue, validateContract, snapQuotes, cliUsageError, normalizeRunnerCommand, applyAmendments, amendmentKindProblems, precheck, alreadyFixedOnBase, READONLY_PROD_RE, EXTERNAL_NEED_RE, intakeHostWork, repoTracks, dropScopeValidates, tagOutOfBand, parseReview, decide, mergeReviewRows, reaskable, criterionLines, closePlan, followupItems, renderPendingFollowups, bucketTally, pendingTracking, unnamedEdges, structureNote, impliedDocDeliverables, convertDelivered } from "./conformance.mjs";
24
25
  import { checkAdmission, hostParallelism, ADMISSION_RETRY_SECONDS } from "./admission.mjs";
25
26
  import { namedPaths, isTrustedIssueComment } from "./prefilter.mjs";
27
+ import { writeStatus, postUpsert, isStatusPost, isUpsertPost, hasSection, clearPipelineLabels } from "./statuscomment.mjs";
26
28
  import { checksAt, mergeCheckEntries, CHECKS_FILE } from "./postdeploy-check.mjs";
27
29
  import { matchBaselines, baselineFailures, foldRegression } from "./baselines.mjs";
28
30
  import { readRollouts, detectNewOffKeys, rolloutModes, liveDeferralBlocks } from "./activation.mjs";
29
31
  import { toolMisses } from "./toolplace.mjs";
30
- import { testRunnerProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract, declaredEnv, depInstallFailures, testRunSummary } from "./preflight.mjs";
32
+ import { testRunnerProblems, preflightProbes, preflightProblems, unsetEnvVars, runPreflight, knownToContract, declaredEnv, depInstallFailures, testRunSummary, projectBinDirs, withLocalBins } from "./preflight.mjs";
31
33
  import { resolveLane, isDefaultLane, isShippedLane, DEFAULT_STAGING_BRANCH } from "./lane.mjs";
32
34
  import { splitGate, rationaleLine } from "./decompose.mjs";
33
35
  import { ceilingFor, predictRestart, handoffFacts, NARROW_NOTE } from "./ceiling.mjs";
@@ -57,6 +59,8 @@ import { parseProdParity, prodParityFailures as prodParityOf } from "./prodparit
57
59
  import { routePathsFromFiles, routeReachabilityFailures } from "./routecheck.mjs";
58
60
  import { docsFailures } from "./docsgate.mjs";
59
61
  import { pageFailures, designSpecApproved, designLabelApproved } from "./pagegate.mjs"; // #5428
62
+ import { uiBuildRule, uiIssue, uiChanged } from "./ui-quality.mjs"; // #5330
63
+ import { designGate, designGateNote, designFailures, specApproved as designSpecOk } from "./design-gate.mjs"; // #5330
60
64
  import { parseCoupled, coupledFailures } from "./coupled.mjs";
61
65
  import { analyzeRelaxations, relaxationFailures } from "./relaxation.mjs";
62
66
  import { startSpeculative } from "./overlap.mjs";
@@ -83,6 +87,8 @@ import { applyArmOverrides } from "../experiment.mjs";
83
87
  import { parseExploreConfig, explorerAgents, explorePlanRule, exploreBuildRule } from "./explore.mjs";
84
88
  import { normaliseFacts, renderFactsRecord, FACTS_MARKER } from "./facts.mjs";
85
89
  import { readDecisionIndex, withDecisionRows, recordDecisions } from "./decisions.mjs";
90
+ import { seamFailures } from "./seam.mjs"; // #5338
91
+ import { notifyConsumers } from "./interfaces.mjs"; // #5338
86
92
  import { normaliseInvalidation, epicOf, fileAmendment, REPLAN_MARKER } from "./replan.mjs";
87
93
  import { claimSurfaces, parseSharedSurfaces, generatorNote } from "./surfaces.mjs";
88
94
  import { parseContextPackConfig, resolveContextMode, parentOf, contextArm, contextPackFor, renderContextRecord, laneType, priorAttempts, linkStateStamp, stateOf } from "./context.mjs";
@@ -273,7 +279,7 @@ const defaultCredExec = (args) => {
273
279
  export async function runCore(o) {
274
280
  const armed = applyArmOverrides(o, o.issue); o = armed.options; // #5206: the arm's overrides shape the lane before any config is parsed
275
281
  const { issue, repo, lane: requestedLane = null, laneOverride = false, branches = {}, cwd, dir, io, builderModel = null, reviewerModel = DEFAULT_REVIEWER_MODEL, fixModel = null,
276
- toolchainOverride = null, testRunners = null, coupledFiles = null, validateRecipes = null, routeReachability = null, docsConfig = null, pagesConfig = null, prodParity = null, envSetup = null, ciMaxMinutes = 360, conformance = "shadow", conformanceKinds = null, conformanceMutation = "off", reviewIncomplete = "needs-human", reproTest = "prefer", reproQuality = "shadow", closeParent = false, mergeWait = "required", maxSessionLimitPauses = DEFAULT_MAX_SESSION_LIMIT_PAUSES, cliIdleMinutes = 15, cliMaxMinutes = 180, cliBusyMinutes = 45, contextCeilingTokens = 120000, contextCeilingBySize = null, turnBudgets = null, laneLimits = null, maxMergeRetries = 5, sessionLimitMaxWaitMs = DEFAULT_SESSION_LIMIT_WAIT_MS, contextWaitSeconds = 5, onProgress = () => {}, emitTelemetry = null, random = Math.random } = o;
282
+ 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, sessionLimitMaxWaitMs = DEFAULT_SESSION_LIMIT_WAIT_MS, contextWaitSeconds = 5, onProgress = () => {}, emitTelemetry = null, random = Math.random } = o;
277
283
  const now = io.now ?? (() => Date.now());
278
284
  const rotator = io.rotator !== undefined ? io.rotator : openRotator({ kind: o.accountRotator }); // #5094
279
285
  // #5205: a rotator with pick() relaunches a limited phase pinned to another account; lane-level rotations and limited accounts
@@ -300,6 +306,8 @@ export async function runCore(o) {
300
306
  let lane = null, base = null, defaults = [], milestone = null; // set by lane resolution, before the lease
301
307
  // #4267: a batch recovery lane for a mechanical needs-human ({code, attempt, final}); #4302: only a final attempt relabels.
302
308
  const recover = o.recover && typeof o.recover.code === "string" ? { code: o.recover.code, attempt: Number.isInteger(o.recover.attempt) ? o.recover.attempt : 1, final: o.recover.final !== false } : null;
309
+ const withLink = (body) => `${issuePrMarker(issue)}\n${body}`; // #5505: the issue → PR link GitHub does not record for a staging PR
310
+ const closeBlockers = (reason, exceptPr = null) => openPrBlockingClose({ repo, io: { gh: ghw }, issue, reason, exceptPr }).catch(() => []); // #5505: fail open
303
311
  let branch = `feat/issue-${issue}-lean`; // #5469: an adopted PR's own head branch replaces it
304
312
  const wt = join(o.worktreeRoot ?? join(cwd, ".claude", "worktrees"), `lean-${issue}`);
305
313
  const t0 = now();
@@ -347,7 +355,20 @@ export async function runCore(o) {
347
355
  usage.input += u.input_tokens ?? 0; usage.output += u.output_tokens ?? 0;
348
356
  usage.cache += (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0);
349
357
  }
358
+ let statusCache = null; // #5592: {id, sections} of this issue's one FORGE:STATUS comment, edited in place
350
359
  const post = async (marker, body, on = issue) => {
360
+ if (on === issue && isStatusPost(marker)) { // machine-state markers: a section of the one status comment, not a comment of their own
361
+ try {
362
+ const r = await writeStatus({ known: statusCache, comments: iss?.comments, trusted: isTrustedIssueComment, markers: Array.isArray(marker) ? marker : [marker], text: body, cap: capComment,
363
+ create: async (b) => /https?:\/\/\S+/.exec(String(await ghw(["issue", "comment", String(on), "-R", repo, "--body", b])))?.[0] ?? null,
364
+ patch: (id, b) => ghw(["api", "-X", "PATCH", `repos/${repo}/issues/comments/${id}`, "-f", `body=${b}`]) });
365
+ statusCache = { id: r.id, sections: r.sections };
366
+ return r.url;
367
+ } catch (e) { if (e?.deferCode) throw e; /* a failed status edit falls back to a plain comment below */ }
368
+ }
369
+ if (on === issue && isUpsertPost(marker)) { // one comment edited in place across requeues (the marker still leads the body)
370
+ return postUpsert({ gh: ghw, repo, issue: on, markers: marker, body, comments: iss?.comments, cap: capComment });
371
+ }
351
372
  const marks = (Array.isArray(marker) ? marker : [marker]).map((m) => `<!-- ${m} -->`).join("\n");
352
373
  const out = String(await ghw(["issue", "comment", String(on), "-R", repo, "--body", capComment(`${marks}\n${body}`)])).trim();
353
374
  return /https?:\/\/\S+/.exec(out)?.[0] ?? null;
@@ -582,6 +603,7 @@ export async function runCore(o) {
582
603
  if (deferTail) { postRun.add("lane-facts", postLaneFacts); postRun.add("trajectory", postTrajectory); } else await postTrajectory();
583
604
  }
584
605
  if (deferTail) postRun.add("teardown", () => teardown(reason, extra)); // last: the structure delta and guard read the worktree
606
+ if (reason === "merged" || reason === "invalid") await clearPipelineLabels({ gh: ghc, repo, issue }); // #5592: a merged or closed issue keeps no needs-human / parked:* / remediation-queue
585
607
  await releaseLease(reason, code, extra.mergedTo ?? null);
586
608
  done = { terminalReason: reason, detail, branch, worktree: wt, cost_usd: usage.cost_usd, tokens: { input: usage.input, output: usage.output, cache: usage.cache }, wall_ms: now() - t0, model_ms: modelMs, phases: phaseLedger.snapshot(),
587
609
  ...(laneHead && reason !== "merged" ? { laneHead: { ...laneHead } } : {}), light, ...(lightVerdict ? { light_eligibility: lightVerdict } : {}), ...(lightUpgrade ? { light_upgrade: lightUpgrade } : {}), // #4453
@@ -931,7 +953,8 @@ export async function runCore(o) {
931
953
  let decisionsNote = ""; // #4901: trusted FORGE:DECISION comments newer than the frozen contract, "" otherwise
932
954
  let carriedPasses = []; // #5331: validate ids that passed on the resume head (resume digest); carried into the builder result while HEAD is unchanged
933
955
  let resumeNote = ""; // #4400: the resume digest of the last run (resume.mjs), "" on a first run or with context_pack off
934
- const implementRestart = () => builderImplementPrompt(vcfg.mode, tcOpts()) + seqBuildNote + hotspotBuildRule(hotFacts) + enumeratingBuildRule(enumList) + invariantsBuildRule(vcfg.invariants) + exploreBuildRule(exploreCfg) + CONTINUE_NOTE.replace("BASE", lane) + resumeNote;
956
+ let uiOn = false; // #5330: the lane changes user-visible frontend (issue text, then contract deliverables): the design-system and visual self-check rules join its prompts
957
+ const implementRestart = () => builderImplementPrompt(vcfg.mode, tcOpts()) + seqBuildNote + hotspotBuildRule(hotFacts) + enumeratingBuildRule(enumList) + invariantsBuildRule(vcfg.invariants) + exploreBuildRule(exploreCfg) + uiBuildRule(uiOn, designConfig) + CONTINUE_NOTE.replace("BASE", lane) + resumeNote;
935
958
  /** #5334: records a builder session that ended without its result line (kill, signal) as one attempt; `at` = its start. */
936
959
  const killedAttempt = (n, e, opts, at) => attempt("implement", n, { killed: true, usage: e.usage ?? null, turns: e.turns ?? null, tools: toolStats(e.toolUses), costUsd: null, durationMs: now() - at, model: opts.model ?? laneModel() ?? null }, opts.mode, opts.trigger, opts.restartOf);
937
960
  async function flushInflight() {
@@ -1326,6 +1349,8 @@ export async function runCore(o) {
1326
1349
  const fetchP = step("fetch", async () => { try { await io.git(["fetch", "origin", lane], { cwd }); } catch { /* offline: use the local ref */ } });
1327
1350
  await step("claim", async () => {
1328
1351
  await label("investigating");
1352
+ // #5592: a live lane is not parked: needs-human, needs-human:*, parked:* and remediation-queue from an earlier run come off (a later park puts them back)
1353
+ await clearPipelineLabels({ gh: ghc, repo, issue, labels: iss.labels });
1329
1354
  await post("FORGE:STARTED", `Started work on #${issue} (base \`${lane}\`).`);
1330
1355
  if (recover) {
1331
1356
  // #4267: the batch decided to recover this issue itself; the label goes so the issue is live again.
@@ -1534,7 +1559,10 @@ export async function runCore(o) {
1534
1559
  const tH = now();
1535
1560
  if (heavyOn) {
1536
1561
  try {
1537
- const root = runTmp ?? join(wt, LEAN_DIR), binDir = join(root, "heavy", "bin"), path = toolchain?.env?.PATH ?? process.env.PATH ?? "";
1562
+ const root = runTmp ?? join(wt, LEAN_DIR), binDir = join(root, "heavy", "bin"), path0 = toolchain?.env?.PATH ?? process.env.PATH ?? "";
1563
+ // #5592: a tool that only exists in a project's .venv/bin or node_modules/.bin (poetry/uv in-project venv, monorepo service) is shimmed too, so the preflight probe and the shim agree
1564
+ let tracked = []; try { tracked = String(await git(["ls-files"])).split("\n").map((x) => x.trim()).filter(Boolean); } catch { /* no git listing */ }
1565
+ const path = withLocalBins(path0, projectBinDirs(wt, tracked));
1538
1566
  const names = await (io.writeHeavyShims ?? writeHeavyShims)(binDir, { path });
1539
1567
  if (names?.length) {
1540
1568
  heavyWaitsFile = join(root, "heavy-waits.jsonl");
@@ -1691,7 +1719,7 @@ export async function runCore(o) {
1691
1719
  const rec = { event: "CONTEXT_PACK", mode: ctxCfg.mode, ...ctxAb, lane_type: ctxLane, sources: p.sources, found: p.found, bytes: p.bytes, items: p.items, truncated: p.truncated,
1692
1720
  hash: p.hash, cached: r.cached, ...(p.recall ? { recall: p.recall.present ? "present" : "absent" } : {}), ...(r.errors?.length ? { errors: r.errors } : {}) };
1693
1721
  ev({ ...rec, pitfalls: inPack }); await emit(rec);
1694
- const seen = trustedComments.some((c) => String(c?.body ?? "").startsWith("<!-- FORGE:CONTEXT -->") && String(c.body).includes(`hash ${p.hash})`));
1722
+ const seen = trustedComments.some((c) => hasSection(c?.body, "FORGE:CONTEXT") && String(c.body).includes(`hash ${p.hash})`));
1695
1723
  if (p.items && !seen) { try { await post("FORGE:CONTEXT", renderContextRecord(p, { mode: ctxCfg.mode, laneType: ctxLane })); } catch { /* best effort */ } }
1696
1724
  T.decisions.push(`Context pack (${ctxCfg.mode}): ${p.items} item(s), ${p.bytes} bytes${p.truncated ? `, ${p.truncated} dropped` : ""}, ${ctxCfg.mode === "on" ? "given to the builder" : "recorded only"}`);
1697
1725
  return p;
@@ -1806,7 +1834,7 @@ export async function runCore(o) {
1806
1834
  for (const x of r.applied) T.decisions.push(`validate recipe rewrote ${x.id}: \`${x.from}\` -> \`${x.to}\``);
1807
1835
  r.contract = foldRegression(r.contract); // #5448: the blast-radius regression set runs as validate G# entries
1808
1836
  const e = autoPostDeployE2e(r.contract); // #5468: production-only e2e/manual rows become post-deploy with a generated check
1809
- for (const x of e.converted) { genChecks[x.check] = x.entry; T.decisions.push(`Production-only e2e/manual requirement ${x.id} frozen as post-deploy with generated check ${x.check}`); }
1837
+ for (const x of e.converted) { if (x.check) genChecks[x.check] = x.entry; T.decisions.push(`Production-only e2e/manual requirement ${x.id} frozen as post-deploy with ${x.check ? `generated check ${x.check}` : "no check (production observation window)"}`); }
1810
1838
  r.contract = e.contract;
1811
1839
  const d = deferChecklessPostDeploy(r.contract);
1812
1840
  if (d.converted.length) T.decisions.push(`Post-deploy with no registered check deferred to the orchestrator: ${d.converted.join(", ")}`);
@@ -1816,6 +1844,9 @@ export async function runCore(o) {
1816
1844
  if ((!io.probeCommand && !io.preflightRun) || !contract || typeof contract !== "object") return [];
1817
1845
  const files = String(await git(["ls-files"]).catch(() => "")).split("\n").map((x) => x.trim()).filter(Boolean);
1818
1846
  const env = laneEnv(), missing = new Set(), misses = []; // #4325: the env the validate commands run with
1847
+ // #5592: tools resolve where the lane runs them from: project-local .venv/bin and node_modules/.bin (as the heavy shims do)
1848
+ const local = projectBinDirs(wt, files);
1849
+ if (local.length) env.PATH = withLocalBins(env.PATH ?? process.env.PATH ?? "", local);
1819
1850
  if (io.probeCommand) {
1820
1851
  const { probes, dropped } = preflightProbes(contract, { repoHas: repoTracks(files) });
1821
1852
  if (dropped) T.anomalies.push(`Validate preflight probed ${probes.length} tool(s); ${dropped} more not probed`);
@@ -2069,7 +2100,7 @@ export async function runCore(o) {
2069
2100
  const tPack = now(); packP = contextPackStep(); ctxPack = await within(packP, waitMs); setupStep("context_pack", tPack);
2070
2101
  if (ctxPack === TIMED_OUT) { ctxPack = null; T.decisions.push(`Context pack not ready in ${waitMs / 1000}s: the plan starts without it`); }
2071
2102
  }
2072
- const planPrompt = () => builderPlanPrompt(issue, tcOpts()) + hotspotPlanNote(hotFacts) + enumeratingPlanNote(enumList) + invariantsPlanNote(vcfg.invariants) + reproPlanNote(reproOn()) + docsPlanNote(docsConfig) + pagePlanNote(pagesConfig) + unrunnableValidateNote(testRunners) + explorePlanRule(exploreCfg) + (ctxCfg.mode === "on" ? contextPackNote(ctxPack) : "");
2103
+ const planPrompt = () => builderPlanPrompt(issue, tcOpts()) + uiBuildRule(uiOn = uiOn || uiIssue(iss ?? {}), designConfig) + hotspotPlanNote(hotFacts) + enumeratingPlanNote(enumList) + invariantsPlanNote(vcfg.invariants) + reproPlanNote(reproOn()) + docsPlanNote(docsConfig) + pagePlanNote(pagesConfig) + unrunnableValidateNote(testRunners) + explorePlanRule(exploreCfg) + (ctxCfg.mode === "on" ? contextPackNote(ctxPack) : "");
2073
2104
  let lightDone = false, lightCommits = false;
2074
2105
  let ffPlan = "full", ffGo = false, lightElig = elig, lightPred = null, ffTriage = null; // #5426: how the plan call runs; ffGo = fast-forward to the light step
2075
2106
  const ffTriageOf = async (raw) => parseTriage(raw, await io.fs.read(`${wt}/${INVESTIGATION_FILE}`).catch(() => ""));
@@ -2139,7 +2170,7 @@ export async function runCore(o) {
2139
2170
  T.plan = "skipped"; T.implement = "skipped"; T.review = "skipped"; T.pr = "none"; T.merge = "n/a";
2140
2171
  T.decisions.push(`Builder verdict: ${result.status}`);
2141
2172
  // #5152: already-fixed is delivered behaviour (`completed`); only invalid is dropped scope (`not planned`)
2142
- await Promise.all([ghw(["issue", "close", String(issue), "-R", repo, "--reason", result.status === "already-fixed" ? "completed" : "not planned"]), label("invalid")]); // #5437: independent calls
2173
+ await Promise.all([result.status === "already-fixed" && (await closeBlockers("completed", resumed?.pr ?? null)).length ? null : ghw(["issue", "close", String(issue), "-R", repo, "--reason", result.status === "already-fixed" ? "completed" : "not planned"]), label("invalid")]); // #5437: independent calls
2143
2174
  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
2144
2175
  return await finish("invalid", result.summary ?? result.status, result.status === "already-fixed" ? { close: "already-fixed" } : {});
2145
2176
  }
@@ -2173,20 +2204,25 @@ export async function runCore(o) {
2173
2204
  return sq.contract;
2174
2205
  };
2175
2206
  contract = snapContract(contract);
2176
- let vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, testPlan: reproOn() });
2207
+ const wtRead = (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } }; // #5585: noindex pages are not public
2208
+ let vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, testPlan: reproOn(), readFile: wtRead });
2177
2209
  const missed = await preflightValidates(contract); // #4328: validate commands the host cannot run share the one correction
2178
2210
  let misses = missed;
2179
- if ((!vc.ok || missed.length || testRunnerProblems(contract, testRunners).length) && sessionId) {
2180
- const problems = [...vc.problems, ...preflightProblems(missed), ...testRunnerProblems(contract, testRunners)];
2181
- T.decisions.push(`Contract rejected (${problems[0]}); resumed once`);
2211
+ const correctContract = async (problems, note) => {
2212
+ T.decisions.push(`Contract rejected (${problems[0]}); ${note}`);
2182
2213
  await builder(++attemptN, contractCorrectionPrompt(problems), sessionId, false, planPrompt, { trigger: "contract_correction" });
2183
2214
  contract = freezeRewrites(dropScope(await readContract()));
2184
2215
  await persistGenChecks();
2185
2216
  await refreshIssue("contract validation");
2186
2217
  contract = snapContract(contract);
2187
- vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, testPlan: reproOn() });
2218
+ vc = validateContract(contract, issueText, { repro: reproOn(), pages: pagesConfig, testPlan: reproOn(), readFile: wtRead });
2219
+ };
2220
+ if ((!vc.ok || missed.length || testRunnerProblems(contract, testRunners).length) && sessionId) {
2221
+ await correctContract([...vc.problems, ...preflightProblems(missed), ...testRunnerProblems(contract, testRunners)], "resumed once");
2188
2222
  if (missed.length) misses = await preflightValidates(contract);
2189
2223
  }
2224
+ if (!vc.ok && sessionId && onlyTestPlanProblems(vc.problems)) await correctContract(vc.problems, "test-plan rules only, resumed a second time"); // #5587
2225
+ 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
2190
2226
  planMisses = misses;
2191
2227
  if (missed.length) {
2192
2228
  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 });
@@ -2212,8 +2248,16 @@ export async function runCore(o) {
2212
2248
  } else {
2213
2249
  T.validate = lightDone ? "light lane (no plan session)" : "resumed (existing branch)";
2214
2250
  }
2251
+ const dgFiles = (frozen?.deliverables ?? []).map((d) => d?.path).filter(Boolean);
2252
+ const designComments = (iss?.comments ?? []).filter(isTrustedIssueComment);
2253
+ 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
2254
+ if (designRoute.route) {
2255
+ ev({ event: "DESIGN_ROUTED", pages: designRoute.pages, blocked: designRoute.blocked });
2256
+ T.decisions.push(`Design gate: ${designRoute.reason}${designRoute.blocked ? " (design.gate: blocking, lane stopped)" : " (advisory)"}`);
2257
+ if (designRoute.blocked) return await needsHuman(`Design gate (forge.yaml design.gate: blocking): ${designRoute.reason}.\n\nRun /design on #${issue}; a FORGE:DESIGN_SPEC comment or the \`${designConfig.specLabel}\` label lifts the hold.`, OUTCOME_CODES.DESIGN_SPEC_REQUIRED, { ask: `Run /design for #${issue} (${designRoute.pages.slice(0, 3).join(", ")})` });
2258
+ }
2215
2259
  { // #5447: the test plan's declared env is checked on the host the lane runs on before building; a missing runner is provisioned once, else the lane ends env.tool_missing (the orchestrator re-places it on a host that has it)
2216
- const probeEnv = async () => { const miss = []; for (const t of declaredEnv(frozen)) { const r = io.runCommand ? await io.runCommand({ command: t === "pytest" ? "python3 -m pytest --version" : `command -v ${t}`, cwd: wt, timeoutMs: 30000, env: laneEnv() }).catch(() => ({ rc: 1 })) : { rc: 0 }; if ((r?.rc ?? 0) !== 0) miss.push(t); } return miss; };
2260
+ const probeEnv = async () => { const miss = []; for (const t of declaredEnv(frozen)) { const r = io.runCommand ? await io.runCommand({ command: t === "pytest" ? "python3 -m pytest --version" : `command -v ${t} >/dev/null || { test -d node_modules/${t} && ! test -e node_modules/.bin/${t}; } || ls -d .venv/lib/python*/site-packages/${t} >/dev/null 2>&1`, cwd: wt, timeoutMs: 30000, env: laneEnv() }).catch(() => ({ rc: 1 })) : { rc: 0 }; if ((r?.rc ?? 0) !== 0) miss.push(t); } return miss; };
2217
2261
  let envMiss = await probeEnv();
2218
2262
  if (envMiss.length) {
2219
2263
  try {
@@ -2279,7 +2323,7 @@ export async function runCore(o) {
2279
2323
  if (!ctxPack && packP) ctxPack = await packP.catch(() => null); // #5434: a pack that missed the plan wait still reaches the build
2280
2324
  const openPaths = (frozen?.deliverables ?? []).map((d) => d?.path); // #5347: facts for the build's opening batch
2281
2325
  const openMap = io.runCommand ? await readTestMapAtRef(git, base).catch(() => null) : null;
2282
- const implementPrompt = builderImplementPrompt(vcfg.mode, tcOpts()) + seqBuildNote + buildOpeningNote({ paths: openPaths, tests: selectCommands(openMap, openPaths), packFiles: ctxCfg.mode === "on" ? ctxPack?.files : [] }) + hotspotBuildRule(hotFacts) + enumeratingBuildRule(enumList) + invariantsBuildRule(vcfg.invariants) + exploreBuildRule(exploreCfg) + generatorNote(surfaceClaim?.generated) + (planned ? "" : (fromCheckpoint ? CONTINUE_NOTE : RERUN_NOTE).replace("BASE", lane)) + (salvagedRef ? SALVAGE_NOTE.replaceAll("REF", salvagedRef) : "") + recoverNote() + (planned ? "" : resumeNote + decisionsNote);
2326
+ const implementPrompt = builderImplementPrompt(vcfg.mode, tcOpts()) + seqBuildNote + buildOpeningNote({ paths: openPaths, tests: selectCommands(openMap, openPaths), packFiles: ctxCfg.mode === "on" ? ctxPack?.files : [] }) + hotspotBuildRule(hotFacts) + enumeratingBuildRule(enumList) + invariantsBuildRule(vcfg.invariants) + exploreBuildRule(exploreCfg) + uiBuildRule(uiOn = uiOn || uiChanged(dgFiles).length > 0, designConfig) + designGateNote(designRoute) + generatorNote(surfaceClaim?.generated) + (planned ? "" : (fromCheckpoint ? CONTINUE_NOTE : RERUN_NOTE).replace("BASE", lane)) + (salvagedRef ? SALVAGE_NOTE.replaceAll("REF", salvagedRef) : "") + recoverNote() + (planned ? "" : resumeNote + decisionsNote);
2283
2327
  liveKeys = ["implementation"];
2284
2328
  { const f = await gateSetup(); if (f) return f; } // #5434: resumed or frozen lanes skip the plan
2285
2329
  stage = "implement"; phaseLedger.enter("implement");
@@ -3007,9 +3051,15 @@ export async function runCore(o) {
3007
3051
  const docsFail = docsConfig ? await docsFailures({ cfg: docsConfig, files, result, diff: String(await git(["diff", "-U0", `${base}...HEAD`]).catch(() => "")), tracked: String(await git(["ls-files"]).catch(() => "")).split("\n").filter(Boolean), run: io.runCommand ? async ({ command }) => (await io.runCommand({ command, cwd: wt, timeoutMs: vcfg.precheckTimeoutSeconds * 1000, env: laneEnv() }).then((x) => x?.r ?? x)) ?? { rc: 127 } : null }) : [];
3008
3052
  // #5428: forge.yaml pages: a public page needs design, SEO and GEO briefs and passes the deterministic page checks; unset = no check
3009
3053
  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 }) : [];
3054
+ // #5330: forge.yaml design.routes (opt-in, blocking only): a user-visible page needs an approved spec and passes the deterministic visual critique
3055
+ 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 ""; } } });
3010
3056
  // #5284: forge.yaml topology.prod_parity: declared production-only surfaces this diff touches need a check result or a justification
3011
3057
  const parityRules = parseProdParity(prodParity);
3012
3058
  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 } }) : [];
3059
+ // #5338: a declared interface whose provider and consumer no longer agree (route, signature, payload) is flagged at lane review
3060
+ const seamRecs = [...readDecisionIndex(repo), ...pendingDecisions].filter((r) => r.seam);
3061
+ const ls = seamRecs.length ? String(await git(["ls-files"]).catch(() => "")).split("\n").filter(Boolean) : [];
3062
+ const seamFail = seamRecs.length ? seamFailures({ records: seamRecs, changedFiles: files, read: (p) => { try { return readFileSync(join(wt, p), "utf8"); } catch { return ""; } }, list: () => ls, superseded: pendingDecisions.map((d) => d.supersedes).filter(Boolean) }) : [];
3013
3063
  // #4705: only the part not hidden behind the validate rerun; 0 when the gate errored or skipped
3014
3064
  const guardRunMs = guardEv && !guardEv.error ? Math.max(0, now() - gateT0 - validateMs) : 0;
3015
3065
  guardAddedMs += guardRunMs;
@@ -3026,7 +3076,7 @@ export async function runCore(o) {
3026
3076
  baselineRuns.push({ ...b, rc: Number.isInteger(x?.rc) ? x.rc : 1, output: String(x?.output ?? "") });
3027
3077
  }
3028
3078
  if (baselineRuns.length) ev({ event: "BASELINES_RUN", runs: baselineRuns.map((b) => ({ run: b.run, rc: b.rc })) });
3029
- const pc = precheck({ baselineFailures: baselineFailures(baselineRuns), contract: effective, result, changedFiles: files, ignore: IGNORE, ciVerified, hotspots, repro: (adequacyIn.repro = repro), validateRuns, repoHas, frozen, checkIds, guardFailures, coupledFailures: await coupledOf(files), relaxationFailures: relaxationFailures(rx), routeFailures, docsFailures: docsFail, pageFailures: pageFail, docsPaths: docsConfig ? [...(docsConfig.paths ?? []), ...(docsConfig.registries ?? [])] : null, prodParityFailures, newOffKeys: await newOffKeysOf(), uiBrowser: uiBrowserOf(files), substitutedRuns, removedPaths, baseFiles: subBaseFiles });
3079
+ const pc = precheck({ baselineFailures: baselineFailures(baselineRuns), contract: effective, result, changedFiles: files, ignore: IGNORE, ciVerified, hotspots, repro: (adequacyIn.repro = repro), validateRuns, repoHas, frozen, checkIds, guardFailures, coupledFailures: await coupledOf(files), relaxationFailures: relaxationFailures(rx), routeFailures, docsFailures: docsFail, pageFailures: [...pageFail, ...designFail], seamFailures: seamFail, docsPaths: docsConfig ? [...(docsConfig.paths ?? []), ...(docsConfig.registries ?? [])] : null, prodParityFailures, newOffKeys: await newOffKeysOf(), uiBrowser: uiBrowserOf(files), substitutedRuns, removedPaths, baseFiles: subBaseFiles });
3030
3080
  // #5447: an install failure for a package the changed files import blocks (env.tool_missing); unrelated ones are logged
3031
3081
  const depFail = depInstallFailures({ results: depResults, changedFiles: files });
3032
3082
  for (const l of depFail.logged) if (!T.decisions.includes(l)) T.decisions.push(l);
@@ -3113,10 +3163,10 @@ export async function runCore(o) {
3113
3163
  const ids = d.state === "nonconforming" ? loneE2eRows(d.failures) : null;
3114
3164
  const cv = ids ? autoPostDeployE2e(effective, ids) : null;
3115
3165
  if (cv && cv.converted.length === ids.length) {
3116
- for (const x of cv.converted) genChecks[x.check] = x.entry;
3117
- effective = cv.contract;
3166
+ for (const x of cv.converted) if (x.check) genChecks[x.check] = x.entry;
3167
+ effective = deferChecklessPostDeploy(cv.contract).contract; // #5524: checkless rows route to the orchestrator
3118
3168
  await persistGenChecks();
3119
- T.decisions.push(`FORGE:DECISION e2e_unverified on ${ids.join(", ")} converted to post-deploy checks ${cv.converted.map((x) => x.check).join(", ")}: the observable is production-only`);
3169
+ T.decisions.push(`FORGE:DECISION e2e_unverified on ${ids.join(", ")} converted to post-deploy ${cv.converted.map((x) => x.check ?? "checkless").join(", ")}: the observable is production-only`);
3120
3170
  d = { state: "conforms", failures: [], review: d.review ?? review, by: "review" };
3121
3171
  }
3122
3172
  }
@@ -3215,7 +3265,7 @@ export async function runCore(o) {
3215
3265
  const sha = String(await git(["rev-parse", base]).catch(() => "")).trim().slice(0, 12) || base;
3216
3266
  const note = `Already fixed on the base: the repro test passes on \`${base}\` (${sha}) without this change, and the diff changes no source file. Closing as delivered.\n\n${list}`;
3217
3267
  T.decisions.push(`Already fixed on base ${sha} (repro BASE=RAN HEAD=RAN)`);
3218
- await ghw(["issue", "close", String(issue), "-R", repo, "--reason", "completed", "--comment", note]);
3268
+ if (!(await closeBlockers("completed", resumed?.pr ?? null)).length) await ghw(["issue", "close", String(issue), "-R", repo, "--reason", "completed", "--comment", note]);
3219
3269
  return await finish("invalid", `already fixed on base ${sha}`, { close: "already-fixed" });
3220
3270
  }
3221
3271
  if (outcome.state === "review.unparseable") return await needsHuman(`The conformance reviewer returned no parseable JSON twice; nothing merged.`, OUTCOME_CODES.REVIEW_NO_VERDICT);
@@ -3296,14 +3346,15 @@ export async function runCore(o) {
3296
3346
  await gitPush(["push", "-u", "origin", branch]);
3297
3347
  laneGuard(lane, "open a PR");
3298
3348
  const prOut = resumed?.pr ? `/pull/${resumed.pr}` : String(await ghw(["pr", "create", "-R", repo, "--base", lane, "--head", branch,
3299
- "--title", `${iss.title} (#${issue})`, "--body", isSplit ? (o.refactorModule ?? (await import("./refactor.mjs"))).renderSplitPrBody({ issue, ...split })
3300
- : renderPrBody({ issue, investigation: await readStage(STAGES[0]), contract: effective, implementation: await readStage(STAGES[1]), result, gitFiles: files, tracked: closing.tracked })])).trim();
3349
+ "--title", `${iss.title} (#${issue})`, "--body", withLink(isSplit ? (o.refactorModule ?? (await import("./refactor.mjs"))).renderSplitPrBody({ issue, ...split })
3350
+ : renderPrBody({ issue, investigation: await readStage(STAGES[0]), contract: effective, implementation: await readStage(STAGES[1]), result, gitFiles: files, tracked: closing.tracked }))])).trim();
3301
3351
  const pr = Number(/\/pull\/(\d+)/.exec(prOut)?.[1] ?? /(\d+)\s*$/.exec(prOut)?.[1]);
3302
3352
  if (!Number.isInteger(pr)) return await needsHuman(`Could not parse the PR number from: ${prOut.slice(0, 200)}`);
3303
3353
  ev({ event: "PR_OPENED", pr });
3304
3354
  await emit({ event: "PR_OPENED", pr });
3355
+ if (!resumed?.pr && !adoptPr) { try { const old = await supersedeOlderPrs({ repo, io: { gh: ghw }, issue, newPr: pr }); if (old.length) T.decisions.push(`Superseded older open PR(s) ${old.map((n) => `#${n}`).join(", ")} (one live PR per issue)`); } catch { /* best effort: the orphan sweep closes it later */ } } // #5505
3305
3356
  if (resumed?.pr && closing.tracked.length) { // an existing PR still has to link the tracking issues visibly
3306
- try { await ghw(["pr", "edit", String(pr), "-R", repo, "--body", renderPrBody({ issue, investigation: await readStage(STAGES[0]), contract: effective, implementation: await readStage(STAGES[1]), result, gitFiles: files, tracked: closing.tracked })]); }
3357
+ try { await ghw(["pr", "edit", String(pr), "-R", repo, "--body", withLink(renderPrBody({ issue, investigation: await readStage(STAGES[0]), contract: effective, implementation: await readStage(STAGES[1]), result, gitFiles: files, tracked: closing.tracked }))]); }
3307
3358
  catch (e) { e.deferCode = OUTCOME_CODES.FOLLOWUP_UNAVAILABLE; e.deferDetail = `could not link the tracking issues on PR #${pr}; nothing merged, rerun to retry`; throw e; }
3308
3359
  }
3309
3360
  if (degraded) {
@@ -3747,7 +3798,7 @@ export async function runCore(o) {
3747
3798
  try { await post("FORGE:TRACKED", `## Left open: live acceptance deferred on a default-on change\nMerged by PR #${pr}, but the rollout is live and these requirements still need live verification:\n${closing.blocks.map((b) => `- ${b.id} (flag ${b.flag})`).join("\n")}\n\nKeep the flag default-off until they are verified, or verify them and close.${closing.tracked.length ? ` Tracked in ${closing.tracked.join(", ")}.` : ""}`); } catch { /* the trajectory decision records it too */ }
3748
3799
  }
3749
3800
  // #5152: a merged change is `completed` even when partial: the remainder is tracked (FORGE:TRACKED), not dropped
3750
- if (!keepOpen) await ghw(["issue", "close", String(issue), "-R", repo, "--reason", "completed"]).catch(() => {});
3801
+ if (!keepOpen && !(await closeBlockers("completed", pr)).length) await ghw(["issue", "close", String(issue), "-R", repo, "--reason", "completed"]).catch(() => {}); // #5505: not while another own PR is open
3751
3802
  if (closing.transferred) { // #5339: record what is transferred, not met
3752
3803
  try { await post("FORGE:TRACKED", `## Left open: transferred, not met\nMerged by PR #${pr}, but these end-to-end/manual requirements were not run in the lane:\n${(closing.transfer ?? closing.open).map((r) => `- ${r.id}: ${r.transferred ? `transferred to epic #${r.transferred} (post-deploy journey)` : "no epic to take it"}`).join("\n")}${closing.tracked.length ? `\n\nTracked in ${closing.tracked.join(", ")}.` : ""}`); } catch { /* the PR body carries them too */ }
3753
3804
  } else if (closing.liveBlocked) { /* #5285: posted above */ } else if (closing.checklist) { // #5240: partial: left open; the unticked criteria, tracked follow-ups and any inert rollout are the record
@@ -3772,6 +3823,10 @@ export async function runCore(o) {
3772
3823
  try { // #4695/#4737: FORGE:DECISION records and supersession are persisted only after the merge
3773
3824
  const rec = await recordDecisions(pendingDecisions, { issue, repo, post });
3774
3825
  if (rec.length) T.decisions.push(`FORGE:DECISION: ${rec.map((d) => d.id).join(", ")}`);
3826
+ for (const d of rec.filter((x) => x.supersedes && x.consumers?.length)) { // #5338: a superseded interface reopens/notifies its consumers, or files one issue per named consumer
3827
+ const n = await notifyConsumers({ rec: d, pr, repo, gh: ghw });
3828
+ T.decisions.push(`Interface ${d.supersedes} superseded by ${d.id}: ${n.map((x) => `${x.consumer} ${x.action}${x.issue ? ` #${x.issue}` : ""}`).join(", ")}`);
3829
+ }
3775
3830
  } catch (e) { T.anomalies.push(`decision records not posted: ${String(e?.message ?? e).slice(0, 160)}`); }
3776
3831
  for (const sp of supersededIds(effective, guardSel)) { // #4693: the reviewer accepted the supersedes amendment; tell the guarded issue
3777
3832
  try { await ghw(["issue", "comment", sp.guard.slice(1), "-R", repo, "--body", supersessionComment({ guard: sp.guard, pr, why: sp.why })]); ev({ event: "supersedes_accepted", guard: sp.guard, pr }); T.decisions.push(`Guard ${sp.guard} superseded: ${sp.why}`); } catch (e) { T.anomalies.push(`supersession of ${sp.guard} not posted: ${String(e?.message ?? e).slice(0, 160)}`); }