forgedock 1.66.0 → 1.67.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 (72) hide show
  1. package/bin/config-schema.mjs +2 -0
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine-cli.mjs +96 -17
  4. package/bin/forgedock.mjs +7 -0
  5. package/bin/help-text.mjs +3 -3
  6. package/bin/introspect-schedule.mjs +98 -0
  7. package/bin/introspect-schedule.test.mjs +67 -0
  8. package/bin/lean/advisory.test.mjs +49 -0
  9. package/bin/lean/amendment-schema.mjs +31 -0
  10. package/bin/lean/attempts.mjs +159 -0
  11. package/bin/lean/attempts.test.mjs +127 -0
  12. package/bin/lean/basered.mjs +55 -0
  13. package/bin/lean/basered.test.mjs +68 -1
  14. package/bin/lean/batch-health.mjs +3 -0
  15. package/bin/lean/batch-health.test.mjs +16 -0
  16. package/bin/lean/batch.mjs +45 -0
  17. package/bin/lean/batch.test.mjs +54 -3
  18. package/bin/lean/capwait.mjs +14 -3
  19. package/bin/lean/capwait.test.mjs +20 -0
  20. package/bin/lean/clear-breaker.mjs +14 -0
  21. package/bin/lean/commentstate.mjs +41 -0
  22. package/bin/lean/commentstate.test.mjs +32 -0
  23. package/bin/lean/concurrency.mjs +89 -0
  24. package/bin/lean/concurrency.test.mjs +113 -0
  25. package/bin/lean/conformance.e2e.test.mjs +4 -2
  26. package/bin/lean/conformance.mjs +35 -3
  27. package/bin/lean/conformance.test.mjs +52 -0
  28. package/bin/lean/efficiency.mjs +162 -0
  29. package/bin/lean/efficiency.test.mjs +79 -0
  30. package/bin/lean/execution.mjs +31 -13
  31. package/bin/lean/execution.test.mjs +46 -0
  32. package/bin/lean/failure-stop.mjs +46 -0
  33. package/bin/lean/failure-stop.test.mjs +45 -0
  34. package/bin/lean/fixtures/capacity-storm.json +609 -0
  35. package/bin/lean/lean.mjs +123 -24
  36. package/bin/lean/lean.test.mjs +137 -46
  37. package/bin/lean/liveness.mjs +37 -0
  38. package/bin/lean/liveness.test.mjs +33 -0
  39. package/bin/lean/orchestrate-attempts.test.mjs +74 -0
  40. package/bin/lean/orchestrate-pause.test.mjs +23 -0
  41. package/bin/lean/orchestrate-reconcile.test.mjs +147 -0
  42. package/bin/lean/orchestrate.mjs +170 -26
  43. package/bin/lean/phaseledger.mjs +6 -0
  44. package/bin/lean/phaseledger.test.mjs +13 -1
  45. package/bin/lean/prompts.mjs +6 -10
  46. package/bin/lean/reconcile.mjs +90 -0
  47. package/bin/lean/recurrence.mjs +38 -2
  48. package/bin/lean/recurrence.test.mjs +56 -1
  49. package/bin/lean/sandbox-remote.mjs +33 -2
  50. package/bin/lean/sched.mjs +19 -0
  51. package/bin/lean/sched.test.mjs +11 -1
  52. package/bin/lean/schedd-health.mjs +4 -4
  53. package/bin/lean/schedd-health.test.mjs +8 -4
  54. package/bin/lean/schedd.mjs +34 -2
  55. package/bin/lean/schedd.test.mjs +55 -2
  56. package/bin/lean/slo.mjs +126 -0
  57. package/bin/lean/slo.test.mjs +112 -0
  58. package/bin/lean/statuscomment.mjs +37 -0
  59. package/bin/lean/statuscomment.test.mjs +48 -1
  60. package/bin/lean/verify.mjs +2 -1
  61. package/bin/pool/agent.mjs +2 -2
  62. package/bin/pool/cli.mjs +16 -1
  63. package/bin/pool/lane-tools.mjs +21 -0
  64. package/bin/stats/attempts.mjs +54 -0
  65. package/bin/stats/attempts.test.mjs +30 -0
  66. package/bin/stats/churn.mjs +49 -0
  67. package/bin/stats/churn.test.mjs +31 -0
  68. package/bin/stats/index.mjs +11 -3
  69. package/commands/orchestrate.md +21 -18
  70. package/docs/OUTCOME-CODES.md +1 -0
  71. package/package.json +1 -1
  72. package/scripts/check-devdocs-freshness.sh +1 -1
