forgedock 1.62.0 → 1.64.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 (87) hide show
  1. package/bin/config-schema.mjs +5 -0
  2. package/bin/engine/outcome-codes.mjs +5 -0
  3. package/bin/engine-cli.mjs +109 -21
  4. package/bin/env/cli.mjs +18 -1
  5. package/bin/lean/basered.mjs +56 -11
  6. package/bin/lean/basered.test.mjs +58 -5
  7. package/bin/lean/batch-health.mjs +46 -4
  8. package/bin/lean/batch-health.test.mjs +55 -1
  9. package/bin/lean/batch.mjs +9 -1
  10. package/bin/lean/batch.test.mjs +74 -7
  11. package/bin/lean/ceiling.mjs +47 -3
  12. package/bin/lean/ceiling.test.mjs +32 -1
  13. package/bin/lean/conformance.e2e.test.mjs +32 -6
  14. package/bin/lean/conformance.mjs +57 -13
  15. package/bin/lean/conformance.test.mjs +93 -1
  16. package/bin/lean/execution.mjs +24 -12
  17. package/bin/lean/execution.test.mjs +59 -9
  18. package/bin/lean/forgedock-lane-workflow.test.mjs +62 -2
  19. package/bin/lean/issuewatch-reconcile.mjs +2 -0
  20. package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
  21. package/bin/lean/issuewatch.mjs +3 -0
  22. package/bin/lean/lanecheck.test.mjs +13 -1
  23. package/bin/lean/lean.mjs +214 -32
  24. package/bin/lean/lean.test.mjs +406 -21
  25. package/bin/lean/live-execution.mjs +25 -0
  26. package/bin/lean/live-execution.test.mjs +35 -1
  27. package/bin/lean/merged-park.mjs +76 -0
  28. package/bin/lean/merged-park.test.mjs +64 -0
  29. package/bin/lean/mergetrain.mjs +357 -0
  30. package/bin/lean/mergetrain.test.mjs +348 -0
  31. package/bin/lean/orchestrate-envhold.test.mjs +62 -0
  32. package/bin/lean/orchestrate-stacking.test.mjs +144 -0
  33. package/bin/lean/orchestrate-train.test.mjs +130 -0
  34. package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
  35. package/bin/lean/orchestrate.mjs +234 -17
  36. package/bin/lean/prompts.mjs +4 -3
  37. package/bin/lean/release-review.mjs +8 -1
  38. package/bin/lean/release-review.test.mjs +42 -2
  39. package/bin/lean/release-status.test.mjs +53 -1
  40. package/bin/lean/release.mjs +6 -3
  41. package/bin/lean/render.mjs +6 -1
  42. package/bin/lean/run-issue-placement.test.mjs +27 -3
  43. package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
  44. package/bin/lean/sandbox-remote.mjs +12 -2
  45. package/bin/lean/sched.mjs +19 -2
  46. package/bin/lean/sched.test.mjs +33 -1
  47. package/bin/lean/schedd-health.mjs +2 -1
  48. package/bin/lean/schedd-health.test.mjs +7 -0
  49. package/bin/lean/schedd.mjs +55 -7
  50. package/bin/lean/schedd.test.mjs +42 -1
  51. package/bin/lean/stacking.mjs +140 -0
  52. package/bin/lean/stacking.test.mjs +98 -0
  53. package/bin/lean/statuscomment.mjs +14 -8
  54. package/bin/lean/statuscomment.test.mjs +18 -1
  55. package/bin/lean/validate-catalog.mjs +1 -1
  56. package/bin/lean/validate-catalog.test.mjs +3 -0
  57. package/bin/lean/worktree.mjs +8 -3
  58. package/bin/lean/worktree.test.mjs +18 -0
  59. package/bin/pool/agent.mjs +325 -46
  60. package/bin/pool/cache-sweep.mjs +2 -0
  61. package/bin/pool/cli.mjs +120 -6
  62. package/bin/pool/disk.mjs +43 -0
  63. package/bin/pool/docker.mjs +21 -5
  64. package/bin/pool/health.mjs +95 -0
  65. package/bin/pool/router.mjs +274 -27
  66. package/bin/runner.mjs +3 -1
  67. package/bin/stats/chains.mjs +101 -0
  68. package/bin/stats/chains.test.mjs +53 -0
  69. package/bin/stats/efficiency.mjs +7 -6
  70. package/bin/stats/efficiency.test.mjs +48 -7
  71. package/bin/stats/index.mjs +11 -3
  72. package/bin/stats/stats.test.mjs +9 -0
  73. package/docs/CONFIG.md +23 -1
  74. package/docs/OUTCOME-CODES.md +4 -0
  75. package/package.json +1 -1
  76. package/pool/README.md +10 -0
  77. package/pool/image/Dockerfile +2 -1
  78. package/pool/image/entrypoint.sh +6 -6
  79. package/pool/image/mirror.sh +71 -0
  80. package/pool/install/install-agent-linux.sh +57 -5
  81. package/pool/install/install-agent-macos.sh +148 -0
  82. package/pool/install/install-agent.ps1 +11 -0
  83. package/pool/install/install-agent.sh +59 -7
  84. package/pool/install/uninstall-agent-linux.sh +75 -0
  85. package/pool/install/uninstall-agent-macos.sh +60 -0
  86. package/pool/install/uninstall-agent.ps1 +1 -0
  87. package/scripts/transition-label.sh +11 -0
