forgedock 1.65.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 (80) 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 +143 -19
  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 +13 -5
  15. package/bin/lean/batch-health.test.mjs +16 -0
  16. package/bin/lean/batch.mjs +62 -0
  17. package/bin/lean/batch.test.mjs +119 -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/depcache.mjs +9 -0
  29. package/bin/lean/efficiency.mjs +162 -0
  30. package/bin/lean/efficiency.test.mjs +79 -0
  31. package/bin/lean/execution.mjs +31 -13
  32. package/bin/lean/execution.test.mjs +46 -0
  33. package/bin/lean/failure-stop.mjs +46 -0
  34. package/bin/lean/failure-stop.test.mjs +45 -0
  35. package/bin/lean/fixtures/capacity-storm.json +609 -0
  36. package/bin/lean/lean.mjs +130 -30
  37. package/bin/lean/lean.test.mjs +138 -47
  38. package/bin/lean/liveness.mjs +37 -0
  39. package/bin/lean/liveness.test.mjs +33 -0
  40. package/bin/lean/orchestrate-attempts.test.mjs +74 -0
  41. package/bin/lean/orchestrate-envhold.test.mjs +17 -0
  42. package/bin/lean/orchestrate-pause.test.mjs +84 -0
  43. package/bin/lean/orchestrate-reconcile.test.mjs +147 -0
  44. package/bin/lean/orchestrate.mjs +202 -28
  45. package/bin/lean/phaseledger.mjs +6 -0
  46. package/bin/lean/phaseledger.test.mjs +13 -1
  47. package/bin/lean/prompts.mjs +6 -10
  48. package/bin/lean/reconcile.mjs +90 -0
  49. package/bin/lean/recurrence.mjs +38 -2
  50. package/bin/lean/recurrence.test.mjs +56 -1
  51. package/bin/lean/sandbox-remote.mjs +33 -2
  52. package/bin/lean/sched.mjs +19 -0
  53. package/bin/lean/sched.test.mjs +11 -1
  54. package/bin/lean/schedd-health.mjs +8 -1
  55. package/bin/lean/schedd-health.test.mjs +19 -0
  56. package/bin/lean/schedd.mjs +97 -10
  57. package/bin/lean/schedd.test.mjs +138 -1
  58. package/bin/lean/slo.mjs +126 -0
  59. package/bin/lean/slo.test.mjs +112 -0
  60. package/bin/lean/statuscomment.mjs +37 -0
  61. package/bin/lean/statuscomment.test.mjs +48 -1
  62. package/bin/lean/verify.mjs +2 -1
  63. package/bin/pool/agent.mjs +46 -8
  64. package/bin/pool/cache-sweep.mjs +41 -4
  65. package/bin/pool/cli.mjs +28 -1
  66. package/bin/pool/health.mjs +18 -0
  67. package/bin/pool/lane-tools.mjs +21 -0
  68. package/bin/pool/mirror-seed.mjs +21 -2
  69. package/bin/pool/router.mjs +6 -2
  70. package/bin/stats/attempts.mjs +54 -0
  71. package/bin/stats/attempts.test.mjs +30 -0
  72. package/bin/stats/churn.mjs +49 -0
  73. package/bin/stats/churn.test.mjs +31 -0
  74. package/bin/stats/index.mjs +11 -3
  75. package/commands/orchestrate.md +21 -18
  76. package/docs/CONFIG.md +1 -0
  77. package/docs/OUTCOME-CODES.md +1 -0
  78. package/package.json +1 -1
  79. package/pool/image/entrypoint.sh +2 -1
  80. package/scripts/check-devdocs-freshness.sh +1 -1
