forgedock 1.63.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 (84) hide show
  1. package/bin/config-schema.mjs +3 -0
  2. package/bin/engine/outcome-codes.mjs +5 -0
  3. package/bin/engine-cli.mjs +88 -12
  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 +6 -1
  10. package/bin/lean/batch.test.mjs +71 -6
  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 +15 -6
  17. package/bin/lean/execution.test.mjs +44 -3
  18. package/bin/lean/issuewatch-reconcile.mjs +2 -0
  19. package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
  20. package/bin/lean/issuewatch.mjs +3 -0
  21. package/bin/lean/lanecheck.test.mjs +13 -1
  22. package/bin/lean/lean.mjs +157 -28
  23. package/bin/lean/lean.test.mjs +289 -21
  24. package/bin/lean/live-execution.mjs +25 -0
  25. package/bin/lean/live-execution.test.mjs +35 -1
  26. package/bin/lean/merged-park.mjs +76 -0
  27. package/bin/lean/merged-park.test.mjs +64 -0
  28. package/bin/lean/mergetrain.mjs +357 -0
  29. package/bin/lean/mergetrain.test.mjs +348 -0
  30. package/bin/lean/orchestrate-envhold.test.mjs +62 -0
  31. package/bin/lean/orchestrate-stacking.test.mjs +23 -1
  32. package/bin/lean/orchestrate-train.test.mjs +130 -0
  33. package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
  34. package/bin/lean/orchestrate.mjs +159 -13
  35. package/bin/lean/prompts.mjs +4 -3
  36. package/bin/lean/release-review.mjs +8 -1
  37. package/bin/lean/release-review.test.mjs +42 -2
  38. package/bin/lean/release-status.test.mjs +53 -1
  39. package/bin/lean/release.mjs +6 -3
  40. package/bin/lean/render.mjs +6 -1
  41. package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
  42. package/bin/lean/sandbox-remote.mjs +12 -2
  43. package/bin/lean/sched.mjs +19 -2
  44. package/bin/lean/sched.test.mjs +33 -1
  45. package/bin/lean/schedd-health.mjs +2 -1
  46. package/bin/lean/schedd-health.test.mjs +7 -0
  47. package/bin/lean/schedd.mjs +55 -7
  48. package/bin/lean/schedd.test.mjs +42 -1
  49. package/bin/lean/stacking.mjs +45 -0
  50. package/bin/lean/stacking.test.mjs +25 -1
  51. package/bin/lean/statuscomment.mjs +14 -8
  52. package/bin/lean/statuscomment.test.mjs +18 -1
  53. package/bin/lean/validate-catalog.mjs +1 -1
  54. package/bin/lean/validate-catalog.test.mjs +3 -0
  55. package/bin/lean/worktree.mjs +8 -3
  56. package/bin/lean/worktree.test.mjs +18 -0
  57. package/bin/pool/agent.mjs +296 -31
  58. package/bin/pool/cli.mjs +120 -6
  59. package/bin/pool/disk.mjs +43 -0
  60. package/bin/pool/docker.mjs +10 -0
  61. package/bin/pool/health.mjs +95 -0
  62. package/bin/pool/router.mjs +274 -27
  63. package/bin/runner.mjs +3 -1
  64. package/bin/stats/chains.mjs +101 -0
  65. package/bin/stats/chains.test.mjs +53 -0
  66. package/bin/stats/efficiency.mjs +7 -6
  67. package/bin/stats/efficiency.test.mjs +48 -7
  68. package/bin/stats/index.mjs +11 -3
  69. package/bin/stats/stats.test.mjs +9 -0
  70. package/docs/CONFIG.md +8 -1
  71. package/docs/OUTCOME-CODES.md +4 -0
  72. package/package.json +1 -1
  73. package/pool/README.md +10 -0
  74. package/pool/image/Dockerfile +2 -1
  75. package/pool/image/entrypoint.sh +6 -6
  76. package/pool/image/mirror.sh +71 -0
  77. package/pool/install/install-agent-linux.sh +57 -5
  78. package/pool/install/install-agent-macos.sh +148 -0
  79. package/pool/install/install-agent.ps1 +11 -0
  80. package/pool/install/install-agent.sh +59 -7
  81. package/pool/install/uninstall-agent-linux.sh +75 -0
  82. package/pool/install/uninstall-agent-macos.sh +60 -0
  83. package/pool/install/uninstall-agent.ps1 +1 -0
  84. package/scripts/transition-label.sh +11 -0
@@ -5,7 +5,7 @@ import { writeFileSync } from "node:fs";
5
5
  import { tmpDir } from "../tests/_tmp.mjs";
6
6
  import { join } from "node:path";
7
7
  import assert from "node:assert/strict";
8
- import { releaseFromCli, gateState } from "./release.mjs";
8
+ import { releaseFromCli, withStubs, gateState } from "./release.mjs";
9
9
  import { controlFromCli, VERBS } from "./release-control.mjs";
10
10
  import { CONTROL_VERBS, collectStatus, renderReleaseStatus, watchStatus, explainIssue, explainPr, renderExplain, parseNextAction, policyFromYaml, registerPlannerRule, PLANNER_RULES } from "./release-status.mjs";
11
11
 
@@ -228,4 +228,56 @@ describe("release status / explain (#5554)", () => {
228
228
  await assert.rejects(run(["status", "--watch", "--interval", "0", "--repo", REPO]), /positive number/);
229
229
  await assert.rejects(releaseFromCli(["status", "--bogus"], { io: fakeIo() }), /unknown option --bogus/);
230
230
  });