@@ -43,6 +43,8 @@ export const TYPES = {
43
43
  "verification.ci_local.extra_commands": "list",
44
44
  "verification.ci_local.budget_minutes": "number",
45
45
  "verification.ci_local.max_parallel": "number",
46
+ "orchestration.merge_train": { enum: ["off", "on"] }, // #5836: lanes end pr-ready and the batch merge train merges (default off)
47
+ "orchestration.merge_train_batch": "posint", // #5837: up to N green PRs of one base validated together on a candidate ref (default 4)
46
48
  "env.snapshots.enabled": "bool",
47
49
  "env.snapshots.store": { enum: ["local", "oci"] },
48
50
  "env.snapshots.keep": "number",
@@ -65,9 +67,11 @@ export const TYPES = {
65
67
  "ci.budget.max_ci_jobs": "number",
66
68
  "ci.budget.monthly_minutes": "number",
67
69
  "ci.budget.shared_regression_job": "scalar",
70
+ "orchestration.stacking": { enum: ["off", "plan", "full"] }, // #5831: plan lanes for dependents of in-batch dependencies (bin/lean/stacking.mjs)
68
71
  "execution.provider": { enum: ["local", "container", "remote", "pool", "actions"] }, // #5748
69
72
  "execution.ci_reserve": "number",
70
73
  "execution.job_limit": "number",
74
+ "execution.public_default": { enum: ["actions"] }, // #5900: opt-in actions lanes for a public repo with no execution.mode
71
75
  "engine.path": { enum: ["core", "full", "lean", "auto"] },
72
76
  "deploy.engine.enabled": "bool",
73
77
  "deploy.engine.stage_timeout_s": "number",
@@ -134,6 +138,7 @@ function typeError(spec, { kind, value }) {
134
138
  if (spec === "list") return kind === "list" ? "" : "a list";
135
139
  if (kind !== "scalar") return "a scalar value";
136
140
  if (spec === "number") return /^-?\d+(\.\d+)?$/.test(bare) ? "" : "a number";
141
+ if (spec === "posint") return /^\d+$/.test(bare) && Number(bare) >= 1 ? "" : "an integer >= 1";
137
142
  if (spec === "bool") return /^(true|false)$/.test(bare) ? "" : "true or false";
138
143
  if (spec && spec.enum) return spec.enum.includes(bare) ? "" : `one of ${spec.enum.join("|")}`;
139
144
  return "";
@@ -65,8 +65,12 @@ export const OUTCOME_CODES = Object.freeze({
65
65
  BASE_RED: "base.red", // forge#5239: a verify.invariants guard fails on the base too; the lane is deferred behind the introducing issue, never needs-human
66
66
  SANDBOX_CAPACITY: "sandbox.capacity", // forge#4254: the sandbox provider had no capacity; deferred with backoff
67
67
  SANDBOX_TRANSIENT: "sandbox.transient", // forge#5095: the sandbox provider answered a 5xx on launch (router/agent infrastructure) or the launch hit a status-less transport error (forge#5656: fetch failed, ECONNRESET, ETIMEDOUT); deferred with backoff, capped by max_deferrals, never needs-human
68
+ SANDBOX_DISK_PRESSURE: "sandbox.disk_pressure", // forge#5891: the agent stopped the lane to save its host drive from filling; the worktree and volume are kept, the requeued lane adopts them
68
69
  SANDBOX_AUTH: "sandbox.auth", // forge#4685: the sandbox provider refused or lacked the credential (HTTP 401/403, no token); deferred, never needs-human
69
70
  SANDBOX_UNREACHABLE: "sandbox.unreachable", // forge#4672: the sandbox provider stayed unreachable past execution.unreachable_window_min; deferred, the sandbox is kept for adopt
71
+ SANDBOX_LOST: "sandbox.lost", // forge#5859: 3+ sandboxes on one pool agent ended without a result within 60s (agent/VM restart); deferred and requeued once, never counted by the breaker or the engine-error relaunch
72
+ SANDBOX_REPO_MISSING: "sandbox.repo_missing", // forge#5890: the lane repo cwd is missing, not a git repo, or git could not spawn there (ENOENT/EACCES); deferred and requeued, never breaker-counted or relaunched as an engine-error
73
+ NET_TRANSIENT: "net.transient", // forge#5947: a git clone/fetch hit a transport failure (curl 56/28, early EOF, invalid index-pack output, unexpected disconnect); deferred with backoff, never breaker-counted or relaunched as an engine-error
70
74
  LEASE_HELD: "lease.held",
71
75
  DEPENDENCY_OPEN: "dependency.open",
72
76
  DESIGN_SPEC_REQUIRED: "design.spec_required", // forge#5330: a page under forge.yaml design.routes has no FORGE:DESIGN_SPEC and design.gate is blocking; needs-human until /design approves a spec
@@ -190,6 +194,7 @@ export function codeForTerminalReason(reason) {
190
194
  case "investigation":
191
195
  return OUTCOME_CODES.COMPLETED;
192
196
  case "awaiting-merge":
197
+ case "pr-ready": // #5836: handed to the merge train
193
198
  case "ci-pending":
194
199
  return OUTCOME_CODES.AWAITING_MERGE;
195
200
  case "invalid": return OUTCOME_CODES.INVALID;
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import { validateForgeYaml, formatFinding } from "./config-schema.mjs";
8
8
  import { parseDocsConfig } from "./lean/docsgate.mjs";
9
+ import { normalizeStacking, parsePlanned, formatPlanned, parseStackedOn, formatStackedOn } from "./lean/stacking.mjs";
9
10
  import { parseOutcomeEvidenceConfig } from "./lean/outcomeevidence.mjs";
10
11
  import { parsePagesConfig, PAGE_RE, designHold } from "./lean/pagegate.mjs";
11
12
  import { parseDesignConfig } from "./lean/design-gate.mjs";
@@ -115,6 +116,24 @@ export function makeIo() {
115
116
  }
116
117
 
117
118
  /** forge.yaml `engine.ci_pending_max_minutes` from the cwd checkout; undefined when absent or invalid. */
119
+ /**
120
+ * #5839: the merge-train A/B reader. Per batch: merged issues per wall-clock hour, slot-hours per merge (summed lane minutes / merged)
121
+ * and post-merge fix sessions (rows that are fix lanes for a merged PR). Compare a batch with orchestration.merge_train on against off at equal parallelism.
122
+ */
123
+ export function mergeThroughput(rows, wallMs) {
124
+ const list = Array.isArray(rows) ? rows : [];
125
+ const merged = list.filter((r) => r?.outcome === "merged").length;
126
+ const slotHours = list.reduce((n, r) => n + (Number(r?.minutes) || 0), 0) / 60;
127
+ const fixes = list.filter((r) => r?.postMergeFix === true || /post-merge fix|broke the merged tree/i.test(String(r?.detail ?? ""))).length;
128
+ const hours = Number(wallMs) > 0 ? wallMs / 3600000 : null;
129
+ return { merged, perHour: hours && merged ? Math.round((merged / hours) * 100) / 100 : null, slotHoursPerMerge: merged ? Math.round((slotHours / merged) * 100) / 100 : null, postMergeFixSessions: fixes };
130
+ }
131
+ export function formatMergeThroughput(rows, wallMs) {
132
+ const t = mergeThroughput(rows, wallMs);
133
+ if (!t.merged) return null;
134
+ return `throughput: merged ${t.merged}, ${t.perHour ?? "n/a"}/hour, slot-hours per merge ${t.slotHoursPerMerge ?? "n/a"}, post-merge fix sessions ${t.postMergeFixSessions}`;
135
+ }
136
+
118
137
  export function readCiPendingMaxMinutes(cwd = process.cwd()) {
119
138
  try {
120
139
  const n = Number(parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.engine?.ci_pending_max_minutes);
@@ -428,6 +447,7 @@ export function readHeavy(cwd = process.cwd()) {
428
447
  * `lane_limits_memory_max`/`lane_limits_cpu_quota`), plus `tasks_max` (#4690, default 1024). `engine.cli_idle_minutes` (default 15) and `engine.cli_max_minutes` (default 180).
429
448
  * `engine.cli_busy_minutes` (default 45, #4405): extra silence allowed while the builder has a live heavy step or heavy-queue entry.
430
449
  * #4390: `engine.context_ceiling_tokens` (default 120000 in runCore; 0 = off).
450
+ * #5829: unset context_ceiling_tokens = `engine.context_window_share` (default 0.5) of the routed model's window; `engine.context_restart_cost_usd` is the cost gate's restart estimate.
431
451
  * #5346: `engine.context_ceiling_by_size` ("S=..,M=..,L=.."; a size without an entry uses context_ceiling_tokens).
432
452
  * #5812: `engine.route_handoff_tokens` (default 40000 in runCore; 0 = always resume): a planning session above it is not resumed by the build, which starts from a digest.
433
453
  * #4392: `engine.turn_budget_s|m|l` (implement turn budget per lane size; defaults 25/60/100, always returned; 0 = off).
@@ -445,6 +465,8 @@ export function readCoreLimits(cwd = process.cwd()) {
445
465
  ...(posNum(y.engine?.cli_max_minutes) ? { cliMaxMinutes: posNum(y.engine.cli_max_minutes) } : {}),
446
466
  ...(posNum(y.engine?.cli_busy_minutes) ? { cliBusyMinutes: posNum(y.engine.cli_busy_minutes) } : {}),
447
467
  ...(/^\d+$/.test(String(y.engine?.context_ceiling_tokens ?? "").trim()) ? { contextCeilingTokens: Number(y.engine.context_ceiling_tokens) } : {}),
468
+ ...(Number(y.engine?.context_window_share) > 0 && Number(y.engine.context_window_share) <= 1 ? { contextWindowShare: Number(y.engine.context_window_share) } : {}), // #5829: default ceiling = this share of the routed model's window
469
+ ...(String(y.engine?.context_restart_cost_usd ?? "").trim() !== "" && Number(y.engine.context_restart_cost_usd) >= 0 ? { contextRestartCostUsd: Number(y.engine.context_restart_cost_usd) } : {}),
448
470
  ...(parseCeilingBySize(y.engine) ? { contextCeilingBySize: parseCeilingBySize(y.engine) } : {}), // #5346
449
471
  ...(/^\d+$/.test(String(y.engine?.route_handoff_tokens ?? "").trim()) ? { routeHandoffTokens: Number(y.engine.route_handoff_tokens) } : {}), // #5812
450
472
  turnBudgets: parseTurnBudgets(y.engine) ?? { ...TURN_BUDGET_DEFAULTS }, // #4392: lanes are budgeted by default
@@ -508,10 +530,10 @@ export function readExecution(cwd = process.cwd()) {
508
530
  export function executionModeExplicit(cwd = process.cwd()) {
509
531
  try { return ["local", "remote", "hybrid"].includes(String(parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"))?.execution?.mode ?? "").trim()); } catch { return false; }
510
532
  }
511
- /** #5748: `exec` with the public-repo default (actions provider) applied; visibility is read once per repo and fails closed to private. */
533
+ /** #5748/#5900: `exec` with the opt-in public-repo default (`execution.public_default: actions`) applied; without the opt-in no API call and no change. Visibility is read once per repo and fails closed to private. */
512
534
  const visibilityCache = new Map();
513
535
  export async function withPublicDefault(exec, { repo, gh, deps = {}, cwd = process.cwd() } = {}) {
514
- if (executionModeExplicit(cwd)) return exec;
536
+ if (exec?.publicDefault !== "actions" || executionModeExplicit(cwd)) return exec;
515
537
  const execMod = await import("./lean/execution.mjs");
516
538
  const key = String(repo ?? "");
517
539
  let isPublic = deps.repoPublic;
@@ -984,7 +1006,7 @@ export function lastLocalRun(dir) {
984
1006
  */
985
1007
  export async function runFromCli(argv, deps = {}) {
986
1008
  const issue = parseInt(argv[0], 10);
987
- if (!Number.isInteger(issue)) throw new Error("usage: forgedock run-issue <issue-number> [--lane <lane>] [--lane-override] [--path core|full] [--recover <code> [--recover-attempt n] [--recover-nonfinal]] [--retry] [--wait-lease] [--local]");
1009
+ if (!Number.isInteger(issue)) throw new Error("usage: forgedock run-issue <issue-number> [--lane <lane>] [--lane-override] [--path core|full] [--recover <code> [--recover-attempt n] [--recover-nonfinal]] [--plan] [--planned <hash>:<sha>] [--retry] [--wait-lease] [--local]");
988
1010
  assertOpenCodeNativeRuntime({ operation: "forgedock run-issue" });
989
1011
  const lane = flag(argv, "--lane");
990
1012
  if (argv.includes("--lane") && (!lane || lane.startsWith("--"))) throw new Error("--lane requires a value: staging or milestone/<slug>");
@@ -994,7 +1016,7 @@ export async function runFromCli(argv, deps = {}) {
994
1016
  const backend = flag(argv, "--backend");
995
1017
  const model = flag(argv, "--model");
996
1018
  // Boolean flag: only counts at a flag position, never as another flag's value.
997
- const retry = argv.some((a, i) => a === "--retry" && !["--lane", "--repo", "--backend", "--model", "--path", "--result-file", "--placement", "--placement-reason", "--recover", "--recover-attempt"].includes(argv[i - 1]));
1019
+ const retry = argv.some((a, i) => a === "--retry" && !["--lane", "--repo", "--backend", "--model", "--path", "--result-file", "--placement", "--placement-reason", "--recover", "--recover-attempt", "--planned", "--stacked-on"].includes(argv[i - 1]));
998
1020
  // forge#3574: --wait-lease blocks (bounded by the lease TTL) until a live
999
1021
  // holder's lease expires or becomes reclaimable. Same flag-position guard.
1000
1022
  const waitLease = argv.some((a, i) => a === "--wait-lease" && !["--lane", "--repo", "--backend", "--model"].includes(argv[i - 1]));
@@ -1017,6 +1039,10 @@ export async function runFromCli(argv, deps = {}) {
1017
1039
  ? { where: placementWhere, reason: String(flag(argv, "--placement-reason") ?? "").slice(0, 300), mode: readExecution()?.mode ?? "local" } : null;
1018
1040
  // #4267: a batch recovery lane for a mechanical needs-human (`--recover <code> [--recover-attempt n]`); #4302: `--recover-nonfinal`
1019
1041
  // marks an attempt the runner may follow with another, so the lane leaves the needs-human relabel to the runner.
1042
+ // #5831: stacked lanes: `--plan` plans a dependent (contract frozen, no build); `--planned <hash>:<sha>` hands its plan to the build lane
1043
+ const plan = argv.includes("--plan");
1044
+ const planned = parsePlanned(flag(argv, "--planned"));
1045
+ const stackedOn = parseStackedOn(flag(argv, "--stacked-on")); // #5832: `<dependency>:<sha>:<branch>`
1020
1046
  const recoverCode = flag(argv, "--recover");
1021
1047
  const recoverAttempt = Number(flag(argv, "--recover-attempt"));
1022
1048
  const recover = recoverCode && !recoverCode.startsWith("--") ? { code: recoverCode, attempt: Number.isInteger(recoverAttempt) && recoverAttempt > 0 ? recoverAttempt : 1, final: !argv.includes("--recover-nonfinal") } : null;
@@ -1109,9 +1135,9 @@ export async function runFromCli(argv, deps = {}) {
1109
1135
  try {
1110
1136
  lres = await runCore({ issue, repo: leanRepo, deferPostRun: true, ...(adopt ? { adopt: true } : {}), ...(lane ? { lane } : {}), laneOverride, branches: readBranches(), cwd: process.cwd(), dir, io: leanIo, path: enginePath, onProgress,
1111
1137
  ...(rotatorKind({ execution: readExecution(process.cwd()), env }) ? { accountRotator: rotatorKind({ execution: readExecution(process.cwd()), env }) } : {}), // #5094, #5205: detected
1112
- onTeardown: (fn) => { teardown = fn; }, ...(env.FORGEDOCK_BATCH_ID ? { batchId: env.FORGEDOCK_BATCH_ID } : {}), ...(placement ? { placement } : {}), ...(recover ? { recover } : {}),
1138
+ onTeardown: (fn) => { teardown = fn; }, ...(env.FORGEDOCK_BATCH_ID ? { batchId: env.FORGEDOCK_BATCH_ID } : {}), ...(placement ? { placement } : {}), ...(recover ? { recover } : {}), ...(plan ? { plan: true } : {}), ...(planned ? { planned } : {}), ...(stackedOn ? { stackedOn } : {}), ...(stackedOn ? { stackedOn } : {}),
1113
1139
  emitTelemetry: deps.emitTelemetry ?? composeEmit(makeEmitTelemetry({ repo: leanRepo }), makeEventEmitter({ repo: leanRepo, config: readEvents() }).emit),
1114
- admission: readAdmission(), heavy: readHeavy(), ...readCoreLimits(), ...readEnvConfig(), ...(readMergeWait() ? { mergeWait: readMergeWait() } : {}), ...(readConformanceMode() ? { conformance: readConformanceMode() } : {}), ...(readConformanceKinds() ? { conformanceKinds: readConformanceKinds() } : {}), ...(readConformanceMutation() ? { conformanceMutation: "report" } : {}), ...(readContextPack() ? { contextPack: readContextPack() } : {}), ...(readSequenceVersioned() ? { sequenceVersioned: readSequenceVersioned() } : {}), ...(readSharedSurfaces() ? { sharedSurfaces: readSharedSurfaces() } : {}), ...(readReviewIncomplete() ? { reviewIncomplete: readReviewIncomplete() } : {}), ...(readLaneInstructions() ? { laneInstructions: readLaneInstructions() } : {}), ...(readReproTest() ? { reproTest: readReproTest() } : {}), ...(readReproQuality() ? { reproQuality: readReproQuality() } : {}), ...(readExplore() ? { explore: readExplore() } : {}), ...(readExperiment() ? { experiment: readExperiment() } : {}), light: readLight(), ...(readCloseParent() ? { closeParent: true } : {}), ...(readReviewTrigger() ? { reviewTrigger: readReviewTrigger() } : {}), ...(readVerify() ? { verify: readVerify() } : {}), ...readPrecheckOptions(), ...(model ? { builderModel: model } : {}), ...(readLeanSetting("reviewer_model") ? { reviewerModel: readLeanSetting("reviewer_model") } : {}), ...(readFixModel() ? { fixModel: readFixModel() } : {}), ...(readBuilderRouting() ? { builderRouting: readBuilderRouting() } : {}), ...(readVerifier() ? { verifier: readVerifier() } : {}), ...(readHostCaps() ? { hostCaps: readHostCaps() } : {}), hostFallback: readHostFallback(), ...readRelayCaps(), ...(readSequenceRegenerate() ? { sequenceRegenerate: readSequenceRegenerate() } : {}), ...(readBaseMerge() ? { baseMerge: readBaseMerge() } : {}), ...(readFollowupsDefaultMilestone() ? { followupsDefaultMilestone: readFollowupsDefaultMilestone() } : {}), ...(readFollowupsRollupLabel() ? { followupsRollupLabel: readFollowupsRollupLabel() } : {}), ...(readCiFailFast() ? { ci: { fail_fast: readCiFailFast() } } : {}), ...(Number.isInteger(Number(readLeanSetting("contract_max_corrections"))) && Number(readLeanSetting("contract_max_corrections")) >= 1 ? { contractMaxCorrections: Number(readLeanSetting("contract_max_corrections")) } : {}), ...(Number.isInteger(Number(readLeanSetting("review_max_resumes"))) && Number(readLeanSetting("review_max_resumes")) >= 1 ? { reviewMaxResumes: Number(readLeanSetting("review_max_resumes")) } : {}) });
1140
+ admission: readAdmission(), heavy: readHeavy(), ...readCoreLimits(), ...readEnvConfig(), ...(readMergeWait() ? { mergeWait: readMergeWait() } : {}), ...(readConformanceMode() ? { conformance: readConformanceMode() } : {}), ...(readConformanceKinds() ? { conformanceKinds: readConformanceKinds() } : {}), ...(readConformanceMutation() ? { conformanceMutation: "report" } : {}), ...(readContextPack() ? { contextPack: readContextPack() } : {}), ...(readSequenceVersioned() ? { sequenceVersioned: readSequenceVersioned() } : {}), ...(readSharedSurfaces() ? { sharedSurfaces: readSharedSurfaces() } : {}), ...(readReviewIncomplete() ? { reviewIncomplete: readReviewIncomplete() } : {}), ...(readLaneInstructions() ? { laneInstructions: readLaneInstructions() } : {}), ...(readReproTest() ? { reproTest: readReproTest() } : {}), ...(readReproQuality() ? { reproQuality: readReproQuality() } : {}), ...(readExplore() ? { explore: readExplore() } : {}), ...(readExperiment() ? { experiment: readExperiment() } : {}), light: readLight(), ...(readCloseParent() ? { closeParent: true } : {}), ...(readOrchestration().mergeTrain === "on" ? { mergeTrain: "on" } : {}), ...(readReviewTrigger() ? { reviewTrigger: readReviewTrigger() } : {}), ...(readVerify() ? { verify: readVerify() } : {}), ...readPrecheckOptions(), ...(model ? { builderModel: model } : {}), ...(readLeanSetting("reviewer_model") ? { reviewerModel: readLeanSetting("reviewer_model") } : {}), ...(readFixModel() ? { fixModel: readFixModel() } : {}), ...(readBuilderRouting() ? { builderRouting: readBuilderRouting() } : {}), ...(readVerifier() ? { verifier: readVerifier() } : {}), ...(readHostCaps() ? { hostCaps: readHostCaps() } : {}), hostFallback: readHostFallback(), ...readRelayCaps(), ...(readSequenceRegenerate() ? { sequenceRegenerate: readSequenceRegenerate() } : {}), ...(readBaseMerge() ? { baseMerge: readBaseMerge() } : {}), ...(readFollowupsDefaultMilestone() ? { followupsDefaultMilestone: readFollowupsDefaultMilestone() } : {}), ...(readFollowupsRollupLabel() ? { followupsRollupLabel: readFollowupsRollupLabel() } : {}), ...(readCiFailFast() ? { ci: { fail_fast: readCiFailFast() } } : {}), ...(Number.isInteger(Number(readLeanSetting("contract_max_corrections"))) && Number(readLeanSetting("contract_max_corrections")) >= 1 ? { contractMaxCorrections: Number(readLeanSetting("contract_max_corrections")) } : {}), ...(Number.isInteger(Number(readLeanSetting("review_max_resumes"))) && Number(readLeanSetting("review_max_resumes")) >= 1 ? { reviewMaxResumes: Number(readLeanSetting("review_max_resumes")) } : {}) });
1115
1141
  } catch (e) { if (!interrupted) report({ terminalReason: "engine-error", detail: String(e?.message ?? e).slice(0, 500) }); throw e; }
1116
1142
  finally { if (!interrupted) for (const [sig, f] of Object.entries(handlers)) off(sig, f); }
1117
1143
  if (interrupted) return lres; // the signal handler reported and exits
@@ -1647,6 +1673,7 @@ async function orchestrateClient(argv, deps = {}) {
1647
1673
  if (sock) execution = (await schedd.request(sock, { op: "set-execution", id, ...patch }, undefined, { timeoutMs: schedd.REQUEST_MS }))?.execution ?? null;
1648
1674
  else { const batchMod = await import("./lean/batch.mjs"); execution = liveExec.applySetExecution(batchMod.openBatch(batchMod.batchRoot(), id), patch); }
1649
1675
  console.log(`batch ${id}: ${liveExec.formatOverride(patch)}`);
1676
+ if (patch.maxRemote !== undefined) { const note = await poolLaneNote(patch.maxRemote, liveExec); if (note) console.log(note); } // #5735
1650
1677
  return { ok: true, batch: id, execution };
1651
1678
  }
1652
1679
  // #4408: --add, and the extra issues of --resume <id> N..., go to the batch (through the daemon when one runs).
@@ -1763,6 +1790,20 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1763
1790
  // #4685: close a tripped breaker without editing state.json; the next --resume (or a running batch's next save) starts closed.
1764
1791
  const b = batchMod.openBatch(root, flag(argv, "--clear-breaker"));
1765
1792
  if (!b.exists()) throw new Error(`no batch ${flag(argv, "--clear-breaker")} in ${root}`);
1793
+ // #5947: a schedd-hosted runner holds the breaker in memory; ask it through the sched socket and say whether it acknowledged.
1794
+ if (!deps.noDaemon) {
1795
+ const schedd = await import("./lean/schedd.mjs");
1796
+ let sock = null;
1797
+ try { sock = await schedd.connectDaemon({ dir: deps.scheddDir ?? (await import("./lean/sched.mjs")).schedDir(), spawnDaemon: null }); } catch { sock = null; }
1798
+ if (sock) {
1799
+ let r = null;
1800
+ try { r = await schedd.request(sock, { op: "clear-breaker", id: b.id }, undefined, { timeoutMs: 15000 }); } catch { r = null; }
1801
+ if (r?.hosted) {
1802
+ sink.line(`batch ${b.id}: ${r.acknowledged ? (r.cleared ? "breaker cleared" : "no breaker was tripped") : "breaker cleared in state.json; the live runner did not acknowledge"}${r.acknowledged ? " (live runner acknowledged)" : ""}`);
1803
+ return { ok: true, batch: b.id, cleared: Boolean(r.cleared), acknowledged: Boolean(r.acknowledged) };
1804
+ }
1805
+ }
1806
+ }
1766
1807
  const st = b.store.load();
1767
1808
  if (st) b.store.save({ ...st, breaker: null, errorTimes: [] });
1768
1809
  sink.line(`batch ${b.id}: ${st?.breaker ? "breaker cleared" : "no breaker was tripped"}`);
@@ -1783,6 +1824,9 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1783
1824
  const { id, patch } = liveExec.parseSetExecution(argv);
1784
1825
  const execution = liveExec.applySetExecution(batchMod.openBatch(root, id), patch);
1785
1826
  sink.line(`batch ${id}: ${liveExec.formatOverride(patch)}`);
1827
+ const drain = liveExec.drainNote(patch);
1828
+ if (drain) sink.line(drain);
1829
+ if (patch.maxRemote !== undefined) { const note = await poolLaneNote(patch.maxRemote, liveExec); if (note) sink.line(note); } // #5735
1786
1830
  return { ok: true, batch: id, execution };
1787
1831
  }
1788
1832
  if (["--show-env", "--set-env", "--unset-env"].some((f) => argv.includes(f))) return envBatch({ argv, root, print: (l) => sink.line(l) });
@@ -1969,9 +2013,9 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1969
2013
  const { runCore } = deps.leanModule;
1970
2014
  const emitTelemetry = deps.emitTelemetry ?? makeEmitTelemetry({ repo });
1971
2015
  lanes = { adopt: null, runOne: (n, ln, ctx = {}) => runCore({ issue: n, repo, lane: ln, deferPostRun: true, // #5437: orchestrate runs result.postRun once the slot is free
1972
- laneOverride, ...(ctx.placement ? { placement: { ...ctx.placement, mode: execMode() } } : {}), ...(ctx.recover ? { recover: ctx.recover } : {}), branches, cwd, dir, io: leanIo, agentId: `orch_${process.pid}_${n}`, emitTelemetry, batchId: batch.id,
2016
+ laneOverride, ...(ctx.placement ? { placement: { ...ctx.placement, mode: execMode() } } : {}), ...(ctx.recover ? { recover: ctx.recover } : {}), ...(ctx.plan ? { plan: true } : {}), ...(ctx.planned ? { planned: ctx.planned } : {}), ...(ctx.stackedOn ? { stackedOn: ctx.stackedOn } : {}), branches, cwd, dir, io: leanIo, agentId: `orch_${process.pid}_${n}`, emitTelemetry, batchId: batch.id,
1973
2017
  ...(rotatorKind({ execution: readExecution(cwd), env }) ? { accountRotator: rotatorKind({ execution: readExecution(cwd), env }) } : {}), // #5094, #5205: detected
1974
- admission: readAdmission(cwd), heavy: readHeavy(cwd), ...readCoreLimits(cwd), ...readEnvConfig(cwd), ...(readMergeWait(cwd) ? { mergeWait: readMergeWait(cwd) } : {}), ...(readConformanceMode(cwd) ? { conformance: readConformanceMode(cwd) } : {}), ...(readConformanceKinds(cwd) ? { conformanceKinds: readConformanceKinds(cwd) } : {}), ...(readConformanceMutation(cwd) ? { conformanceMutation: "report" } : {}), ...(readContextPack(cwd) ? { contextPack: readContextPack(cwd) } : {}), ...(readSequenceVersioned(cwd) ? { sequenceVersioned: readSequenceVersioned(cwd) } : {}), ...(readSharedSurfaces(cwd) ? { sharedSurfaces: readSharedSurfaces(cwd) } : {}), ...(readReviewIncomplete(cwd) ? { reviewIncomplete: readReviewIncomplete(cwd) } : {}), ...(readLaneInstructions(cwd) ? { laneInstructions: readLaneInstructions(cwd) } : {}), ...(readReproTest(cwd) ? { reproTest: readReproTest(cwd) } : {}), ...(readReproQuality(cwd) ? { reproQuality: readReproQuality(cwd) } : {}), ...(readExplore(cwd) ? { explore: readExplore(cwd) } : {}), ...(readExperiment(cwd) ? { experiment: readExperiment(cwd) } : {}), light: readLight(cwd), ...(readCloseParent(cwd) ? { closeParent: true } : {}), ...(readReviewTrigger(cwd) ? { reviewTrigger: readReviewTrigger(cwd) } : {}), ...(readVerify(cwd) ? { verify: readVerify(cwd) } : {}), ...readPrecheckOptions(cwd), ...(model ? { builderModel: model } : {}), ...(readLeanSetting("reviewer_model", cwd) ? { reviewerModel: readLeanSetting("reviewer_model", cwd) } : {}), ...(readFixModel(cwd) ? { fixModel: readFixModel(cwd) } : {}), ...(readBuilderRouting(cwd) ? { builderRouting: readBuilderRouting(cwd) } : {}), ...(readVerifier(cwd) ? { verifier: readVerifier(cwd) } : {}), ...(readHostCaps(cwd) ? { hostCaps: readHostCaps(cwd) } : {}), hostFallback: readHostFallback(cwd), ...readRelayCaps(), ...(readSequenceRegenerate(cwd) ? { sequenceRegenerate: readSequenceRegenerate(cwd) } : {}), ...(readBaseMerge(cwd) ? { baseMerge: readBaseMerge(cwd) } : {}), ...(readFollowupsDefaultMilestone(cwd) ? { followupsDefaultMilestone: readFollowupsDefaultMilestone(cwd) } : {}), ...(readFollowupsRollupLabel(cwd) ? { followupsRollupLabel: readFollowupsRollupLabel(cwd) } : {}), ...(readCiFailFast(cwd) ? { ci: { fail_fast: readCiFailFast(cwd) } } : {}), ...(Number.isInteger(Number(readLeanSetting("contract_max_corrections", cwd))) && Number(readLeanSetting("contract_max_corrections", cwd)) >= 1 ? { contractMaxCorrections: Number(readLeanSetting("contract_max_corrections", cwd)) } : {}), ...(Number.isInteger(Number(readLeanSetting("review_max_resumes", cwd))) && Number(readLeanSetting("review_max_resumes", cwd)) >= 1 ? { reviewMaxResumes: Number(readLeanSetting("review_max_resumes", cwd)) } : {}) }) };
2018
+ admission: readAdmission(cwd), heavy: readHeavy(cwd), ...readCoreLimits(cwd), ...readEnvConfig(cwd), ...(readMergeWait(cwd) ? { mergeWait: readMergeWait(cwd) } : {}), ...(readConformanceMode(cwd) ? { conformance: readConformanceMode(cwd) } : {}), ...(readConformanceKinds(cwd) ? { conformanceKinds: readConformanceKinds(cwd) } : {}), ...(readConformanceMutation(cwd) ? { conformanceMutation: "report" } : {}), ...(readContextPack(cwd) ? { contextPack: readContextPack(cwd) } : {}), ...(readSequenceVersioned(cwd) ? { sequenceVersioned: readSequenceVersioned(cwd) } : {}), ...(readSharedSurfaces(cwd) ? { sharedSurfaces: readSharedSurfaces(cwd) } : {}), ...(readReviewIncomplete(cwd) ? { reviewIncomplete: readReviewIncomplete(cwd) } : {}), ...(readLaneInstructions(cwd) ? { laneInstructions: readLaneInstructions(cwd) } : {}), ...(readReproTest(cwd) ? { reproTest: readReproTest(cwd) } : {}), ...(readReproQuality(cwd) ? { reproQuality: readReproQuality(cwd) } : {}), ...(readExplore(cwd) ? { explore: readExplore(cwd) } : {}), ...(readExperiment(cwd) ? { experiment: readExperiment(cwd) } : {}), light: readLight(cwd), ...(readCloseParent(cwd) ? { closeParent: true } : {}), ...(readOrchestration(cwd).mergeTrain === "on" ? { mergeTrain: "on" } : {}), ...(readReviewTrigger(cwd) ? { reviewTrigger: readReviewTrigger(cwd) } : {}), ...(readVerify(cwd) ? { verify: readVerify(cwd) } : {}), ...readPrecheckOptions(cwd), ...(model ? { builderModel: model } : {}), ...(readLeanSetting("reviewer_model", cwd) ? { reviewerModel: readLeanSetting("reviewer_model", cwd) } : {}), ...(readFixModel(cwd) ? { fixModel: readFixModel(cwd) } : {}), ...(readBuilderRouting(cwd) ? { builderRouting: readBuilderRouting(cwd) } : {}), ...(readVerifier(cwd) ? { verifier: readVerifier(cwd) } : {}), ...(readHostCaps(cwd) ? { hostCaps: readHostCaps(cwd) } : {}), hostFallback: readHostFallback(cwd), ...readRelayCaps(), ...(readSequenceRegenerate(cwd) ? { sequenceRegenerate: readSequenceRegenerate(cwd) } : {}), ...(readBaseMerge(cwd) ? { baseMerge: readBaseMerge(cwd) } : {}), ...(readFollowupsDefaultMilestone(cwd) ? { followupsDefaultMilestone: readFollowupsDefaultMilestone(cwd) } : {}), ...(readFollowupsRollupLabel(cwd) ? { followupsRollupLabel: readFollowupsRollupLabel(cwd) } : {}), ...(readCiFailFast(cwd) ? { ci: { fail_fast: readCiFailFast(cwd) } } : {}), ...(Number.isInteger(Number(readLeanSetting("contract_max_corrections", cwd))) && Number(readLeanSetting("contract_max_corrections", cwd)) >= 1 ? { contractMaxCorrections: Number(readLeanSetting("contract_max_corrections", cwd)) } : {}), ...(Number.isInteger(Number(readLeanSetting("review_max_resumes", cwd))) && Number(readLeanSetting("review_max_resumes", cwd)) >= 1 ? { reviewMaxResumes: Number(readLeanSetting("review_max_resumes", cwd)) } : {}) }) };
1975
2019
  } else {
1976
2020
  const laneScript = deps.laneScript ?? fileURLToPath(new URL("./forgedock.mjs", import.meta.url));
1977
2021
  // #4690: lanes learn K (the default MemoryMax is derived from it); one line says so when no scope caps them.
@@ -1987,12 +2031,16 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1987
2031
  if (uncapped) (deps.out ?? ((l) => console.log(l)))(uncapped);
1988
2032
  // #4256: the placement orchestrate decided for a lane (ctx.placement) reaches it as --placement/--placement-reason.
1989
2033
  // #4267: a recovery lane (ctx.recover) reaches it as --recover/--recover-attempt.
1990
- const placementOf = new Map(), recoverOf = new Map();
1991
- const laneArgs = (n, ln) => { const pl = placementOf.get(n), rc = recoverOf.get(n); return ["--repo", repo, ...(ln ? ["--lane", ln] : []), ...(laneOverride ? ["--lane-override"] : []), ...(model ? ["--model", model] : []),
1992
- ...(pl ? ["--placement", pl.where, "--placement-reason", pl.reason ?? ""] : []), ...(rc ? ["--recover", rc.code, "--recover-attempt", String(rc.attempt ?? 1), ...(rc.final === false ? ["--recover-nonfinal"] : [])] : [])]; };
2034
+ const placementOf = new Map(), recoverOf = new Map(), planOf = new Map(), plannedOf = new Map(), stackedOf = new Map(); // #5831, #5832
2035
+ const laneArgs = (n, ln) => { const pl = placementOf.get(n), rc = recoverOf.get(n), pn = plannedOf.get(n), so = stackedOf.get(n); return ["--repo", repo, ...(ln ? ["--lane", ln] : []), ...(laneOverride ? ["--lane-override"] : []), ...(model ? ["--model", model] : []),
2036
+ ...(pl ? ["--placement", pl.where, "--placement-reason", pl.reason ?? ""] : []), ...(rc ? ["--recover", rc.code, "--recover-attempt", String(rc.attempt ?? 1), ...(rc.final === false ? ["--recover-nonfinal"] : [])] : []),
2037
+ ...(planOf.get(n) ? ["--plan"] : []), ...(pn ? ["--planned", formatPlanned(pn)] : []), ...(so ? ["--stacked-on", formatStackedOn(so)] : [])]; };
1993
2038
  const withPlacement = (l) => ({ runOne: (n, ln, ctx = {}) => {
1994
2039
  if (ctx.placement) placementOf.set(n, ctx.placement); else placementOf.delete(n);
1995
2040
  if (ctx.recover) recoverOf.set(n, ctx.recover); else recoverOf.delete(n);
2041
+ if (ctx.plan) planOf.set(n, true); else planOf.delete(n);
2042
+ if (ctx.planned) plannedOf.set(n, ctx.planned); else plannedOf.delete(n);
2043
+ if (ctx.stackedOn) stackedOf.set(n, ctx.stackedOn); else stackedOf.delete(n);
1996
2044
  return l.runOne(n, ln, ctx);
1997
2045
  }, adopt: l.adopt });
1998
2046
  const execMod = await import("./lean/execution.mjs");
@@ -2000,7 +2048,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2000
2048
  execForNeeds = exec ?? null;
2001
2049
  hybrid = exec?.mode === "hybrid" && Number.isInteger(exec.maxRemote) && exec.maxRemote >= 1;
2002
2050
  let remoteStop = null; // #4612: the sandbox provider's checkpoint stop, used only when the cancel asks for it
2003
- if (exec && (execMod.placement(exec) === "remote" || hybrid)) {
2051
+ if (exec && ((execMod.placement(exec) === "remote" && Number.isInteger(exec.maxRemote) && exec.maxRemote >= 1) || hybrid)) {
2004
2052
  // #4253: lanes run in sandboxes, ledger-tracked per lane, admitted against max_remote instead of the host cap.
2005
2053
  let gitDir = null;
2006
2054
  try { gitDir = resolvePath(cwd, String(await leanIo.git(["rev-parse", "--git-common-dir"], { cwd })).trim()); } catch { gitDir = null; }
@@ -2072,12 +2120,15 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2072
2120
  lanes = { ...lanes, stopLane, releaseLease };
2073
2121
  }
2074
2122
  const orch = deps.orchestration ?? readOrchestration(cwd);
2123
+ const train = orch.mergeTrain === "on" ? (deps.train ?? (await import("./lean/mergetrain.mjs")).createMergeTrain({ gh: (a) => leanIo.gh(a), repo, batchSize: orch.mergeTrainBatch ?? 4,
2124
+ flaky: readYamlList(cwd, "verify", "flaky") ?? [], onBaseRed: async (r) => (await import("./lean/basered.mjs")).reportTrainBaseRed({ ghc: (a) => leanIo.gh(a), repo, ...r }) })) : null; // #5836: off (default) builds nothing; #5838: bisection seams
2075
2125
  // #4965: --auto-children overrides forge.yaml; it is part of plan.argv, so --resume keeps it
2076
2126
  const autoMod = _autoChildren, yamlAuto = readAutoChildren(cwd);
2077
2127
  const autoChildren = { mode: argv.includes("--auto-children") ? autoMod.parseAutoModeFlag(flag(argv, "--auto-children")) : yamlAuto.mode, pollS: yamlAuto.pollS,
2078
2128
  epics: epicsOf(argv) };
2079
2129
  // #4304: recovery lanes run on the core path only (run-issue throws on --recover with full), so a full-path repo gets none.
2080
2130
  const recoveryOn = Boolean(orch.recovery?.maxAttempts) && (deps.enginePath !== undefined ? deps.enginePath : readEnginePath(cwd)) !== "full";
2131
+ const stackingOn = (orch.stacking === "plan" || orch.stacking === "full") && (deps.enginePath !== undefined ? deps.enginePath : readEnginePath(cwd)) !== "full"; // #5831: plan lanes run on the core path only
2081
2132
  if (orch.recovery?.maxAttempts && !recoveryOn) sink.line("recovery: off (engine.path is full; recovery lanes run on the core path only)");
2082
2133
  // #5315: a forge.yaml key that is unknown, ignored by this engine path, mistyped or a deprecated alias is named at batch start, never silent.
2083
2134
  try { for (const f of validateForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8"), { path: deps.enginePath !== undefined ? deps.enginePath : readEnginePath(cwd) })) sink.line(`config: ${formatFinding(f)}`); } catch { /* no forge.yaml: nothing to validate */ }
@@ -2242,8 +2293,15 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2242
2293
  try { healthTimers = batchHealth.scheduleChecks({ batch, created: healthCreated, config: healthConf, now: healthNow, ...(deps.healthTimer ? { setTimer: deps.healthTimer.set, clearTimer: deps.healthTimer.clear } : {}), check: healthCheck }); } catch { /* health is advisory */ }
2243
2294
  let rampProbe = {};
2244
2295
  try { rampProbe = (deps.host ?? (await import("./lean/effects.mjs")).makeHostProbe()); } catch { rampProbe = {}; } // #5845: the live cap subtracts lanes still ramping
2296
+ try { // #5847: report the effective concurrency, its source and a missing forge.yaml; never blocks a batch
2297
+ const host = { cores: () => cpus().length, memAvailableMb, rampingMb: rampProbe.rampingMb };
2298
+ const d = schedMod.describeConcurrency({ parallel, parallelFrom: flag(argv, "--parallel") != null ? "--parallel" : "default", cwd, yamlFound: existsSync(join(cwd, "forge.yaml")),
2299
+ ...(registry ? { registryCap: registry.cap(), globalParallel: orch.globalParallel ?? null, derivedCap: liveLaneCap(null, { cfg: readAdmission(cwd), host })() } : {}) });
2300
+ for (const l of [d.line, ...d.warnings]) sink.line(l);
2301
+ } catch { /* advisory */ }
2245
2302
  try {
2246
2303
  rows = await orchestrate({
2304
+ ...(train ? { train } : {}),
2247
2305
  ...(estimate ? { estimate } : {}),
2248
2306
  beforeAdmit,
2249
2307
  ...(preflight ? { preflight } : {}),
@@ -2251,7 +2309,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2251
2309
  trusted: (n) => trustedOf.get(n) === true,
2252
2310
  autoChildren,
2253
2311
  ...(autoMod.addsEpicChildren(autoChildren.mode) ? { getChildren: async () => ({ list: await autoMod.readChildList({ gh: (a) => leanIo.gh(a), repo, fields: childFields ??= await autoMod.hostListFields((a) => leanIo.gh(a)) }), elsewhere: autoMod.liveElsewhere({ batchMod, root, self: batch.id, repo }) }) } : {}),
2254
- issues, parallel, prefilter, resolveLane: laneOf, store: batch.store, getParallel: batch.readParallel, getAdded: batch.readAdded, getRequeued: batch.readRequeued, getCancelled: batch.readCancel, getHeld: batch.readHeld, expireHolds: batch.expireHolds, getHoldInfo: batch.readHoldInfo, getGates: batch.readGates, baseWait: baseWaits.size ? baseWaitOf(baseWaits, { io, leanIo, cwd }) : null, ...lanes,
2312
+ issues, parallel, prefilter, resolveLane: laneOf, store: batch.store, getParallel: batch.readParallel, getClearBreaker: batch.readClearBreaker, ackClearBreaker: batch.ackClearBreaker, getAdded: batch.readAdded, getRequeued: batch.readRequeued, getCancelled: batch.readCancel, getHeld: batch.readHeld, expireHolds: batch.expireHolds, getHoldInfo: batch.readHoldInfo, getGates: batch.readGates, baseWait: baseWaits.size ? baseWaitOf(baseWaits, { io, leanIo, cwd }) : null, ...lanes,
2255
2313
  breaker: orch.breaker, maxDeferrals: orch.maxDeferrals, ...(Number.isInteger(orch.transientRetries) ? { transientRetries: orch.transientRetries } : {}), ...(deps.pollMs ? { pollMs: deps.pollMs } : {}), ...budget, limits, identity, rotator, batchId: batch.id, drift, lifecycle, integration,
2256
2314
  ...(registry ? { sched: { registry, batch: batch.id, repo, cap: liveLaneCap(orch.globalParallel ?? null, { cfg: readAdmission(cwd), host: { cores: () => cpus().length, memAvailableMb, rampingMb: rampProbe.rampingMb } }), exclusive: true }, priorityOf: async (n) => schedMod.priorityFromLabels(await labelNames(n)) } : {}),
2257
2315
  // #5174: hold new local admissions while loadavg/cores is above engine.overload_load_per_core (host-wide batches only)
@@ -2259,6 +2317,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2259
2317
  ...(remote ? { remote } : {}),
2260
2318
  // #4267: mechanical needs-human outcomes are recovered in the batch; every runner decision is a FORGE:DECISION.
2261
2319
  ...(recoveryOn ? { recovery: orch.recovery } : {}),
2320
+ ...(stackingOn ? { stacking: orch.stacking, ...(orch.stacking === "full" ? { readPrReady: async (n) => (await makeProjector(io, { repo }).readState(n))?.prReady ?? null } : {}) } : {}), // #5831, #5832: PR-ready is read from the dependency lane's FORGE:STATE
2262
2321
  decide: deps.decide ?? (async (d) => {
2263
2322
  if (d?.issue == null) { sink.line(`decision: ${d?.what} (why: ${d?.why}; alternative: ${d?.alternative})`); return; }
2264
2323
  const body = `## Decision (batch ${batch.id})\n**What**: ${d.what}\n**Why**: ${d.why}\n**Alternative**: ${d.alternative}`;
@@ -2320,6 +2379,9 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2320
2379
  if (pfLine) report.push(pfLine);
2321
2380
  let heavyStats = null; // #4169: live heavy-semaphore queue next to the per-phase waits the lanes reported
2322
2381
  try { heavyStats = deps.heavyStats !== undefined ? deps.heavyStats : (await import("./lean/heavy.mjs")).openHeavy(schedMod.schedDir()).stats(); } catch { heavyStats = null; }
2382
+ const trainLine = train ? (await import("./lean/mergetrain.mjs")).formatTrainSummary(train.stats()) : null; // #5836
2383
+ if (trainLine) report.push(trainLine);
2384
+ { const tl = formatMergeThroughput(rows, Date.now() - (Date.parse(batch.startedAt ?? batch.started_at ?? "") || NaN)); if (tl) report.push(tl); } // #5839
2323
2385
  const waitLine = formatWaitSummary(rows, heavyStats);
2324
2386
  if (waitLine) report.push(waitLine);
2325
2387
  report.push(formatLedgerSummary(rows)); // #4908: per-phase wall time, n/a without ledger rows
@@ -2339,6 +2401,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2339
2401
  report.push(await budgetReportLine({ cwd, repo, gh: (a) => leanIo.gh(a) })); // #5278: month usage, projection and any auto switch to local-first
2340
2402
  const adequacyLine = formatTestAdequacySummary(rows); // #5449
2341
2403
  if (adequacyLine) report.push(adequacyLine);
2404
+ try { const cl = (await import("./lean/stacking.mjs")).formatCascadeSummary(rows); if (cl) report.push(cl); } catch { /* #5833: the cascade line never fails a batch */ }
2342
2405
  const shadowLine = formatShadowSummary(rows); // #4398
2343
2406
  if (shadowLine) report.push(shadowLine);
2344
2407
  const decompLine = formatDecompositionSummary(rows); // #4396
@@ -2364,7 +2427,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2364
2427
  // #4917: a batch with any pending issue is not finished: no report, so a resume or the daemon picks it up
2365
2428
  let unfinished = false;
2366
2429
  try { unfinished = (batch.pendingIssues().length > 0 || batch.unrunAdds().length > 0 || batch.unrunRequeues().length > 0) && !batch.readCancel(); } catch { unfinished = false; } // a cancel ends the batch for good
2367
- if (!unfinished) try { batch.writeReport({ rows, crossLane, ok, reclaimed, ...(dag?.edges ? { dag: { planned: dag.edges.length, falseHolds: removedEdges } } : {}), report: report.join("\n") }); } catch { /* the report is a cache of the rows */ }
2430
+ if (!unfinished) try { batch.writeReport({ rows, crossLane, ok, reclaimed, ...(rows.some((r) => r.stacked) ? { cascades: (await import("./lean/stacking.mjs")).cascadeRate(rows) } : {}), ...(dag?.edges ? { dag: { planned: dag.edges.length, falseHolds: removedEdges } } : {}), report: report.join("\n") }); } catch { /* the report is a cache of the rows */ }
2368
2431
  try { await healthCheck("end"); } catch { /* #5167: health never fails a batch */ }
2369
2432
  return { rows, crossLane, batch: batch.id, reclaimed, ok };
2370
2433
  }
@@ -2445,18 +2508,21 @@ export function makeDispatchCheck({ gh, repo, owner: batchOwner = null, batchId
2445
2508
  }
2446
2509
 
2447
2510
  /**
2448
- * #4318: the batch runner's needs-human relabel. Re-reads the issue first: closed, or a live FORGE:STATE lease (the runner
2449
- * never holds one, so it is another actor's) → "skipped". Label first: a failed label add → "failed" with no comment (a
2511
+ * #4318: the batch runner's needs-human relabel. Re-reads the issue first: closed, a live FORGE:STATE lease (the runner
2512
+ * never holds one, so it is another actor's), or a merged fix not reopened since (#5759) → "skipped". Label first: a failed label add → "failed" with no comment (a
2450
2513
  * resume retries); then the capped FORGE:NEEDS_HUMAN comment, whose failure keeps the label → true.
2451
2514
  */
2452
2515
  export function makeRelabelNeedsHuman({ gh, repo, now = () => Date.now() }) {
2453
2516
  return async ({ issue, evidence, parked = null }) => {
2454
2517
  const { stateOf } = await import("./lean/context.mjs");
2455
2518
  try {
2456
- const v = JSON.parse(await gh(["issue", "view", String(issue), "-R", repo, "--json", "state,body"]));
2519
+ const v = JSON.parse(await gh(["issue", "view", String(issue), "-R", repo, "--json", "state,body,labels,closedByPullRequestsReferences"]));
2457
2520
  if (String(v?.state ?? "").toUpperCase() === "CLOSED") return "skipped";
2458
2521
  const lease = stateOf(v?.body)?.lease;
2459
2522
  if (lease && Number(lease.until) > now()) return "skipped";
2523
+ // #5759: a fix that already merged (any head) is not parked; an issue reopened after the merge still is
2524
+ const { mergedEvidence } = await import("./lean/merged-park.mjs");
2525
+ if (await mergedEvidence({ gh, repo, issue, view: v })) return "skipped";
2460
2526
  } catch { /* unreadable: relabel as before */ }
2461
2527
  // #4656: a mechanical park carries its code and PR on `parked:<code>` and joins the remediation queue, not the human queue.
2462
2528
  if (parked?.code) {
@@ -2614,7 +2680,9 @@ export async function scheddFromCli(argv, deps = {}) {
2614
2680
  for (const b of st.batches) {
2615
2681
  const age = b.lastProgressAgeSec == null ? "no progress yet" : `last progress ${b.lastProgressAgeSec}s ago`;
2616
2682
  const pend = b.pendingAdds?.length ? `, pending adds: ${b.pendingAdds.map((n) => `#${n}`).join(" ")}` : "";
2617
- console.log(` ${b.id}${b.running ? "" : " (not hosted)"}: ${age}${pend}`);
2683
+ const ln = b.lanes ? `, running ${b.lanes.running}/${b.lanes.k} (local ${b.lanes.local}, remote ${b.lanes.remote})` : "";
2684
+ const alive = b.lanesAliveAgeSec == null ? "" : `, lanes alive ${b.lanesAliveAgeSec}s ago`;
2685
+ console.log(` ${b.id}${b.running ? "" : " (not hosted)"}: ${age}${ln}${alive}${pend}`);
2618
2686
  }
2619
2687
  for (const l of schedd.sharedPendingLines(st.batches)) console.log(l); // #5471
2620
2688
  if (st.host) { const h = formatOverload(st.host) ?? formatHostLoad(st.host); if (h) console.log(`schedd: ${st.host.overloaded ? h : `host ${h}`}`); } // #5174
@@ -2632,7 +2700,8 @@ export async function scheddFromCli(argv, deps = {}) {
2632
2700
  const bm = await import("./lean/batch.mjs");
2633
2701
  const unfinished = () => { const root = bm.batchRoot(); return bm.listBatches(root).filter((id) => { try { const b = bm.openBatch(root, id); const br = b.store.peek()?.breaker; return !!b.readPlan()?.daemon && !b.isTerminal() && b.pendingIssues().length > 0 && !(br && !br.transport); } catch { return false; } }); };
2634
2702
  const start = () => { if (schedd.unitState() === null) schedd.defaultSpawn({ dir }); else schedd.startUnit(); };
2635
- return (deps.watchdog ?? health.watchdog)({ dir, ...(sec > 0 ? { stallMs: sec * 1000 } : {}), unfinished, start });
2703
+ const batchVerdicts = () => schedd.batchVerdicts(bm.batchRoot());
2704
+ return (deps.watchdog ?? health.watchdog)({ dir, ...(sec > 0 ? { stallMs: sec * 1000 } : {}), unfinished, start, batchVerdicts });
2636
2705
  }
2637
2706
  if (argv.length) throw new Error("usage: forgedock schedd [status | watchdog [--stall-sec N]]");
2638
2707
  (deps.renice ?? (await import("./lean/schedd-health.mjs")).bestEffortRenice)(); // #4780: lanes must not starve the scheduler
@@ -2821,7 +2890,9 @@ export async function schedFromCli(argv, deps = {}) {
2821
2890
  console.log(`repo weights: ${ws.length ? ws.map(([r, n]) => `${r}=${n}`).join(", ") : "equal (none set)"}`);
2822
2891
  for (const e of st.slots) console.log(` running ${who(e)} dispatcher ${e.pid}${e.lanePid ? ` lane ${e.lanePid}` : ""}`);
2823
2892
  for (const e of st.queue) console.log(` queued ${who(e)} dispatcher ${e.pid}`);
2824
- for (const l of schedMod.remoteLines(st)) console.log(l); // #4964
2893
+ const batchMod = await import("./lean/batch.mjs");
2894
+ const agentOf = (e) => { const bm = batchMod; const r = bm.openBatch(bm.batchRoot(), e.batch).store.peek()?.running?.[e.issue]; return r?.placement?.agent ?? r?.agent ?? null; };
2895
+ for (const l of schedMod.remoteLines(st, { agentOf })) console.log(l); // #4964
2825
2896
  try { for (const l of (await import("./lean/batch-health.mjs")).summaryLines((await import("./lean/batch.mjs")).batchRoot())) console.log(l); } catch { /* advisory */ } // #5314
2826
2897
  return st;
2827
2898
  }
@@ -2874,7 +2945,8 @@ export function readOrchestration(cwd = process.cwd()) {
2874
2945
  const errors = int(o.breaker_errors ?? o.errors, 3), windowMin = int(o.breaker_window_min ?? o.window_min, 30);
2875
2946
  const gp = int(o.global_parallel, null);
2876
2947
  const recoveryMax = int(o.recovery_max_attempts ?? o.max_attempts, 1);
2877
- return { breaker: errors > 0 && windowMin > 0 ? { errors, window_min: windowMin } : null, maxDeferrals: int(o.max_deferrals, 3), transientRetries: int(o.transient_retries, 4), blockedLabel: String(o.blocked_label ?? "blocked").trim(), globalParallel: gp >= 1 ? gp : null,
2948
+ return { mergeTrain: String(o.merge_train ?? "off").trim().toLowerCase() === "on" ? "on" : "off", /* #5836 */ mergeTrainBatch: int(o.merge_train_batch, 4) >= 1 ? int(o.merge_train_batch, 4) : 4, /* #5837 */ breaker: errors > 0 && windowMin > 0 ? { errors, window_min: windowMin } : null, maxDeferrals: int(o.max_deferrals, 3), transientRetries: int(o.transient_retries, 4), blockedLabel: String(o.blocked_label ?? "blocked").trim(), globalParallel: gp >= 1 ? gp : null,
2949
+ stacking: normalizeStacking(o.stacking), // #5831
2878
2950
  recovery: { maxAttempts: recoveryMax, mechanicalMaxAttempts: Math.max(int(o.recovery_mechanical_max_attempts ?? o.mechanical_max_attempts, 2), recoveryMax) }, // #4725: env/base/sequence codes have their own budget
2879
2951
  // #4525: parked-PR base sync. The parser flattens one level, so `base_sync.enabled|union_globs` arrive as `enabled|union_globs` (or flat `base_sync_*`).
2880
2952
  baseSync: { enabled: String(o.base_sync_enabled ?? o.enabled ?? "true").trim().toLowerCase() !== "false",
@@ -3146,3 +3218,19 @@ export async function probeFromCli(argv, deps = {}) {
3146
3218
  console.log(formatProbeSummary(rows) || "probes: nothing to run");
3147
3219
  return { rows };
3148
3220
  }
3221
+
3222
+ /**
3223
+ * #5735: the `--set-max-remote` lane note (live-execution.mjs remoteLaneNote) from the pool router's `GET /agents`.
3224
+ * Best effort: no router, an error or no answer within ~5 s gives null, so the set itself never fails because of it.
3225
+ */
3226
+ async function poolLaneNote(n, liveExec, { env = process.env, timeoutMs = 5000 } = {}) {
3227
+ let timer = null;
3228
+ try {
3229
+ const { poolRouterConfig, remoteTransportFor } = await import("./lean/execution.mjs");
3230
+ const endpoint = poolRouterConfig({ env })?.endpoint;
3231
+ if (!endpoint) return null;
3232
+ const t = remoteTransportFor({ provider: "pool", endpoint }, { env });
3233
+ const lanes = await Promise.race([t.agentLanes(), new Promise((resolve) => { timer = setTimeout(() => resolve(null), timeoutMs); timer.unref?.(); })]);
3234
+ return liveExec.remoteLaneNote(n, lanes);
3235
+ } catch { return null; } finally { clearTimeout(timer); }
3236
+ }
package/bin/env/cli.mjs CHANGED
@@ -36,6 +36,17 @@ function parseArgs(argv) {
36
36
  }
37
37
  return o;
38
38
  }
39
+ /** #5947: a bare mirror is usable when it has refs (packed-refs entries or refs/ files) and no zero-length object or pack file. */
40
+ export function mirrorHealthy(fs, dir) {
41
+ try {
42
+ const walk = (d, f) => { for (const e of fs.readdirSync(d, { withFileTypes: true })) { const p = join(d, e.name); if (e.isDirectory()) { if (!walk(p, f)) return false; } else if (!f(p)) return false; } return true; };
43
+ let refs = false;
44
+ try { refs = fs.readFileSync(join(dir, "packed-refs"), "utf8").split("\n").some((l) => /^[0-9a-f]{40,64} /.test(l)); } catch { /* no packed-refs */ }
45
+ if (!refs && fs.existsSync(join(dir, "refs"))) refs = !walk(join(dir, "refs"), () => false);
46
+ if (!refs) return false;
47
+ return !fs.existsSync(join(dir, "objects")) || walk(join(dir, "objects"), (p) => fs.statSync(p).size > 0);
48
+ } catch { return false; }
49
+ }
39
50
  const num = (v, def) => (v !== undefined && /^\d+$/.test(String(v)) ? Number(v) : def);
40
51
  const gb = (n) => (Number.isFinite(n) ? `${(n / 2 ** 30).toFixed(2)} GB` : "?");
41
52
 
@@ -117,8 +128,14 @@ export async function envFromCli(argv, { fs = nodeFs, exec = defaultExec, out =
117
128
  // Pool-host helper (bin/pool/agent.mjs envEnsureArgs). A missing mirror or a failed install leaves lanes on today's path.
118
129
  const prefix = o.prefix ?? ENV_PREFIX;
119
130
  if (!o.mirror || !fs.existsSync(o.mirror)) { out(`env ensure: mirror ${o.mirror ?? "(none)"} not ready`); return 0; }
131
+ // #5947: a mirror with no refs or a zero-length object (a timed-out build) is not trusted: clone direct from the repo URL, else report not ready.
132
+ let src = o.mirror;
133
+ if (!mirrorHealthy(fs, o.mirror)) {
134
+ if (!o.url) { out(`env ensure: mirror ${o.mirror} is not healthy (no refs or an empty object); not ready`); return 0; }
135
+ src = o.url;
136
+ }
120
137
  if (fs.existsSync(prefix)) { process.stderr.write(`env ensure: ${prefix} already exists (run in a fresh build container)\n`); return 1; }
121
- try { await exec("git", ["clone", "--quiet", "--shared", ...(o.ref ? ["--branch", o.ref] : []), o.mirror, prefix], { timeoutMs: 10 * 60000 }); }
138
+ try { await exec("git", ["clone", "--quiet", ...(src === o.mirror ? ["--shared"] : []), ...(o.ref ? ["--branch", o.ref] : []), src, prefix], { timeoutMs: 10 * 60000 }); }
122
139
  catch (e) { process.stderr.write(`env ensure: clone failed: ${String(e.stderr || e.message).slice(0, 300)}\n`); return 1; }
123
140
  const d = await describe(prefix);
124
141
  const r = await buildLocal({ wt: prefix, deps, store, desc: d, fs, exec, repo: o.repo ?? null, ref: o.ref ?? null, commit: await git(prefix, ["rev-parse", "HEAD"]) });
@@ -12,17 +12,20 @@ import { join } from "node:path";
12
12
 
13
13
  const TIMEOUT_RC = 124, MISSING_RC = 127;
14
14
  const FILE_RE = /(?:^|[\s"'`(=:])((?:\.{0,2}\/)?[\w.-]+(?:\/[\w.-]+)+\.(?:py|mjs|cjs|js|jsx|ts|tsx|go|rs|rb|sh|ya?ml|json))\b/g;
15
+ const ENV_RE = /ModuleNotFoundError|ImportError|fail(?:s|ed)? closed|unknown revision|bad revision|not a valid ref|Needed a single revision/i;
16
+ const OUTPUT_TAIL = 4096, DAY_MS = 86400000;
15
17
  const TEST_RE = /(?:^|[/_.-])(?:tests?|spec)(?:[/_.-]|$)/i;
16
18
 
17
19
  /** Split failed `{command, rc}` rows by their base run `{command, rc}`: base red only when the base run itself failed (a timeout or missing runner is no evidence, so the failure stays the lane's). */
18
20
  export function classifyBaseRed({ failed = [], baseRuns = [] } = {}) {
19
21
  const byCmd = new Map((baseRuns ?? []).map((b) => [b?.command, b]));
20
- const laneOwn = [], baseRed = [];
22
+ const laneOwn = [], baseRed = [], env = [];
21
23
  for (const f of failed ?? []) {
22
24
  const b = byCmd.get(f.command), rc = Number(b?.rc);
23
- (b && Number.isInteger(rc) && rc !== 0 && rc !== TIMEOUT_RC && rc !== MISSING_RC ? baseRed : laneOwn).push(f);
25
+ if (!(b && Number.isInteger(rc) && rc !== 0 && rc !== TIMEOUT_RC && rc !== MISSING_RC)) laneOwn.push(f);
26
+ else (ENV_RE.test(String(b.output ?? "")) ? env : baseRed).push(f); // an environment signature in the base output is no evidence the base is red
24
27
  }
25
- return { laneOwn, baseRed };
28
+ return { laneOwn, baseRed, env };
26
29
  }
27
30
 
28
31
  /** Repo-relative file paths named in a command and its failure output, non-test paths first (the guarded code, not the guard). */
@@ -65,18 +68,20 @@ export async function attribute({ failed = [], git, base } = {}) {
65
68
  return null;
66
69
  }
67
70
 
68
- /** Run each command once on a detached worktree of `mergeBase`, returning `[{command, rc}]`; removed afterwards. Empty when the worktree cannot be made (every failure then stays the lane's). */
71
+ /** Run each command once on a detached worktree of `mergeBase`, returning `[{command, rc, output}]` (output: ~4KB tail), with BASE_SHA and LANE_CHECK_BASE set to the merge base sha so diff-scoped guards see an empty diff; removed afterwards. Empty when the worktree cannot be made (every failure then stays the lane's). */
69
72
  export async function runOnBase({ commands = [], git, runCommand, mergeBase, cwd, env, timeoutMs, fs = nodeFs } = {}) {
70
73
  let dir = null;
71
74
  const out = [];
72
75
  try {
73
76
  dir = fs.mkdtempSync(join(tmpdir(), "basered-"));
74
77
  await git(["worktree", "add", "--detach", dir, mergeBase]);
78
+ let sha = ""; try { sha = String(await git(["rev-parse", mergeBase])).trim(); } catch { /* fall back to the ref */ }
79
+ env = { ...(env ?? {}), BASE_SHA: sha || mergeBase, LANE_CHECK_BASE: sha || mergeBase };
75
80
  try { if (fs.existsSync(join(cwd, "node_modules"))) fs.symlinkSync(join(cwd, "node_modules"), join(dir, "node_modules")); } catch { /* best effort */ }
76
81
  for (const command of commands) {
77
82
  let r;
78
83
  try { r = await runCommand({ command, cwd: dir, timeoutMs, env }); } catch (e) { r = { rc: MISSING_RC, output: String(e?.message ?? e) }; }
79
- out.push({ command, rc: Number.isInteger(r?.rc) ? r.rc : 1 });
84
+ out.push({ command, rc: Number.isInteger(r?.rc) ? r.rc : 1, output: String(r?.output ?? "").slice(-OUTPUT_TAIL) });
80
85
  }
81
86
  } catch { /* no base tree: no verdict */ } finally {
82
87
  if (dir) {
@@ -87,10 +92,15 @@ export async function runOnBase({ commands = [], git, runCommand, mergeBase, cwd
87
92
  return out;
88
93
  }
89
94
 
90
- /** Comment body that marks the introducing issue (or the new tracking issue) as the cause of a red base. */
91
- export function baseRedNote({ base, att, laneIssue, commands }) {
95
+ /** Dedupe key line (base + sha12) searched for before a new issue is filed. */
96
+ export function baseRedKey(base, sha) { return sha ? `<!-- FORGE:BASE_RED_KEY ${base}@${String(sha).slice(0, 12)} -->` : ""; }
97
+
98
+ /** Comment body that marks the introducing issue (or the new tracking issue) as the cause of a red base; `outputs` maps command to the base run's output tail. */
99
+ export function baseRedNote({ base, att, laneIssue, commands, outputs = {}, sha }) {
92
100
  const cmds = commands.map((c) => `- \`${c}\``).join("\n");
93
- return `<!-- FORGE:BASE_RED -->\n## Base is red\nThese guard command(s) fail on \`${base}\`${att ? ` at \`${att.sha.slice(0, 12)}\` or earlier; last change to the files they name: \`${att.sha.slice(0, 12)}\` ${att.subject}` : ""}:\n${cmds}\n\nLane #${laneIssue} is deferred behind the fix; it is not needs-human. Fix the base (or reopen this issue) and the lane resumes.`;
101
+ const tails = commands.filter((c) => outputs?.[c]).map((c) => `Base output of \`${c}\` (tail):\n\`\`\`\n${String(outputs[c]).slice(-OUTPUT_TAIL).replace(/```/g, "’’’")}\n\`\`\``).join("\n\n");
102
+ const key = baseRedKey(base, att?.sha ?? sha);
103
+ return `<!-- FORGE:BASE_RED -->\n${key ? `${key}\n` : ""}## Base is red\nThese guard command(s) fail on \`${base}\`${att ? ` at \`${att.sha.slice(0, 12)}\` or earlier; last change to the files they name: \`${att.sha.slice(0, 12)}\` ${att.subject}` : ""}:\n${cmds}\n\n${tails ? `${tails}\n\n` : ""}Lane #${laneIssue} is deferred behind the fix; it is not needs-human. Fix the base (or reopen this issue) and the lane resumes.`;
94
104
  }
95
105
 
96
106
  /**
@@ -98,8 +108,31 @@ export function baseRedNote({ base, att, laneIssue, commands }) {
98
108
  * issue gets a comment and is reopened when closed; no issue number files a new `base-red` tracking issue. Returns the
99
109
  * issue number, or null when GitHub could not be written (the lane still defers).
100
110
  */
101
- export async function reportBaseRed({ ghc, repo, base, att, laneIssue, commands }) {
102
- const body = baseRedNote({ base, att, laneIssue, commands });
111
+ export async function reportBaseRed({ ghc, repo, base, att, laneIssue, commands, outputs, baseSha, commitDate }) {
112
+ return fileBaseRed({ ghc, repo, att, key: baseRedKey(base, att?.sha ?? baseSha), commitDate, body: baseRedNote({ base, att, laneIssue, commands, outputs, sha: baseSha }), title: `fix: ${base} is red on guard command ${commands[0] ?? ""}` });
113
+ }
114
+
115
+ /**
116
+ * #5838: the merge train found `checks` red on the bare `base` tip `baseSha` while bisecting batch `batch`: a red base, not a
117
+ * culprit, so no PR is handed back. Filed through the same red-base path (a `base-red` tracking issue); returns its number or null.
118
+ */
119
+ export async function reportTrainBaseRed({ ghc, repo, base, baseSha, checks = [], batch }) {
120
+ const list = checks.map((c) => `- \`${c.name}\`${c.url ? ` ${c.url}` : ""}`).join("\n");
121
+ const key = baseRedKey(base, baseSha);
122
+ const body = `<!-- FORGE:BASE_RED -->\n${key ? `${key}\n` : ""}## Base is red\nThese required check(s) fail on the bare \`${base}\` tip \`${String(baseSha ?? "").slice(0, 12)}\`, found while bisecting merge-train batch ${batch}:\n${list}\n\nNo PR of the batch is handed back; they stay in the train and merge once the base is fixed.`;
123
+ return fileBaseRed({ ghc, repo, att: null, key, body, title: `fix: ${base} is red on required check ${checks[0]?.name ?? ""}` });
124
+ }
125
+
126
+ /** Issues carrying `key`, newest first: [{number, state, closedAt, createdAt}]. Empty on any failure. */
127
+ async function findKeyed({ ghc, repo, key }) {
128
+ try {
129
+ const raw = await ghc(["issue", "list", "-R", repo, "--state", "all", "--search", `${key.replace(/^<!-- | -->$/g, "")} in:body`, "--json", "number,state,closedAt,createdAt,body", "--limit", "20"]);
130
+ const rows = JSON.parse(String(raw));
131
+ return (Array.isArray(rows) ? rows : []).filter((r) => String(r?.body ?? "").includes(key)).sort((x, y) => Number(y.number) - Number(x.number));
132
+ } catch { return []; }
133
+ }
134
+
135
+ async function fileBaseRed({ ghc, repo, att, body, title, key, commitDate }) {
103
136
  try {
104
137
  if (att?.issue) {
105
138
  let state = "";
@@ -108,7 +141,19 @@ export async function reportBaseRed({ ghc, repo, base, att, laneIssue, commands
108
141
  await ghc(["issue", "comment", String(att.issue), "-R", repo, "--body", body]);
109
142
  return att.issue;
110
143
  }
111
- const url = String(await ghc(["issue", "create", "-R", repo, "--title", `fix: ${base} is red on guard command ${commands[0] ?? ""}`.slice(0, 120), "--body", body])).trim();
144
+ if (key) {
145
+ const hits = await findKeyed({ ghc, repo, key }), cut = Date.parse(commitDate ?? "");
146
+ const open = hits.find((h) => String(h.state).toUpperCase() === "OPEN");
147
+ const reopen = !open && hits.find((h) => Number.isFinite(cut) && Date.parse(h.closedAt) > cut);
148
+ const recent = !open && !reopen && hits.find((h) => Date.now() - Date.parse(h.createdAt) < DAY_MS); // at most one new issue per base+SHA per day
149
+ const hit = open ?? reopen ?? recent;
150
+ if (hit) {
151
+ if (hit === reopen) await ghc(["issue", "reopen", String(hit.number), "-R", repo]);
152
+ await ghc(["issue", "comment", String(hit.number), "-R", repo, "--body", body]);
153
+ return Number(hit.number);
154
+ }
155
+ }
156
+ const url = String(await ghc(["issue", "create", "-R", repo, "--title", title.slice(0, 120), "--body", body])).trim();
112
157
  const n = url.match(/\/issues\/(\d+)/);
113
158
  return n ? Number(n[1]) : null;
114
159
  } catch { return null; }