forgedock 1.37.0 → 1.38.1

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 (81) hide show
  1. package/bin/engine/outcome-codes.mjs +12 -3
  2. package/bin/engine/telemetry-seam.mjs +5 -0
  3. package/bin/engine-cli.mjs +97 -18
  4. package/bin/forgedock.mjs +13 -2
  5. package/bin/lean/activation.mjs +76 -0
  6. package/bin/lean/activation.test.mjs +75 -0
  7. package/bin/lean/admission.mjs +17 -1
  8. package/bin/lean/batch.mjs +51 -21
  9. package/bin/lean/batch.test.mjs +95 -5
  10. package/bin/lean/conformance.mjs +53 -4
  11. package/bin/lean/conformance.test.mjs +24 -1
  12. package/bin/lean/decision-engine.mjs +217 -0
  13. package/bin/lean/decision-engine.test.mjs +159 -0
  14. package/bin/lean/effects.mjs +39 -13
  15. package/bin/lean/execution.mjs +74 -5
  16. package/bin/lean/execution.test.mjs +64 -1
  17. package/bin/lean/explore.test.mjs +1 -1
  18. package/bin/lean/guards.mjs +3 -2
  19. package/bin/lean/guards.test.mjs +24 -3
  20. package/bin/lean/heavy.mjs +15 -2
  21. package/bin/lean/heavy.test.mjs +31 -2
  22. package/bin/lean/issuewatch-release.mjs +245 -0
  23. package/bin/lean/issuewatch-release.test.mjs +244 -0
  24. package/bin/lean/issuewatch.mjs +386 -0
  25. package/bin/lean/issuewatch.test.mjs +280 -0
  26. package/bin/lean/lane.mjs +4 -3
  27. package/bin/lean/lane.test.mjs +12 -0
  28. package/bin/lean/lean.mjs +103 -16
  29. package/bin/lean/lean.test.mjs +127 -5
  30. package/bin/lean/needs-human-premise.mjs +177 -0
  31. package/bin/lean/needs-human-premise.test.mjs +136 -0
  32. package/bin/lean/orchestrate-blocked.test.mjs +71 -0
  33. package/bin/lean/orchestrate.mjs +93 -21
  34. package/bin/lean/postdeploy-check.mjs +88 -2
  35. package/bin/lean/postdeploy-check.test.mjs +78 -0
  36. package/bin/lean/prodwatch-sources.mjs +165 -0
  37. package/bin/lean/prodwatch-sources.test.mjs +108 -0
  38. package/bin/lean/prompts.mjs +9 -3
  39. package/bin/lean/recovery.test.mjs +14 -0
  40. package/bin/lean/relay.mjs +182 -0
  41. package/bin/lean/relay.test.mjs +214 -0
  42. package/bin/lean/sandbox-provider.contract.test.mjs +13 -1
  43. package/bin/lean/sandbox-remote.mjs +53 -9
  44. package/bin/lean/sched.test.mjs +30 -0
  45. package/bin/lean/schedd-health.mjs +69 -0
  46. package/bin/lean/schedd-health.test.mjs +51 -0
  47. package/bin/lean/schedd.mjs +29 -12
  48. package/bin/lean/schedd.test.mjs +40 -4
  49. package/bin/lean/sequence.mjs +57 -24
  50. package/bin/lean/sequence.test.mjs +71 -0
  51. package/bin/pool/agent.mjs +15 -1
  52. package/bin/pool/router.mjs +43 -5
  53. package/bin/runner.mjs +18 -1
  54. package/commands/deploy-pr.md +12 -0
  55. package/commands/forgedock-init.md +1 -0
  56. package/commands/orchestrate/phase-4-execution.md +1 -0
  57. package/commands/orchestrate.md +1 -0
  58. package/commands/review-pr.md +17 -13
  59. package/docs/CONFIG.md +73 -2
  60. package/docs/DECISIONS.md +32 -0
  61. package/docs/ISSUE-WATCH.md +95 -0
  62. package/docs/NORTHSTAR-TEMPLATE.md +21 -0
  63. package/docs/OUTCOME-CODES.md +2 -1
  64. package/docs/TELEMETRY.md +7 -0
  65. package/package.json +1 -2
  66. package/pool/README.md +1 -1
  67. package/pool/image/Dockerfile +2 -1
  68. package/pool/image/cs-relay +31 -0
  69. package/pool/image/entrypoint.sh +10 -0
  70. package/pool/install/install-schedd.sh +22 -0
  71. package/pool/install/unit-hardening.sh +6 -0
  72. package/scripts/postdeploy-rollup-link.sh +40 -0
  73. package/scripts/postdeploy-rollup-link.test.sh +46 -0
  74. package/scripts/refresh-bot-token.sh +122 -0
  75. package/scripts/review-delta.sh +14 -4
  76. package/scripts/review-delta.test.sh +21 -0
  77. package/scripts/review-finalize.sh +69 -25
  78. package/scripts/review-finalize.test.sh +32 -0
  79. package/scripts/review-pr-arguments.test.sh +10 -0
  80. package/scripts/review-pr-changed-verification.test.sh +54 -0
  81. package/scripts/review-pr-delta-wiring.test.sh +1 -1