231
+
232
+ it("#5848: `release --merge --watch` without a valid release.yaml prints the reason and check-config hint, exits 1, shows no older record", async () => {
233
+ const io = fakeIo({ state: { ...STATE, status: "refused" } });
234
+ const code = await releaseFromCli(["--merge", "--watch", "--repo", REPO], { io, cwd: managedDir, env: { FORGEDOCK_RELEASE_DIR: join(managedDir, "rel") }, deps: {} });
235
+ const out = io.printed.join("\n");
236
+ assert.equal(code, 1);
237
+ assert.match(out, /refused: no valid \.forge\/release\.yaml.*check-config/);
238
+ assert.ok(!out.includes(ID), out);
239
+ });
240
+ it("#5848: plain `release --merge` without a valid release.yaml also refuses with the check-config hint and exits 1", async () => {
241
+ const io = fakeIo({ state: { ...STATE, status: "refused" } });
242
+ const code = await releaseFromCli(["--merge", "--repo", REPO], { io, cwd: managedDir, env: { FORGEDOCK_RELEASE_DIR: join(managedDir, "rel") }, deps: {} });
243
+ const out = io.printed.join("\n");
244
+ assert.equal(code, 1);
245
+ assert.match(out, /check-config/);
246
+ assert.ok(!out.includes(ID), out);
247
+ });
248
+
249
+ it("#5848: `release --merge --watch` with a valid release.yaml prints only the record this start created", async () => {
250
+ const io = fakeIo({ state: { ...STATE, status: "refused" }, active: { lease: null, holds: [] } });
251
+ const policy = "schema: 1\nbranches: {default: main, integration: staging}\nunits:\n api: {paths: [\"services/api/**\"], criticality: high}\nlanes:\n release: {pipeline: full, ci_tier: T3, base: integration}\ndeploy:\n pipelines:\n full: {workflow: deploy.yml, trigger: push, wait: true}\nci:\n tiers: {T3: {jobs: [e2e]}}\n";
252
+ io.git = (a) => { if (String(a[1]).endsWith(".forge/release.yaml")) return policy; throw new Error("git"); };
253
+ io.now = () => Date.UTC(2026, 10, 20, 1, 2, 3);
254
+ io.runningLanes = async () => [];
255
+ const refs = {}, commits = {}, trees = {}; // an in-memory git ledger: what this start writes is what the watch reads
256
+ const miss = () => Object.assign(new Error("HTTP 404"), { status: 404 });
257
+ io.api = async (m, p, body) => {
258
+ const n = Object.keys(commits).length + 1;
259
+ if (m === "POST" && p.endsWith("/git/trees")) { trees[`t${n}`] = { ...(body.base_tree ? trees[body.base_tree] : {}), ...Object.fromEntries(body.tree.map((f) => [f.path, f.content])) }; return { sha: `t${n}` }; }
260
+ if (m === "POST" && p.endsWith("/git/commits")) { commits[`c${n}`] = body.tree; return { sha: `c${n}` }; }
261
+ if (m === "POST" && p.endsWith("/git/refs")) { const br = body.ref.replace("refs/heads/", ""); if (refs[br]) throw Object.assign(new Error("HTTP 422"), { status: 422 }); refs[br] = body.sha; return {}; }
262
+ if (m === "PATCH") { refs[/git\/refs\/heads\/(.+)$/.exec(p)[1]] = body.sha; return {}; }
263
+ if (m !== "GET") return {};
264
+ let r;
265
+ if ((r = /git\/commits\/(.+)$/.exec(p))) return { tree: { sha: commits[r[1]] } };
266
+ if ((r = /git\/ref\/heads\/(.+)$/.exec(p))) { if (!refs[r[1]]) throw miss(); return { object: { sha: refs[r[1]] } }; }
267
+ if ((r = /git\/matching-refs\/heads\/(.*)$/.exec(p))) return Object.keys(refs).filter((b) => b.startsWith(r[1])).map((b) => ({ ref: `refs/heads/${b}` }));
268
+ if ((r = /contents\/([^?]+)\?ref=(.+)$/.exec(p))) { const f = trees[commits[refs[decodeURIComponent(r[2])]]]?.[r[1]]; if (f === undefined) throw miss(); return { content: Buffer.from(f).toString("base64") }; }
269
+ throw miss();
270
+ };
271
+ const steps = { preflight: async () => ({ stopped: true, why: "stub stop" }) }; // the start ends non-terminal, so the watch begins
272
+ let polls = 0; io.sleep = async () => { if (++polls > 2) throw new Error("watch-ended"); }; // a stopped release never turns terminal: end the loop after a few polls
273
+ await assert.rejects(releaseFromCli(["--merge", "--watch", "--repo", REPO], { io, cwd: managedDir, env: { FORGEDOCK_RELEASE_DIR: join(managedDir, "rel2") }, steps: withStubs(steps) }), /watch-ended/);
274
+ const out = io.printed.join("\n");
275
+ const created = /release (r[\w-]+): stopped at preflight/.exec(out)?.[1];
276
+ assert.ok(created && created !== ID, out);
277
+ assert.ok(Object.keys(refs).includes(`forge-ledger/${created}`), "the start wrote its ledger");
278
+ const watched = io.printed.filter((l) => l.startsWith("status=") || /status=/.test(l)).map((l) => /\b(r\d{8}-[\w-]+)/.exec(l)?.[1]).filter(Boolean);
279
+ assert.ok(watched.length && watched.every((w) => w === created), out); // the watch shows the created release only
280
+ assert.ok(!out.includes(ID), out);
281
+ assert.doesNotMatch(out, /no valid \.forge\/release\.yaml/);
282
+ });
231
283
  });