@@ -0,0 +1,90 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5978: standing orders. A batch started with `--select <query>` keeps owning every open issue the selector matches:
4
+ // matching issues join, closed or moved ones leave, and an issue that ended deferred / held / engine-error / conformance-failed is
5
+ // re-admitted by policy instead of by an operator. Pure helpers; the runner (orchestrate.mjs) feeds the results through its
6
+ // existing add/requeue seams (the query is issue-watch's `search` selector, handed to gh unchanged, K2; no import, so batch.mjs can use this module), so the DAG, priority and lane rules are the ones a `--add` already gets (K1).
7
+
8
+ /** How often the runner re-reads the selector ("every few minutes"). */
9
+ export const RECONCILE_MS = 3 * 60 * 1000;
10
+ /** Deferred issues retry with exponential backoff from this base, capped at DEFER_CAP_MS. */
11
+ export const DEFER_BASE_MS = 5 * 60 * 1000;
12
+ export const DEFER_CAP_MS = 2 * 60 * 60 * 1000;
13
+ /** A held / engine-error issue is a fresh attempt after this cooldown even if no version moved. */
14
+ export const HELD_COOLDOWN_MS = 6 * 60 * 60 * 1000;
15
+ /** The breaker auto-resets after this cooldown when its failures were environmental. */
16
+ export const BREAKER_COOLDOWN_MS = 15 * 60 * 1000;
17
+
18
+ /** gh args listing the open issues `select` matches (a GitHub search query: `no:milestone`, `milestone:X`, `label:Y`). */
19
+ export const selectArgs = (repo, select) => ["issue", "list", "-R", repo, "--state", "open", "--search", String(select), "--limit", "500", "--json", "number,labels,milestone,title"];
20
+
21
+ /** Open issue numbers (and labels) from the `gh issue list --json` output; null when it cannot be read (nobody leaves on a failed read). */
22
+ export function parseSelected(text) {
23
+ let v;
24
+ try { v = JSON.parse(text); } catch { return null; }
25
+ if (!Array.isArray(v)) return null;
26
+ return v.filter((x) => Number.isSafeInteger(x?.number) && x.number > 0).map((x) => ({ number: x.number, labels: (x.labels ?? []).map((l) => (typeof l === "string" ? l : l?.name)).filter(Boolean) }));
27
+ }
28
+
29
+ /**
30
+ * Diff the selector result against batch membership.
31
+ * @returns {{join:number[], leave:number[]}} join: open matches not in the batch; leave: pending members (not running, no result row) no longer open/matching
32
+ */
33
+ export function diffSelection({ open, members, pending, running, results, matched = null }) {
34
+ const have = new Set(members), now = new Set(open.map((o) => o.number));
35
+ const join = [...now].filter((n) => !have.has(n)).sort((a, b) => a - b);
36
+ // #6022: only an issue the selector matched can leave it; env.* issues, children, --add and argv members never did
37
+ const leave = pending.filter((n) => (!matched || matched.has(n)) && !now.has(n) && !running.has(n) && !results.has(n));
38
+ return { join, leave };
39
+ }
40
+
41
+ /** Human codes (credentials, spend, customer, promotion, product decision): the only reasons an issue may stay unscheduled. */
42
+ const HUMAN = /\b(credentials?|secrets?\b.*\b(needed|missing|required)|api[ -]?keys?|spend|billing|payment|budget approval|customers?|promotion|promote|product decision|needs?[- ]decision|human[- ]code)\b/i;
43
+ export const HUMAN_LABEL = /^(human[:/-].+|needs?-(credentials|spend|customer|promotion|product-decision))$/i;
44
+ export const humanCode = (row, labels = []) => labels.some((l) => HUMAN_LABEL.test(l)) || (row?.outcome === "needs-human" && !row?.conformance && HUMAN.test(String(row?.detail ?? "")));
45
+
46
+ /** Failure details that are environmental (VM restart, mirror, network): a breaker tripped by them may close itself (#5947 classes). */
47
+ export const environmentalDetail = (detail) => /\b(vm (restart|reboot)|restart(ed|ing)|mirror|network|dns|econn(reset|refused)|etimedout|connection (reset|refused|timed out)|net\.transient|sandbox\.lost|unreachable)\b/i.test(String(detail ?? ""));
48
+
49
+ /** @returns {number} ms to wait before deferred attempt number `n` (0-based) is retried */
50
+ export const backoffMs = (n) => Math.min(DEFER_CAP_MS, DEFER_BASE_MS * 2 ** Math.max(0, Math.min(n, 16)));
51
+
52
+ /**
53
+ * Re-admission policy for rows that ended without success. `state` is `Map<issue, {n, since, version, base, conformanceTried}>`
54
+ * (kept in batch state); it is updated in place. Returns the issues to requeue with the reason, and the parked "needs decision" list.
55
+ * @param {{results:Map<number,object>, state:Map<number,object>, now:number, version:string|null, base:string|null, labels?:(n:number)=>string[]}} p
56
+ */
57
+ export function readmitDue({ results, state, now, version = null, base = null, labels = () => [] }) {
58
+ const requeue = [], parked = [];
59
+ for (const [n, row] of results) {
60
+ const o = row?.outcome;
61
+ const isConf = Boolean(row?.conformance) && o === "needs-human";
62
+ if (!["deferred", "held", "engine-error"].includes(o) && !isConf) { state.delete(n); continue; }
63
+ if (humanCode(row, labels(n))) continue;
64
+ let s = state.get(n);
65
+ if (!s || s.outcome !== o) { s = { n: s?.n ?? 0, since: now, version, base, outcome: o, conformanceTried: s?.conformanceTried ?? 0 }; state.set(n, s); }
66
+ if (o === "deferred") {
67
+ if (now - s.since >= backoffMs(s.n)) { requeue.push({ issue: n, reason: `deferred: retry ${s.n + 1} after backoff (cap ${DEFER_CAP_MS / 3600000} h)` }); state.set(n, { ...s, n: s.n + 1, since: now, outcome: null }); }
68
+ } else if (isConf) {
69
+ if (s.conformanceTried >= 1) { parked.push({ issue: n, why: "conformance failed after one retry on a moved base" }); continue; }
70
+ if (base && s.base && base !== s.base) { requeue.push({ issue: n, reason: "conformance: one more attempt, the base moved" }); state.set(n, { ...s, conformanceTried: s.conformanceTried + 1, since: now, outcome: null, base }); }
71
+ else if (!s.base && base) state.set(n, { ...s, base });
72
+ } else {
73
+ const moved = version && s.version && version !== s.version;
74
+ if (moved || now - s.since >= HELD_COOLDOWN_MS) { requeue.push({ issue: n, reason: moved ? `${o}: agent/lane-image version changed` : `${o}: cooldown elapsed, fresh attempt` }); state.set(n, { ...s, since: now, version, outcome: null }); }
75
+ }
76
+ }
77
+ return { requeue, parked };
78
+ }
79
+
80
+ /**
81
+ * The breaker may close itself: an environmental failure signature, the cooldown elapsed and the pool healthy again.
82
+ * (Lives in clear-breaker.mjs as `decideAutoReset`; re-exported here for the policy tests.)
83
+ */
84
+ export { decideAutoReset } from "./clear-breaker.mjs";
85
+
86
+ /** One "needs decision" digest for the parked issues: a single decision body, empty string when nothing is parked. */
87
+ export const needsDecisionDigest = (parked) => (parked.length ? `needs decision (${parked.length}): ${parked.map((p) => `#${p.issue} (${p.why})`).join("; ")}` : "");
88
+
89
+ /** Whether a merge into `lane` leaves the issue open on GitHub (`Closes` only fires on the default branch): staging / milestone lanes. */
90
+ export const closesManually = (lane, defaultBranch = "main") => Boolean(lane) && lane !== defaultBranch && /^(staging|milestone\/|release\/|lane\/)/.test(String(lane));
@@ -54,9 +54,20 @@ export function pathsOverlap(a, b) {
54
54
  return Boolean(x && y) && (x === y || x.startsWith(`${y}/`) || y.startsWith(`${x}/`));
55
55
  }
56
56
 
57
+ /** #5979: backticked error/outcome-code/test signatures of the issue body (identifier-shaped, not a path). */
58
+ function symptomTerms(body) {
59
+ return [...new Set([...String(body ?? "").matchAll(/`([A-Za-z][\w.:-]{3,79})`/g)].map((m) => m[1].toLowerCase()).filter((t) => !/\.(?:m?[jt]sx?|md|json|ya?ml|py|sh)$/.test(t)))];
60
+ }
61
+
62
+ /** #5979: a subjectHistory row shares the issue's symptom: it matched on a code-shaped term (outcome code, error name, symbol), on two or more terms, or its title carries a backticked signature of the issue. */
63
+ function symptomMatch(row, terms) {
64
+ const m = (row?.matched ?? []).map(String);
65
+ return m.some((t) => /[._:-]|\d|[a-z][A-Z]|^[A-Z0-9_]{3,}$/.test(t)) || m.length >= 2 || terms.some((t) => String(row?.title ?? "").toLowerCase().includes(t));
66
+ }
67
+
57
68
  /**
58
69
  * Count earlier merged fixes on the same symptom and the same area. A subjectHistory row counts when it is a merged PR
59
- * whose files (`mergedPrFiles[number]`) overlap a path the issue names. A `Recurs #n` link is an explicit symptom match:
70
+ * whose files (`mergedPrFiles[number]`) overlap a path the issue names AND that shares the symptom (#5979: path-only overlap never counts). A `Recurs #n` link is an explicit symptom match:
60
71
  * it counts when its files overlap or are unknown (the author declared the same area). Rows without overlap never count.
61
72
  * @returns {{recurs:boolean, count:number, threshold:number, evidence:{number:number, title:string, via:string, paths:string[]}[], reason:string}}
62
73
  */
@@ -64,9 +75,11 @@ export function detectRecurrence({ rows = [], mergedPrFiles = {}, body = "", nam
64
75
  const named = [...new Set((namedPaths ?? []).map(clean).filter(Boolean))];
65
76
  const filesOf = (n) => (mergedPrFiles instanceof Map ? mergedPrFiles.get(n) : mergedPrFiles?.[n]);
66
77
  const evidence = [], seen = new Set();
78
+ const sym = symptomTerms(body);
67
79
  for (const r of rows ?? []) {
68
80
  const n = Number(r?.number);
69
81
  if (!Number.isSafeInteger(n) || seen.has(n) || r?.kind !== "PR" || r?.status !== "merged") continue;
82
+ if (!symptomMatch(r, sym)) continue; // #5979: path overlap alone is the same area, not the same symptom
70
83
  const paths = (filesOf(n) ?? []).map(clean).filter((f) => named.some((p) => pathsOverlap(f, p)));
71
84
  if (!paths.length) continue;
72
85
  seen.add(n);
@@ -88,14 +101,28 @@ export function detectRecurrence({ rows = [], mergedPrFiles = {}, body = "", nam
88
101
  return { recurs, count, threshold: t, evidence, reason };
89
102
  }
90
103
 
104
+ /** #6016: a staging->default release PR head (`release/...`). */
105
+ export const isReleaseHead = (ref) => /^release\//.test(String(ref ?? ""));
106
+
91
107
  /**
92
108
  * The engine-side gather: subjectHistory rows plus one file-list read per merged row (capped). `io`: {gh, git}. Never
93
109
  * throws: a failed source contributes nothing and lands in `errors`.
94
110
  */
95
- export async function recurrenceFacts({ io, repo, issue, title = "", body = "", base = null, namedPaths = [], threshold, exclude = [] }) {
111
+ export async function recurrenceFacts({ io, repo, issue, title = "", body = "", base = null, namedPaths = [], threshold, exclude = [], createdAt = null }) {
96
112
  const errors = [];
97
113
  let rows = [];
98
114
  try { const h = await subjectHistory({ io, repo, issue, title, body, base, exclude }); rows = h.rows ?? []; errors.push(...(h.errors ?? [])); } catch (e) { errors.push(`recurrence: ${String(e?.message ?? e).slice(0, 80)}`); }
115
+ // #6016: a release PR (head release/*) touches every shipped file, and a PR merged after the issue was filed cannot be an
116
+ // earlier fix that did not hold: neither is evidence. A row whose metadata cannot be read stays (explicit Recurs links too).
117
+ const created = Date.parse(createdAt ?? "");
118
+ const notEvidence = new Set();
119
+ for (const r of rows.filter((x) => x?.kind === "PR" && x?.status === "merged").slice(0, MAX_RECURRENCE_ROWS)) {
120
+ try {
121
+ const m = JSON.parse(String(await io.gh(["api", `repos/${repo}/pulls/${Number(r.number)}`, "--jq", "{head: .head.ref, merged: .merged_at}"])));
122
+ if (isReleaseHead(m?.head) || (Number.isFinite(created) && Date.parse(m?.merged ?? "") > created)) notEvidence.add(Number(r.number));
123
+ } catch { /* unreadable: keep the row */ }
124
+ }
125
+ rows = rows.filter((r) => !notEvidence.has(Number(r?.number)));
99
126
  const wanted = [...new Set([...rows.filter((r) => r?.kind === "PR" && r?.status === "merged").map((r) => Number(r.number)), ...recursLinks(body)])].slice(0, MAX_RECURRENCE_ROWS);
100
127
  const mergedPrFiles = {};
101
128
  if (namedPaths.length) {
@@ -121,6 +148,12 @@ Prefer "delete" or "replace" of the earlier fixes; "extend" needs its reason in
121
148
  /** #5751: a design lane's contract must carry design {why_failed, disposition delete|replace|extend, outcome {metric, target}}. */
122
149
  export function designContractFailures(contract, detection) {
123
150
  if (!detection?.recurs) return [];
151
+ // #5918/#5979: a design block is demanded once. Asked for on an earlier run and still absent, it is not demanded again: the repeat parks (failure.repeated) for a decision.
152
+ if (detection.demanded) {
153
+ const d0 = contract?.design;
154
+ if (d0 && typeof d0 === "object" && !Array.isArray(d0)) return designContractFailures(contract, { ...detection, demanded: false });
155
+ return [{ code: C.FAILURE_REPEATED, kind: "design_missing_repeated", detail: `recurring issue (${detection.count} earlier fixes): the design block was already demanded on an earlier run and is still missing; parked for a decision instead of demanding it again` }];
156
+ }
124
157
  const d = contract?.design, problems = [];
125
158
  const s = (v) => typeof v === "string" && v.trim();
126
159
  if (!d || typeof d !== "object" || Array.isArray(d)) problems.push("no design block");
@@ -131,3 +164,6 @@ export function designContractFailures(contract, detection) {
131
164
  }
132
165
  return problems.length ? [{ code: C.RECURRENCE_DESIGN_MISSING, kind: "design_missing", detail: `recurring issue (${detection.count} earlier fixes) routed to a design lane: ${problems.join("; ")}` }] : [];
133
166
  }
167
+
168
+ /** #5979: true when an earlier NEEDS_HUMAN/PARKED comment of the issue already reported the missing design block. */
169
+ export const designDemanded = (comments) => (Array.isArray(comments) ? comments : []).some((c) => /<!--\s*FORGE:(?:NEEDS_HUMAN|PARKED)/.test(String(c?.body ?? "")) && /routed to a design lane:/.test(String(c?.body ?? "")));
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { parseRecurrenceConfig, detectRecurrence, recursLinks, pathsOverlap, recurrenceFacts, designLaneNote, designContractFailures } from "./recurrence.mjs";
5
+ import { parseRecurrenceConfig, detectRecurrence, recursLinks, pathsOverlap, recurrenceFacts, designLaneNote, designContractFailures, isReleaseHead } from "./recurrence.mjs";
6
6
 
7
7
  const row = (number, o = {}) => ({ number, kind: "PR", status: "merged", title: `fix leak ${number}`, matched: ["reservation", "leak"], ...o });
8
8
  const NAMED = ["src/billing/reserve.js"];
@@ -76,6 +76,27 @@ describe("recurrence detection (#5751)", () => {
76
76
  });
77
77
  });
78
78
 
79
+ describe("recurrence evidence excludes release PRs and later merges (#6016)", () => {
80
+ const gh = (meta) => async (a) => {
81
+ const j = a.join(" ");
82
+ if (j.includes("search/issues")) return [10, 11, 12].map((n) => JSON.stringify({ number: n, title: `pr ${n}`, pr: true, merged: true })).join("\n");
83
+ const f = /pulls\/(\d+)\/files/.exec(j); if (f) return "src/billing/reserve.js\n";
84
+ const m = /pulls\/(\d+)$/.exec(a[1] ?? ""); if (m) return JSON.stringify(meta[m[1]]);
85
+ throw new Error("unexpected " + j);
86
+ };
87
+ it("a release PR and a PR merged after the issue was filed are not earlier fixes", async () => {
88
+ const meta = { 10: { head: "release/20261123-1", merged: "2026-11-01T00:00:00Z" }, 11: { head: "feat/x", merged: "2026-11-20T00:00:00Z" }, 12: { head: "feat/y", merged: "2026-11-02T00:00:00Z" } };
89
+ const d = await recurrenceFacts({ io: { gh: gh(meta) }, repo: "o/r", issue: 7, title: "reservation leak", body: "See src/billing/reserve.js", namedPaths: NAMED, threshold: 2, createdAt: "2026-11-10T00:00:00Z" });
90
+ assert.deepEqual(d.evidence.map((e) => e.number), [12]);
91
+ assert.equal(d.recurs, false);
92
+ });
93
+ it("isReleaseHead matches only release/ heads", () => {
94
+ assert.equal(isReleaseHead("release/1"), true);
95
+ assert.equal(isReleaseHead("feat/release/1"), false);
96
+ assert.equal(isReleaseHead(null), false);
97
+ });
98
+ });
99
+
79
100
  describe("design lane (#5751)", () => {
80
101
  const det = detectRecurrence({ rows: [row(10), row(11)], mergedPrFiles: { 10: NAMED, 11: NAMED }, namedPaths: NAMED });
81
102
  it("the plan note names the earlier fixes and asks why they failed, delete or replace, a measurable outcome and allows a split", () => {
@@ -97,3 +118,37 @@ describe("design lane (#5751)", () => {
97
118
  assert.deepEqual(designContractFailures({}, { recurs: false }), [], "an ordinary lane needs no design block");
98
119
  });
99
120
  });
121
+
122
+ import { designDemanded } from "./recurrence.mjs";
123
+ describe("symptom match and one-time design demand (#5979)", () => {
124
+ const files = { 10: NAMED, 11: NAMED };
125
+ it("path-only overlap without a symptom match does not recur", () => {
126
+ const rows = [row(10, { matched: ["billing"], title: "tidy billing" }), row(11, { matched: ["reserve"], title: "rename" })];
127
+ const d = detectRecurrence({ rows, mergedPrFiles: files, namedPaths: NAMED, body: "the page is slow" });
128
+ assert.equal(d.recurs, false);
129
+ assert.equal(d.count, 0);
130
+ });
131
+ it("a code-shaped symptom plus path still recurs", () => {
132
+ const rows = [row(10, { matched: ["reservation.leak"] }), row(11, { matched: ["reservation.leak"] })];
133
+ assert.equal(detectRecurrence({ rows, mergedPrFiles: files, namedPaths: NAMED }).recurs, true);
134
+ });
135
+ it("a backticked signature of the issue in the row title is a symptom match", () => {
136
+ const rows = [row(10, { matched: ["billing"], title: "fix `ERR_RESERVE` crash" }), row(11, { matched: ["billing"], title: "again ERR_RESERVE" })];
137
+ assert.equal(detectRecurrence({ rows, mergedPrFiles: files, namedPaths: NAMED, body: "throws `ERR_RESERVE`" }).recurs, true);
138
+ });
139
+ it("a Recurs link is unchanged", () => {
140
+ assert.equal(detectRecurrence({ rows: [], mergedPrFiles: { 5: NAMED, 6: NAMED }, body: "Recurs #5, #6", namedPaths: NAMED }).recurs, true);
141
+ });
142
+ it("a design block already demanded on an earlier run is not demanded again", () => {
143
+ const det = { recurs: true, count: 2, demanded: true };
144
+ const f = designContractFailures({}, det);
145
+ assert.equal(f.length, 1);
146
+ assert.equal(f[0].kind, "design_missing_repeated");
147
+ assert.equal(designContractFailures({}, { ...det, demanded: false })[0].kind, "design_missing");
148
+ assert.deepEqual(designContractFailures({ design: { why_failed: "w", disposition: "replace", outcome: { metric: "m", target: "t" } } }, det), []);
149
+ });
150
+ it("designDemanded reads an earlier NEEDS_HUMAN naming the design lane", () => {
151
+ assert.equal(designDemanded([{ body: "<!-- FORGE:NEEDS_HUMAN -->\nrecurring issue (2 earlier fixes) routed to a design lane: no design block" }]), true);
152
+ assert.equal(designDemanded([{ body: "<!-- FORGE:NEEDS_HUMAN -->\nother" }]), false);
153
+ });
154
+ });
@@ -78,6 +78,8 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
78
78
  const e = new Error(`sandbox ${what}: HTTP ${r.status}${who ? ` (${who} auth${reason ? `: ${reason}` : ""})` : ""}`);
79
79
  e.status = r.status;
80
80
  if (hop) e.hop = hop;
81
+ if (typeof r.data?.code === "string" && r.data.code.startsWith("pool.")) e.poolCode = r.data.code; // #5985: the pool's refusal code reaches the deferral row
82
+ if (r.data?.live && typeof r.data.live === "object") e.live = { load_per_core: r.data.live.load_per_core, mem_available_gb: r.data.live.mem_available_gb };
81
83
  if (reason) e.reason = reason;
82
84
  if ([500, 502, 503, 504].includes(r.status)) e.transient = true; // #4672: a router restart or gateway blip, retried by the lane poll; #5095: 500 too
83
85
  if (r.status === 429 || r.status === 503) e.retryable = true;
@@ -141,8 +143,24 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
141
143
  const sb = r.data.sandboxes && typeof r.data.sandboxes === "object" ? Object.keys(r.data.sandboxes) : [];
142
144
  return { agents, total: int(r.data.remote_lanes) ?? sb.filter((id) => id.startsWith("fdrsbx-")).length };
143
145
  },
146
+ /** #5985: finished-lane usage rows (`{repo, cpu_avg, ...}`) of every pool agent (`GET /agents/:name/usage`), for the light/heavy lane class. A bad answer throws. */
147
+ async usageHistory() {
148
+ const r = await call("GET", "/agents");
149
+ if (!r.ok) throw fail("usage history", r);
150
+ const names = (Array.isArray(r.data?.agents) ? r.data.agents : []).map((a) => a?.name).filter((n) => typeof n === "string");
151
+ const rows = [];
152
+ for (const n of names) { try { const u = await call("GET", `/agents/${encodeURIComponent(n)}/usage`); if (u.ok && Array.isArray(u.data?.rows)) rows.push(...u.data.rows); } catch { /* one agent down: its rows are unknown */ } }
153
+ return rows;
154
+ },
144
155
  async relayPending(id) { const r = await call("GET", `${p(id)}/relay`); return r.ok && Array.isArray(r.data?.requests) ? r.data.requests : []; },
145
156
  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; },
157
+ /** #5991: the pool agent that runs `agent` (any agent when unnamed) answers `GET /agents` and is not paused; errors propagate. */
158
+ async agentOnline(agent = null) {
159
+ const r = await call("GET", "/agents");
160
+ const list = r.ok && Array.isArray(r.data?.agents) ? r.data.agents : null;
161
+ if (!list) throw fail("agents", r);
162
+ return list.some((a) => a?.ok === true && !a.paused && (!agent || a.name === agent));
163
+ },
146
164
  async capacity() {
147
165
  // `free` (#4540) and agent liveness `online`/`total` (#4547) are each optional; none valid is unknown.
148
166
  const ok = (v) => Number.isInteger(v) && v >= 0;
@@ -152,13 +170,19 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
152
170
  reached = true;
153
171
  if (r.ok) { const { free, online, total } = r.data ?? {}; out = { ...(ok(free) ? { free } : {}), ...(ok(online) ? { online } : {}), ...(ok(total) ? { total } : {}) }; }
154
172
  } catch (e) { out = {}; lastErr = e; }
155
- if (out.online === undefined) {
173
+ if (out.online === undefined || out.load_per_core === undefined) {
156
174
  // #4788: a router without /status liveness: online = agents answering and not paused, as bin/pool/router.mjs status() does.
157
175
  try {
158
176
  const r = await call("GET", "/agents");
159
177
  reached = true;
160
178
  const list = r.ok && Array.isArray(r.data?.agents) ? r.data.agents : null;
161
- if (list) out = { ...out, online: list.filter((a) => a?.ok === true && !a.paused).length, total: list.length };
179
+ if (list && out.online === undefined) out = { ...out, online: list.filter((a) => a?.ok === true && !a.paused).length, total: list.length };
180
+ // #5985: live host figures (worst agent); a pool reporting none leaves them unknown
181
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
182
+ const loads = (list ?? []).map((a) => num(a?.load_per_core ?? a?.live?.load_per_core)).filter((v) => v !== null);
183
+ const mems = (list ?? []).map((a) => num(a?.mem_available_gb ?? a?.live?.mem_available_gb)).filter((v) => v !== null);
184
+ if (loads.length) out = { ...out, load_per_core: Math.max(...loads) };
185
+ if (mems.length) out = { ...out, mem_available_gb: Math.min(...mems) };
162
186
  } catch (e) { lastErr = e; /* liveness stays unknown */ }
163
187
  }
164
188
  // #5048 (release review REG-2): a router that answered neither call is unreachable: throw, so the pool is marked down
@@ -302,11 +326,18 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
302
326
  if (runLog) mergeRemoteLog(env.FORGE_RUNS_DIR || join(homedir(), ".forge", "runs"), h.issue, runLog, { repo });
303
327
  return rest;
304
328
  },
329
+ /** #5991: is the pool agent of this handle answering? Unknown (null) without transport support; transport errors propagate. */
330
+ async agentOnline(h) {
331
+ if (typeof transport.agentOnline !== "function") return null;
332
+ return transport.agentOnline(typeof h?.agent === "string" && h.agent ? h.agent : null);
333
+ },
305
334
  async capacity() {
306
335
  // #5048: no capacity() is unknown (null); a transport error propagates, so the caller can report the pool down
307
336
  if (typeof transport.capacity !== "function") return null;
308
337
  return (await transport.capacity()) ?? null;
309
338
  },
339
+ /** #5985: the pool's usage-history rows; null when the transport has none. */
340
+ async usageHistory() { return typeof transport.usageHistory === "function" ? (await transport.usageHistory()) ?? null : null; },
310
341
  /** #4612: a graceful stop at the lane's checkpoint; false when unsupported or failed. Never destroys the sandbox. */
311
342
  async stop(h) {
312
343
  if (typeof transport.stop !== "function") { stopWhy.set(h.id, "the transport has no stop"); return false; }
@@ -25,6 +25,7 @@ import { closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statS
25
25
  import { homedir } from "node:os";
26
26
  import { join } from "node:path";
27
27
  import { writeAtomic } from "./batch.mjs";
28
+ import { formatConcurrency } from "./concurrency.mjs";
28
29
 
29
30
  export const DEFAULT_PRIORITY = 2;
30
31
  export const LOCK_WAIT_MS = 2000;
@@ -260,6 +261,24 @@ export function remoteLines(st, { agentOf = null } = {}) {
260
261
  return out;
261
262
  }
262
263
 
264
+ /**
265
+ * #5985: `sched show`/status lines `batch B concurrency: running/K/ceiling (limiting factor)`, from each running batch's last
266
+ * controller event in `log.jsonl` (`eventsOf(batch) -> rows`); `achieved` is running over the configured ceiling. Empty when none logged.
267
+ */
268
+ export function concurrencyLines(st, { eventsOf = null } = {}) {
269
+ if (typeof eventsOf !== "function") return [];
270
+ const batches = [...new Set([...(st?.slots ?? []), ...(st?.remote ?? [])].map((e) => e.batch).filter(Boolean))];
271
+ const out = [];
272
+ for (const b of batches) {
273
+ let last = null;
274
+ try { for (const r of eventsOf(b) ?? []) if (r?.event === "concurrency") last = r; } catch { last = null; }
275
+ if (!last || !Number.isInteger(last.ceiling)) continue;
276
+ const running = Number.isInteger(last.running) ? last.running : 0;
277
+ out.push(`batch ${b} ${formatConcurrency({ running, k: last.k, ceiling: last.ceiling, factor: last.factor })}; achieved ${running} of ${last.ceiling} configured`);
278
+ }
279
+ return out;
280
+ }
281
+
263
282
  /** #5847: batch-start report of the effective concurrency K, the host cap and which source set it; pure and read-only. */
264
283
  export function describeConcurrency({ parallel, parallelFrom = "default", registryCap = null, globalParallel = null, derivedCap = null, yamlFound = true, cwd = "." } = {}) {
265
284
  const pos = (n) => (Number.isInteger(n) && n > 0 ? n : null);
@@ -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 { describeConcurrency, grantOrder, openSched, priorityFromLabels, remoteLines } from "./sched.mjs";
8
+ import { concurrencyLines, 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
 
@@ -601,3 +601,13 @@ describe("describeConcurrency", () => {
601
601
  assert.deepEqual(describeConcurrency({ parallel: 1 }).warnings, []);
602
602
  });
603
603
  });
604
+
605
+ describe("concurrencyLines (#5985)", () => {
606
+ it("prints running/K/ceiling (limiting factor) with achieved vs configured from the last controller event", () => {
607
+ const rows = [{ event: "concurrency", k: 8, ceiling: 8, running: 8, factor: "ceiling" }, { issue: 3, outcome: "merged" }, { event: "concurrency", k: 4, ceiling: 8, running: 3, factor: "host_load" }];
608
+ const st = { slots: [{ batch: "b1" }], remote: [{ batch: "b1" }, { batch: "b2" }] };
609
+ const lines = concurrencyLines(st, { eventsOf: (b) => (b === "b1" ? rows : []) });
610
+ assert.deepEqual(lines, ["batch b1 concurrency: 3/4/8 (host_load); achieved 3 of 8 configured"]);
611
+ assert.deepEqual(concurrencyLines(st), []);
612
+ });
613
+ });
@@ -55,15 +55,15 @@ 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, batchVerdicts = null, unit = null, emit = null } = {}) {
58
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m), unfinished = () => [], start = null, restart = null, batchVerdicts = null, unit = null, emit = null } = {}) {
59
59
  const c = stallCheck({ dir, stallMs, now, alive });
60
60
  if (batchVerdicts) { try { for (const l of batchVerdicts() ?? []) log(`schedd watchdog: ${l}`); } catch { /* advisory */ } } // #5938: one verdict line per batch
61
61
  // #5966: the unit says active but no daemon answers (no live pid/heartbeat): alert and restart it, whether or not batches are unfinished
62
- if (c.status === "down" && start && unit && ["active", "activating"].includes((() => { try { return unit(); } catch { return null; } })())) {
62
+ if (c.status === "down" && restart && unit && ["active", "activating"].includes((() => { try { return unit(); } catch { return null; } })())) {
63
63
  log(`schedd watchdog: ALERT unit is active but no daemon answers (schedd status: not running); restarting the unit`);
64
64
  try { emit?.({ type: "schedd.unit-no-daemon", at: now() }); } catch { /* advisory */ }
65
- try { await start(); } catch (e) { log(`schedd watchdog: start failed: ${e?.message ?? e}`); return { ...c, killed: null, alerted: true, started: false }; }
66
- return { ...c, killed: null, alerted: true, started: true };
65
+ try { await restart(); } catch (e) { log(`schedd watchdog: restart failed: ${e?.message ?? e}`); return { ...c, killed: null, alerted: true, started: false, restarted: false }; }
66
+ return { ...c, killed: null, alerted: true, started: true, restarted: true }; // `systemctl start` is a no-op on an active unit, so this must be a restart
67
67
  }
68
68
  if (c.status === "down" && start) {
69
69
  let ids = [];
@@ -71,16 +71,20 @@ describe("schedd heartbeat and watchdog (#4780)", () => {
71
71
 
72
72
  it("#5966: a down daemon while the unit is active alerts, emits an event and restarts the unit, even with no unfinished batches", async () => {
73
73
  const dir = tmpDir("schedd-wd-unit-"), lines = [], events = [];
74
- let starts = 0;
75
- const run = (unit) => watchdog({ dir, now: () => 0, alive: () => false, unfinished: () => [], start: async () => { starts++; }, unit, emit: (e) => events.push(e), log: (m) => lines.push(m) });
74
+ let starts = 0, restarts = 0;
75
+ const run = (unit, restart = async () => { restarts++; }) => watchdog({ dir, now: () => 0, alive: () => false, unfinished: () => [], start: async () => { starts++; }, restart, unit, emit: (e) => events.push(e), log: (m) => lines.push(m) });
76
76
  const r = await run(() => "active");
77
77
  assert.equal(r.started, true);
78
78
  assert.equal(r.alerted, true);
79
- assert.equal(starts, 1);
79
+ assert.equal(r.restarted, true);
80
+ assert.deepEqual([restarts, starts], [1, 0], "an active unit is restarted, never started");
80
81
  assert.equal(events[0].type, "schedd.unit-no-daemon");
81
82
  assert.ok(lines.some((l) => l.includes("ALERT")));
82
83
  await run(() => "inactive");
83
84
  await run(() => null);
84
- assert.equal(starts, 1, "an inactive or absent unit with nothing unfinished is left down");
85
+ assert.equal(restarts, 1, "an inactive or absent unit with nothing unfinished is left down");
86
+ const f = await run(() => "active", async () => { throw new Error("denied"); });
87
+ assert.deepEqual([f.started, f.restarted, f.alerted], [false, false, true]);
88
+ assert.match(lines.at(-1), /restart failed: denied/);
85
89
  });
86
90
  });
@@ -34,6 +34,8 @@
34
34
  * Exit reasons (#4503): every exit logs a line: `idle, exiting`, `exiting (<signal>|uncaught: …)`, `lost lock|socket …,
35
35
  * exiting` (checked every `lockCheckMs`: the lock no longer holds this pid, or the socket is gone; nothing it does not own
36
36
  * is removed), then `exited (code N)`. Taking over a dead owner's lock is logged, so a SIGKILLed daemon leaves a trace.
37
+ * Standing orders (#5978): a `--select` batch's reconcile tick (selector join/leave, re-admission, breaker auto-reset) runs inside the
38
+ * batch's runner, which this daemon hosts: no watcher process, and no change to how the daemon or its batches are kept alive.
37
39
  * Upgrade handover (#5204): the same `lockCheckMs` tick compares `installedVersion()` (the `version` of the package.json of
38
40
  * this install) with the version loaded at start. When the install moved (`npm i -g`, `forgedock update`) it logs
39
41
  * `schedd: install moved v<old> → v<new>; handing over` once, runs `close()` (no admission, lanes keep running, lock and
@@ -42,7 +44,7 @@
42
44
  * `interrupted: upgrade vX→vY` row (orchestrate.mjs).
43
45
  * `runBatch({argv, cwd, env, sink, keepBreaker, signal})` is injected (engine-cli `runBatch`); `sink` gets `batch(b)`, `row(r)`, `line(text)`.
44
46
  */
45
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeSync } from "node:fs";
47
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
46
48
  import { createConnection, createServer } from "node:net";
47
49
  import { execFileSync, spawn } from "node:child_process";
48
50
  import { homedir, tmpdir } from "node:os";
@@ -52,6 +54,10 @@ import { fileURLToPath } from "node:url";
52
54
  import { schedDir, pidAlive } from "./sched.mjs";
53
55
  import { DEFAULT_STALL_MIN, FIRST_HOUR_FILE, FIRST_HOUR_MIN, batchVerdict, clearStaleStall, decideStallAction, evaluateDispatchStall, firstHourReport, readHealth, recordStallAlert, recordStallRecovery, runningSplit, writeFirstHour } from "./batch-health.mjs";
54
56
  import { probeBatchEnv } from "./lanecheck.mjs";
57
+ import { computeEfficiency, idleCause, operatorEvents, readEfficiency, writeEfficiency } from "./efficiency.mjs";
58
+ import { ledgerPass, parseSloConfig } from "./slo.mjs";
59
+ import { introspectReportPath } from "../introspect-schedule.mjs";
60
+ import { parseForgeYaml } from "../forge-utils.mjs";
55
61
  import { HEARTBEAT_MS, writeHeartbeat, clearHeartbeat } from "./schedd-health.mjs";
56
62
  import { batchRoot, listBatches, openBatch, SECRET_ENV } from "./batch.mjs";
57
63
  import { killTrackedChildren } from "./effects.mjs";
@@ -221,7 +227,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
221
227
  lockCheckMs = LOCK_CHECK_MS, admitMs = Number(process.env.FORGEDOCK_SCHEDD_ADMIT_MS) || ADMIT_MS, lagMs = LAG_MS, stallCheckMs = Number(process.env.FORGEDOCK_SCHEDD_STALL_CHECK_MS) || 60_000, stallMin = Number(process.env.FORGEDOCK_SCHEDD_STALL_MIN) || DEFAULT_STALL_MIN, due = null, dueMs = Number(process.env.FORGEDOCK_SCHEDD_DUE_MS) || DUE_MS, preflight = null,
222
228
  abandonMs = (Number(process.env.FORGEDOCK_SCHEDD_ABANDON_DAYS) > 0 ? Number(process.env.FORGEDOCK_SCHEDD_ABANDON_DAYS) * 24 * 3600 * 1000 : ABANDON_AGE_MS), killChildren = killTrackedChildren,
223
229
  hostLoad = liveOverload(), installedVersion = readInstalledVersion, respawn = undefined, probeEnv = (env) => probeBatchEnv(env), restartForStall = undefined,
224
- exit = null, hardExitMs = HARD_EXIT_MS, unit = unitState, probe = undefined, successorMs = SUCCESSOR_MS, successorPollMs = 200, rehost = undefined } = {}) {
230
+ exit = null, hardExitMs = HARD_EXIT_MS, unit = unitState, probe = undefined, successorMs = SUCCESSOR_MS, successorPollMs = 200, rehost = undefined, sloGh = undefined, introspect = undefined } = {}) {
225
231
  const startOpts = arguments[0] ?? {};
226
232
  const p = scheddPaths(dir);
227
233
  // #5204: default handover target: a new daemon from the (new) install unless systemd restarts the unit itself
@@ -615,6 +621,26 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
615
621
  phase("watch");
616
622
  try { await watchPass(); } finally { watching = false; phase("idle"); }
617
623
  };
624
+ // #5987: per-pass efficiency ledger + SLO filing (default-off) + one introspect run at batch end. Advisory: every failure is swallowed.
625
+ const sloGhDefault = (args) => new Promise((ok, no) => { import("node:child_process").then(({ execFile }) => execFile("gh", args, { timeout: 30000 }, (e, out) => (e ? no(e) : ok(String(out))))); });
626
+ async function efficiencyTick(b, plan, state, { now, reported, cancelled }) {
627
+ try {
628
+ if (cancelled || !state) return;
629
+ const repoCwd = plan.cwd ?? process.cwd();
630
+ let cfg;
631
+ try { cfg = parseSloConfig(parseForgeYaml(readFileSync(join(repoCwd, "forge.yaml"), "utf8"))); } catch { cfg = parseSloConfig({}); }
632
+ const ceiling = b.readParallel() ?? Number(state.parallel ?? plan.parallel) ?? 0, running = Object.keys(state.running ?? {}).length;
633
+ const sample = reported ? null : { t: now, running, ceiling: Number.isFinite(ceiling) ? ceiling : running, ready: (state.pending ?? []).length, ...((c) => (c ? { cause: c } : {}))(b.readPause?.() ? "auth-pause" : idleCause(b.readLog(), now) ?? (b.readHeld().length ? "hold" : undefined)) };
634
+ const r = await ledgerPass({ batch: b, sample, cfg, gh: sloGh ?? sloGhDefault, now, repo: plan.repo ?? null, operator: operatorEvents(b.dir), compute: computeEfficiency, readEff: readEfficiency, writeEff: writeEfficiency, reportPath: cfg.fileIssues ? introspectReportPath(repoCwd) : null });
635
+ if (r?.actions?.length) log(`schedd: slo ${r.actions.map((a) => `${a.op} ${a.sig} #${a.issue}`).join(", ")}`);
636
+ const mark = join(b.dir, "introspect.json");
637
+ if (reported && cfg.fileIssues && !existsSync(mark)) {
638
+ writeEfficiency(b.dir, { ...r.eff, introspect: { at: new Date(now).toISOString() } });
639
+ writeFileSync(mark, JSON.stringify({ at: new Date(now).toISOString() }) + "\n", { mode: 0o600 });
640
+ (introspect ?? ((id, cwd) => spawn(process.execPath, [join(fileURLToPath(new URL("..", import.meta.url)), "introspect-schedule.mjs"), "--run"], { cwd, stdio: "ignore", detached: true, windowsHide: true }).unref()))(b.id, repoCwd);
641
+ }
642
+ } catch { /* advisory */ }
643
+ }
618
644
  async function watchPass() {
619
645
  const now = Date.now();
620
646
  for (const id of listBatches(root)) {
@@ -626,6 +652,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
626
652
  const created = Date.parse(plan.created ?? "");
627
653
  if (b.isTerminal() && (!Number.isFinite(created) || now - created >= 24 * 3600_000)) continue; // nothing left to report or re-host
628
654
  const reported = !!b.readReport(), cancelled = !!b.readCancel(), state = b.store.peek(), isHosted = hosted.has(id) || starting.has(id);
655
+ await efficiencyTick(b, plan, state, { now, reported, cancelled }); // #5987: advisory; never throws, never changes dispatch
629
656
  const stallOpts = { held: b.readHeld(), paused: b.readPause?.() ?? null, parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported, lanesAliveMs: lanesAlive(b, state) };
630
657
  let stall = evaluateDispatchStall(state, stallOpts);
631
658
  if (stall && preflight) { // #5745: name the preflight gate holding admission (advisory; dispatch decisions are unchanged)
@@ -746,6 +773,11 @@ export function startUnit({ run = execFileSync } = {}) {
746
773
  try { run("systemctl", ["--user", "start", "--no-block", UNIT], { timeout: 5000, stdio: "ignore" }); } catch { /* reported by the connect retry */ }
747
774
  }
748
775
 
776
+ /** Restart the installed unit (best effort); `start` is a no-op on an active unit with no daemon (#5966). */
777
+ export function restartUnit({ run = execFileSync } = {}) {
778
+ try { run("systemctl", ["--user", "restart", "--no-block", UNIT], { timeout: 5000, stdio: "ignore" }); } catch { /* the next watchdog run alerts again */ }
779
+ }
780
+
749
781
  /**
750
782
  * Connect to the daemon. When nobody listens it is started: a systemd-managed instance (`unitState()` active, activating
751
783
  * or reloading: restarting) is waited for and never raced by a second daemon, an installed but stopped unit is started
@@ -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, batchVerdicts } from "./schedd.mjs";
12
+ import { findUnhosted, startDaemon, scheddPaths, connectDaemon, request, unitState, SCHEDD_SCRIPT, mergeEnv, batchEnv, droppedEnv, sanitizePath, redactEnv, exitOnSignals, readInstalledVersion, batchVerdicts, restartUnit } 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";
@@ -541,6 +541,25 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
541
541
  } finally { await d.close(); }
542
542
  });
543
543
 
544
+ it("R3: efficiencyTick reads forge.yaml from plan.cwd (not the daemon cwd) and spawns introspect there", async () => {
545
+ const dir = tmpDir("schedd-slo-cwd-"), root = join(dir, "batches"), repo = join(dir, "repo"), id = "b20261126-000000-6025", ghCalls = [], spawned = [];
546
+ mkdirSync(repo, { recursive: true });
547
+ const b = openBatch(root, id);
548
+ b.writePlan({ daemon: true, repo: "o/r", cwd: repo, created: new Date().toISOString() });
549
+ b.store.save({ v: 1, order: [1], results: {}, running: {}, pending: [], parallel: 2 });
550
+ b.writeReport({ done: true });
551
+ const start = () => startDaemon({ dir, root, runBatch: async () => ({}), log: () => {}, resumeOnStart: false, stallCheckMs: 50, sloGh: async (a) => { ghCalls.push(a); return "[]"; }, introspect: (i, cwd) => spawned.push([i, cwd]) });
552
+ writeFileSync(join(repo, "forge.yaml"), "orchestrate:\n slo:\n file_issues: false\n");
553
+ let d = await start();
554
+ try { await new Promise((r) => setTimeout(r, 600)); } finally { await d.close(); }
555
+ assert.deepEqual(spawned, [], "file_issues false in plan.cwd is honored");
556
+ assert.equal(ghCalls.length, 0);
557
+ writeFileSync(join(repo, "forge.yaml"), "orchestrate:\n slo:\n file_issues: true\n");
558
+ d = await start();
559
+ try { await until(() => spawned.length === 1, 8000); } finally { await d.close(); }
560
+ assert.deepEqual(spawned[0], [id, repo], "introspect runs on the batch repo");
561
+ });
562
+
544
563
  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 () => {
545
564
  const dir = tmpDir("schedd-stall-clear-"), root = join(dir, "batches"), id = "b20261122-000000-5938", lines = [];
546
565
  const b = openBatch(root, id);
@@ -840,13 +859,15 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
840
859
  const dir = tmpDir("schedd-settled-"), order = [];
841
860
  let version = "1.51.0";
842
861
  const d = await startDaemon({ dir, root: join(dir, "batches"), log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => null,
843
- exit: (c) => order.push(`exit${c}`), respawn: () => order.push("respawn"), probe: async () => { order.push("probe"); return true; }, successorMs: 200, successorPollMs: 10, runBatch: async () => ({}) });
862
+ exit: (c) => order.push(`daemon-exit${c}`), respawn: () => order.push("respawn"), probe: async () => { order.push("probe"); return true; }, successorMs: 200, successorPollMs: 10, runBatch: async () => ({}) });
844
863
  version = "1.52.0";
845
864
  await d.closed;
846
865
  order.push("closed-seen"); // what scheddFromCli used to exit on
847
866
  await d.settled();
848
867
  order.push("settled");
868
+ order.push(`exit${d.stopCode()}`); // the CLI's exit(stopCode), issued only once settled() resolved
849
869
  assert.ok(order.indexOf("respawn") < order.indexOf("settled") && order.indexOf("probe") < order.indexOf("settled"), order.join(","));
870
+ assert.ok(order.indexOf("probe") < order.indexOf("settled") && order.indexOf("settled") < order.indexOf("exit1"), `exit1 after respawn, probe and settled: ${order.join(",")}`);
850
871
  assert.equal(d.stopCode(), 1);
851
872
  });
852
873
 
@@ -1107,6 +1128,15 @@ describe("schedd under load and restart (#4775)", () => {
1107
1128
  await assert.rejects(connectDaemon({ dir: tmpDir("schedd-unit-"), spawnDaemon: null, unit: () => { throw new Error("not consulted"); } }), { code: "ENOENT" });
1108
1129
  });
1109
1130
 
1131
+ it("restartUnit issues systemctl --user restart --no-block and never throws", () => {
1132
+ const calls = [];
1133
+ restartUnit({ run: (...a) => { calls.push(a); } });
1134
+ assert.equal(calls[0][0], "systemctl");
1135
+ assert.deepEqual(calls[0][1].slice(0, 3), ["--user", "restart", "--no-block"]);
1136
+ assert.equal(calls[0][1].length, 4);
1137
+ restartUnit({ run: () => { throw new Error("x"); } });
1138
+ });
1139
+
1110
1140
  it("unitState reads the systemctl state (also from a non-zero exit) and is null without a unit file", () => {
1111
1141
  assert.equal(unitState({ exists: () => false }), null);
1112
1142
  assert.equal(unitState({ exists: () => true, run: () => "activating\n" }), "activating");
@@ -1177,6 +1207,29 @@ describe("schedd under load and restart (#4775)", () => {
1177
1207
  } finally { await d.close(); }
1178
1208
  });
1179
1209
 
1210
+ it("#6001 scheddFromCli handover: exit(stopCode) runs only after the successor is spawned and probed (awaits d.settled)", async () => {
1211
+ const events = [], tick = () => new Promise((r) => setTimeout(r, 15));
1212
+ const d = { running: true, closed: Promise.resolve(), stopCode: () => 1, rehosted: () => null,
1213
+ settled: async () => { await tick(); events.push("respawn"); await tick(); events.push("probe"); } };
1214
+ const res = await scheddFromCli([], { scheddDir: tmpDir("schedd-cli-h-"), startDaemon: async () => d, processOn: () => {}, exit: (c) => events.push(`exit${c}`), due: null, renice: () => {}, batchDeps: {} });
1215
+ assert.deepEqual(events, ["respawn", "probe", "exit1"]);
1216
+ assert.deepEqual(res, { running: false, exitCode: 1 });
1217
+ });
1218
+
1219
+ it("#6001 scheddFromCli rehost: exit waits for the rehosted daemon's closed and settled", async () => {
1220
+ const events = [], tick = () => new Promise((r) => setTimeout(r, 15));
1221
+ let closeB, settleB;
1222
+ const b = { running: true, closed: new Promise((r) => { closeB = r; }), stopCode: () => 1, rehosted: () => null, settled: () => new Promise((r) => { settleB = r; }) };
1223
+ const a = { running: true, closed: Promise.resolve(), stopCode: () => 1, rehosted: () => b, settled: async () => {} };
1224
+ const done = scheddFromCli([], { scheddDir: tmpDir("schedd-cli-r-"), startDaemon: async () => a, processOn: () => {}, exit: (c) => events.push(`exit${c}`), due: null, renice: () => {}, batchDeps: {} });
1225
+ await tick();
1226
+ assert.deepEqual(events, [], "exit must wait for the rehosted daemon's closed");
1227
+ closeB(); await tick();
1228
+ assert.deepEqual(events, [], "exit must wait for the rehosted daemon's settled");
1229
+ settleB(); await done;
1230
+ assert.deepEqual(events, ["exit1"]);
1231
+ });
1232
+
1180
1233
  it("the unit stands by while another daemon holds the lock instead of exiting 0 (no Restart=always loop)", async () => {
1181
1234
  const dir = tmpDir("schedd-sb-"), root = tmpDir("schedd-sb-b-");
1182
1235
  const owner = spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: "ignore" });