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
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
5
5
  import { reviewStep, fixStep, missingReviewers, SPEC_PANEL, MAX_DELTA_PASSES, realSeam, withIntegrityMarker, TEST_GATE_SKIP_NO_TESTS, testGatePrompt, integrationTestCount, resolveSkillName } from "./release-review.mjs";
6
6
  import { readFileSync } from "node:fs";
7
7
  import { EventEmitter } from "node:events";
8
- import { reviewStagingJson } from "../review-staging.mjs";
8
+ import { reviewStagingJson, classifyChecks, cancelOnlyChecks } from "../review-staging.mjs";
9
9
 
10
10
  const H1 = "a".repeat(40), H2 = "b".repeat(40);
11
11
  const manifest = (head, delta = null) => ({ pr: 7, headSha: head, bundle: [1, 2], scopeMode: "full", contextFile: "/sd/review-ctx-7.json", launchedFile: "/sd/7_launched", briefs: [{ domain: "security", path: "/sd/brief-security.md" }], delta });
@@ -266,6 +266,7 @@ describe("fixStep", () => {
266
266
 
267
267
  it("only pending CI (#5519): blocks without a CI issue or lane; a real failure alongside still files", async () => {
268
268
  const s = fakeSeam();
269
+ s.summary = async () => ({ code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 1, ciPendingOnly: true }, lines: [] });
269
270
  const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 1, ciPendingOnly: true } } }));
270
271
  assert.match(r.reason, /still pending/);
271
272
  assert.deepEqual(s.log, []);
@@ -274,8 +275,47 @@ describe("fixStep", () => {
274
275
  assert.ok(s2.log.some((e) => e[0] === "fix-issue"));
275
276
  });
276
277
 
278
+ it("#5912: a stale pending-only GATE_FAILURE is re-summarised on resume and passes once CI is green", async () => {
279
+ const s = fakeSeam();
280
+ const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 3, ciPendingOnly: true } } }));
281
+ assert.equal(r.verdict, "APPROVE FOR DEPLOY");
282
+ assert.deepEqual(s.log, [["summary", []]]);
283
+ });
284
+
285
+ it("#5912: a GATE_FAILURE with a blocking finding is not re-summarised away", async () => {
286
+ const s = fakeSeam();
287
+ await fixStep(ctx(s, { review: { result: { ...failed, ciFailing: 0, ciPendingOnly: false } } }));
288
+ assert.ok(s.log.some((e) => e[0] === "fix-issue"));
289
+ });
290
+
291
+ it("#5912: a moved head is not re-summarised on resume", async () => {
292
+ const s = fakeSeam({ heads: [H2] });
293
+ await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 3, ciPendingOnly: true } } }));
294
+ assert.ok(!s.log.some((e) => e[0] === "summary"));
295
+ });
296
+
297
+ it("#5912: still pending after the re-summarise blocks with the pending reason", async () => {
298
+ const s = fakeSeam({ summary: { code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 2, ciPendingOnly: true }, lines: [] } });
299
+ const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 3, ciPendingOnly: true } } }));
300
+ assert.match(r.reason, /still pending/);
301
+ assert.equal(s.log.filter((e) => e[0] === "summary").length, 1);
302
+ });
303
+
304
+ it("#5912: nothing pending and nothing failed names the verdict and never says still pending", async () => {
305
+ const s = fakeSeam({ summary: { code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 0 }, lines: [] } });
306
+ const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 0 } } }));
307
+ assert.match(r.reason, /BLOCK DEPLOY \(FORGE:GATE_FAILURE\).*neither/);
308
+ assert.doesNotMatch(r.reason, /still pending/);
309
+ });
310
+
311
+ it("#5912: only forge/deploy-gate and the gate marker non-green gives zero blocking checks", () => {
312
+ const checks = [{ name: "build", bucket: "pass" }, { name: "forge/deploy-gate", bucket: "fail" }, { name: "Check for FORGE gate markers", bucket: "pending" }];
313
+ assert.equal(classifyChecks(checks, ["build"]).blocking, 0);
314
+ assert.deepEqual(cancelOnlyChecks(checks, ["build"]), []);
315
+ });
316
+
277
317
  it("blocks when the verdict is not a pass but there is nothing to fix", async () => {
278
- assert.match((await fixStep(ctx(fakeSeam(), { review: { result: { ...failed, blocking: [], ciFailing: 0 } } }))).reason, /nothing to fix|neither/);
318
+ assert.match((await fixStep(ctx(Object.assign(fakeSeam(), { summary: async () => ({ code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 0 }, lines: [] }) }), { review: { result: { ...failed, blocking: [], ciFailing: 0 } } }))).reason, /nothing to fix|neither/);
279
319
  });
