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,49 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { splitAdvisory, ADVISORY_KINDS } from "./conformance.mjs";
6
+ import { OUTCOME_CODES as C } from "../engine/outcome-codes.mjs";
7
+ import { genericInstallCommands } from "../pool/lane-tools.mjs";
8
+
9
+ describe("advisory gates (unclog)", () => {
10
+ it("shape rules are advisory; failing checks, regressions and unimplemented requirements block", () => {
11
+ const rows = [
12
+ { code: C.CONFORMANCE_SCOPE_CREEP, kind: "scope_creep", detail: "x" },
13
+ { code: C.CONFORMANCE_SCOPE_CREEP, detail: "review-side creep has no kind" },
14
+ { code: C.CONFORMANCE_UNIMPLEMENTED, kind: "check_unknown", detail: "post-deploy check id" },
15
+ { code: C.RECURRENCE_DESIGN_MISSING, kind: "design_missing", detail: "no design block" },
16
+ { code: C.CONFORMANCE_UNIMPLEMENTED, kind: "amendment_invalid", detail: "unknown or incomplete amendment" },
17
+ { code: C.CONFORMANCE_UNIMPLEMENTED, kind: "validate_failed", detail: "V1 failed" },
18
+ { code: C.CONFORMANCE_UNIMPLEMENTED, kind: "requirement_unimplemented", detail: "R1" },
19
+ { code: C.CONFORMANCE_REGRESSION, kind: "guard_broken", detail: "G1" },
20
+ ];
21
+ const { block, advisory } = splitAdvisory(rows);
22
+ assert.deepEqual(block.map((f) => f.kind), ["validate_failed", "requirement_unimplemented", "guard_broken"]);
23
+ assert.equal(advisory.length, 5);
24
+ });
25
+ it("never lists a kind that proves the change wrong", () => {
26
+ for (const k of ["validate_failed", "validate_missing", "guard_broken", "requirement_unimplemented", "repro_red_green", "substitute_unverified", "untracked_deferral", "prod_parity_unjustified", "outcome_evidence_missing"]) assert.ok(!ADVISORY_KINDS.includes(k), k);
27
+ });
28
+ it("a code the repo explicitly enforces stays blocking", () => {
29
+ const { block, advisory } = splitAdvisory([{ code: C.CONFORMANCE_SCOPE_CREEP, kind: "scope_creep", detail: "x" }], { enforce: [C.CONFORMANCE_SCOPE_CREEP] });
30
+ assert.equal(block.length, 1); assert.equal(advisory.length, 0);
31
+ });
32
+ it("empty and missing input", () => {
33
+ assert.deepEqual(splitAdvisory(undefined), { block: [], advisory: [] });
34
+ });
35
+ });
36
+
37
+ describe("generic sandbox install (unclog)", () => {
38
+ it("installs by miss kind, mapping import names to packages", () => {
39
+ assert.match(genericInstallCommands({ kind: "python-module", tool: "yaml" })[0], /pip install --user --quiet PyYAML/);
40
+ assert.match(genericInstallCommands({ kind: "python-module", tool: "requests" })[0], /pip install --user --quiet requests/);
41
+ assert.match(genericInstallCommands({ kind: "node-module", tool: "@adobe/css-tools" })[0], /^npm install --no-save .* @adobe\/css-tools$/);
42
+ assert.match(genericInstallCommands({ kind: "command", tool: "shellcheck" })[0], /apt-get install -y --no-install-recommends shellcheck/);
43
+ assert.match(genericInstallCommands({ kind: "command", tool: "shellcheck" }, { root: false })[0], /^sudo sh -c /);
44
+ });
45
+ it("refuses unsafe names and kinds nothing can install", () => {
46
+ for (const m of [{ kind: "command", tool: "a;rm -rf /" }, { kind: "command", tool: "$(x)" }, { kind: "command", tool: "../x" }, { kind: "command", tool: "bin/x" }, { kind: "environment", tool: "db" }, { kind: "forgedock-path", tool: "forgedock" }, {}])
47
+ assert.deepEqual(genericInstallCommands(m), [], JSON.stringify(m));
48
+ });
49
+ });
@@ -0,0 +1,31 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5979: the amendment shapes the builder may write to result.json, as data. The builder prompt, the correction prompt and the
5
+ * tests render from this one list, so the prompt never documents a shape the validator (conformance.mjs) rejects, nor omits one it accepts.
6
+ * Pure: no imports.
7
+ */
8
+
9
+ /** kind -> {shape, doc, example}. `supersedes` takes only a "#N" guard issue or a mechanism, never a validate-row id (G2): that is substitute-validate. */
10
+ export const AMENDMENT_SHAPES = Object.freeze({
11
+ "add-deliverable": { shape: `{"kind":"add-deliverable","path":"<file>"}`, doc: "a file not listed.", example: { kind: "add-deliverable", path: "bin/x.mjs", why: "needed" } },
12
+ "add-requirement": { shape: `{"kind":"add-requirement","requirement":{"id":"R9","quote":"<verbatim from the issue>","disposition":"deliver|defer|post-deploy"}}`, doc: "a missed requirement.", example: { kind: "add-requirement", requirement: { id: "R9", quote: "q", disposition: "deliver" }, why: "missed" } },
13
+ defer: { shape: `{"kind":"defer|post-deploy","requirement":"R#","why":"","check":"<id>"}`, doc: `separate work or a post-deploy check, filed as a follow-up. Not "type"; unknown kinds are rejected. One requirement id per row. An impossible deliverable is a defer, not a new kind.`, example: { kind: "defer", requirement: "R1", why: "separate work", check: "c1" } },
14
+ "post-deploy": { example: { kind: "post-deploy", requirement: "R1", why: "measured after release", check: "c1" } },
15
+ "amend-requirement": { shape: `{"kind":"amend-requirement","requirement":"R#","text":"<revised wording>"}`, doc: "reworded.", example: { kind: "amend-requirement", requirement: "R1", text: "revised", why: "reworded" } },
16
+ supersedes: { shape: `{"kind":"supersedes","guard":"#N"}`, doc: `overrides a guard_broken failure; {"kind":"supersedes","mechanism":"<name>"} retires every guard whose test this lane deletes. A validate-row id is never a supersedes guard.`, example: { kind: "supersedes", guard: "#123", why: "obsolete" } },
17
+ "substitute-validate": { shape: `{"kind":"substitute-validate","validate":"G2","command":"<runnable equivalent>"}`, doc: "a validate row whose command is unrunnable.", example: { kind: "substitute-validate", validate: "G2", command: "node --test a.test.mjs", why: "frozen command is unrunnable" } },
18
+ "out-of-band": { shape: `{"kind":"out-of-band","requirement":"R#","evidence":"<job that measures it>"}`, doc: "measured by a job.", example: { kind: "out-of-band", requirement: "R1", evidence: ".github/workflows/bench.yml", why: "measured by the bench job" } },
19
+ decision: { shape: `{"kind":"decision","decision":{"choice":"","anchors":["<base path>"],"supersedes":"<id>"}}`, doc: "supersedes changes an H-row.", example: { kind: "decision", decision: { choice: "c", anchors: ["bin/x.mjs"] }, why: "w" } },
20
+ });
21
+
22
+ export const AMEND_KINDS = Object.freeze(["add-deliverable", "add-requirement", "defer", "post-deploy", "amend-requirement", "supersedes", "decision", "substitute-validate", "out-of-band"]);
23
+
24
+ /** One valid example per kind (supersedes only with #N). */
25
+ export const AMENDMENT_EXAMPLES = Object.freeze(AMEND_KINDS.map((k) => AMENDMENT_SHAPES[k].example));
26
+
27
+ /** The builder-prompt bullet list, in the order the prompt documents them. */
28
+ export function amendmentPromptLines() {
29
+ return ["add-deliverable", "add-requirement", "defer", "amend-requirement", "supersedes", "substitute-validate", "out-of-band", "decision"]
30
+ .map((k) => `- ${AMENDMENT_SHAPES[k].shape}: ${AMENDMENT_SHAPES[k].doc}`).join("\n");
31
+ }
@@ -0,0 +1,159 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5986: the per-issue attempts ledger `{attempts, signatures[], lastInputHash, spend}`. It lives in the batch state.json (cache) and is
5
+ * mirrored as one hidden `FORGE:ATTEMPTS` comment (the register). Readmission needs a new input hash; the same hash after a failure is
6
+ * refused (`loop.no_new_input`); a lifetime budget breach escalates once (`FORGE:ESCALATION`, needs-human) until the hash changes.
7
+ * Nothing here clears the ledger: releaseHeld, --requeue and --set-env leave it alone. A missing ledger always admits.
8
+ */
9
+ import { createHash } from "node:crypto";
10
+ import { amendmentKindProblems } from "./conformance.mjs";
11
+ import { parseContractComment } from "./render.mjs";
12
+ import { postUpsert, findLeading, engineCommentCount } from "./statuscomment.mjs";
13
+
14
+ export const ATTEMPTS_MARKER = "FORGE:ATTEMPTS";
15
+ export const ESCALATION_MARKER = "FORGE:ESCALATION";
16
+ export const NO_NEW_INPUT = "loop.no_new_input";
17
+ export const DEFAULT_ISSUE_ATTEMPTS = 4;
18
+ export const DEFAULT_MAX_IDENTICAL = 2;
19
+
20
+ const sha = (s) => createHash("sha256").update(String(s)).digest("hex").slice(0, 16);
21
+ const majorMinor = (v) => (/^v?(\d+)\.(\d+)/.exec(String(v ?? "")) ?? []).slice(1, 3).join(".");
22
+ const labelName = (l) => (typeof l === "string" ? l : l?.name);
23
+
24
+ /** Hash of what a person can change: title+body, labels (not needs-human), operator FORGE:DECISION comments, engine and sandbox engine major.minor, contract hash. */
25
+ export function computeInputHash({ title = "", body = "", labels = [], decisions = [], engineVersion = null, sandboxVersion = null, contractHash = null } = {}) {
26
+ const ls = (labels ?? []).map(labelName).filter((n) => n && n !== "needs-human" && !String(n).startsWith("needs-human:")).sort();
27
+ return sha(JSON.stringify([String(title), String(body), ls, (decisions ?? []).map(String), majorMinor(engineVersion), majorMinor(sandboxVersion), contractHash ?? null]));
28
+ }
29
+
30
+ export const emptyLedger = () => ({ attempts: 0, signatures: [], lastInputHash: null, spend: 0 });
31
+ export function normalizeLedger(x) {
32
+ if (!x || typeof x !== "object") return emptyLedger();
33
+ return { attempts: Number.isInteger(x.attempts) && x.attempts > 0 ? x.attempts : 0, signatures: Array.isArray(x.signatures) ? x.signatures.map((s) => ({ ...s, sig: String(s?.sig ?? "") })) : [],
34
+ lastInputHash: typeof x.lastInputHash === "string" ? x.lastInputHash : null, spend: Number(x.spend) > 0 ? Number(x.spend) : 0, ...(Number.isInteger(x.comments) && x.comments >= 0 ? { comments: x.comments } : {}), ...(x.escalated ? { escalated: x.escalated } : {}) };
35
+ }
36
+
37
+ /** `{maxAttempts, maxIdentical}` from the orchestration config (posint, else the defaults 4 and 2). */
38
+ export const budgets = (cfg) => ({ maxAttempts: Number(cfg?.maxAttempts) >= 1 ? Math.floor(cfg.maxAttempts) : DEFAULT_ISSUE_ATTEMPTS, maxIdentical: Number(cfg?.maxIdentical) >= 1 ? Math.floor(cfg.maxIdentical) : DEFAULT_MAX_IDENTICAL });
39
+
40
+ /** The ledger after one failed lane (a new object): attempts+1, the signature with its run link, the hash it ran under, spend added. */
41
+ export function recordFailure(ledger, { signature, hash = null, spend = 0, run = null }) {
42
+ const l = normalizeLedger(ledger);
43
+ const changed = hash && l.lastInputHash && hash !== l.lastInputHash; // a new input starts a new escalation window, the lifetime counters stay
44
+ const { escalated, ...rest } = l; // `comments` (the engine comment count seen at the last mirror) rides along
45
+ return { ...rest, ...(escalated && !changed ? { escalated } : {}), attempts: l.attempts + 1, signatures: [...l.signatures, { sig: String(signature ?? ""), ...(hash ? { hash } : {}), ...(run ? { run } : {}) }], lastInputHash: hash ?? l.lastInputHash, spend: Math.round((l.spend + (Number(spend) || 0)) * 1e6) / 1e6 };
46
+ }
47
+
48
+ /** The breach of the lifetime budget, or null: attempts reached the cap, or one signature exceeded `maxIdentical` failures. */
49
+ export function breach(ledger, cfg) {
50
+ const l = normalizeLedger(ledger), { maxAttempts, maxIdentical } = budgets(cfg);
51
+ const counts = new Map();
52
+ for (const s of l.signatures) counts.set(s.sig, (counts.get(s.sig) ?? 0) + 1);
53
+ const worst = [...counts].sort((a, b) => b[1] - a[1])[0];
54
+ if (worst && worst[1] > maxIdentical) return { kind: "identical", detail: `failure signature \`${worst[0]}\` repeated ${worst[1]} times (max_identical_signature ${maxIdentical})` };
55
+ if (l.attempts >= maxAttempts) return { kind: "attempts", detail: `${l.attempts} lanes ran (max_attempts_per_issue ${maxAttempts})` };
56
+ return null;
57
+ }
58
+
59
+ /**
60
+ * Admission of a re-run. `hash` null (unreadable input) fails open. Returns {ok:true} or {ok:false, code, reason}: `escalate` (a budget
61
+ * breach not yet escalated), or `loop.no_new_input` (the same input after a failure).
62
+ */
63
+ export function admitInput(ledger, hash, cfg) {
64
+ const l = normalizeLedger(ledger);
65
+ if (!hash || !l.attempts || !l.lastInputHash || hash !== l.lastInputHash) return { ok: true };
66
+ const b = breach(l, cfg);
67
+ if (b && !l.escalated) return { ok: false, code: "escalate", reason: b.detail };
68
+ const last = l.signatures[l.signatures.length - 1]?.sig;
69
+ return { ok: false, code: NO_NEW_INPUT, reason: `input unchanged since the last failure${last ? ` (\`${last}\`)` : ""}${b ? `; ${b.detail}` : ""}` };
70
+ }
71
+
72
+ export const markEscalated = (ledger, at) => ({ ...normalizeLedger(ledger), escalated: at ?? true });
73
+
74
+ /** The one consolidated FORGE:ESCALATION body: signatures with run links, spend, what unblocks it. */
75
+ export function renderEscalation(ledger, reason) {
76
+ const l = normalizeLedger(ledger);
77
+ const rows = l.signatures.map((s, i) => `${i + 1}. \`${s.sig}\`${s.run ? ` (${s.run})` : ""}`);
78
+ return [`Escalated to a person after ${l.attempts} attempt${l.attempts === 1 ? "" : "s"}: ${reason}.`, "", ...rows, "", `Spend: $${l.spend.toFixed(2)}`,
79
+ "No further lanes run until the issue's input changes (edit the issue, add a FORGE:DECISION, or upgrade the engine); removing needs-human alone does not readmit it."].join("\n");
80
+ }
81
+
82
+ /** Hidden FORGE:ATTEMPTS comment body and its parse (null when absent or malformed). */
83
+ export const renderAttempts = (ledger) => `<!-- ${ATTEMPTS_MARKER} ${JSON.stringify(normalizeLedger(ledger))} -->`;
84
+ export function parseAttempts(body) {
85
+ const m = new RegExp(`^\\s*<!--\\s*${ATTEMPTS_MARKER}\\s+(\\{.*\\})\\s*-->`, "s").exec(String(body ?? ""));
86
+ if (!m) return null;
87
+ try { return normalizeLedger(JSON.parse(m[1])); } catch { return null; }
88
+ }
89
+
90
+ const ID_RE = /^#?\d+$/;
91
+ /**
92
+ * The shared amendment schema (#5986, extends #5979 past guard ids): kind/path/requirement presence plus field types. Returns the
93
+ * rejection strings, [] when valid; the lane returns them to the builder once and never posts a rejected shape.
94
+ */
95
+ export function validateAmendments(amendments) {
96
+ if (amendments !== undefined && amendments !== null && !Array.isArray(amendments)) return ["amendments must be an array"];
97
+ const out = [...amendmentKindProblems(amendments)];
98
+ for (const a of amendments ?? []) {
99
+ if (!a || typeof a !== "object") { out.push(`amendment must be an object: ${JSON.stringify(a ?? null).slice(0, 120)}`); continue; }
100
+ const tag = JSON.stringify(a).slice(0, 200);
101
+ if (a.why !== undefined && typeof a.why !== "string") out.push(`amendment 'why' must be a string: ${tag}`);
102
+ if (a.path !== undefined && typeof a.path !== "string") out.push(`amendment 'path' must be a string: ${tag}`);
103
+ if (a.kind === "supersedes" && a.guard !== undefined && !ID_RE.test(String(a.guard))) out.push(`supersedes 'guard' must be an issue id like #123: ${tag}`);
104
+ if (a.kind === "decision") {
105
+ const d = a.decision;
106
+ if (!d || typeof d !== "object" || typeof d.choice !== "string" || !d.choice.trim() || (d.anchors !== undefined && !Array.isArray(d.anchors))) out.push(`decision needs {choice: string, anchors: [paths]}: ${tag}`);
107
+ }
108
+ }
109
+ return [...new Set(out)];
110
+ }
111
+
112
+ /** Hash of the last trusted, parseable FORGE:CONTRACT comment (the frozen contract), or null. */
113
+ export function frozenContractHash(comments, trusted) {
114
+ let h = null;
115
+ for (const c of comments ?? []) {
116
+ const b = String(c?.body ?? "");
117
+ if (!b.startsWith("<!-- FORGE:CONTRACT -->") || !trusted(c)) continue;
118
+ const fc = parseContractComment(b);
119
+ if (fc?.hash) h = fc.hash;
120
+ }
121
+ return h;
122
+ }
123
+
124
+ /**
125
+ * The orchestrate seam, bound to GitHub: `hash(n)` reads the issue and computes the input hash (null on any read failure: fail open),
126
+ * `load(n)` reads the FORGE:ATTEMPTS comment, `mirror(n, ledger)` upserts it, `notify(...)` posts the one escalation or the no-new-input note.
127
+ */
128
+ export function makeAttemptsSeam({ gh, repo, engineVersion = null, sandboxVersion = null, cfg = {}, trusted = null, contractHash = null }) {
129
+ const view = async (n) => JSON.parse(String(await gh(["issue", "view", String(n), "-R", repo, "--json", "title,body,labels,comments"])));
130
+ const isTrusted = async () => trusted ?? (await import("./prefilter.mjs")).isTrustedIssueComment;
131
+ return {
132
+ cfg,
133
+ async hash(n) {
134
+ try {
135
+ const v = await view(n), t = await isTrusted();
136
+ const decisions = (v.comments ?? []).filter((c) => /^\s*<!--\s*FORGE:DECISION\b/.test(c?.body ?? "") && t(c)).map((c) => c.body);
137
+ return computeInputHash({ title: v.title, body: v.body, labels: v.labels, decisions, engineVersion, sandboxVersion, contractHash: contractHash ? await contractHash(n) : frozenContractHash(v.comments, t) });
138
+ } catch { return null; }
139
+ },
140
+ async load(n) {
141
+ try { const c = findLeading((await view(n)).comments, ATTEMPTS_MARKER, await isTrusted()); return c ? parseAttempts(c.body) : null; } catch { return null; }
142
+ },
143
+ /** Upserts the ledger comment; returns the issue's engine comment count (for stats). */
144
+ async mirror(n, ledger) {
145
+ const t = await isTrusted();
146
+ await postUpsert({ gh, repo, issue: n, markers: ATTEMPTS_MARKER, body: "", trusted: t, attrs: JSON.stringify(normalizeLedger(ledger)) });
147
+ try { return engineCommentCount((await view(n)).comments, t); } catch { return null; }
148
+ },
149
+ async notify({ issue, code, ledger, reason, relabel = false }) {
150
+ if (code === "escalate") {
151
+ await postUpsert({ gh, repo, issue, markers: ESCALATION_MARKER, body: renderEscalation(ledger, reason), trusted: await isTrusted() });
152
+ await gh(["issue", "edit", String(issue), "-R", repo, "--add-label", "needs-human"]);
153
+ } else {
154
+ await postUpsert({ gh, repo, issue, markers: "FORGE:NO_NEW_INPUT", body: `${NO_NEW_INPUT}: ${reason}. Not readmitted; the existing label stays.`, trusted: await isTrusted() });
155
+ if (relabel) await gh(["issue", "edit", String(issue), "-R", repo, "--add-label", "needs-human"]).catch(() => {}); // the label stays: a removal without new input does not readmit
156
+ }
157
+ },
158
+ };
159
+ }
@@ -0,0 +1,127 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { computeInputHash, emptyLedger, normalizeLedger, recordFailure, breach, admitInput, markEscalated, frozenContractHash, renderEscalation, renderAttempts, parseAttempts, validateAmendments, budgets, makeAttemptsSeam } from "./attempts.mjs";
6
+ import { renderContract } from "./render.mjs";
7
+ import { postKeyed } from "./statuscomment.mjs";
8
+
9
+ const base = { title: "t", body: "b", labels: ["bug"], decisions: [], engineVersion: "1.2.3", sandboxVersion: "1.2.0", contractHash: "c1" };
10
+ const fail = (l, sig, hash) => recordFailure(l, { signature: sig, hash, spend: 1.5, run: `run-${(l?.attempts ?? 0) + 1}` });
11
+
12
+ describe("#5986 input hash", () => {
13
+ it("changes with body, title, labels, decisions, engine major.minor and contract; not with needs-human or a patch bump", () => {
14
+ const h = computeInputHash(base);
15
+ for (const k of [{ body: "b2" }, { title: "t2" }, { labels: ["bug", "x"] }, { decisions: ["FORGE:DECISION ok"] }, { engineVersion: "1.3.0" }, { sandboxVersion: "2.0.0" }, { contractHash: "c2" }]) assert.notEqual(computeInputHash({ ...base, ...k }), h, JSON.stringify(k));
16
+ assert.equal(computeInputHash({ ...base, labels: ["bug", { name: "needs-human" }] }), h);
17
+ assert.equal(computeInputHash({ ...base, engineVersion: "1.2.9" }), h);
18
+ assert.equal(computeInputHash({ ...base, labels: ["x", "bug"] }), computeInputHash({ ...base, labels: ["bug", "x"] }));
19
+ });
20
+ });
21
+
22
+ describe("#5986 admission, budgets, escalation", () => {
23
+ const cfg = {};
24
+ it("defaults are 4 and 2; a missing ledger admits; a changed hash admits", () => {
25
+ assert.deepEqual(budgets(undefined), { maxAttempts: 4, maxIdentical: 2 });
26
+ assert.deepEqual(admitInput(null, "H1", cfg), { ok: true });
27
+ assert.deepEqual(admitInput(fail(null, "s", "H1"), "H2", cfg), { ok: true });
28
+ assert.deepEqual(admitInput(fail(null, "s", "H1"), null, cfg), { ok: true }, "unreadable input fails open");
29
+ });
30
+ it("same hash after a failure is refused with loop.no_new_input", () => {
31
+ const a = admitInput(fail(null, "ci.red:x", "H1"), "H1", cfg);
32
+ assert.equal(a.ok, false); assert.equal(a.code, "loop.no_new_input"); assert.match(a.reason, /ci\.red:x/);
33
+ });
34
+ it("the 3rd identical signature breaches; 4 lanes breach; different signatures stay under max_identical", () => {
35
+ let l = fail(null, "s", "H1"); l = fail(l, "s", "H2");
36
+ assert.equal(breach(l, cfg), null);
37
+ assert.equal(breach(fail(l, "s", "H3"), cfg).kind, "identical");
38
+ let m = null; for (const [i, s] of ["a", "b", "c", "d"].entries()) m = fail(m, s, `H${i}`);
39
+ assert.equal(breach(m, cfg).kind, "attempts");
40
+ assert.equal(breach(m, { maxAttempts: 5 }), null);
41
+ });
42
+ it("a breach escalates once at the same hash, then loop.no_new_input; a new hash admits and clears the escalated flag after the next failure", () => {
43
+ let l = null; for (let i = 1; i <= 3; i++) l = fail(l, "s", `H${i}`);
44
+ assert.equal(admitInput(l, "H3", cfg).code, "escalate");
45
+ l = markEscalated(l);
46
+ assert.equal(admitInput(l, "H3", cfg).code, "loop.no_new_input");
47
+ assert.deepEqual(admitInput(l, "H4", cfg), { ok: true });
48
+ assert.equal(fail(l, "s", "H4").escalated, undefined, "the next window escalates again");
49
+ });
50
+ it("the ledger round-trips through the FORGE:ATTEMPTS comment and the escalation names signatures, runs and spend", () => {
51
+ const l = fail(fail(null, "ci.red", "H1"), "base.conflict", "H1");
52
+ assert.deepEqual(parseAttempts(renderAttempts(l)), normalizeLedger(l));
53
+ assert.equal(parseAttempts("hello"), null);
54
+ assert.deepEqual(normalizeLedger(undefined), emptyLedger());
55
+ const body = renderEscalation(l, "2 lanes");
56
+ assert.match(body, /ci\.red[\s\S]*run-1[\s\S]*base\.conflict[\s\S]*Spend: \$3\.00/);
57
+ });
58
+ it("counters survive a releaseHeld-style round trip through JSON state", () => {
59
+ const l = fail(fail(null, "s", "H1"), "s", "H1");
60
+ assert.deepEqual(normalizeLedger(JSON.parse(JSON.stringify(l))), normalizeLedger(l));
61
+ });
62
+ });
63
+
64
+ describe("#5986 contract hash in the input hash", () => {
65
+ it("frozenContractHash takes the last trusted FORGE:CONTRACT comment; none gives null", () => {
66
+ assert.equal(frozenContractHash([{ body: "hi" }], () => true), null);
67
+ assert.equal(frozenContractHash([], () => true), null);
68
+ const mk = (c, h) => ({ body: `<!-- FORGE:CONTRACT -->\n${renderContract(c, h)}` });
69
+ assert.equal(frozenContractHash([mk({ requirements: [] }, "aaa111aaa111"), mk({ requirements: [] }, "bbb222bbb222")], () => true), "bbb222bbb222");
70
+ assert.equal(frozenContractHash([mk({ requirements: [] }, "aaa111aaa111")], () => false), null, "untrusted comments are ignored");
71
+ const h = (contractHash) => computeInputHash({ ...base, contractHash });
72
+ assert.notEqual(h("aaa111aaa111"), h("bbb222bbb222"));
73
+ });
74
+ });
75
+
76
+ describe("#5986 shared amendment schema", () => {
77
+ it("accepts valid shapes and rejects wrong types with a message", () => {
78
+ assert.deepEqual(validateAmendments([{ kind: "add-deliverable", path: "a.mjs", why: "x" }, { kind: "decision", decision: { choice: "c", anchors: ["a.mjs"] }, why: "y" }]), []);
79
+ assert.deepEqual(validateAmendments(undefined), []);
80
+ assert.ok(validateAmendments([{ kind: "nope" }]).length);
81
+ assert.match(validateAmendments([{ kind: "add-deliverable", path: 5 }])[0], /path/);
82
+ assert.match(validateAmendments([{ kind: "supersedes", guard: "abc", why: "x" }]).join(), /guard/);
83
+ assert.match(validateAmendments([{ kind: "decision", decision: { anchors: "a" }, why: "x" }]).join(), /choice/);
84
+ assert.match(validateAmendments({ kind: "x" })[0], /array/);
85
+ });
86
+ });
87
+
88
+ describe("#5986 synthetic replay of looping issue timelines", () => {
89
+ // shapes of the AlterLab timelines (#40762 repeated builder.blocked, #41419 repeated amendments, #41262 mixed signatures); the real logs are not in the repo
90
+ const timelines = [
91
+ { name: "#40762", sigs: () => "builder.blocked", amend: () => "same amendment", every: 1000 },
92
+ { name: "#41419", sigs: () => "ci.red:same", amend: (i) => `amendment ${i % 3}`, every: 1000 },
93
+ { name: "#41262", sigs: (i) => `sig${i % 3}`, amend: (i) => `amendment ${i}`, every: 1000 },
94
+ ];
95
+ for (const t of timelines) it(`${t.name}: at most 4 lanes and 12 engine comments over a 30-readmit timeline with no new input`, async () => {
96
+ let issueBody = "b"; const comments = [], gh = async (a) => {
97
+ if (a[1] === "view") return JSON.stringify({ comments, title: "t", body: issueBody, labels: [] });
98
+ if (a[1] === "comment") { comments.push({ author: { login: "rapiercraft-forgedock" }, url: `https://x/issues/1#issuecomment-${comments.length + 1}`, body: a[a.indexOf("--body") + 1] }); return comments.at(-1).url; }
99
+ if (a[0] === "api") { const id = Number(/comments\/(\d+)/.exec(a[3])[1]); comments[id - 1].body = a[a.indexOf("-f") + 1].slice(5); }
100
+ return "";
101
+ };
102
+ const trusted = (c) => c.author?.login === "rapiercraft-forgedock";
103
+ const seam = makeAttemptsSeam({ gh, repo: "o/r", trusted, cfg: { maxAttempts: 4, maxIdentical: 2 } });
104
+ let ledger = null, lanes = 0;
105
+ for (let i = 0; i < 30; i++) { // readmitted every poll, the issue never edited
106
+ issueBody = `b${Math.floor(i / t.every)}`;
107
+ const hash = await seam.hash(1), a = admitInput(ledger, hash, seam.cfg);
108
+ if (!a.ok) { if (a.code === "escalate") ledger = markEscalated(ledger); await seam.notify({ issue: 1, code: a.code, ledger, reason: a.reason }); continue; }
109
+ lanes++;
110
+ await postKeyed({ gh, repo: "o/r", issue: 1, marker: "FORGE:AMENDMENT", body: t.amend(i), trusted });
111
+ ledger = recordFailure(ledger, { signature: t.sigs(i), hash });
112
+ await seam.mirror(1, ledger);
113
+ if (breach(ledger, seam.cfg) && !ledger.escalated) { ledger = markEscalated(ledger); await seam.notify({ issue: 1, code: "escalate", ledger, reason: "x" }); }
114
+ }
115
+ assert.ok(lanes <= 4, `lanes ${lanes}`);
116
+ assert.ok(comments.length <= 12, `comments ${comments.length}`);
117
+ });
118
+ it("a single unchanged-input timeline runs at most 4 lanes and posts one escalation", async () => {
119
+ let ledger = null, lanes = 0;
120
+ for (let i = 0; i < 20; i++) {
121
+ const a = admitInput(ledger, "H", { maxAttempts: 4, maxIdentical: 2 });
122
+ if (!a.ok) { if (a.code === "escalate") ledger = markEscalated(ledger); continue; }
123
+ lanes++; ledger = recordFailure(ledger, { signature: "s", hash: "H" });
124
+ }
125
+ assert.ok(lanes <= 4, `lanes ${lanes}`);
126
+ });
127
+ });
@@ -158,3 +158,58 @@ async function fileBaseRed({ ghc, repo, att, body, title, key, commitDate }) {
158
158
  return n ? Number(n[1]) : null;
159
159
  } catch { return null; }