@@ -633,7 +633,7 @@ export async function releaseFromCli(argv, deps = {}) {
633
633
  if (argv[0] === "control") throw new Error(`unknown control verb ${argv[1] ?? ""}; ${RELEASE_USAGE}`);
634
634
  const unknown = argv.filter((a, i) => a.startsWith("--") && !["--repo", "--merge", "--watch", "--resume", "--lane", "--interval"].includes(a) && !(argv[i - 1] === "--resume" || argv[i - 1] === "--repo" || argv[i - 1] === "--lane" || argv[i - 1] === "--interval"));
635
635
  if (unknown.length) throw new Error(`unknown option ${unknown[0]}; ${RELEASE_USAGE}`);
636
- if (argv.includes("--watch")) { // the bare flag delegates to the status loop (#5554)
636
+ if (argv.includes("--watch") && !argv.includes("--merge")) { // the bare flag delegates to the status loop (#5554); `--merge` is a start (#5848)
637
637
  const pick = (f) => (flag(argv, f) ? [f, flag(argv, f)] : []);
638
638
  return statusCli(["status", ...(flag(argv, "--resume") ? [flag(argv, "--resume")] : []), "--watch", ...pick("--repo"), ...pick("--interval")], { io, cwd, env, deps });
639
639
  }
@@ -656,6 +656,7 @@ export async function releaseFromCli(argv, deps = {}) {
656
656
  const { conductorGuard } = await import("./release-conductor.mjs"); // #5564: a configured conductor must exist on the default branch
657
657
  const noConductor = conductorGuard({ io, policy: pol, def: readBranches(cwd).default || "main" });
658
658
  if (noConductor) { io.print(`release: refused: ${noConductor}`); return 1; }
659
+ if (!pol && !resume) { io.print("release: refused: no valid .forge/release.yaml on the default branch (run release check-config)"); return 1; } // #5848: same reason as `release plan`
659
660
  config.policy = pol; config.fix = parseFixConfig(pol?.ci?.fix); // #5567: ci.fix.max_rounds / co_start / full_run_workflow
660
661
  config.deployPipeline = pol?.lanes?.[flag(argv, "--lane")]?.pipeline ?? "full"; // service/hotfix lanes dispatch with unit inputs
661
662
  if (pol?.verify) { // #5562: verification layers; risk class picks the soak minutes
@@ -674,11 +675,13 @@ export async function releaseFromCli(argv, deps = {}) {
674
675
  try { io.print(await budgetReportLine({ cwd, repo, gh: (a) => io.gh(a), now: io.now(), release: since ? await releaseRuns({ gh: (a) => io.gh(a), repo, sinceMs: since }) : null })); } catch { /* best effort */ }
675
676
  };
676
677
  await budget(null);
677
- const r = await runRelease({ io, repo, opts: { merge: argv.includes("--merge"), lane: flag(argv, "--lane") }, config, branches: readBranches(cwd), root, id, mounts: deps.mounts });
678
+ const r = await runRelease({ io, repo, opts: { merge: argv.includes("--merge"), lane: flag(argv, "--lane") }, config, branches: readBranches(cwd), root, id, mounts: deps.mounts, steps: deps.steps });
678
679
  const line = r.status === "done" ? `release ${id}: done` : `release ${id}: ${r.status} at ${r.step}: ${r.reason} (resume: forgedock release --resume ${id})`;
679
680
  io.print(line);
680
681
  try { await budget(Date.parse(openRelease(root, id).load()?.startedAt) || null); } catch { /* best effort */ }
681
- return r.status === "refused" ? 1 : r.status === "blocked" ? BLOCKED_EXIT : 0;
682
+ const code = r.status === "refused" ? 1 : r.status === "blocked" ? BLOCKED_EXIT : 0;
683
+ if (argv.includes("--watch") && code === 0 && r.status !== "done") return statusCli(["status", id, "--watch", "--repo", repo, ...(flag(argv, "--interval") ? ["--interval", flag(argv, "--interval")] : [])], { io, cwd, env, deps }); // #5848: watch the record this start created
684
+ return code;
682
685
  }
683
686
 
684
687
  /** `forgedock release verify <sha> [--repo R]`: exit 0 when the release head is the snapshot plus its recorded cherry-picks of staging commits, else 1. */
@@ -168,10 +168,15 @@ export function renderTestAdequacy(rows) {
168
168
  export function renderReview(rv, contract, adequacy = null) {
169
169
  const rows = contract.requirements.map((r) => {
170
170
  const x = (rv.requirements ?? []).find((y) => y.id === r.id) ?? {};
171
+ if (r.disposition === "guidance") return `| ${esc(r.id)} | ${esc(`guidance (non-binding): ${r.why ?? ""}`)} | ${esc(x.note || x.evidence)} | |`; // #5750: stance and reason
171
172
  const oob = r.verify === "out_of_band" ? ` (out of band${r.evidence ? `: ${r.evidence}` : ""})` : "";
172
173
  return `| ${esc(r.id)} | ${oob ? esc(`${x.status ?? ""}${oob}`) : esc(x.status)}${r.tracked ? ` (tracked ${r.tracked})` : ""} | ${esc(x.evidence)} | ${esc(x.validated_by)} |`;
173
174
  }).join("\n");
174
- const cov = rv.issue_coverage ?? [];
175
+ const guidance = contract.requirements.filter((r) => r.disposition === "guidance");
176
+ const guide = new Set(guidance.map((r) => r.id)), guideQuotes = new Set(guidance.map((r) => r.quote));
177
+ // #5750: guidance rows are non-binding, so they are not counted as covered issue requirements (matched by contract_ids, else by quote)
178
+ const isGuide = (c) => c.guidance === true || (Array.isArray(c.contract_ids) && c.contract_ids.length ? c.contract_ids.every((id) => guide.has(id)) : guideQuotes.has(c.quote));
179
+ const cov = (rv.issue_coverage ?? []).filter((c) => !isGuide(c));
175
180
  return `## Conformance Review\n**Verdict:** CONFORMS (computed by the engine from the rows below)\n\n| Requirement | Status | Evidence | Validated by |\n| --- | --- | --- | --- |\n${rows}\n\n**Issue coverage:** ${cov.filter((c) => c.status === "covered").length}/${cov.length} issue requirement(s) covered by the contract\n**Scope:** ${(rv.scope ?? []).map((s) => `\`${escl(s.file)}\` ← ${escl(s.authorized_by)}`).join(", ") || NR}\n**Preserve:** ${(rv.preserve ?? []).map((p) => `${escl(p.id)} ${escl(p.status)}`).join(", ") || "none"}\n**Regressions:** none${renderTestAdequacy(adequacy)}\n\n**Notes:** ${escl(rv.summary)}`;
176
181
  }
177
182
 
@@ -219,6 +219,12 @@ describe("remote adapter (#4254)", () => {
219
219
  await assert.rejects(t504.launch({ id: "x" }), (e) => e.status === 504 && e.transient === true && e.retryable !== true && e.retryInSeconds === undefined);
220
220
  });
221
221
 
222
+ it("#5957 httpTransport: a disk-paused sandbox (#5891) is still running, never exited", async () => {
223
+ const t = (state) => httpTransport({ endpoint: "https://pool.example", token: TOKEN, fetchFn: async () => ({ status: 200, ok: true, text: async () => JSON.stringify({ state }), headers: { get: () => null } }) });
224
+ assert.equal(await t("paused").status("x"), "running");
225
+ assert.equal(await t("exited").status("x"), "exited");
226
+ });
227
+
222
228
  it("#5053 httpTransport: a 401 on status is transient and names its hop; a launch 401 is not transient", async () => {
223
229
  const reply = (status, body) => ({ status, ok: status < 300, text: async () => JSON.stringify(body), headers: { get: () => null } });
224
230
  const t = httpTransport({ endpoint: "https://pool.example", token: TOKEN, fetchFn: async () => reply(401, { error: "unauthorized", hop: "agent", agent: "a1", reason: "agent auth: router token rejected by agent" }) });
@@ -92,10 +92,10 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
92
92
  if (r.status === 404) return "gone";
93
93
  if (!r.ok) throw Object.assign(fail("status", r), r.status === 401 ? { transient: true } : {}); // #5053: the sandbox launched, so a 401 is retried like an unreachable pool
94
94
  const s = String(r.data?.state ?? "");
95
- return s === "running" || s === "pending" || s === "starting" ? "running" : s === "gone" ? "gone" : "exited";
95
+ return s === "running" || s === "pending" || s === "starting" || s === "paused" ? "running" : s === "gone" ? "gone" : "exited";
96
96
  },
97
97
  async logs(id, cursor = 0) { const r = await call("GET", `${p(id)}/logs?cursor=${encodeURIComponent(cursor)}`); return r.ok ? { text: String(r.data?.text ?? ""), cursor: r.data?.cursor ?? cursor } : { text: "", cursor }; },
98
- async result(id) { const r = await call("GET", `${p(id)}/result`); if (r.status === 401) throw Object.assign(fail("result", r), { transient: true }); if (r.ok && r.data?.drained === true) return { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_CAPACITY, retryInSeconds: 60, cost_usd: 0, detail: `sandbox ${id} was drained to free capacity for reserved work (${String(r.data.reason ?? "").slice(0, 120)}); rescheduled` }; /* #5856 */ return r.ok && r.data && typeof r.data === "object" ? r.data : null; },
98
+ async result(id) { const r = await call("GET", `${p(id)}/result`); if (r.status === 401) throw Object.assign(fail("result", r), { transient: true }); if (r.ok && r.data?.disk_pressure === true) return { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_DISK_PRESSURE, retryInSeconds: 120, cost_usd: 0, detail: `sandbox ${id} was stopped to save the host drive (disk pressure); worktree and volume kept, requeued to resume` }; /* #5891 */ if (r.ok && r.data?.drained === true) return { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_CAPACITY, retryInSeconds: 60, cost_usd: 0, detail: `sandbox ${id} was drained to free capacity for reserved work (${String(r.data.reason ?? "").slice(0, 120)}); rescheduled` }; /* #5856 */ return r.ok && r.data && typeof r.data === "object" ? r.data : null; },
99
99
  async usage(id) { const r = await call("GET", `${p(id)}/usage`); return r.ok && Number.isFinite(Number(r.data?.minutes)) ? { minutes: Number(r.data.minutes), ...(typeof r.data.agent === "string" && r.data.agent ? { agent: r.data.agent } : {}) } : null; }, // agent: #4549, optional
100
100
  async stop(id) { const r = await call("POST", `${p(id)}/stop`); if (r.ok) return true; if (r.status === 404 || r.status === 405) return false; throw fail("stop", r); },
101
101
  async destroy(id) { const r = await call("DELETE", p(id)); if (r.ok || r.status === 404) return true; throw fail("destroy", r); },
@@ -114,6 +114,16 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
114
114
  if (!Array.isArray(r.data?.agents)) throw new Error("agent disk: malformed router answer");
115
115
  return r.data.agents.map((a) => ({ name: String(a?.name ?? "?"), disk_free_gb: Number.isFinite(a?.disk_free_gb) ? a.disk_free_gb : null }));
116
116
  },
117
+ /** #5735: lane sandboxes per pool agent (`GET /agents` -> `agents[].lanes {used, ceiling}`) and across all batches (`remote_lanes`; else the `fdrsbx-` keys of `sandboxes`). A bad answer throws. */
118
+ async agentLanes() {
119
+ const r = await call("GET", "/agents");
120
+ if (!r.ok) throw fail("agent lanes", r);
121
+ if (!Array.isArray(r.data?.agents)) throw new Error("agent lanes: malformed router answer");
122
+ const int = (v) => (Number.isInteger(v) && v >= 0 ? v : null);
123
+ const agents = r.data.agents.map((a) => ({ name: String(a?.name ?? "?"), used: int(a?.lanes?.used) ?? 0, ceiling: int(a?.lanes?.ceiling) }));
124
+ const sb = r.data.sandboxes && typeof r.data.sandboxes === "object" ? Object.keys(r.data.sandboxes) : [];
125
+ return { agents, total: int(r.data.remote_lanes) ?? sb.filter((id) => id.startsWith("fdrsbx-")).length };
126
+ },
117
127
  async relayPending(id) { const r = await call("GET", `${p(id)}/relay`); return r.ok && Array.isArray(r.data?.requests) ? r.data.requests : []; },
118
128
  async relayAnswer(id, rid, out) { const r = await call("POST", `${p(id)}/relay/${encodeURIComponent(rid)}`, out); if (!r.ok) throw fail("relay answer", r); return true; },
119
129
  async capacity() {
@@ -251,9 +251,26 @@ export function openSched(dir = schedDir(), { now = () => Date.now(), pid = proc
251
251
  }
252
252
 
253
253
  /** #4964: `sched show` lines for remote (pool) lanes and an unreachable pool; empty when there are none. */
254
- export function remoteLines(st) {
255
- const out = (st?.remote ?? []).map((e) => ` remote #${e.issue} ${e.repo ?? "-"} batch ${e.batch ?? "-"} sandbox ${e.sandbox ?? "-"} agent ${e.agent ?? "-"} dispatcher ${e.pid}`);
254
+ export function remoteLines(st, { agentOf = null } = {}) {
255
+ // #5938: the registry entry can predate placement; the batch run record's placement names the agent once the sandbox is placed
256
+ const agent = (e) => { if (e.agent) return e.agent; try { return agentOf?.(e) ?? "-"; } catch { return "-"; } };
257
+ const out = (st?.remote ?? []).map((e) => ` remote #${e.issue} ${e.repo ?? "-"} batch ${e.batch ?? "-"} sandbox ${e.sandbox ?? "-"} agent ${agent(e)} dispatcher ${e.pid}`);
256
258
  const down = st?.pool ?? [];
257
259
  if (down.length) out.push(`pool: unreachable (${down.map((e) => `batch ${e.batch}${e.reason ? `: ${e.reason}` : ""}`).join("; ")})`);
258
260
  return out;
259
261
  }
262
+
263
+ /** #5847: batch-start report of the effective concurrency K, the host cap and which source set it; pure and read-only. */
264
+ export function describeConcurrency({ parallel, parallelFrom = "default", registryCap = null, globalParallel = null, derivedCap = null, yamlFound = true, cwd = "." } = {}) {
265
+ const pos = (n) => (Number.isInteger(n) && n > 0 ? n : null);
266
+ const [reg, glob, derived] = [pos(registryCap), pos(globalParallel), pos(derivedCap)];
267
+ let cap = null, source = "none";
268
+ if (reg !== null) { cap = reg; source = "forgedock sched cap"; }
269
+ else if (glob !== null && (derived === null || glob <= derived)) { cap = glob; source = "forge.yaml orchestration.global_parallel"; }
270
+ else if (derived !== null) { cap = derived; source = "host-derived limit"; }
271
+ const line = `concurrency: K=${parallel} (host cap ${cap ?? "none"} from ${source}) [K from ${parallelFrom}]`;
272
+ const warnings = [];
273
+ if (cap !== null && Number(parallel) > cap) warnings.push(`warning: K=${parallel} exceeds the host cap ${cap} (${source}); lanes beyond ${cap} queue. Raise it with: forgedock sched cap ${parallel}`);
274
+ if (!yamlFound) warnings.push(`warning: no forge.yaml in ${cwd}; defaults apply (global_parallel unset, host-derived admission limits)`);
275
+ return { line, warnings };
276
+ }
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
5
5
  import { writeFileSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
  import { tmpDir } from "../tests/_tmp.mjs";
8
- import { grantOrder, openSched, priorityFromLabels, remoteLines } from "./sched.mjs";
8
+ import { describeConcurrency, grantOrder, openSched, priorityFromLabels, remoteLines } from "./sched.mjs";
9
9
  import { orchestrate, estimateLaneMinutes, laneHistory, formatEstimateSummary, EST_DEFAULT_MIN, POST_DEPLOY_EST_MIN } from "./orchestrate.mjs";
10
10
  import { schedFromCli } from "../engine-cli.mjs";
11
11
 
@@ -555,6 +555,13 @@ describe("sched show lists remote (pool) lanes (#4964)", () => {
555
555
  assert.deepEqual(remoteLines({}), []);
556
556
  });
557
557
 
558
+ it("#5938: a placed remote lane shows its agent name, from the registry or the batch run record; `-` only when neither knows it", () => {
559
+ const e = { issue: 7, repo: "o/r", batch: "B", sandbox: "sb1", pid: 9 };
560
+ assert.match(remoteLines({ remote: [{ ...e, agent: "legion" }] })[0], /agent legion /);
561
+ assert.match(remoteLines({ remote: [e] }, { agentOf: () => "atlas" })[0], /agent atlas /);
562
+ assert.match(remoteLines({ remote: [e] }, { agentOf: () => { throw new Error("no batch"); } })[0], /agent - /);
563
+ });
564
+
558
565
  it("orchestrate publishes a remote lane while it runs, drops it after, and never acquires a slot", async () => {
559
566
  const { handle } = world();
560
567
  const reg = handle(531);
@@ -569,3 +576,28 @@ describe("sched show lists remote (pool) lanes (#4964)", () => {
569
576
  assert.equal(reg.list().remote.length, 0);
570
577
  });
571
578
  });
579
+
580
+ describe("describeConcurrency", () => {
581
+ it("describeConcurrency line format", () => {
582
+ const r = describeConcurrency({ parallel: 6, parallelFrom: "--parallel", registryCap: 2 });
583
+ assert.equal(r.line, "concurrency: K=6 (host cap 2 from forgedock sched cap) [K from --parallel]");
584
+ });
585
+ it("describeConcurrency reports K, cap and source", () => {
586
+ assert.match(describeConcurrency({ parallel: 2, globalParallel: 3 }).line, /host cap 3 from forge\.yaml orchestration\.global_parallel/);
587
+ assert.match(describeConcurrency({ parallel: 2, globalParallel: 5, derivedCap: 4 }).line, /host cap 4 from host-derived limit/);
588
+ const none = describeConcurrency({ parallel: 2 });
589
+ assert.match(none.line, /host cap none from none/);
590
+ assert.deepEqual(none.warnings, []);
591
+ });
592
+ it("describeConcurrency warns when K exceeds cap", () => {
593
+ const r = describeConcurrency({ parallel: 6, registryCap: 2 });
594
+ assert.equal(r.warnings.length, 1);
595
+ assert.match(r.warnings[0], /forgedock sched cap 6/);
596
+ assert.deepEqual(describeConcurrency({ parallel: 2, registryCap: 2 }).warnings, []);
597
+ });
598
+ it("describeConcurrency warns when forge.yaml is missing", () => {
599
+ const r = describeConcurrency({ parallel: 1, yamlFound: false, cwd: "/x" });
600
+ assert.match(r.warnings[0], /no forge\.yaml in \/x; defaults apply/);
601
+ assert.deepEqual(describeConcurrency({ parallel: 1 }).warnings, []);
602
+ });
603
+ });
@@ -55,8 +55,9 @@ export function tickText(c) {
55
55
  * @returns the check, plus `killed` (and `started` when it started one)
56
56
  */
57
57
  export async function watchdog({ dir = schedDir(), stallMs = STALL_MS, now = () => Date.now(), alive = pidAlive, kill = (p, s) => process.kill(p, s),
58
- sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m), unfinished = () => [], start = null } = {}) {
58
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m), unfinished = () => [], start = null, batchVerdicts = null } = {}) {
59
59
  const c = stallCheck({ dir, stallMs, now, alive });
60
+ if (batchVerdicts) { try { for (const l of batchVerdicts() ?? []) log(`schedd watchdog: ${l}`); } catch { /* advisory */ } } // #5938: one verdict line per batch
60
61
  if (c.status === "down" && start) {
61
62
  let ids = [];
62
63
  try { ids = unfinished() ?? []; } catch { ids = []; }
@@ -57,6 +57,13 @@ describe("schedd heartbeat and watchdog (#4780)", () => {
57
57
  assert.match(lines.at(-1), /start failed: no unit/);
58
58
  });
59
59
 
60
+ it("#5938: the watchdog logs one verdict line per batch and leaves the heartbeat behaviour alone", async () => {
61
+ const dir = tmpDir("hb-verdict-"), lines = [];
62
+ const r = await watchdog({ dir, now: () => 0, alive: () => false, log: (m) => lines.push(m), batchVerdicts: () => ["batch b1: healthy", "batch b2: stalled -> no action, needs you (x)"] });
63
+ assert.equal(r.status, "down");
64
+ assert.deepEqual(lines, ["schedd watchdog: batch b1: healthy", "schedd watchdog: batch b2: stalled -> no action, needs you (x)"]);
65
+ });
66
+
60
67
  it("bestEffortRenice never throws", () => {
61
68
  assert.equal(bestEffortRenice(() => { throw new Error("EACCES"); }), false);
62
69
  assert.equal(bestEffortRenice(() => {}), true);
@@ -11,6 +11,7 @@
11
11
  * {op:"attach", id, resume?} → (`resume` also clears a pending cancel, #4592) log.jsonl rows replayed, then live rows/lines and done; a finished batch replays report.json
12
12
  * ({type:"done", replay:true}) unless it has unrun added issues; a batch nobody hosts is resumed here
13
13
  * {op:"set-parallel", id, k} → {type:"ok", parallel}
14
+ * {op:"clear-breaker", id} → {type:"ok", cleared, acknowledged, hosted} (#5947): a hosted runner resets its in-memory breaker (request file + ack); otherwise state.json is rewritten
14
15
  * {op:"set-execution", id, maxRemote?, mode?} → {type:"ok", execution} (#5138): live max_remote / placement (remote|hybrid|local); remote/hybrid refused for a batch with no provider
15
16
  * {op:"requeue", id, issues, reason, by} → {type:"ok", requeued, refused, hosted, reopened} (#4550): see batch.requeue; a finished batch is hosted again
16
17
  * {op:"add", id, issues} → {type:"ok", added, skipped, hosted} (#4408): merged into the batch's `add` file, which a
@@ -41,7 +42,7 @@
41
42
  * `interrupted: upgrade vX→vY` row (orchestrate.mjs).
42
43
  * `runBatch({argv, cwd, env, sink, keepBreaker, signal})` is injected (engine-cli `runBatch`); `sink` gets `batch(b)`, `row(r)`, `line(text)`.
43
44
  */
44
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
45
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeSync } from "node:fs";
45
46
  import { createConnection, createServer } from "node:net";
46
47
  import { execFileSync, spawn } from "node:child_process";
47
48
  import { homedir, tmpdir } from "node:os";
@@ -49,7 +50,7 @@ import { createHash } from "node:crypto";
49
50
  import { delimiter, join, resolve } from "node:path";
50
51
  import { fileURLToPath } from "node:url";
51
52
  import { schedDir, pidAlive } from "./sched.mjs";
52
- import { DEFAULT_STALL_MIN, FIRST_HOUR_FILE, FIRST_HOUR_MIN, decideStallAction, evaluateDispatchStall, firstHourReport, readHealth, recordStallAlert, recordStallRecovery, writeFirstHour } from "./batch-health.mjs";
53
+ import { DEFAULT_STALL_MIN, FIRST_HOUR_FILE, FIRST_HOUR_MIN, batchVerdict, clearStaleStall, decideStallAction, evaluateDispatchStall, firstHourReport, readHealth, recordStallAlert, recordStallRecovery, runningSplit, writeFirstHour } from "./batch-health.mjs";
53
54
  import { probeBatchEnv } from "./lanecheck.mjs";
54
55
  import { HEARTBEAT_MS, writeHeartbeat, clearHeartbeat } from "./schedd-health.mjs";
55
56
  import { batchRoot, listBatches, openBatch, SECRET_ENV } from "./batch.mjs";
@@ -57,6 +58,28 @@ import { killTrackedChildren } from "./effects.mjs";
57
58
  import { applySetExecution } from "./live-execution.mjs";
58
59
  import { liveOverload } from "./hostload.mjs";
59
60
 
61
+ /** #5938: epoch ms of the newest lane log of a running issue (a lane heartbeat), or null. */
62
+ export function lanesAlive(b, state) {
63
+ let best = null;
64
+ for (const n of Object.keys(state?.running ?? {})) { try { const m = statSync(b.logFile(n)).mtimeMs; if (best === null || m > best) best = m; } catch { /* no lane log yet */ } }
65
+ return best;
66
+ }
67
+
68
+ /** #5938: one verdict line per unfinished daemon batch (offline, from saved state): healthy, stalled -> action, or stalled -> no action. */
69
+ export function batchVerdicts(root, { now = Date.now(), windowMin = DEFAULT_STALL_MIN } = {}) {
70
+ const out = [];
71
+ for (const id of listBatches(root)) {
72
+ try {
73
+ const b = openBatch(root, id);
74
+ if (!b.readPlan()?.daemon || b.isTerminal()) continue;
75
+ const state = b.store.peek(), stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: false, lastProgressMs: b.lastProgressMs(), now, windowMin, lanesAliveMs: lanesAlive(b, state) });
76
+ const decision = stall ? decideStallAction(stall, { recovery: readHealth(b.dir)?.stallRecovery ?? null, hosted: false }) : null;
77
+ out.push(batchVerdict(id, stall, decision));
78
+ } catch { /* one unreadable batch has no verdict */ }
79
+ }
80
+ return out;
81
+ }
82
+
60
83
  /** #5471: `schedd status` warning lines for issues pending in two or more hosted batches. */
61
84
  export function sharedPendingLines(batches) {
62
85
  const shared = new Map();
@@ -310,10 +333,14 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
310
333
  for (const id of [...ids].sort()) {
311
334
  await yieldLoop();
312
335
  const isHosted = hosted.has(id) || starting.has(id);
313
- let last = null, pending = [], pend = [];
314
- try { const b = openBatch(root, id); last = b.lastProgressMs(); pending = b.unrunAdds(); pend = b.pendingIssues(); } catch { /* a half-written batch */ }
336
+ let last = null, pending = [], pend = [], split = null, alive = null;
337
+ try {
338
+ const b = openBatch(root, id); last = b.lastProgressMs(); pending = b.unrunAdds(); pend = b.pendingIssues();
339
+ const st = b.store.peek(); split = runningSplit(st, b.readParallel());
340
+ alive = lanesAlive(b, st); // #5938: lane output is a heartbeat
341
+ } catch { /* a half-written batch */ }
315
342
  if (!isHosted && !pending.length) continue;
316
- out.push({ id, running: isHosted, lastProgressAt: last === null ? null : new Date(last).toISOString(), lastProgressAgeSec: last === null ? null : Math.max(0, Math.round((now - last) / 1000)), pendingAdds: pending, pending: pend });
343
+ out.push({ id, running: isHosted, lastProgressAt: last === null ? null : new Date(last).toISOString(), lastProgressAgeSec: last === null ? null : Math.max(0, Math.round((now - last) / 1000)), ...(split ? { lanes: { running: split.running, k: split.k, local: split.local, remote: split.remote } } : {}), lanesAliveAgeSec: alive === null ? null : Math.max(0, Math.round((now - alive) / 1000)), pendingAdds: pending, pending: pend });
317
344
  }
318
345
  return out;
319
346
  };
@@ -335,6 +362,27 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
335
362
  b.setParallel(Number(req.k));
336
363
  return send({ type: "ok", parallel: Number(req.k) }, true);
337
364
  }
365
+ if (req.op === "clear-breaker") {
366
+ // #5947: a hosted runner holds the breaker in memory; it consumes the request file and acks. An unhosted (or silent) batch gets the state.json rewrite.
367
+ const b = openBatch(root, req.id);
368
+ if (!b.exists()) throw new Error(`no batch ${req.id} in ${root}`);
369
+ const isHosted = hosted.has(req.id);
370
+ let acknowledged = false, cleared = false;
371
+ if (isHosted) {
372
+ const at = b.requestClearBreaker();
373
+ for (let i = 0; i < 140 && !acknowledged; i++) {
374
+ const a = b.readClearBreakerAck();
375
+ if (a && a.at >= at) { acknowledged = true; cleared = Boolean(a.cleared); } else await new Promise((r) => setTimeout(r, 50));
376
+ }
377
+ }
378
+ if (!acknowledged) {
379
+ b.readClearBreaker(); // drop an unconsumed request so it cannot clear a later trip
380
+ const st = b.store.load();
381
+ cleared = Boolean(st?.breaker);
382
+ if (st) b.store.save({ ...st, breaker: null, errorTimes: [] });
383
+ }
384
+ return send({ type: "ok", cleared, acknowledged, hosted: isHosted }, true);
385
+ }
338
386
  if (req.op === "set-execution") {
339
387
  // #5138: live max_remote / placement mode; the hosted runner re-reads the batch's `execution` file on every admission.
340
388
  const b = openBatch(root, req.id);
@@ -520,7 +568,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
520
568
  const created = Date.parse(plan.created ?? "");
521
569
  if (b.isTerminal() && (!Number.isFinite(created) || now - created >= 24 * 3600_000)) continue; // nothing left to report or re-host
522
570
  const reported = !!b.readReport(), cancelled = !!b.readCancel(), state = b.store.peek(), isHosted = hosted.has(id) || starting.has(id);
523
- const stallOpts = { held: b.readHeld(), parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported };
571
+ const stallOpts = { held: b.readHeld(), parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported, lanesAliveMs: lanesAlive(b, state) };
524
572
  let stall = evaluateDispatchStall(state, stallOpts);
525
573
  if (stall && preflight) { // #5745: name the preflight gate holding admission (advisory; dispatch decisions are unchanged)
526
574
  let gates = [];
@@ -538,7 +586,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
538
586
  log(`schedd: batch ${id} abandoned (not hosted, ${state.pending.length} pending, no progress for ${Math.round((now - last) / 86400_000)} days)`);
539
587
  continue;
540
588
  }
541
- if (!stall) continue;
589
+ if (!stall) { if (clearStaleStall(b, { now })) log(`schedd: batch ${id} STALL CLEARED`); continue; } // #5938: re-evaluated every tick; a stored stall that no longer holds is cleared
542
590
  // #5806: the batch env is probed first (a PATH without gh/git/node stalls every resume the same way); the first stall of a
543
591
  // ready set is recovered once (health.json stallRecovery survives a daemon restart), a repeat alerts with the probed cause.
544
592
  let probe = null;
@@ -9,7 +9,7 @@ import { join } from "node:path";
9
9
  import { tmpDir } from "../tests/_tmp.mjs";
10
10
  import { openBatch, isLaneAlive, listBatches, SECRET_ENV, scanStats } from "./batch.mjs";
11
11
  import { killTrackedChildren, runWithInput, trackedChildCount } from "./effects.mjs";
12
- import { findUnhosted, startDaemon, scheddPaths, connectDaemon, request, unitState, SCHEDD_SCRIPT, mergeEnv, batchEnv, droppedEnv, sanitizePath, redactEnv, exitOnSignals, readInstalledVersion } from "./schedd.mjs";
12
+ import { findUnhosted, startDaemon, scheddPaths, connectDaemon, request, unitState, SCHEDD_SCRIPT, mergeEnv, batchEnv, droppedEnv, sanitizePath, redactEnv, exitOnSignals, readInstalledVersion, batchVerdicts } from "./schedd.mjs";
13
13
  import { schedDir } from "./sched.mjs";
14
14
  import { readHeartbeat } from "./schedd-health.mjs";
15
15
  import { formatTable, orchestrate } from "./orchestrate.mjs";
@@ -149,6 +149,25 @@ describe("schedd host scheduler (#4192)", () => {
149
149
  } finally { await h.cleanup(); }
150
150
  });
151
151
 
152
+ it("#5947 clear-breaker on a hosted batch reaches the live runner, which acknowledges it (no daemon restart)", async () => {
153
+ const h = host();
154
+ try {
155
+ const d = await h.daemon();
156
+ const all = capture(() => h.inWork(() => orchestrateFromCli(["1", "2", "--parallel", "1", "--repo", "o/r", "--no-prefilter"], h.client)));
157
+ await until(() => h.launched().length === 1 && h.lanePids().length === 1);
158
+ const [id] = listBatches(h.root);
159
+ const r = await request(await connectDaemon({ dir: h.sched, spawnDaemon: null }), { op: "clear-breaker", id }, undefined, { timeoutMs: 20000 });
160
+ assert.equal(r.type, "ok");
161
+ assert.equal(r.hosted, true);
162
+ assert.equal(r.acknowledged, true, "the hosted runner consumed the request and acked");
163
+ assert.equal(openBatch(h.root, id).readClearBreakerAck().cleared, false, "no breaker was tripped");
164
+ assert.equal(existsSync(join(h.root, id, "clear-breaker")), false, "the request file is consumed");
165
+ assert.equal((await request(await connectDaemon({ dir: h.sched, spawnDaemon: null }), { op: "status" })).pid, d.pid, "same daemon");
166
+ writeFileSync(h.release, "");
167
+ await all;
168
+ } finally { await h.cleanup(); }
169
+ });
170
+
152
171
  it("a client that disconnects does not stop the batch; --resume reattaches, and replays the report once done", async () => {
153
172
  const h = host(); h.enter(); // admission off: this test needs >1 concurrent local lane on any host
154
173
  try {
@@ -486,6 +505,28 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
486
505
  } finally { await d.close(); }
487
506
  });
488
507
 
508
+ it("#5938: a stored stall clears within one tick (STALL CLEARED) once the batch is at K; status shows running/K and the split; the watchdog verdict is healthy", async () => {
509
+ const dir = tmpDir("schedd-stall-clear-"), root = join(dir, "batches"), id = "b20261122-000000-5938", lines = [];
510
+ const b = openBatch(root, id);
511
+ b.writePlan({ daemon: true, repo: "o/r", created: new Date(Date.now() - 90 * 60000).toISOString() });
512
+ b.store.save({ v: 1, order: [1, 2, 3], results: {}, running: {}, pending: [1, 2, 3], parallel: 2 });
513
+ const old = new Date(Date.now() - 30 * 60000);
514
+ utimesSync(join(b.dir, "state.json"), old, old);
515
+ assert.match(batchVerdicts(root, { windowMin: 10 })[0], /stalled/);
516
+ writeFileSync(join(b.dir, "health.json"), JSON.stringify({ stall: { at: new Date().toISOString(), sig: "1,2,3", detail: "old" } }) + "\n");
517
+ b.store.save({ v: 1, order: [1, 2, 3], results: {}, running: { 1: { startedAt: 1 }, 2: { startedAt: 1, remote: true } }, pending: [1, 2, 3], parallel: 2 });
518
+ utimesSync(join(b.dir, "state.json"), old, old);
519
+ const runBatch = async ({ sink }) => { sink.batch({ id, dir: b.dir }); return await new Promise(() => {}); };
520
+ const d = await startDaemon({ dir, root, runBatch, log: (m) => lines.push(m), resumeOnStart: true, stallCheckMs: 50, stallMin: 10 });
521
+ try {
522
+ await until(() => !readFileSync(join(b.dir, "health.json"), "utf8").includes("stall\""), 8000);
523
+ assert.match(readFileSync(join(b.dir, "batch.log"), "utf8"), /STALL CLEARED/);
524
+ assert.equal(batchVerdicts(root, { windowMin: 10 })[0], `batch ${id}: healthy`);
525
+ const st = await request(await connectDaemon({ dir, spawnDaemon: null }), { op: "status" });
526
+ assert.deepEqual(st.batches.find((x) => x.id === id).lanes, { running: 2, k: 2, local: 1, remote: 1 });
527
+ } finally { await d.close(); }
528
+ });
529
+
489
530
  it("#5806: a hosted runner wedged in setup restarts the daemon once (decision logged); the same stall again alerts and never loops", async () => {
490
531
  const dir = tmpDir("schedd-stall-setup-"), root = join(dir, "batches"), id = "b20261121-000000-5806";
491
532
  const b = openBatch(root, id);
@@ -93,3 +93,48 @@ export function stackedBaseBlock({ prBase, lane, stackedBranch = null, dependenc
93
93
  if (prBase !== lane) return `merge.stacked_base: PR base ${prBase || "?"} is not the lane ${lane}`;
94
94
  return null;
95
95
  }
96
+
97
+ /** #5833 (phase 3): cascade kinds recorded on a stacked dependent's row (`cascade`, `cascades`). */
98
+ export const CASCADES = ["rebase", "reverify", "restart", "replan"];
99
+
100
+ /**
101
+ * Which cascade a stacked dependent needs now, or null (nothing moved). `depState`: open | merged | closed (closed = ended without a merge).
102
+ * merged -> rebase onto the lane; closed -> replan on the lane base; open with a moved head -> reverify (clean rebase) or restart (conflict).
103
+ * @param {{depState:string, depHeadSha?:string|null, stackedSha?:string|null, rebaseConflict?:boolean}} a
104
+ */
105
+ export function cascadeDecision({ depState, depHeadSha = null, stackedSha = null, rebaseConflict = false }) {
106
+ if (depState === "merged") return "rebase";
107
+ if (depState === "closed") return "replan";
108
+ if (depState !== "open" || !depHeadSha || !stackedSha || depHeadSha === stackedSha) return null;
109
+ return rebaseConflict ? "restart" : "reverify";
110
+ }
111
+
112
+ /**
113
+ * The checks the dependency's final diff invalidates: a command naming a path (token with `/`) is kept when a changed path equals it or
114
+ * lies under it (or it lies under the changed path); a command naming no path cannot be scoped and is always kept.
115
+ * @param {{changedPaths:string[], checks:string[]}} a
116
+ */
117
+ export function invalidatedChecks({ changedPaths = [], checks = [] }) {
118
+ const norm = (t) => t.replace(/^["']|["']$/g, "").replace(/^\.\//, "").replace(/\/+$/, "");
119
+ return checks.filter((c) => {
120
+ const toks = String(c).split(/\s+/).map(norm).filter((t) => t.includes("/") && !t.startsWith("-") && !/^[a-z]+:\/\//.test(t));
121
+ if (!toks.length) return true;
122
+ return toks.some((t) => changedPaths.some((p) => p === t || p.startsWith(`${t}/`) || t.startsWith(`${p}/`)));
123
+ });
124
+ }
125
+
126
+ /** Batch-report metric: cascades per stacked dependent and the cost of the rework (rows carry `stacked`, `cascades`, `cascade_cost_usd`, `cascade_minutes`). */
127
+ export function cascadeRate(rows = []) {
128
+ const st = rows.filter((r) => r?.stacked);
129
+ const list = st.map((r) => (Array.isArray(r.cascades) ? r.cascades : r.cascade ? [r.cascade] : []));
130
+ const cascades = list.reduce((s, l) => s + l.length, 0);
131
+ const round = (x, k) => Math.round(x * k) / k;
132
+ return { stacked: st.length, cascades, perStacked: st.length ? round(cascades / st.length, 100) : 0,
133
+ reworkCostUsd: round(st.reduce((s, r) => s + (Number(r.cascade_cost_usd) || 0), 0), 1e6), reworkMinutes: round(st.reduce((s, r) => s + (Number(r.cascade_minutes) || 0), 0), 10) };
134
+ }
135
+
136
+ /** One report line, or null when nothing was stacked. */
137
+ export function formatCascadeSummary(rows) {
138
+ const m = cascadeRate(rows);
139
+ return m.stacked ? `stacked lanes: ${m.stacked} dependent(s), ${m.cascades} cascade(s) (${m.perStacked}/dependent), rework $${m.reworkCostUsd.toFixed(2)} / ${m.reworkMinutes} min` : null;
140
+ }
@@ -3,7 +3,7 @@
3
3
  // #5831: stacked lanes phase 1 — the pure helpers.
4
4
  import { describe, it } from "node:test";
5
5
  import assert from "node:assert/strict";
6
- import { normalizeStacking, planAdmissible, formatPlanned, parsePlanned, planStale, stackAdmissible, formatStackedOn, parseStackedOn, validStackedOn, stackedBaseBlock } from "./stacking.mjs";
6
+ import { normalizeStacking, planAdmissible, formatPlanned, parsePlanned, planStale, stackAdmissible, formatStackedOn, parseStackedOn, validStackedOn, stackedBaseBlock, cascadeDecision, invalidatedChecks, cascadeRate, formatCascadeSummary, CASCADES } from "./stacking.mjs";
7
7
 
8
8
  const SAT = new Set(["merged", "invalid"]);
9
9
  const base = { n: 2, edges: [1], results: new Map(), pending: [1, 2], running: new Map(), planTried: new Set(), satisfied: SAT };
@@ -72,3 +72,27 @@ describe("stacked builds, phase 2 (#5832)", () => {
72
72
  assert.equal(stackedBaseBlock({ prBase: "staging", lane: "staging", dependencyMerged: false }), null, "not stacked");
73
73
  });
74
74
  });
75
+
76
+ describe("cascades (#5833)", () => {
77
+ it("cascadeDecision: merged -> rebase, closed -> replan, moved head -> reverify or restart on a conflict, nothing moved -> null", () => {
78
+ assert.equal(cascadeDecision({ depState: "merged" }), "rebase");
79
+ assert.equal(cascadeDecision({ depState: "closed" }), "replan");
80
+ assert.equal(cascadeDecision({ depState: "open", depHeadSha: "b", stackedSha: "a" }), "reverify");
81
+ assert.equal(cascadeDecision({ depState: "open", depHeadSha: "b", stackedSha: "a", rebaseConflict: true }), "restart");
82
+ assert.equal(cascadeDecision({ depState: "open", depHeadSha: "a", stackedSha: "a" }), null);
83
+ assert.equal(cascadeDecision({ depState: "unknown", depHeadSha: "b", stackedSha: "a" }), null);
84
+ assert.deepEqual(CASCADES, ["rebase", "reverify", "restart", "replan"]);
85
+ });
86
+ it("invalidatedChecks keeps path-scoped checks the diff touches and every unscoped check", () => {
87
+ const checks = ["node --test bin/lean/stacking.test.mjs", "node --test docs/x.test.mjs", "pnpm lint", "eslint src/"];
88
+ assert.deepEqual(invalidatedChecks({ changedPaths: ["bin/lean/stacking.mjs", "src/a.ts"], checks }), ["pnpm lint", "eslint src/"]);
89
+ assert.deepEqual(invalidatedChecks({ changedPaths: ["bin/lean/stacking.test.mjs"], checks }), ["node --test bin/lean/stacking.test.mjs", "pnpm lint", "eslint src/"]);
90
+ assert.deepEqual(invalidatedChecks({ changedPaths: [], checks }), ["pnpm lint", "eslint src/"]);
91
+ });
92
+ it("cascadeRate: cascades per stacked dependent and the rework cost; non-stacked rows are ignored", () => {
93
+ const rows = [{ issue: 1, outcome: "merged" }, { issue: 2, stacked: true, cascades: ["reverify", "rebase"], cascade_cost_usd: 0.5, cascade_minutes: 3 }, { issue: 3, stacked: true }];
94
+ assert.deepEqual(cascadeRate(rows), { stacked: 2, cascades: 2, perStacked: 1, reworkCostUsd: 0.5, reworkMinutes: 3 });
95
+ assert.equal(formatCascadeSummary([{ issue: 1 }]), null);
96
+ assert.match(formatCascadeSummary(rows), /2 dependent\(s\), 2 cascade\(s\)/);
97
+ });
98
+ });
@@ -155,14 +155,20 @@ export const isPipelineLabel = (name) => { const n = String(name ?? ""); return
155
155
  export const pipelineLabels = (labels) => (labels ?? []).map((l) => (typeof l === "string" ? l : l?.name)).filter(isPipelineLabel);
156
156
 
157
157
  /**
158
- * Remove the pipeline labels from an issue. `labels` is what the caller already read (names or `{name}`); null re-reads them.
159
- * Best effort, returns the removed names ([] when none or on failure).
158
+ * Remove the pipeline labels from an issue, one call per label so one failing removal leaves the others removed (#5759).
159
+ * `labels` is what the caller already read (names or `{name}`); null re-reads them. Returns the removed names; `onFail(names, err)`
160
+ * receives the labels whose removal (or the re-read, names []) failed.
160
161
  */
161
- export async function clearPipelineLabels({ gh, repo, issue, labels = null }) {
162
+ export async function clearPipelineLabels({ gh, repo, issue, labels = null, onFail = null }) {
163
+ const removed = [], failed = [];
164
+ let names;
162
165
  try {
163
- const names = pipelineLabels(labels ?? JSON.parse(String(await gh(["issue", "view", String(issue), "-R", repo, "--json", "labels"])))?.labels);
164
- if (!names.length) return [];
165
- await gh(["issue", "edit", String(issue), "-R", repo, "--remove-label", names.join(",")]);
166
- return names;
167
- } catch { return []; }
166
+ names = pipelineLabels(labels ?? JSON.parse(String(await gh(["issue", "view", String(issue), "-R", repo, "--json", "labels"])))?.labels);
167
+ } catch (e) { try { onFail?.([], e); } catch { /* reporting is best effort */ } return []; }
168
+ let last = null;
169
+ for (const name of names) {
170
+ try { await gh(["issue", "edit", String(issue), "-R", repo, "--remove-label", name]); removed.push(name); } catch (e) { failed.push(name); last = e; }
171
+ }
172
+ if (failed.length) { try { onFail?.(failed, last); } catch { /* reporting is best effort */ } }
173
+ return removed;
168
174
  }