280
320
  });
281
321
 
@@ -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
 
@@ -8,7 +8,7 @@ import { join } from "node:path";
8
8
  import { tmpDir } from "../tests/_tmp.mjs";
9
9
  import { parseExecution, openExecutionBudget } from "./execution.mjs";
10
10
  import { makeLedger } from "./ledger.mjs";
11
- import { runFromCli } from "../engine-cli.mjs";
11
+ import { runFromCli, withPublicDefault } from "../engine-cli.mjs";
12
12
 
13
13
  const logs = async (fn) => { const out = [], l = console.log; console.log = (x) => out.push(String(x)); try { return { res: await fn(), out }; } finally { console.log = l; } };
14
14
 
@@ -83,10 +83,17 @@ describe("run-issue placement (#5542)", () => {
83
83
 
84
84
  describe("run-issue public-repo default placement (#5748)", () => {
85
85
  const inEmptyDir = async (fn) => { const prev = process.cwd(); process.chdir(tmpDir("nocfg-")); try { return await fn(); } finally { process.chdir(prev); } };
86
- it("a public repo with no execution config places the lane on the actions provider", async () => {
86
+ const inDir = async (yaml, fn) => { const prev = process.cwd(), dir = tmpDir("cfg-"); writeFileSync(join(dir, "forge.yaml"), yaml); process.chdir(dir); try { return await fn(); } finally { process.chdir(prev); } };
87
+ it("#5900: a public repo with no execution config keeps the local default (actions is opt-in)", async () => {
88
+ const prov = fakeProvider(() => ({ terminalReason: "merged" }));
89
+ const { deps, ran } = setup("pubdef-off", prov, { execution: undefined, repoPublic: true });
90
+ await inEmptyDir(() => logs(() => runFromCli(["7", "--repo", "o/r", "--lane", "staging"], { ...deps, leanModule: core(ran) })));
91
+ assert.equal(ran.length, 1); assert.deepEqual(prov.calls, []);
92
+ });
93
+ it("a public repo with execution.public_default: actions and no mode places the lane on the actions provider", async () => {
87
94
  const prov = fakeProvider((n) => ({ terminalReason: "merged", pr: 100 + n, cost_usd: 0 }));
88
95
  const { deps } = setup("pubdef", prov, { execution: undefined, repoPublic: true });
89
- const { res, out } = await inEmptyDir(() => logs(() => runFromCli(["7", "--repo", "o/r", "--no-prefilter"], deps)));
96
+ const { res, out } = await inDir("execution:\n public_default: actions\n", () => logs(() => runFromCli(["7", "--repo", "o/r", "--no-prefilter"], deps)));
90
97
  assert.deepEqual(prov.calls.filter((c) => c[0] === "start").map((c) => c[1]), [7]);
91
98
  assert.equal(res.res?.terminalReason ?? res.terminalReason, "merged");
92
99
  assert.ok(out.some((l) => /^placement: remote execution \(actions\)/.test(l)), out.join("\n"));
@@ -109,3 +116,20 @@ describe("run-issue public-repo default placement (#5748)", () => {
109
116
  });
110
117
  });
111
118
 
119
+
120
+ describe("public-repo actions default is opt-in (#5900)", () => {
121
+ const ghThrows = async () => { throw new Error("visibility must not be read without the opt-in"); };
122
+ it("no execution.public_default: exec unchanged and no visibility call, public repo or not", async () => {
123
+ const dir = tmpDir("pubdef-");
124
+ writeFileSync(join(dir, "forge.yaml"), "project:\n name: x\n");
125
+ assert.equal(await withPublicDefault(undefined, { repo: "o/r", gh: ghThrows, cwd: dir }), undefined);
126
+ const e = parseExecution({ image: "i:1" });
127
+ assert.equal(await withPublicDefault(e, { repo: "o/r", gh: ghThrows, cwd: dir }), e);
128
+ });
129
+ it("opted in + public + no mode: actions provider", async () => {
130
+ const dir = tmpDir("pubdef-");
131
+ writeFileSync(join(dir, "forge.yaml"), "execution:\n public_default: actions\n");
132
+ const r = await withPublicDefault(parseExecution({ public_default: "actions" }), { repo: "o/r", gh: ghThrows, cwd: dir, deps: { repoPublic: true } });
133
+ assert.equal(r.provider, "actions");
134
+ });
135
+ });
@@ -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);