160
160
  }
161
+
162
+ // #5992: one red-base verdict per (repo, base ref), valid for BASE_PROBE_TTL_MS and only while the base sha is unchanged.
163
+ export const BASE_PROBE_TTL_MS = 10 * 60 * 1000;
164
+ const probeCache = new Map();
165
+ const probeKey = (repo, base) => `${repo ?? ""}\u0000${base}`;
166
+
167
+ /** Cached verdict `{red, sha, att, commands, outputs}` for (repo, base) at `sha`; null on a miss, an expired entry or a moved sha. */
168
+ export function cachedBaseVerdict({ repo, base, sha, now = Date.now(), ttlMs = BASE_PROBE_TTL_MS } = {}) {
169
+ const e = probeCache.get(probeKey(repo, base));
170
+ if (!e || !sha || e.sha !== sha || now - e.at >= ttlMs) return null;
171
+ return e.verdict;
172
+ }
173
+
174
+ /** Record a verdict for (repo, base) at `sha` (a lane's guardRed shares its red result so later lanes and the dispatcher skip the probe). */
175
+ export function recordBaseVerdict({ repo, base, sha, red, att = null, commands = [], outputs = {}, now = Date.now() } = {}) {
176
+ if (!sha) return null;
177
+ const verdict = { red: !!red, sha, att, commands, outputs };
178
+ probeCache.set(probeKey(repo, base), { sha, at: now, verdict });
179
+ return verdict;
180
+ }
181
+
182
+ export function clearBaseVerdicts() { probeCache.clear(); }
183
+
184
+ /**
185
+ * #5992: the dispatcher's one probe per (repo, base sha). `readSha()` gives the current base sha; a fresh cache entry for it is
186
+ * returned as is, otherwise `commands` run once on the base (runOnBase) and the verdict, with its attribution, is cached.
187
+ * Never throws; null when the sha or the base run gives no evidence (a timeout or env failure is not a red base).
188
+ */
189
+ export async function probeBase({ repo, base, commands = [], readSha, git, runCommand, cwd, env, timeoutMs, now = Date.now(), ttlMs = BASE_PROBE_TTL_MS, fs = nodeFs } = {}) {
190
+ try {
191
+ if (!commands.length) return null;
192
+ const sha = String((await readSha()) ?? "").trim();
193
+ if (!sha) return null;
194
+ const hit = cachedBaseVerdict({ repo, base, sha, now, ttlMs });
195
+ if (hit) return hit;
196
+ const baseRuns = await runOnBase({ commands, git, runCommand, mergeBase: sha, cwd, env, timeoutMs, fs });
197
+ const { baseRed } = classifyBaseRed({ failed: commands.map((command) => ({ command })), baseRuns });
198
+ if (!baseRuns.length) return null;
199
+ const cmds = baseRed.map((f) => f.command);
200
+ const att = cmds.length ? await attribute({ failed: baseRuns.filter((b) => cmds.includes(b.command)), git, base: sha }) : null;
201
+ const outputs = Object.fromEntries(baseRuns.filter((b) => cmds.includes(b.command)).map((b) => [b.command, b.output]));
202
+ return recordBaseVerdict({ repo, base, sha, red: cmds.length > 0, att, commands: cmds, outputs, now });
203
+ } catch { return null; }
204
+ }
205
+
206
+ /**
207
+ * #5992: a lane that touches none of the files the red guard names (the attributed `att.files`) may bypass the base.red hold;
208
+ * the guard is re-run on the merged tree at merge. False without both a known surface and a known lane diff (never guess a bypass).
209
+ */
210
+ export function bypassesGuard({ laneFiles = [], att = null } = {}) {
211
+ const surface = (att?.files ?? []).map((f) => String(f).replace(/^\.\//, "").replace(/\/+$/, "")).filter(Boolean);
212
+ const lane = (laneFiles ?? []).map((f) => String(f).trim().replace(/^\.\//, "")).filter(Boolean);
213
+ if (!surface.length || !lane.length) return false;
214
+ return !lane.some((f) => surface.some((s) => f === s || f.startsWith(`${s}/`)));
215
+ }
@@ -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 { classifyBaseRed, baseRedPaths, issueOf, attribute, runOnBase, reportBaseRed } from "./basered.mjs";
5
+ import { classifyBaseRed, baseRedPaths, issueOf, attribute, runOnBase, reportBaseRed, probeBase, bypassesGuard, cachedBaseVerdict, recordBaseVerdict, clearBaseVerdicts, BASE_PROBE_TTL_MS } from "./basered.mjs";
6
6
 
7
7
  const SHA = "13834f1c51".padEnd(40, "0");
8
8
 
@@ -117,3 +117,70 @@ describe("reportTrainBaseRed (#5838)", () => {
117
117
  assert.match(cr[cr.indexOf("--title") + 1], /staging is red on required check build/);
118
118
  });
119
119
  });
120
+
121
+ describe("base probe cache (#5992)", () => {
122
+ const SHA2 = "2".repeat(40);
123
+ const mk = (sha, rc = 1) => {
124
+ const calls = { run: 0 };
125
+ const git = async (a) => (a[0] === "rev-parse" ? sha : a[0] === "log" ? `${sha}\x1ffix: x (#7)\x1f` : "");
126
+ const runCommand = async () => { calls.run++; return { rc, output: "tests/guard.test.mjs failed" }; };
127
+ return { calls, git, runCommand, readSha: async () => sha };
128
+ };
129
+ const base = { repo: "o/r", base: "staging", commands: ["guard"], cwd: process.cwd(), timeoutMs: 1000 };
130
+
131
+ it("hit within the TTL: one probe run serves every later call and carries the attribution", async () => {
132
+ clearBaseVerdicts();
133
+ const m = mk(SHA);
134
+ const a = await probeBase({ ...base, ...m, now: 1000 });
135
+ const b = await probeBase({ ...base, ...m, now: 1000 + BASE_PROBE_TTL_MS - 1 });
136
+ assert.equal(m.calls.run, 1);
137
+ assert.equal(a.red, true);
138
+ assert.deepEqual(b, a);
139
+ assert.equal(b.att.issue, 7);
140
+ });
141
+
142
+ it("miss after the TTL", async () => {
143
+ clearBaseVerdicts();
144
+ const m = mk(SHA);
145
+ await probeBase({ ...base, ...m, now: 1000 });
146
+ await probeBase({ ...base, ...m, now: 1000 + BASE_PROBE_TTL_MS });
147
+ assert.equal(m.calls.run, 2);
148
+ });
149
+
150
+ it("miss when the base sha moves; a green base is cached as not red", async () => {
151
+ clearBaseVerdicts();
152
+ const m = mk(SHA);
153
+ await probeBase({ ...base, ...m, now: 1000 });
154
+ const m2 = mk(SHA2, 0);
155
+ const v = await probeBase({ ...base, ...m2, now: 1001 });
156
+ assert.equal(m2.calls.run, 1);
157
+ assert.equal(v.red, false);
158
+ assert.equal(cachedBaseVerdict({ repo: "o/r", base: "staging", sha: SHA, now: 1002 }), null);
159
+ });
160
+
161
+ it("a lane's recorded red verdict is reused without a probe run; an env failure is no verdict of red", async () => {
162
+ clearBaseVerdicts();
163
+ recordBaseVerdict({ repo: "o/r", base: "staging", sha: SHA, red: true, commands: ["guard"], now: 5 });
164
+ const m = mk(SHA);
165
+ assert.equal((await probeBase({ ...base, ...m, now: 6 })).red, true);
166
+ assert.equal(m.calls.run, 0);
167
+ clearBaseVerdicts();
168
+ const env = mk(SHA);
169
+ env.runCommand = async () => ({ rc: 1, output: "ModuleNotFoundError: x" });
170
+ assert.equal((await probeBase({ ...base, ...env, now: 7 })).red, false);
171
+ });
172
+ });
173
+
174
+ describe("#5992: path-scoped guard bypass", () => {
175
+ const att = { sha: "a".repeat(40), files: ["src/guard.mjs", "tests/dir"] };
176
+ it("bypasses a lane clear of the guarded surface", () => assert.equal(bypassesGuard({ laneFiles: ["docs/a.md"], att }), true));
177
+ it("does not bypass when the lane touches a named file or a file under a named dir", () => {
178
+ assert.equal(bypassesGuard({ laneFiles: ["docs/a.md", "src/guard.mjs"], att }), false);
179
+ assert.equal(bypassesGuard({ laneFiles: ["tests/dir/x.mjs"], att }), false);
180
+ });
181
+ it("does not bypass without a known surface or lane diff, or on a sibling-prefix name", () => {
182
+ assert.equal(bypassesGuard({ laneFiles: ["a"], att: null }), false);
183
+ assert.equal(bypassesGuard({ laneFiles: [], att }), false);
184
+ assert.equal(bypassesGuard({ laneFiles: ["tests/directory.mjs"], att }), true);
185
+ });
186
+ });
@@ -13,6 +13,7 @@ import { appendFileSync, existsSync, readFileSync } from "node:fs";
13
13
  import { spawn as spawnProc } from "node:child_process";
14
14
  import { join } from "node:path";
15
15
  import { listBatches, openBatch, REQUEUABLE, writeAtomic } from "./batch.mjs";
16
+ import { efficiencyLine, readEfficiency } from "./efficiency.mjs";
16
17
 
17
18
  export const DEFAULT_HEALTH = Object.freeze({ rootFailed: true, terminalShare: 0.5, stalled: true, checksMin: Object.freeze([15, 60]), issue: null, notifyCommand: null });
18
19
  /** #5469: a hold older than this many hours is flagged (`config.holdHours` overrides). */
@@ -224,6 +225,8 @@ export function batchStatusLines(root, id, { now = Date.now() } = {}) {
224
225
  const k = Array.isArray(g?.lanes) ? g.lanes.length : Number(g?.requeued) || 0;
225
226
  if (g?.agent) out.push(` agent ${g.agent} restarted at ${g.at ?? "?"}; ${k} lane${k === 1 ? "" : "s"} requeued (sandbox.lost)${g.closed ? "" : ", waiting for the agent"}`);
226
227
  }
228
+ const eff = efficiencyLine(readEfficiency(b.dir)); // #5987: the efficiency ledger, when the daemon wrote one
229
+ if (eff) out.push(` ${eff}`);
227
230
  return out;
228
231
  }
229
232
 
@@ -406,3 +406,19 @@ describe("#5938 stall verdict is re-evaluated: full K, recovery lanes, pool capa
406
406
  assert.match(batchVerdict("b1", s, { action: "alert", cause: "no gh" }), /stalled -> no action, needs you \(no gh;/);
407
407
  });
408
408
  });