@@ -0,0 +1,67 @@
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 * as fs from "node:fs";
6
+ import { join } from "node:path";
7
+ import { tmpDir } from "./tests/_tmp.mjs";
8
+ import { runIntrospect, installIntrospectSchedule, renderIntrospectCron, renderIntrospectSystemd, introspectUnitName } from "./introspect-schedule.mjs";
9
+
10
+ describe("#5987 introspect schedule", () => {
11
+ it("renders a daily systemd unit and a tagged cron line that run stats --file-issues", () => {
12
+ const s = renderIntrospectSystemd({ cwd: "/work/r", node: "/n", bin: "/b/forgedock.mjs" });
13
+ assert.match(s.service, /ExecStart="\/n" ".*introspect-schedule.mjs" --run/);
14
+ assert.match(s.timer, /OnCalendar=daily/);
15
+ assert.match(renderIntrospectCron({ cwd: "/work/r", node: "/n", bin: "/b/f.mjs" }), /^17 4 \* \* \* cd "\/work\/r" .*introspect-schedule.mjs" --run .*# forgedock-introspect \/work\/r$/);
16
+ });
17
+
18
+ it("systemd: installs once (rewrite, no duplicate), removes when disabled", async () => {
19
+ const home = tmpDir("isch-"), calls = [];
20
+ const exec = async (c, a) => { calls.push([c, ...a].join(" ")); return ""; };
21
+ const o = { cwd: "/work/r", home, platform: "linux", exec, node: "/n", bin: "/b" };
22
+ assert.equal((await installIntrospectSchedule(o)).status, "installed");
23
+ assert.equal((await installIntrospectSchedule(o)).status, "installed");
24
+ const name = introspectUnitName("/work/r"), dir = join(home, ".config", "systemd", "user");
25
+ assert.deepEqual(fs.readdirSync(dir).sort(), [`${name}.service`, `${name}.timer`]);
26
+ assert.equal((await installIntrospectSchedule({ ...o, enabled: false })).status, "removed");
27
+ assert.equal(fs.existsSync(join(dir, `${name}.timer`)), false);
28
+ assert.equal((await installIntrospectSchedule({ ...o, enabled: false })).status, "off");
29
+ });
30
+
31
+ it("cron fallback replaces only its own line and dedupes", async () => {
32
+ let tab = "0 1 * * * other\n17 4 * * * x # forgedock-introspect /work/r2\n";
33
+ const exec = async (c, a, input) => { if (c === "systemctl") throw new Error("no systemd"); if (a[0] === "-l") return tab; tab = input; return ""; };
34
+ const o = { cwd: "/work/r", platform: "linux", exec, node: "/n", bin: "/b" };
35
+ await installIntrospectSchedule(o); await installIntrospectSchedule(o);
36
+ const lines = tab.trim().split("\n");
37
+ assert.equal(lines.filter((l) => l.endsWith("# forgedock-introspect /work/r")).length, 1);
38
+ assert.equal(lines.length, 3, "other lines kept");
39
+ assert.equal((await installIntrospectSchedule({ ...o, enabled: false })).status, "removed");
40
+ assert.equal(tab.trim().split("\n").length, 2);
41
+ });
42
+
43
+ it("never throws", async () => {
44
+ const r = await installIntrospectSchedule({ cwd: "/w", platform: "darwin", exec: async () => { throw new Error("boom"); } });
45
+ assert.ok(["off", "failed", "removed"].includes(r.status) || r.status === "installed");
46
+ });
47
+
48
+ it("runIntrospect files the report once, dedupes an unchanged report, adopts an open issue, and honors file_issues: false", async () => {
49
+ const home = tmpDir("isch-run-"), cwd = tmpDir("isch-cwd-"), calls = [];
50
+ const gh = async (a) => { calls.push(a); return a[1] === "list" ? "[]" : a[1] === "create" ? "https://x/issues/9\n" : ""; };
51
+ const run = async () => "adequate 80%";
52
+ fs.writeFileSync(join(cwd, "forge.yaml"), "orchestrate:\n slo:\n file_issues: false\n");
53
+ assert.equal((await runIntrospect({ cwd, home, run, gh })).action, "disabled");
54
+ assert.equal(calls.length, 0);
55
+ fs.rmSync(join(cwd, "forge.yaml"));
56
+ assert.equal((await runIntrospect({ cwd, home, run, gh })).action, "disabled", "no forge.yaml: default does not file");
57
+ assert.equal(calls.length, 0);
58
+ fs.writeFileSync(join(cwd, "forge.yaml"), "orchestrate:\n slo:\n file_issues: true\n");
59
+ const a = await runIntrospect({ cwd, home, run, gh });
60
+ assert.equal(a.action, "create"); assert.equal(a.issue, 9);
61
+ assert.equal((await runIntrospect({ cwd, home, run, gh })).action, "unchanged", "prior report: nothing filed");
62
+ const c = await runIntrospect({ cwd, home, run: async () => "adequate 70%", gh });
63
+ assert.equal(c.action, "comment"); assert.equal(c.issue, 9);
64
+ assert.equal(calls.filter((x) => x[1] === "create").length, 1);
65
+ assert.doesNotMatch(calls.at(-1).at(-1), /report: |\.forge\/introspect|\/introspect\//, "no local path posted");
66
+ });
67
+ });
@@ -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
+ });