@@ -0,0 +1,165 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Production signal adapters for `prod_watch` (#4833, part of #4768). Each `prod_watch.sources` entry is a set of shell
5
+ * commands that print JSON or text; the adapters turn that into one normalised signal shape
6
+ * `{id, source, title, severity, owner, first_seen, last_seen, body, query?}`. Read-only by contract: `runAdapter` executes
7
+ * only the declared `list`/`read`/`run` commands through the injected `io.exec`; `close` is reachable only through
8
+ * `closeSignal`, which refuses without an audit record and writes it before the command runs. Pure apart from `io`
9
+ * (`exec`, `audit`, `now`); no LLM, no fs, no network of its own. Repo-agnostic: the commands come from forge.yaml (#1347).
10
+ */
11
+
12
+ const KINDS = ["memo", "alertmanager", "sql", "prometheus"];
13
+ const SOURCE_KEYS = ["kind", "list", "read", "close", "run", "queries"];
14
+ const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._:@=-]{0,199}$/; // ids come from command output (untrusted): never shell-active
15
+ const SAFE_QUERY = /^[^'"`$;|&<>\\\n\r]+$/; // queries come from config but still must not break out of the command
16
+ const SAFE_REASON = /^[A-Za-z0-9 ._,:#()/-]{1,200}$/;
17
+ const SEVERITIES = { p0: "P0", p1: "P1", p2: "P2", p3: "P3", critical: "P0", page: "P0", high: "P1", error: "P1", warning: "P2", medium: "P2", low: "P3", info: "P3" };
18
+ const MAX_IDS = 500, MAX_BODY = 4000;
19
+
20
+ const isStr = (v) => typeof v === "string" && v.trim() !== "";
21
+ const iso = (v) => { if (v == null || v === "") return null; const d = new Date(typeof v === "number" && v < 1e11 ? v * 1000 : v); return Number.isNaN(d.getTime()) ? null : d.toISOString(); };
22
+ export const normalizeSeverity = (v) => SEVERITIES[String(v ?? "").trim().toLowerCase()] ?? "unknown";
23
+ const fill = (tpl, vars) => String(tpl).replace(/\{(\w+)\}/g, (m, k) => (k in vars ? vars[k] : m));
24
+ const parseJson = (s) => { try { return JSON.parse(s); } catch { return undefined; } };
25
+
26
+ /** The normalised signal; `raw` supplies the fields (already mapped by a per-kind normaliser), `source` is `{name}`. */
27
+ export function normalizeSignal(raw, source) {
28
+ const r = raw ?? {};
29
+ const out = {
30
+ id: String(r.id ?? ""),
31
+ source: String(source?.name ?? r.source ?? ""),
32
+ title: String(r.title ?? r.id ?? "").slice(0, 300),
33
+ severity: normalizeSeverity(r.severity),
34
+ owner: isStr(r.owner) ? r.owner : null,
35
+ first_seen: iso(r.first_seen),
36
+ last_seen: iso(r.last_seen ?? r.first_seen),
37
+ body: String(r.body ?? "").slice(0, MAX_BODY),
38
+ };
39
+ if (r.query != null) out.query = String(r.query);
40
+ return out;
41
+ }
42
+
43
+ /** Validate the `prod_watch.sources` map (or `{prod_watch:{sources}}`) into `[{name, kind, list?, read?, close?, run?, queries?}]`; throws on bad config. */
44
+ export function parseSources(cfg) {
45
+ const map = cfg?.prod_watch?.sources ?? cfg?.sources ?? cfg;
46
+ if (!map || typeof map !== "object" || Array.isArray(map)) throw new Error("prod_watch.sources must be a map of name -> source");
47
+ return Object.entries(map).map(([name, s]) => {
48
+ if (!s || typeof s !== "object") throw new Error(`source ${name}: must be a map`);
49
+ for (const k of Object.keys(s)) if (!SOURCE_KEYS.includes(k)) throw new Error(`source ${name}: unknown key ${k}`);
50
+ for (const k of ["list", "read", "close", "run"]) if (s[k] != null && !isStr(s[k])) throw new Error(`source ${name}: ${k} must be a command string`);
51
+ const kind = s.kind ?? (s.list && s.read ? "memo" : s.run && s.queries ? "sql" : null);
52
+ if (!KINDS.includes(kind)) throw new Error(`source ${name}: cannot infer kind (set kind: ${KINDS.join("|")})`);
53
+ const out = { name, kind };
54
+ for (const k of ["list", "read", "close", "run"]) if (s[k]) out[k] = s[k];
55
+ if (kind === "memo" && !(out.list && out.read)) throw new Error(`source ${name}: memo needs list and read`);
56
+ if (kind !== "memo" && !out.run) throw new Error(`source ${name}: ${kind} needs run`);
57
+ if (kind === "sql" || kind === "prometheus") {
58
+ if (!Array.isArray(s.queries) || !s.queries.length) throw new Error(`source ${name}: ${kind} needs queries`);
59
+ out.queries = s.queries.map((q, i) => {
60
+ const n = kind === "sql" ? (typeof q === "string" ? { name: q, sql: q } : q) : q;
61
+ const text = kind === "sql" ? n?.sql ?? n?.name : n?.expr;
62
+ if (!n || typeof n !== "object" || !isStr(text) || !SAFE_QUERY.test(text)) throw new Error(`source ${name}: query ${i} is missing or has shell-active characters`);
63
+ if (kind === "sql") return { name: String(n.name ?? text), sql: text };
64
+ if (!Number.isFinite(Number(n.threshold))) throw new Error(`source ${name}: prometheus query ${i} needs a numeric threshold`);
65
+ const op = n.op ?? ">";
66
+ if (![">", ">=", "<", "<="].includes(op)) throw new Error(`source ${name}: prometheus query ${i} has a bad op`);
67
+ return { name: String(n.name ?? text), expr: text, threshold: Number(n.threshold), op };
68
+ });
69
+ } else if (s.queries != null) throw new Error(`source ${name}: queries only apply to sql/prometheus`);
70
+ return out;
71
+ });
72
+ }
73
+
74
+ // ── per-kind normalisers (pure: command output -> signals) ──────────────────────────────────────────────────────
75
+ const sevFromText = (t) => /\bseverity\W+(\w+)/i.exec(t)?.[1];
76
+ /** One memo (`read` output: JSON object or free text) -> signal. */
77
+ export function normalizeMemo(id, text, source) {
78
+ const j = parseJson(text);
79
+ if (j && typeof j === "object" && !Array.isArray(j)) return normalizeSignal({ ...j, id: j.id ?? id, body: j.body ?? text }, source);
80
+ const t = String(text ?? "");
81
+ return normalizeSignal({ id, title: t.split("\n").find((l) => l.trim())?.replace(/^#+\s*/, "").trim() || id, severity: sevFromText(t), owner: /\bowner\W+([\w.@-]+)/i.exec(t)?.[1], body: t }, source);
82
+ }
83
+ /** Alertmanager v2 `GET /alerts` JSON (array) -> signals; id is the alert fingerprint. */
84
+ export function normalizeAlertmanager(json, source) {
85
+ const arr = Array.isArray(json) ? json : [];
86
+ return arr.map((a) => normalizeSignal({
87
+ id: a.fingerprint ?? a.labels?.alertname, title: a.labels?.alertname ?? a.annotations?.summary, severity: a.labels?.severity, owner: a.labels?.team ?? a.labels?.owner,
88
+ first_seen: a.startsAt, last_seen: a.updatedAt ?? a.startsAt, body: [a.annotations?.summary, a.annotations?.description].filter(Boolean).join("\n") || JSON.stringify(a.labels ?? {}),
89
+ }, source));
90
+ }
91
+ /** SQL result rows (array, or `{rows}`) of query `q` -> one signal per row. */
92
+ export function normalizeSql(json, q, source) {
93
+ const rows = Array.isArray(json) ? json : Array.isArray(json?.rows) ? json.rows : [];
94
+ return rows.map((r, i) => normalizeSignal({
95
+ id: `${q.name}:${r.id ?? r.key ?? i}`, title: r.title ?? q.name, severity: r.severity, owner: r.owner, first_seen: r.first_seen, last_seen: r.last_seen, body: JSON.stringify(r), query: q.name,
96
+ }, source));
97
+ }
98
+ const crosses = (v, op, t) => (op === ">" ? v > t : op === ">=" ? v >= t : op === "<" ? v < t : v <= t);
99
+ /** Prometheus instant-vector JSON (`{data:{result}}` or the bare result array) -> a signal per sample that crosses `q.threshold`. */
100
+ export function normalizePrometheus(json, q, source, now = Date.now()) {
101
+ const res = Array.isArray(json) ? json : json?.data?.result ?? [];
102
+ return res.flatMap((s) => {
103
+ const v = Number(Array.isArray(s.value) ? s.value[1] : s.value);
104
+ if (!Number.isFinite(v) || !crosses(v, q.op, q.threshold)) return [];
105
+ const labels = s.metric ?? {};
106
+ return [normalizeSignal({
107
+ id: `${q.name}:${Object.keys(labels).sort().map((k) => `${k}=${labels[k]}`).join(",") || "all"}`.replace(/[^A-Za-z0-9._:@=,-]/g, "_"), title: `${q.name} ${q.op} ${q.threshold}`,
108
+ severity: labels.severity, owner: labels.team ?? labels.owner, first_seen: now, last_seen: now, body: `${q.name}=${v} (${q.op} ${q.threshold}) ${JSON.stringify(labels)}`, query: q.expr,
109
+ }, source)];
110
+ });
111
+ }
112
+
113
+ /** Run one source's declared read commands; returns `{signals, errors}`. Executes only `list`/`read`/`run`, never `close`. */
114
+ export async function runAdapter(source, io) {
115
+ const signals = [], errors = [];
116
+ const exec = async (cmd) => { const r = await io.exec(cmd); if (r?.code !== 0) throw new Error(`exit ${r?.code ?? "?"}`); return String(r.stdout ?? ""); };
117
+ const guard = async (label, fn) => { try { await fn(); } catch (e) { errors.push(`${source.name}: ${label}: ${e.message}`); } };
118
+ if (source.kind === "memo") {
119
+ await guard("list", async () => {
120
+ const out = await exec(source.list);
121
+ const j = parseJson(out);
122
+ const ids = (Array.isArray(j) ? j.map(String) : out.split(/\r?\n/).map((l) => l.trim()).filter(Boolean));
123
+ if (ids.length > MAX_IDS) errors.push(`${source.name}: list truncated to ${MAX_IDS} of ${ids.length}`);
124
+ for (const id of ids.slice(0, MAX_IDS)) {
125
+ if (!SAFE_ID.test(id)) { errors.push(`${source.name}: skipped unsafe id`); continue; }
126
+ await guard(`read ${id}`, async () => signals.push(normalizeMemo(id, await exec(fill(source.read, { id })), source)));
127
+ }
128
+ });
129
+ } else if (source.kind === "alertmanager") {
130
+ await guard("run", async () => {
131
+ const j = parseJson(await exec(source.run));
132
+ if (j === undefined) throw new Error("output is not JSON");
133
+ signals.push(...normalizeAlertmanager(j, source));
134
+ });
135
+ } else {
136
+ for (const q of source.queries ?? []) {
137
+ await guard(`run ${q.name}`, async () => {
138
+ const j = parseJson(await exec(fill(source.run, source.kind === "sql" ? { sql: q.sql, query: q.sql } : { expr: q.expr, query: q.expr })));
139
+ if (j === undefined) throw new Error("output is not JSON");
140
+ signals.push(...(source.kind === "sql" ? normalizeSql(j, q, source) : normalizePrometheus(j, q, source, io.now?.() ?? Date.now())));
141
+ });
142
+ }
143
+ }
144
+ return { signals, errors };
145
+ }
146
+
147
+ /**
148
+ * The only path to a source's `close` command. Needs `source.close`, a safe signal id and reason, an `audit` record
149
+ * `{by}` and an `io.audit(record)` sink; the record is written BEFORE the command runs (a failing sink aborts the close).
150
+ * Returns `{ok, code}`.
151
+ */
152
+ export async function closeSignal(source, signal, { issue, reason, audit } = {}, io = {}) {
153
+ if (!source?.close) throw new Error(`source ${source?.name}: no close command declared`);
154
+ if (!audit || !isStr(audit.by)) throw new Error("closeSignal requires an audit record {by}");
155
+ if (typeof io.audit !== "function") throw new Error("closeSignal requires io.audit");
156
+ if (!SAFE_ID.test(String(signal?.id ?? ""))) throw new Error("closeSignal: unsafe signal id");
157
+ if (!SAFE_REASON.test(String(reason ?? ""))) throw new Error("closeSignal: reason missing or has shell-active characters");
158
+ if (!/^\d+$/.test(String(issue ?? ""))) throw new Error("closeSignal: issue must be a number");
159
+ const at = new Date(io.now?.() ?? Date.now()).toISOString();
160
+ await io.audit({ event: "close", source: source.name, id: signal.id, issue: Number(issue), reason, by: audit.by, at });
161
+ const r = await io.exec(fill(source.close, { id: signal.id, issue: String(issue), reason }));
162
+ const ok = r?.code === 0;
163
+ try { await io.audit({ event: "close_result", source: source.name, id: signal.id, ok, code: r?.code ?? null, at }); } catch { /* the pre-exec record already stands */ }
164
+ return { ok, code: r?.code ?? null };
165
+ }
@@ -0,0 +1,108 @@
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 { parseSources, runAdapter, closeSignal, normalizeSignal } from "./prodwatch-sources.mjs";
6
+
7
+ const spy = (answers) => { const calls = []; return { calls, exec: async (cmd) => { calls.push(cmd); const a = answers(cmd); return a ?? { code: 1, stdout: "" }; } }; };
8
+ const KEYS = ["id", "source", "title", "severity", "owner", "first_seen", "last_seen", "body"];
9
+
10
+ describe("parseSources", () => {
11
+ it("infers kinds and validates", () => {
12
+ const s = parseSources({ prod_watch: { sources: {
13
+ m: { list: "ls", read: "cat {id}", close: "rm {id}" }, q: { run: "psql {sql}", queries: ["a.sql"] },
14
+ a: { kind: "alertmanager", run: "am" }, p: { kind: "prometheus", run: "prom '{expr}'", queries: [{ name: "err", expr: "up == 0", threshold: 1 }] } } } });
15
+ assert.deepEqual(s.map((x) => x.kind), ["memo", "sql", "alertmanager", "prometheus"]);
16
+ assert.equal(s[3].queries[0].op, ">");
17
+ });
18
+ it("rejects unknown keys, missing commands, shell-active queries", () => {
19
+ assert.throws(() => parseSources({ x: { list: "ls", read: "cat", write: "x" } }), /unknown key/);
20
+ assert.throws(() => parseSources({ x: { kind: "memo", list: "ls" } }), /list and read/);
21
+ assert.throws(() => parseSources({ x: { run: "r", queries: ["a; rm -rf /"] } }), /shell-active/);
22
+ assert.throws(() => parseSources({ x: { kind: "prometheus", run: "r", queries: [{ expr: "up", threshold: "x" }] } }), /threshold/);
23
+ });
24
+ });
25
+
26
+ describe("adapters", () => {
27
+ it("memo: lists, reads, normalises, skips unsafe ids, reports read failures", async () => {
28
+ const [src] = parseSources({ memos: { list: "LIST", read: "READ {id}" } });
29
+ const io = spy((c) => c === "LIST" ? { code: 0, stdout: "m-1\nm-2\n$(evil)\n" } : c === "READ m-1" ? { code: 0, stdout: "# Disk full\nseverity: critical\nowner: infra\n" } : null);
30
+ const { signals, errors } = await runAdapter(src, io);
31
+ assert.equal(signals.length, 1);
32
+ assert.deepEqual(Object.keys(signals[0]).slice(0, 8), KEYS);
33
+ assert.equal(signals[0].severity, "P0"); assert.equal(signals[0].owner, "infra"); assert.equal(signals[0].title, "Disk full");
34
+ assert.equal(errors.length, 2);
35
+ assert.ok(!io.calls.some((c) => c.includes("evil")));
36
+ });
37
+ it("alertmanager: v2 alerts", async () => {
38
+ const [src] = parseSources({ a: { kind: "alertmanager", run: "AM" } });
39
+ const j = [{ fingerprint: "abc123", labels: { alertname: "HighErr", severity: "warning", team: "api" }, annotations: { summary: "errors up" }, startsAt: "2026-01-01T00:00:00Z" }];
40
+ const { signals } = await runAdapter(src, spy(() => ({ code: 0, stdout: JSON.stringify(j) })));
41
+ assert.equal(signals[0].id, "abc123"); assert.equal(signals[0].severity, "P2"); assert.equal(signals[0].owner, "api");
42
+ assert.equal(signals[0].first_seen, "2026-01-01T00:00:00.000Z");
43
+ });
44
+ it("sql: one signal per row with query", async () => {
45
+ const [src] = parseSources({ s: { run: "SQL {sql}", queries: ["slo.sql"] } });
46
+ const io = spy(() => ({ code: 0, stdout: JSON.stringify([{ id: 7, severity: "high" }, { key: "k" }]) }));
47
+ const { signals } = await runAdapter(src, io);
48
+ assert.deepEqual(signals.map((s) => s.id), ["slo.sql:7", "slo.sql:k"]);
49
+ assert.equal(signals[0].query, "slo.sql"); assert.equal(signals[0].severity, "P1");
50
+ assert.deepEqual(io.calls, ["SQL slo.sql"]);
51
+ });
52
+ it("prometheus: only samples crossing the threshold", async () => {
53
+ const [src] = parseSources({ p: { kind: "prometheus", run: "PROM {expr}", queries: [{ name: "err", expr: "rate(e)", threshold: 0.5 }] } });
54
+ const j = { data: { result: [{ metric: { job: "a" }, value: [1, "0.9"] }, { metric: { job: "b" }, value: [1, "0.1"] }] } };
55
+ const { signals } = await runAdapter(src, spy(() => ({ code: 0, stdout: JSON.stringify(j) })));
56
+ assert.equal(signals.length, 1); assert.equal(signals[0].id, "err:job=a"); assert.equal(signals[0].query, "rate(e)");
57
+ });
58
+ it("non-JSON or failing output becomes an error, not a throw", async () => {
59
+ const [src] = parseSources({ a: { kind: "alertmanager", run: "AM" } });
60
+ assert.equal((await runAdapter(src, spy(() => ({ code: 0, stdout: "nope" })))).errors.length, 1);
61
+ assert.equal((await runAdapter(src, spy(() => ({ code: 2, stdout: "" })))).errors.length, 1);
62
+ });
63
+ it("normalizeSignal omits query when absent and coerces severity", () => {
64
+ const s = normalizeSignal({ id: "x", severity: "bogus" }, { name: "n" });
65
+ assert.equal("query" in s, false); assert.equal(s.severity, "unknown"); assert.equal(s.first_seen, null);
66
+ });
67
+ });
68
+
69
+ describe("read-only enforcement", () => {
70
+ it("runAdapter never executes close for any kind", async () => {
71
+ const srcs = parseSources({
72
+ m: { list: "LIST", read: "READ {id}", close: "CLOSE {id}" }, s: { run: "RUN {sql}", queries: ["a.sql"], close: "CLOSE2" },
73
+ a: { kind: "alertmanager", run: "AM", close: "CLOSE3" } });
74
+ const io = spy((c) => ({ code: 0, stdout: c === "LIST" ? "m1" : "[]" }));
75
+ for (const s of srcs) await runAdapter(s, io);
76
+ assert.ok(io.calls.length >= 3);
77
+ assert.ok(io.calls.every((c) => !c.startsWith("CLOSE")), io.calls.join("|"));
78
+ });
79
+ });
80
+
81
+ describe("closeSignal", () => {
82
+ const [src] = parseSources({ m: { list: "ls", read: "cat {id}", close: "CLOSE {id} --issue {issue} --reason {reason}" } });
83
+ const sig = { id: "m-1" };
84
+ it("audits before exec and runs the declared close", async () => {
85
+ const log = [];
86
+ const io = { exec: async (c) => { log.push(c); return { code: 0, stdout: "" }; }, audit: async (r) => { log.push(r.event); }, now: () => 0 };
87
+ const r = await closeSignal(src, sig, { issue: 12, reason: "fixed in #12", audit: { by: "prodwatch" } }, io);
88
+ assert.equal(r.ok, true);
89
+ assert.deepEqual(log, ["close", "CLOSE m-1 --issue 12 --reason fixed in #12", "close_result"]);
90
+ });
91
+ it("refuses without audit record, sink, close command, or with unsafe input; never execs", async () => {
92
+ const calls = [];
93
+ const io = { exec: async (c) => { calls.push(c); return { code: 0 }; }, audit: async () => {} };
94
+ await assert.rejects(closeSignal(src, sig, { issue: 1, reason: "r" }, io), /audit record/);
95
+ await assert.rejects(closeSignal(src, sig, { issue: 1, reason: "r", audit: { by: "x" } }, { exec: io.exec }), /io.audit/);
96
+ await assert.rejects(closeSignal({ name: "n" }, sig, { issue: 1, reason: "r", audit: { by: "x" } }, io), /no close/);
97
+ await assert.rejects(closeSignal(src, { id: "a;b" }, { issue: 1, reason: "r", audit: { by: "x" } }, io), /unsafe/);
98
+ await assert.rejects(closeSignal(src, sig, { issue: 1, reason: "r; rm", audit: { by: "x" } }, io), /reason/);
99
+ await assert.rejects(closeSignal(src, sig, { issue: "1 2", reason: "r", audit: { by: "x" } }, io), /issue/);
100
+ assert.deepEqual(calls, []);
101
+ });
102
+ it("a failing audit sink aborts the close", async () => {
103
+ const calls = [];
104
+ const io = { exec: async (c) => { calls.push(c); return { code: 0 }; }, audit: async () => { throw new Error("disk"); } };
105
+ await assert.rejects(closeSignal(src, sig, { issue: 1, reason: "r", audit: { by: "x" } }, io), /disk/);
106
+ assert.deepEqual(calls, []);
107
+ });
108
+ });
@@ -162,7 +162,8 @@ If the issue is already fixed or invalid, write ${RESULT_FILE} {"status":"alread
162
162
  "preserve":[{"id":"P1","what":"<caller, contract or behaviour that must not change, with its path>"}],
163
163
  "validate":[{"id":"V1","command":"<exact command: the new regression test plus the existing tests that reference the files you change; a git diff compares against the merge base (origin/<lane>...HEAD), never the moving origin/<lane> tip>"}],
164
164
  "decisions":[{"id":"K1","choice":"<a non-obvious choice: a new dependency, a copied pattern, a boundary relied on>","justification":"<why, with file:line>","source":"doc|lint|precedent|spec"}]}
165
- Every requirement and acceptance criterion in the issue and its maintainers' comments is one requirement, quoted verbatim (others' comments are context, not requirements). Never drop or narrow one silently: "defer" (separate work) and "post-deploy" (only checkable after a deploy) are judged by the reviewer and, if accepted, filed by the engine as a tracked follow-up issue. Every defer or post-deploy row has one "bucket": post-deploy (needs a release), verify-now (parent already on the default branch), date:YYYY-MM-DD (absolute, never a relative wait), owner:<action> (credentials, spend, settings; disposition defer, never post-deploy) or new-issue (future work). One sentence is one row. An outcome criterion this change can ship as a test, metric or alert is "deliver". A requirement you can do in this change is "deliver". A deliver requirement whose result is only measured outside the lane (Lighthouse, field perf, a nightly or report-only suite) is "verify":"out_of_band" with "evidence" naming the job or workflow that measures it (delivered by its instrumentation). The engine tags such quotes itself; set "verify":"in_lane" when this change can check it. List every file you will change as a deliverable; tests are always allowed.
165
+ Every requirement and acceptance criterion in the issue and its maintainers' comments is one requirement, quoted verbatim (others' comments are context, not requirements). Never drop or narrow one silently: "defer" (separate work) and "post-deploy" (only checkable after a deploy) are judged by the reviewer and, if accepted, filed by the engine as a tracked follow-up issue. Every defer or post-deploy row has one "bucket": post-deploy (needs a release), verify-now (parent already on the default branch), date:YYYY-MM-DD (absolute, never a relative wait), owner:<action> (credentials, spend, settings, promotion of a default-off flag; disposition defer, never post-deploy) or new-issue (future work). One sentence is one row. An outcome criterion this change can ship as a test, metric or alert is "deliver". A requirement you can do in this change is "deliver". A deliver requirement whose result is only measured outside the lane (Lighthouse, field perf, a nightly or report-only suite) is "verify":"out_of_band" with "evidence" naming the job or workflow that measures it (delivered by its instrumentation). The engine tags such quotes itself; set "verify":"in_lane" when this change can check it. List every file you will change as a deliverable; tests are always allowed.
166
+ A new default-off flag or rollout key needs an activation row: defer, bucket \`owner:promote:<flag>\`, why = first cohort, guard metrics, shadow evidence (an AC naming shadow/cohort/treated fails if it ships off).
166
167
  A [type:e2e] requirement needs a validate that runs a real e2e check (repo e2e set, Playwright, live stack), not a stubbed unit test; else post-deploy.
167
168
  A validate or repro command must not read a $TMPDIR file it did not create: each run gets a fresh TMPDIR.
168
169
  Scope is enforced by the engine: it checks the changed files against the deliverables plus typed amendments itself, so do not write a file-allowlist or denylist validate (git diff --name-only | grep); the engine drops such a validate at freeze.
@@ -290,7 +291,7 @@ export function missingEntriesPrompt(missing, mode = "local") {
290
291
  return `These tests enumerate the siblings of symbols or files this change adds, but do not name them (CI will fail on the stale list):\n${missing.slice(0, 30).map((m) => `- ${m.symbol} (${m.module}) -> ${m.test}:${m.line}`).join("\n")}\n\nFor each, add the symbol to that test's list, ${NOT_MEMBER}. ${rerun(mode)}, commit, and update ${IMPLEMENTATION_FILE} and ${RESULT_FILE}. Do not push or touch GitHub.`;
291
292
  }
292
293
 
293
- const RENUMBER_RULE = "Renumber the lane's files, never the base's: rename each with git mv to its new number, keep the SQL (or other migration source) byte-identical except a first-line header naming its own number/tag, which follows the new one, change a numbered document (e.g. an ADR) only in its own number (its title), regenerate the snapshot and journal with the repo's own migration generator (never hand- or text-merge the journal), keep journal entries strictly ordered, and update every reference to the old name, including the series index (e.g. docs/adr/README.md) so it lists both the base's entry and yours.";
294
+ const RENUMBER_RULE = "Renumber the lane's files, never the base's: rename each with git mv to its new number, keep the SQL (or other migration source) byte-identical except that its own old number/name (first-line header, self-references, a `_rollback` pointer) is replaced by the new one, change a numbered document (e.g. an ADR) only in its own number (its title), regenerate the snapshot and journal with the repo's own migration generator (never hand- or text-merge the journal), keep journal entries strictly ordered, and update every reference to the old name, including the series index (e.g. docs/adr/README.md) so it lists both the base's entry and yours.";
294
295
 
295
296
  /** #4322: lane-added sequence-numbered files whose number the base already uses, at hand-off or after a base-sync. */
296
297
  export function sequencePrompt(collisions, lane, mode = "local") {
@@ -304,6 +305,11 @@ export function sequenceSyncNote(files) {
304
305
  return hit ? ` A numbered migration or its journal conflicts: do not text-merge it. ${RENUMBER_RULE}` : "";
305
306
  }
306
307
 
308
+ /** #4732: base-sync before a deterministic renumber: only the non-sequence conflicts are the builder's. */
309
+ export function sequenceSyncPrompt(base, files, mode = "local") {
310
+ return `Merging ${base} into this branch conflicts in: ${files.join(", ")}. Resolve only these conflicts preserving both this fix's intent and the base's changes, ${syncChecks(mode)}, and commit the merge. The sequence-numbered files are already resolved: do not renumber anything. Do not push.`;
311
+ }
312
+
307
313
  export function contractCorrectionPrompt(problems) {
308
314
  return `Your ${CONTRACT_FILE} is not valid:\n${problems.slice(0, 20).map((p) => `- ${p}`).join("\n")}\n\nFix the contract (planning only, no code, no commit) and stop. Do not push or touch GitHub.`;
309
315
  }
@@ -342,7 +348,7 @@ export const HUMAN_BLOCK_REASONS = Object.freeze(["credentials", "spend", "promo
342
348
  const BLOCK_RULES = `"blocked" needs a typed "block" in ${RESULT_FILE}, one of:
343
349
  - {"kind":"dependency","issues":[N]}: an open upstream issue must land first. The engine requeues this issue behind it.
344
350
  - {"kind":"split-required","subissues":[{"title":"","body":"","depends_on":[0],"files":["<path>"]}],"size":{"files":N,"lines":N}}: too big for one change. The engine files the sub-issues (depends_on = indexes of earlier sub-issues; files = the files or dirs each will edit, also accepted as "paths") only when every sub-issue's files are disjoint from the others' or the whole change's size estimate exceeds ${SPLIT_MIN_FILES} files or ${SPLIT_MIN_LINES} lines; otherwise keep one lane: an ordered checklist in the contract with a validate per item. In an admitted split, when siblings would edit the same hub (a barrel or index export list, a union type, a shared test fixture, an index doc), pre-stage its slots in the earliest sub-issue and make the others depend on it, or give each sibling its own per-feature file; the engine serialises sub-issues that still share a file.
345
- - {"kind":"human","why":"${HUMAN_BLOCK_REASONS.join("|")}"}: only an external action agents cannot take, or a product decision too critical for agents.
351
+ - {"kind":"human","why":"${HUMAN_BLOCK_REASONS.join("|")}"}: only an external action agents cannot take, or a product decision too critical for agents. Optional "remainder":[{"title","body"}]: the agent-doable rest, filed as its own issue.
346
352
  "An upstream issue must land first", "needs a split" and "needs prod data that read-only monitoring can read" are never "human".
347
353
  A check that times out (rc 124) is host load, never a block or "human" product-decision: run the narrowest targeted command for your changed files and say the full one could not finish in time.
348
354
  Remote sandbox lacking a host-only capability (sops, prod_monitor, ops_credentials): name it in the summary; the host reruns the lane.`;
@@ -33,6 +33,20 @@ describe("in-batch recovery of mechanical needs-human (#4267)", () => {
33
33
  const NH = (code, detail = `ended ${code}`, more = {}) => ({ terminalReason: "needs-human", code, detail, ...more });
34
34
  const byIssue = (rows) => Object.fromEntries(rows.map((r) => [r.issue, r]));
35
35
 
36
+ it("#4725: mechanical codes get their own budget (2), apart from the conformance one; an open-PR base conflict is not parked while it remains", async () => {
37
+ const { rows, calls } = await batch({ 1: [NH("base.conflict", "conflicts", { pr: 50 }), NH("base.conflict", "conflicts", { pr: 50 }), { terminalReason: "merged", pr: 50 }] },
38
+ {}, { recovery: { maxAttempts: 1, mechanicalMaxAttempts: 2 } });
39
+ assert.equal(byIssue(rows)[1].outcome, "merged");
40
+ assert.deepEqual(calls.map((c) => c.recover?.attempt ?? 0), [0, 1, 2]);
41
+ assert.equal(calls[1].recover.final, false); assert.equal(calls[2].recover.final, true);
42
+ // conformance codes stay at maxAttempts: ci.red gets one recovery only
43
+ const c = await batch({ 2: [NH("ci.red", "red", { pr: 51 })] }, {}, { recovery: { maxAttempts: 1, mechanicalMaxAttempts: 2 } });
44
+ assert.equal(c.calls.length, 2);
45
+ // a mechanical recovery does not spend the conformance budget
46
+ const m = await batch({ 3: [NH("ci.red", "red"), NH("env.tool_missing", "no tool"), { terminalReason: "merged" }] }, {}, { recovery: { maxAttempts: 1, mechanicalMaxAttempts: 2 } });
47
+ assert.equal(byIssue(m.rows)[3].outcome, "merged");
48
+ });
49
+
36
50
  it("ci.red: one recovery lane on the PR; green re-queues the issue and its dependent in the same batch, no operator action", async () => {
37
51
  const { rows, calls, decisions } = await batch({ 1: [NH("ci.red", "Required check(s) failed on PR #101: test"), { terminalReason: "merged", pr: 101 }], 2: [{ terminalReason: "merged", pr: 102 }] }, { 2: "**Depends on**: #1" });
38
52
  const r = byIssue(rows);
@@ -0,0 +1,182 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Read-only capability relay (#4778), zero LLM. A sandbox lane that needs a host-only capability (e.g. `prod_monitor`)
5
+ * runs the operator's read-only wrapper (`obs-psql ...`) through `cs-relay`: the request goes sandbox -> pool agent ->
6
+ * router queue, the dispatching host picks it up on its per-lane status poll (`servicePending`), gates it against the
7
+ * forge.yaml `execution.relay_commands` allowlist (`relayGate`), runs it without a shell (`runRelayed`) and posts the
8
+ * redacted output back. The key and the wrapper never leave the host; the router only queues.
9
+ * Pre-fetch: the frozen contract's simple validate/repro_test commands that pass the gate (`relayPrefetchCommands`) are
10
+ * run by the host at dispatch and shipped with the lane.
11
+ */
12
+ import { execFile } from "node:child_process";
13
+ import { createHash } from "node:crypto";
14
+ import { parseContractComment } from "./render.mjs";
15
+ import { isTrustedIssueComment } from "./prefilter.mjs";
16
+ import { redact } from "./sandbox-remote.mjs";
17
+
18
+ const CAP_RE = /^[a-z][a-z0-9_-]*$/;
19
+ const COMMAND_RE = /^[A-Za-z0-9_][A-Za-z0-9._-]*\*?$/;
20
+ const NAME_RE = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
21
+ export const RELAY_REFUSED_RC = 126;
22
+ /** The router parses a POST body at 1 MiB (pool/http.mjs readJson); an answer is capped well under it, envelope and escaping included. */
23
+ export const RELAY_ANSWER_MAX_BYTES = 512 * 1024;
24
+
25
+ /**
26
+ * `capability:command` entries (list or comma string) -> `{capability: [command, ...]}`. A command is an exact name or a
27
+ * prefix glob with one trailing `*` (`obs-*`); no path separators, whitespace or other glob characters. Invalid entries are ignored.
28
+ */
29
+ export function parseRelayCommands(list) {
30
+ const raw = Array.isArray(list) ? list : typeof list === "string" && list.trim() ? list.split(",") : [];
31
+ const out = {};
32
+ for (const x of raw) {
33
+ const t = String(x ?? "").trim(), i = t.indexOf(":");
34
+ if (i <= 0) continue;
35
+ const cap = t.slice(0, i).trim().toLowerCase(), cmd = t.slice(i + 1).trim();
36
+ if (!CAP_RE.test(cap) || !COMMAND_RE.test(cmd)) continue;
37
+ (out[cap] ??= []).includes(cmd) || out[cap].push(cmd);
38
+ }
39
+ return out;
40
+ }
41
+
42
+ /** The exact (non-glob) command names of an allowlist: the wrappers the lane image shims. */
43
+ export function relayCommandNames(relay) {
44
+ return [...new Set(Object.values(relay ?? {}).flat().filter((c) => NAME_RE.test(c)))].sort();
45
+ }
46
+
47
+ /** `{ok: true, capability}` when argv[0] is allowlisted (exact name or prefix glob, never a path); else `{ok: false, reason}`. */
48
+ export function relayGate(argv, relay) {
49
+ if (!Array.isArray(argv) || !argv.length || !argv.every((a) => typeof a === "string")) return { ok: false, reason: "relay: argv must be a non-empty string list" };
50
+ const cmd = argv[0];
51
+ if (!NAME_RE.test(cmd)) return { ok: false, reason: `relay: ${JSON.stringify(cmd)} not allowlisted` };
52
+ for (const [capability, cmds] of Object.entries(relay ?? {})) {
53
+ for (const c of Array.isArray(cmds) ? cmds : []) {
54
+ if (c === cmd || (c.endsWith("*") && c.length > 1 && cmd.length >= c.length && cmd.startsWith(c.slice(0, -1)))) return { ok: true, capability };
55
+ }
56
+ }
57
+ return { ok: false, reason: `relay: ${cmd} not allowlisted` };
58
+ }
59
+
60
+ /**
61
+ * Run an argv on the host: execFile, no shell, the host env, a timeout and an output cap; every known secret is redacted.
62
+ * `{rc, stdout, stderr, truncated?}`; a timeout is rc 124, a missing command rc 127. Never throws.
63
+ */
64
+ export function runRelayed(argv, { timeoutMs = 120000, maxBytes = 1 << 20, secrets = [], execFileFn = execFile } = {}) {
65
+ return new Promise((resolve) => {
66
+ const done = (rc, stdout, stderr, extra = {}) => resolve({ rc, stdout: redact(stdout, secrets), stderr: redact(stderr, secrets), ...extra });
67
+ try {
68
+ execFileFn(argv[0], argv.slice(1), { shell: false, timeout: timeoutMs, maxBuffer: maxBytes, encoding: "utf8", windowsHide: true }, (err, stdout = "", stderr = "") => {
69
+ if (!err) return done(0, stdout, stderr);
70
+ if (err.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") return done(1, stdout, `${stderr}\nrelay: output over ${maxBytes} bytes, truncated`, { truncated: true });
71
+ if (err.code === "ENOENT") return done(127, "", `relay: ${argv[0]} not found on the dispatching host`);
72
+ if (err.killed) return done(124, stdout, `${stderr}\nrelay: timed out after ${Math.round(timeoutMs / 1000)}s`);
73
+ return done(Number.isInteger(err.code) ? err.code : 1, stdout, stderr || String(err.message ?? ""));
74
+ });
75
+ } catch (e) { done(1, "", `relay: ${e?.message ?? e}`); }
76
+ });
77
+ }
78
+
79
+ /** A shell command split into argv when it is one simple command (no pipes, lists, redirects, expansions); else null. */
80
+ export function simpleArgv(command) {
81
+ const s = String(command ?? "").trim();
82
+ const argv = [];
83
+ let cur = null, q = null;
84
+ for (let i = 0; i < s.length; i++) {
85
+ const ch = s[i];
86
+ if (q === "'") { if (ch === "'") q = null; else cur += ch; continue; }
87
+ if (q === '"') {
88
+ if (ch === '"') q = null;
89
+ else if (ch === "$" || ch === "`") return null;
90
+ else if (ch === "\\" && i + 1 < s.length && '"\\'.includes(s[i + 1])) cur += s[++i];
91
+ else cur += ch;
92
+ continue;
93
+ }
94
+ if (ch === "'" || ch === '"') { q = ch; cur ??= ""; continue; }
95
+ if ("|;&<>$`\n(){}".includes(ch)) return null;
96
+ if (ch === "\\") { if (i + 1 >= s.length) return null; cur = (cur ?? "") + s[++i]; continue; }
97
+ if (/\s/.test(ch)) { if (cur !== null) { argv.push(cur); cur = null; } continue; }
98
+ cur = (cur ?? "") + ch;
99
+ }
100
+ if (q) return null;
101
+ if (cur !== null) argv.push(cur);
102
+ return argv.length ? argv : null;
103
+ }
104
+
105
+ /** lean.mjs `contractHash` (not imported: lean.mjs reaches this module through execution.mjs). */
106
+ const frozenHash = (text) => createHash("sha256").update(String(text)).digest("hex").slice(0, 12);
107
+
108
+ /**
109
+ * Pre-fetch candidates (#4778): the simple validate/repro_test commands the gate allows from the last frozen contract,
110
+ * `[{argv}]`. Only a trusted FORGE:CONTRACT comment whose hash verifies counts, as in lean.mjs readFrozenContract: an
111
+ * outsider's contract comment never chooses what the host runs (release #4820 API-1).
112
+ */
113
+ export function relayPrefetchCommands({ comments = [] } = {}, relay = null) {
114
+ if (!relay || !Object.keys(relay).length) return [];
115
+ let contract = null;
116
+ for (const c of Array.isArray(comments) ? comments : []) {
117
+ if (typeof c !== "object" || !isTrustedIssueComment(c)) continue;
118
+ const b = String(c.body ?? "").trimStart();
119
+ if (!b.startsWith("<!-- FORGE:CONTRACT -->")) continue;
120
+ const fc = parseContractComment(b);
121
+ if (fc?.contract && typeof fc.contract === "object" && frozenHash(fc.text) === fc.hash) contract = fc.contract;
122
+ }
123
+ if (!contract) return [];
124
+ const cmds = (Array.isArray(contract.validate) ? contract.validate : []).map((v) => v?.command);
125
+ if (typeof contract.repro_test?.command === "string") cmds.push(contract.repro_test.command);
126
+ const out = [], seen = new Set();
127
+ for (const c of cmds) {
128
+ const argv = typeof c === "string" ? simpleArgv(c) : null;
129
+ if (!argv || !relayGate(argv, relay).ok) continue;
130
+ const k = JSON.stringify(argv);
131
+ if (!seen.has(k)) { seen.add(k); out.push({ argv }); }
132
+ }
133
+ return out;
134
+ }
135
+
136
+ /**
137
+ * An answer whose serialized JSON fits `max` bytes: unchanged when it already does, else stdout (then stderr) is trimmed
138
+ * (never mid-character), a truncation notice is appended to stderr and rc is 1 (as runRelayed does for its own cap).
139
+ */
140
+ export function capAnswer(out, max = RELAY_ANSWER_MAX_BYTES) {
141
+ const size = (o) => Buffer.byteLength(JSON.stringify(o));
142
+ if (size(out) <= max) return out;
143
+ const notice = `relay: output over ${max} bytes, truncated`;
144
+ const trim = (s, n) => Buffer.from(s).subarray(0, Math.max(0, Buffer.byteLength(s) - n)).toString("utf8").replace(/\uFFFD$/, "");
145
+ const build = (stdout, stderr) => ({ rc: 1, stdout, stderr: stderr ? `${stderr}\n${notice}` : notice });
146
+ let { stdout, stderr } = out;
147
+ let res = build(stdout, stderr);
148
+ while (size(res) > max && (stdout || stderr)) {
149
+ const excess = size(res) - max;
150
+ if (stdout) stdout = trim(stdout, excess); else stderr = trim(stderr, excess);
151
+ res = build(stdout, stderr);
152
+ }
153
+ return res;
154
+ }
155
+
156
+ /**
157
+ * Service a sandbox's pending relay requests: gate each, run the allowed ones, refuse the rest (rc 126), post every answer.
158
+ * Each stream is capped (capStream) and the whole answer is then bounded to RELAY_ANSWER_MAX_BYTES (capAnswer) so it fits the router's body limit; an answer the router still rejects with a 4xx (not 429) is replaced by a small
159
+ * rc 1 answer, so the command is never re-run on every poll (release #4820 INFRA-1). Returns how many were answered.
160
+ */
161
+ export const RELAY_ANSWER_STREAM_MAX = 256 * 1024;
162
+ const capStream = (s) => { const t = String(s ?? ""); return t.length > RELAY_ANSWER_STREAM_MAX ? `${t.slice(0, RELAY_ANSWER_STREAM_MAX)}\n[relay: output truncated at ${RELAY_ANSWER_STREAM_MAX} chars]\n` : t; };
163
+ export async function servicePending({ transport, id, relay, run = runRelayed, secrets = [] } = {}) {
164
+ if (typeof transport?.relayPending !== "function" || typeof transport.relayAnswer !== "function") return 0;
165
+ let list = [];
166
+ try { list = (await transport.relayPending(id)) ?? []; } catch { return 0; }
167
+ let n = 0;
168
+ for (const req of Array.isArray(list) ? list : []) {
169
+ if (typeof req?.rid !== "string" || !req.rid) continue;
170
+ const g = relayGate(req.argv, relay);
171
+ const raw = g.ok ? await run(req.argv, { secrets }) : { rc: RELAY_REFUSED_RC, stdout: "", stderr: g.reason };
172
+ const out = capAnswer({ rc: Number.isInteger(raw?.rc) ? raw.rc : 1, stdout: capStream(redact(raw?.stdout, secrets)), stderr: capStream(redact(raw?.stderr, secrets)) }); // a custom runner is redacted too
173
+ try { await transport.relayAnswer(id, req.rid, out); n++; }
174
+ catch (e) {
175
+ const st = e?.status;
176
+ if (Number.isInteger(st) && st >= 400 && st < 500 && st !== 429) { // deterministic rejection: retrying would re-run the command every poll
177
+ try { await transport.relayAnswer(id, req.rid, { rc: 1, stdout: "", stderr: `relay: answer rejected by the router (HTTP ${st}), output too large or invalid` }); n++; } catch { /* the next poll retries */ }
178
+ } // transient/429/statusless: the next poll retries
179
+ }
180
+ }
181
+ return n;
182
+ }