409
+
410
+ describe("#5987 efficiency status line", () => {
411
+ it("batch status shows the efficiency line with and without breaches; none without a ledger", async () => {
412
+ const { writeEfficiency } = await import("./efficiency.mjs");
413
+ const root = tmpDir("bh-eff-");
414
+ mkdirSync(join(root, "b1"));
415
+ const b = openBatch(root, "b1");
416
+ b.writePlan({ argv: ["1"], created: new Date().toISOString() });
417
+ assert.ok(!statusLines(root, { batch: "b1" }).some((l) => /efficiency:/.test(l)));
418
+ const eff = { v: 1, concurrency: { running: 3, ceiling: 12, achieved: 3 }, limiters: ["sandbox.capacity", "pool.host_load"], breaches: [] };
419
+ writeEfficiency(b.dir, eff);
420
+ assert.ok(statusLines(root, { batch: "b1" }).includes(" efficiency: 3/12 lanes (25%) - limiter sandbox.capacity pool.host_load"));
421
+ writeEfficiency(b.dir, { ...eff, breaches: [{ issue: 6001 }, { issue: 6001 }] });
422
+ assert.ok(statusLines(root, { batch: "b1" }).includes(" efficiency: 3/12 lanes (25%) - limiter sandbox.capacity pool.host_load; 2 SLO breaches -> FD#6001"));
423
+ });
424
+ });
@@ -20,6 +20,7 @@ import { spawn } from "node:child_process";
20
20
  import { createHash } from "node:crypto";
21
21
  import { homedir, hostname } from "node:os";
22
22
  import { dirname, join, resolve, sep } from "node:path";
23
+ import { humanCode } from "./reconcile.mjs";
23
24
  import { sanitizeOverride, validateExecutionPatch } from "./live-execution.mjs";
24
25
 
25
26
  export const RAM_FS = new Set(["tmpfs", "ramfs"]);
@@ -113,6 +114,23 @@ const readAdded = (file) => {
113
114
  export const REQUEUABLE = (outcome) => ["needs-human", "engine-error", "held", "invalid", "skipped", "ci-pending", "pr-ready", "budget-exceeded", "lane-refused", "deferred"].includes(outcome) || /^dependency-/.test(String(outcome));
114
115
  /** Key of one requeue entry; the runner records the applied keys in state.json `requeueApplied`. */
115
116
  /** #5832: the `{dependency, branch, sha}` a stacked build of `issue` was admitted on (batch state `stacked`), or null. Rows carry `stacked`/`stackedOn`. */
117
+ /**
118
+ * #6008: sandboxes kept for adopt (issue, since, age, phase). `state.kept` records them as the lane returned them; a running
119
+ * remote record (handle) of a batch whose dispatcher is gone (`live` false) is a kept sandbox too. Newest listing order: by issue.
120
+ */
121
+ export function keptSandboxes(state, { now = Date.now(), live = false } = {}) {
122
+ const out = new Map();
123
+ for (const [k, v] of Object.entries(state?.kept ?? {})) {
124
+ const issue = Number(k); if (!Number.isSafeInteger(issue) || !v) continue;
125
+ out.set(issue, { issue, since: v.since ?? null, phase: v.phase ?? null, ...(v.id ? { id: v.id } : {}) });
126
+ }
127
+ if (!live) for (const [k, rec] of Object.entries(state?.running ?? {})) {
128
+ const issue = Number(k);
129
+ if (!Number.isSafeInteger(issue) || out.has(issue) || !(rec?.handle || rec?.remote)) continue;
130
+ out.set(issue, { issue, since: rec.startedAt ?? null, phase: rec.phase ?? null, ...(rec.handle?.id ? { id: rec.handle.id } : {}) });
131
+ }
132
+ return [...out.values()].sort((a, b) => a.issue - b.issue).map((e) => ({ ...e, ageMs: (() => { const t = typeof e.since === "number" ? e.since : Date.parse(e.since); return Number.isFinite(t) ? Math.max(0, now - t) : null; })() }));
133
+ }
116
134
  export const stackedOnOf = (state, issue) => state?.stacked?.[issue] ?? null;
117
135
 
118
136
  export const requeueKey = (e) => `${e.issue}@${e.at}`;
@@ -185,6 +203,31 @@ export const dispatchOwner = (root, repo, issue, exceptId, opts = {}) => {
185
203
  return (live.find((o) => o.running) ?? live.find((o) => o.id < exceptId))?.id ?? null;
186
204
  };
187
205
 
206
+ /**
207
+ * #5978: coverage of a selector batch: every open issue the selector matches is exactly one of running, queued, backing-off (a
208
+ * deferral or re-admission wait), waiting on deps, human-blocked (the only reason to stay unscheduled), or `unscheduled`
209
+ * (the unhealthy state: matches but nothing will run it). Shared by `forgedock orchestrate --status`.
210
+ * @param {{state:object, open:Array<{number:number,labels?:string[]}>, now?:number}} p
211
+ */
212
+ export function coverage({ state, open, now = Date.now() }) {
213
+ const st = state ?? {}, pending = new Set(st.pending ?? []), res = st.results ?? {}, readmit = st.readmit ?? {};
214
+ const out = { running: [], queued: [], backingOff: [], waitingDeps: [], humanBlocked: [], unscheduled: [] };
215
+ for (const { number: n, labels = [] } of open ?? []) {
216
+ const row = res[n], deps = (st.deps?.[n] ?? []).filter((d) => res[d]?.outcome !== "merged" && res[d]?.outcome !== "invalid");
217
+ if (st.running && Object.hasOwn(st.running, String(n))) out.running.push(n);
218
+ else if (row && humanCode(row, labels)) out.humanBlocked.push(n);
219
+ else if (!row && labels.some((l) => humanCode(null, [l]))) out.humanBlocked.push(n);
220
+ else if (pending.has(n) && (st.notBefore?.[n] ?? 0) > now) out.backingOff.push(n);
221
+ else if (pending.has(n) && deps.length) out.waitingDeps.push(n);
222
+ else if (pending.has(n)) out.queued.push(n);
223
+ else if (row && ["deferred", "held", "engine-error"].includes(row.outcome) && readmit[n]) out.backingOff.push(n);
224
+ else if (row && (row.outcome === "pr-ready" || row.outcome === "ci-pending")) out.queued.push(n); // a PR is on its way to merge
225
+ else if (row && /^(skipped|held)$/.test(row.outcome) && deps.length) out.waitingDeps.push(n);
226
+ else out.unscheduled.push(n);
227
+ }
228
+ return out;
229
+ }
230
+
188
231
  /** Handle on one batch directory. */
189
232
  export function openBatch(root, id) {
190
233
  if (!ID_RE.test(String(id ?? ""))) throw new Error(`invalid batch id ${JSON.stringify(id)}`);
@@ -300,6 +343,8 @@ export function openBatch(root, id) {
300
343
  readRequeued: () => readRequeueFile(f("requeue")),
301
344
  /** Entries the runner has not applied yet (a finished or unhosted batch with a pending requeue). */
302
345
  unrunRequeues: () => { const done = new Set(readJson(f("state.json"))?.requeueApplied ?? []); return readRequeueFile(f("requeue")).filter((e) => !done.has(requeueKey(e))); },
346
+ /** #6008: the kept-sandbox listing of this batch (issue, since, ageMs, phase); `live` = its dispatcher is running. */
347
+ keptSandboxes: (live = false) => keptSandboxes(readJson(f("state.json")), { live }),
303
348
  /** Issues held by `--hold` (#4592): the `hold` file, sorted unique positive integers; [] when missing or invalid. */
304
349
  readHeld: () => readAdded(f("hold")),
305
350
  /** #4656: gates waiting on issues (`gates` file: [{ name, waitsOn: [n...], since? }], written by the ship/settle pre-flight); [] when missing or invalid. */