forgedock 1.56.0 → 1.58.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 (140) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +2 -1
  3. package/bin/engine/phases.mjs +4 -3
  4. package/bin/engine-cli.mjs +48 -12
  5. package/bin/forgedock.mjs +52 -3
  6. package/bin/gc.mjs +43 -6
  7. package/bin/help-text.mjs +4 -2
  8. package/bin/lean/batch-health.mjs +5 -1
  9. package/bin/lean/batch-health.test.mjs +7 -1
  10. package/bin/lean/batch.mjs +7 -2
  11. package/bin/lean/batch.test.mjs +45 -0
  12. package/bin/lean/conformance.e2e.test.mjs +3 -2
  13. package/bin/lean/conformance.mjs +118 -20
  14. package/bin/lean/conformance.test.mjs +172 -3
  15. package/bin/lean/decisions.mjs +98 -1
  16. package/bin/lean/decisions.test.mjs +30 -1
  17. package/bin/lean/depcache.mjs +124 -13
  18. package/bin/lean/depcache.test.mjs +121 -3
  19. package/bin/lean/design-gate.mjs +144 -0
  20. package/bin/lean/design-gate.test.mjs +169 -0
  21. package/bin/lean/effects-cap.test.mjs +17 -0
  22. package/bin/lean/effects.mjs +58 -13
  23. package/bin/lean/heavy.mjs +25 -8
  24. package/bin/lean/hostload.test.mjs +28 -0
  25. package/bin/lean/intake.mjs +97 -0
  26. package/bin/lean/intake.test.mjs +105 -0
  27. package/bin/lean/interfaces.mjs +181 -0
  28. package/bin/lean/interfaces.test.mjs +192 -0
  29. package/bin/lean/issuewatch-install.mjs +52 -12
  30. package/bin/lean/issuewatch-install.test.mjs +50 -0
  31. package/bin/lean/issuewatch-parity.mjs +16 -3
  32. package/bin/lean/issuewatch-parity.test.mjs +32 -0
  33. package/bin/lean/issuewatch-reconcile.mjs +29 -1
  34. package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
  35. package/bin/lean/issuewatch.mjs +34 -3
  36. package/bin/lean/issuewatch.test.mjs +49 -1
  37. package/bin/lean/lanecheck.test.mjs +15 -4
  38. package/bin/lean/lean.mjs +110 -24
  39. package/bin/lean/lean.test.mjs +183 -4
  40. package/bin/lean/orchestrate-blocked.test.mjs +18 -2
  41. package/bin/lean/orchestrate-owned.test.mjs +14 -5
  42. package/bin/lean/orchestrate.mjs +26 -4
  43. package/bin/lean/orphan-pr.mjs +3 -2
  44. package/bin/lean/orphan-pr.test.mjs +8 -1
  45. package/bin/lean/pagegate.mjs +35 -12
  46. package/bin/lean/pagegate.test.mjs +39 -1
  47. package/bin/lean/preflight.mjs +35 -1
  48. package/bin/lean/preflight.test.mjs +27 -1
  49. package/bin/lean/prompts.mjs +2 -1
  50. package/bin/lean/reap.test.mjs +39 -0
  51. package/bin/lean/recovery.test.mjs +28 -3
  52. package/bin/lean/release-config.mjs +169 -0
  53. package/bin/lean/release-config.test.mjs +132 -0
  54. package/bin/lean/release-control.mjs +171 -0
  55. package/bin/lean/release-control.test.mjs +167 -0
  56. package/bin/lean/release-deploy.mjs +209 -0
  57. package/bin/lean/release-deploy.test.mjs +217 -0
  58. package/bin/lean/release-fence.mjs +50 -0
  59. package/bin/lean/release-fence.test.mjs +105 -0
  60. package/bin/lean/release-flakes.mjs +139 -0
  61. package/bin/lean/release-flakes.test.mjs +116 -0
  62. package/bin/lean/release-gates.mjs +230 -0
  63. package/bin/lean/release-gates.test.mjs +146 -0
  64. package/bin/lean/release-ledger.mjs +176 -0
  65. package/bin/lean/release-ledger.test.mjs +226 -0
  66. package/bin/lean/release-minutes.mjs +102 -0
  67. package/bin/lean/release-minutes.test.mjs +107 -0
  68. package/bin/lean/release-nightly.mjs +75 -0
  69. package/bin/lean/release-nightly.test.mjs +48 -0
  70. package/bin/lean/release-postmerge.mjs +8 -2
  71. package/bin/lean/release-review.e2e.test.mjs +1 -0
  72. package/bin/lean/release-review.mjs +54 -7
  73. package/bin/lean/release-review.test.mjs +76 -7
  74. package/bin/lean/release-status.mjs +300 -0
  75. package/bin/lean/release-status.test.mjs +220 -0
  76. package/bin/lean/release-unitmap.mjs +35 -0
  77. package/bin/lean/release-unitmap.test.mjs +41 -0
  78. package/bin/lean/release-verify.mjs +221 -0
  79. package/bin/lean/release-verify.test.mjs +176 -0
  80. package/bin/lean/release.mjs +244 -22
  81. package/bin/lean/release.test.mjs +44 -0
  82. package/bin/lean/render.mjs +3 -1
  83. package/bin/lean/run-issue-placement.test.mjs +82 -0
  84. package/bin/lean/sandbox-remote.mjs +16 -0
  85. package/bin/lean/schedd.mjs +1 -1
  86. package/bin/lean/seam.mjs +115 -0
  87. package/bin/lean/seam.test.mjs +118 -0
  88. package/bin/lean/selftest-journey.mjs +40 -2
  89. package/bin/lean/selftest-journey.test.mjs +43 -3
  90. package/bin/lean/statuscomment.mjs +168 -0
  91. package/bin/lean/statuscomment.test.mjs +133 -0
  92. package/bin/lean/ui-quality.mjs +57 -0
  93. package/bin/lean/ui-quality.test.mjs +55 -0
  94. package/bin/lean/visual-gate.test.mjs +63 -0
  95. package/bin/pool/agent.mjs +16 -2
  96. package/bin/pool/router.mjs +5 -1
  97. package/bin/review-staging.mjs +5 -3
  98. package/bin/stats/card.mjs +117 -0
  99. package/bin/stats/card.test.mjs +109 -0
  100. package/bin/stats/conformance-outcomes.test.mjs +2 -1
  101. package/bin/stats/depth.mjs +1 -1
  102. package/bin/stats/gh-retry.test.mjs +152 -0
  103. package/bin/stats/github-source.mjs +147 -14
  104. package/bin/stats/index.mjs +35 -2
  105. package/bin/stats/stats.test.mjs +31 -3
  106. package/bin/vendor/js-yaml/LICENSE +21 -0
  107. package/bin/vendor/js-yaml/PIN.md +7 -0
  108. package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
  109. package/commands/design-render-critique-loop.md +2 -0
  110. package/commands/design.md +2 -0
  111. package/commands/issue.md +1 -1
  112. package/commands/milestone.md +1 -1
  113. package/commands/review-pr-agents/frontend.md +1 -0
  114. package/commands/review-pr-staging.md +5 -0
  115. package/docs/CONFIG.md +95 -2
  116. package/docs/ISSUE-WATCH.md +7 -0
  117. package/docs/OUTCOME-CODES.md +1 -0
  118. package/docs/STATS.md +10 -0
  119. package/docs/design/visual-gate.md +25 -0
  120. package/docs/eval/adversarial-bench.md +2 -2
  121. package/docs/eval/corpus/adversarial-v1.json +3 -3
  122. package/docs/site/start-a-new-project.md +7 -0
  123. package/docs/spec/forge-protocol-v1.md +31 -0
  124. package/package.json +1 -1
  125. package/pool/README.md +2 -0
  126. package/scripts/acceptance-red-green.sh +15 -1
  127. package/scripts/acceptance-red-green.test.sh +12 -0
  128. package/scripts/bench-adversarial.mjs +4 -0
  129. package/scripts/bench-lightlane.mjs +4 -1
  130. package/scripts/bootstrap-create.mjs +8 -2
  131. package/scripts/ci-local/scoping.mjs +19 -0
  132. package/scripts/ci-local.test.sh +16 -3
  133. package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
  134. package/scripts/plan-validate-live.mjs +9 -6
  135. package/scripts/review-prepare.sh +7 -1
  136. package/scripts/review-roster.sh +5 -2
  137. package/scripts/review-roster.test.sh +9 -0
  138. package/scripts/visual-gate.mjs +64 -0
  139. package/templates/bootstrap/technical-spike.md +17 -0
  140. package/templates/contracts/seam-check.mjs +236 -0
@@ -0,0 +1,97 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Intake pause read from GitHub truth (#5555, epic #5549 Phase 0, invariant I18). `forgedock intake pause|resume|status`
5
+ * writes `_active.intake` on the ledger control branch (audit line in controls.jsonl) and the `forge:intake-paused` label on
6
+ * the tracker issue; the issue watch reads `_active`, the active ledger entry and the open `release/*|train/*|hotfix/*` PR
7
+ * heads, so every host honours the pause with no local state. Only used when forge.yaml `release.managed` is on.
8
+ */
9
+ import { updateActive, ACTIVE, LEDGER_PREFIX } from "./release-ledger.mjs";
10
+
11
+ export const INTAKE_LABEL = "forge:intake-paused";
12
+ export const RELEASE_HEAD_RE = /^(release|train|hotfix)\//;
13
+ const isMissing = (e) => e?.status === 404 || /HTTP 404|Not Found/i.test(String(e?.message ?? e));
14
+
15
+ /** `get(path)→parsed JSON` that returns null on a 404; `gh` is a runner `(args)→string`. */
16
+ export const ghGet = (gh) => async (path) => {
17
+ try { return JSON.parse(String(await gh(["api", path])) || "null"); } catch (e) { if (isMissing(e) || /HTTP 404|Not Found/i.test(String(e?.stderr ?? ""))) return null; throw e; }
18
+ };
19
+
20
+ async function readJsonFile(get, repo, branch, file) {
21
+ const r = await get(`repos/${repo}/contents/${file}?ref=${encodeURIComponent(branch)}`);
22
+ if (!r) return null;
23
+ try { return JSON.parse(Buffer.from(r.content ?? "", "base64").toString("utf8")); } catch { return null; }
24
+ }
25
+ /** `_active.active.json` or `{}` when the control branch does not exist. */
26
+ export const readActive = async (get, repo) => (await readJsonFile(get, repo, ACTIVE, "active.json")) ?? {};
27
+
28
+ /**
29
+ * Why claims must stop, from GitHub only: `{paused: false}` or `{paused: true, reason, source, resume?}`. Checks, in order,
30
+ * `_active.intake.paused`, an active ledger entry (the lease's release has a ledger without an end `status`) and an open PR
31
+ * whose head is `release/*|train/*|hotfix/*`. `resume` is set when the pause names a release whose ledger has ended and
32
+ * `autoResume` (freeze.intake_auto_resume) is on: the caller clears the pause (WAVE_DONE).
33
+ */
34
+ export async function githubPause({ get, repo, autoResume = false }) {
35
+ const active = await readActive(get, repo);
36
+ const ended = async (id) => { const st = await readJsonFile(get, repo, `${LEDGER_PREFIX}${id}`, "state.json"); return st ? !!st.status : null; };
37
+ const relId = active.lease?.release;
38
+ const live = relId ? (await ended(relId)) !== true : false;
39
+ if (active.intake?.paused) {
40
+ const rel = active.intake.release;
41
+ const done = autoResume && rel ? (await ended(rel)) === true : false;
42
+ if (!done) return { paused: true, source: "intake", reason: `intake paused${active.intake.reason ? `: ${active.intake.reason}` : ""}${active.intake.by ? ` (by ${active.intake.by})` : ""}` };
43
+ if (!live) return { paused: false, resume: true, reason: `release ${rel} ended` };
44
+ }
45
+ if (live) return { paused: true, source: "ledger", reason: `release ${relId} active in the ledger` };
46
+ const prs = (await get(`repos/${repo}/pulls?state=open&per_page=100`)) ?? [];
47
+ const pr = prs.find((p) => RELEASE_HEAD_RE.test(String(p?.head?.ref ?? "")));
48
+ if (pr) return { paused: true, source: "pr", reason: `open release PR #${pr.number} (${pr.head.ref})` };
49
+ return { paused: false };
50
+ }
51
+
52
+ /** Pause or resume intake: key-scoped `_active.intake` write with an audit entry, then the tracker label. */
53
+ export async function setIntake({ io, repo, paused, reason = null, by = null, tracker = null, release = null, now = Date.now() }) {
54
+ const at = new Date(now).toISOString();
55
+ const r = await updateActive({ io, repo, credential: "driver" }, ["intake"], () => ({
56
+ patch: { intake: paused ? { paused: true, reason, by, at, ...(release ? { release } : {}) } : { paused: false, by, at } },
57
+ control: { at, verb: paused ? "intake-pause" : "intake-resume", by, ...(reason ? { reason } : {}), ...(release ? { release } : {}) },
58
+ }));
59
+ if (!r.ok) return r;
60
+ let label = null;
61
+ if (tracker) {
62
+ try {
63
+ if (paused) await io.api("POST", `repos/${repo}/issues/${tracker}/labels`, { labels: [INTAKE_LABEL] });
64
+ else await io.api("DELETE", `repos/${repo}/issues/${tracker}/labels/${encodeURIComponent(INTAKE_LABEL)}`);
65
+ label = true;
66
+ } catch (e) { if (!(!paused && isMissing(e))) label = String(e?.message ?? e); }
67
+ }
68
+ return { ...r, label };
69
+ }
70
+
71
+ const flag = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
72
+ const USAGE = "usage: forgedock intake pause|resume|status [--reason <text>] [--tracker <issue>] [--release <id>] [--repo owner/repo]";
73
+
74
+ /** `forgedock intake pause|resume|status`. */
75
+ export async function intakeFromCli(argv, deps = {}) {
76
+ const [op] = argv;
77
+ if (!["pause", "resume", "status"].includes(op)) throw new Error(USAGE);
78
+ const { readFileSync } = await import("node:fs"), { join } = await import("node:path");
79
+ const { readReleaseConfig, realReleaseIo } = await import("./release.mjs");
80
+ const cwd = deps.cwd ?? process.cwd(), print = deps.print ?? ((l) => console.log(l));
81
+ const io = deps.io ?? realReleaseIo({ env: deps.env ?? process.env, cwd });
82
+ let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* defaults */ }
83
+ const config = readReleaseConfig(raw);
84
+ const repo = flag(argv, "--repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
85
+ const tracker = Number(String(flag(argv, "--tracker") ?? config.tracker ?? "").replace("#", "")) || null;
86
+ const get = async (path) => { try { return await io.api("GET", path); } catch (e) { if (isMissing(e)) return null; throw e; } };
87
+ if (op === "status") {
88
+ const a = (await readActive(get, repo)).intake, g = await githubPause({ get, repo, autoResume: config.intakeAutoResume });
89
+ print(`intake: ${g.paused ? "PAUSED" : "running"}${g.reason ? ` (${g.reason})` : ""}${a?.at ? ` last change ${a.at}` : ""}`);
90
+ return { ok: true, ...g };
91
+ }
92
+ const by = deps.by ?? (await io.gh(["api", "user", "-q", ".login"]).then((s) => String(s).trim()).catch(() => null));
93
+ const r = await setIntake({ io, repo, paused: op === "pause", reason: flag(argv, "--reason"), by, tracker, release: flag(argv, "--release"), now: io.now?.() ?? Date.now() });
94
+ if (!r.ok) throw new Error(`intake ${op} failed: ${r.refused ?? "lost the _active race"}`);
95
+ print(`intake ${op === "pause" ? "paused" : "resumed"}${tracker ? ` (label ${INTAKE_LABEL} on #${tracker}${typeof r.label === "string" ? `: ${r.label}` : ""})` : ""}`);
96
+ return { ok: true };
97
+ }
@@ -0,0 +1,105 @@
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 { tmpDir } from "../tests/_tmp.mjs";
6
+ import { githubPause, setIntake, readActive, intakeFromCli, INTAKE_LABEL } from "./intake.mjs";
7
+
8
+ const REPO = "o/r";
9
+ const err = (status) => Object.assign(new Error(`HTTP ${status}`), { status });
10
+
11
+ /** In-memory GitHub shared by every "host": _active branch files, ledger states, open PRs, issue labels. */
12
+ function fakeGh({ prs = [], ledgers = {} } = {}) {
13
+ const g = { files: {}, head: null, prs, ledgers, labels: new Set(), calls: [], n: 0, commits: {} };
14
+ const b64 = (t) => ({ content: Buffer.from(t).toString("base64") });
15
+ g.api = async (method, path, body) => {
16
+ g.calls.push(`${method} ${path}`);
17
+ let m;
18
+ if ((m = /git\/ref\/heads\/(.+)$/.exec(path))) { if (m[1] !== "_active" || !g.head) throw err(404); return { object: { sha: g.head } }; }
19
+ if ((m = /git\/commits\/(\w+)$/.exec(path))) return { tree: { sha: g.commits[m[1]] } };
20
+ if (method === "POST" && /git\/trees$/.test(path)) { const files = { ...(g.commits.__files ?? {}) }; for (const e of body.tree) files[e.path] = e.content; g.commits.__files = files; return { sha: `t${++g.n}` }; }
21
+ if (method === "POST" && /git\/commits$/.test(path)) { const sha = `c${++g.n}`; g.commits[sha] = body.tree; return { sha }; }
22
+ if (method === "POST" && /git\/refs$/.test(path)) { g.head = body.sha; g.files = { ...g.commits.__files }; return {}; }
23
+ if (method === "PATCH" && /git\/refs\//.test(path)) { g.head = body.sha; g.files = { ...g.commits.__files }; return {}; }
24
+ if ((m = /contents\/([^?]+)\?ref=(.+)$/.exec(path))) {
25
+ const br = decodeURIComponent(m[2]);
26
+ if (br === "_active") { if (g.files[m[1]] === undefined) throw err(404); return b64(g.files[m[1]]); }
27
+ const st = g.ledgers[br.replace("forge-ledger/", "")]; if (!st) throw err(404); return b64(JSON.stringify(st));
28
+ }
29
+ if (/pulls\?state=open/.test(path)) return g.prs;
30
+ if (method === "POST" && /issues\/\d+\/labels$/.test(path)) { body.labels.forEach((l) => g.labels.add(l)); return []; }
31
+ if (method === "DELETE" && /issues\/\d+\/labels\//.test(path)) { g.labels.delete(decodeURIComponent(path.split("/labels/")[1])); return []; }
32
+ throw new Error(`unrouted ${method} ${path}`);
33
+ };
34
+ g.get = async (p) => { try { return await g.api("GET", p); } catch (e) { if (e.status === 404) return null; throw e; } };
35
+ return g;
36
+ }
37
+
38
+ describe("intake pause from GitHub (#5555)", () => {
39
+ it("the 2026-11-12 case: an open release/* PR pauses with no local state or _active", async () => {
40
+ const g = fakeGh({ prs: [{ number: 9, head: { ref: "release/20261112-1" } }] });
41
+ const r = await githubPause({ get: g.get, repo: REPO });
42
+ assert.equal(r.paused, true); assert.equal(r.source, "pr"); assert.match(r.reason, /#9/);
43
+ });
44
+ it("train/*, hotfix/* heads pause; feature heads do not", async () => {
45
+ for (const ref of ["train/a", "hotfix/b"]) assert.equal((await githubPause({ get: fakeGh({ prs: [{ number: 1, head: { ref } }] }).get, repo: REPO })).paused, true);
46
+ assert.equal((await githubPause({ get: fakeGh({ prs: [{ number: 1, head: { ref: "feat/x" } }] }).get, repo: REPO })).paused, false);
47
+ });
48
+ it("intake pause on host A is honoured by host B, writes the label and an audit line; resume reverses", async () => {
49
+ const g = fakeGh();
50
+ const r = await setIntake({ io: { api: g.api }, repo: REPO, paused: true, reason: "freeze", by: "op", tracker: 7, now: 1_000 });
51
+ assert.ok(r.ok); assert.ok(g.labels.has(INTAKE_LABEL));
52
+ assert.equal((await readActive(g.get, REPO)).intake.paused, true);
53
+ assert.match(g.files["controls.jsonl"], /"verb":"intake-pause"/);
54
+ const hostB = await githubPause({ get: g.get, repo: REPO });
55
+ assert.equal(hostB.paused, true); assert.match(hostB.reason, /freeze/);
56
+ await setIntake({ io: { api: g.api }, repo: REPO, paused: false, by: "op", tracker: 7, now: 2_000 });
57
+ assert.equal(g.labels.has(INTAKE_LABEL), false);
58
+ assert.equal((await githubPause({ get: g.get, repo: REPO })).paused, false);
59
+ assert.equal(g.files["controls.jsonl"].trim().split("\n").length, 2);
60
+ });
61
+ it("an active ledger entry pauses; an ended one does not", async () => {
62
+ const g = fakeGh({ ledgers: { "r20261112-101500-1": { status: undefined } } });
63
+ g.files["active.json"] = JSON.stringify({ lease: { holder: "h", release: "r20261112-101500-1" } }); g.head = "x";
64
+ assert.equal((await githubPause({ get: g.get, repo: REPO })).source, "ledger");
65
+ g.ledgers["r20261112-101500-1"] = { status: "done" };
66
+ assert.equal((await githubPause({ get: g.get, repo: REPO })).paused, false);
67
+ });
68
+ it("auto-resume: a pause naming an ended release resumes only when enabled", async () => {
69
+ const g = fakeGh({ ledgers: { "r1": { status: "done" } } });
70
+ await setIntake({ io: { api: g.api }, repo: REPO, paused: true, release: "r1", now: 1 });
71
+ assert.equal((await githubPause({ get: g.get, repo: REPO })).paused, true);
72
+ const r = await githubPause({ get: g.get, repo: REPO, autoResume: true });
73
+ assert.equal(r.paused, false); assert.equal(r.resume, true);
74
+ });
75
+ it("CLI pause writes through io.api and status reports it", async () => {
76
+ const g = fakeGh(), out = [];
77
+ const io = { api: g.api, gh: async () => JSON.stringify({}), now: () => 5 };
78
+ await intakeFromCli(["pause", "--repo", REPO, "--reason", "why", "--tracker", "3"], { io, by: "me", print: (l) => out.push(l), cwd: "/nonexistent" });
79
+ const s = await intakeFromCli(["status", "--repo", REPO], { io, print: (l) => out.push(l), cwd: "/nonexistent" });
80
+ assert.equal(s.paused, true); assert.match(out.join("\n"), /PAUSED/);
81
+ await assert.rejects(intakeFromCli(["bogus"], { io }), /usage/);
82
+ });
83
+ });
84
+
85
+ describe("issue-watch pass reads GitHub intake (#5555)", () => {
86
+ const run = async (yaml, g) => {
87
+ const { writeFileSync } = await import("node:fs"), { join } = await import("node:path");
88
+ const { runWatch, validateWatch } = await import("./issuewatch.mjs");
89
+ const cwd = tmpDir("intake-"), dir = tmpDir("intake-w-");
90
+ writeFileSync(join(cwd, "forge.yaml"), yaml);
91
+ const gh = async (a) => { g.calls.push(`gh ${a.join(" ")}`); if (a[0] === "api") return JSON.stringify(await g.get(a[1])); throw new Error(`unexpected gh ${a.join(" ")}`); };
92
+ const io = { env: { FORGEDOCK_WATCH_DIR: dir, PATH: "" }, gh, now: () => 1_000, sleep: async () => {}, releaseInFlight: () => null };
93
+ return runWatch({ watch: validateWatch("w", { mode: "batch" }), repo: REPO, io, dir, branches: {}, defaults: [], once: true, cwd });
94
+ };
95
+ it("managed: an open release PR pauses the pass within one poll and nothing is claimed", async () => {
96
+ const g = fakeGh({ prs: [{ number: 9, head: { ref: "release/20261112-1" } }] });
97
+ const state = await run("release:\n managed: true\n", g);
98
+ assert.match(state.paused.reason, /release PR #9/); assert.equal(state.claimed.length, 0);
99
+ });
100
+ it("unmanaged (defaults): no GitHub call is made for the pause", async () => {
101
+ const g = fakeGh({ prs: [{ number: 9, head: { ref: "release/x" } }] });
102
+ await run("project: x\n", g).catch(() => {});
103
+ assert.equal(g.calls.filter((c) => /pulls|contents|git\/ref/.test(c)).length, 0);
104
+ });
105
+ });
@@ -0,0 +1,181 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5338: architecture and interface contracts bound into the decision register. One module for the four engine seams:
5
+ * - validation: a spike or feature epic with two or more slices needs an `## Interfaces` section (rationale line plus at
6
+ * least one boundary row with anchors); `checkInterfaces` is the pure check, `forgedock interfaces check` the gate
7
+ * (`/milestone` and `/issue` run it before creating an epic, `bootstrap-create` before creating a backlog);
8
+ * - registration: `seedDecisions` writes each Interfaces row and each anchored architecture choice into the register
9
+ * (FORGE:DECISION comment on the spike/epic issue + the local index), once per id; the lane contract then carries
10
+ * them as preserve rows (decisions.mjs withDecisionRows) and conformance fails a change under their anchors that
11
+ * neither reports the row intact nor supersedes it (conformance.mjs interfaceDecisionFailures);
12
+ * - contract tests: `writeContracts` generates one seam contract test per row with a machine form (seam.mjs);
13
+ * - consumers: `consumerNotices` / `notifyConsumers` reopen (or notify) the consumer issues, or file one issue per
14
+ * named consumer, when a lane's `supersedes` decision lands.
15
+ * Pure except the injected gh/fs; no LLM.
16
+ */
17
+ import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
18
+ import { dirname, join } from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+ import { interfaceDecisions, interfaceRows, parseDecisionComment, renderDecision, readDecisionIndex, writeDecisionIndex } from "./decisions.mjs";
21
+ import { renderSeamTest } from "./seam.mjs";
22
+
23
+ export const INTERFACES_SECTION = "Interfaces";
24
+ export const INTERFACE_CHANGED_MARKER = "FORGE:INTERFACE_CHANGED";
25
+ const SEAM_CHECK = fileURLToPath(new URL("../../templates/contracts/seam-check.mjs", import.meta.url));
26
+
27
+ const h2 = (text) => {
28
+ const secs = [];
29
+ let fence = null;
30
+ for (const line of String(text ?? "").replace(/\r\n/g, "\n").split("\n")) {
31
+ const f = /^[ \t]*(`{3,}|~{3,})/.exec(line);
32
+ if (f) { fence = fence ? (f[1][0] === fence ? null : fence) : f[1][0]; if (secs.length) secs.at(-1).lines.push(line); continue; }
33
+ const h = fence ? null : /^##(?!#)[ \t]+(.+?)[ \t]*$/.exec(line);
34
+ if (h) secs.push({ heading: h[1], lines: [] }); else if (secs.length) secs.at(-1).lines.push(line);
35
+ }
36
+ return secs;
37
+ };
38
+
39
+ const SLICE_HEADING = /^(slices?|children|sub-?issues|waves?|work items|issues|milestone plan|plan)\b/i;
40
+ const LIST_ITEM = /^\s*(?:[-*+]\s+(?:\[[ xX]\]\s+)?|\d+[.)]\s+)\S/;
41
+
42
+ /** Slices of a spike (numbered items of its Milestone plan) or of an epic (list items of its Slices/Children/... section). */
43
+ export function sliceCount(text, kind = "auto") {
44
+ const secs = h2(text), plan = secs.find((x) => /^milestone plan/i.test(x.heading));
45
+ if (kind === "spike" || (kind === "auto" && plan)) return (plan?.lines.join("\n").match(/(?:^|\s)\d+\.\s/g) ?? []).length;
46
+ const listed = secs.filter((x) => SLICE_HEADING.test(x.heading)).flatMap((x) => x.lines.filter((l) => LIST_ITEM.test(l)));
47
+ if (listed.length) return listed.length;
48
+ return String(text ?? "").split("\n").filter((l) => /^\s*[-*]\s+\[[ xX]\]\s+#\d+/.test(l)).length;
49
+ }
50
+
51
+ /**
52
+ * Pure check of the Interfaces section. `required` once the body has two or more slices; then the section, its
53
+ * `**Rationale**:` line are needed, and for an epic (the spike template ships a placeholder row) at least one boundary row
54
+ * with anchors. `kind` is "spike", "epic" or "auto" (a body with a Milestone plan section is a spike).
55
+ * Also lists rows whose signature has a machine form but whose Anchors cell declares no provider/consumer sides
56
+ * (`unchecked`: no contract test can be generated for them).
57
+ */
58
+ export function checkInterfaces(text, { kind = "auto" } = {}) {
59
+ const slices = sliceCount(text, kind), required = slices >= 2;
60
+ const spike = kind === "spike" || (kind === "auto" && h2(text).some((x) => /^milestone plan/i.test(x.heading)));
61
+ const sec = h2(text).find((x) => x.heading.toLowerCase().startsWith(INTERFACES_SECTION.toLowerCase()));
62
+ const rows = interfaceRows(text);
63
+ const problems = [];
64
+ if (required && !sec) problems.push(`no \`## ${INTERFACES_SECTION}\` section: ${slices} slices need one row per boundary (signature or schema, auth mode, owner issue, anchors)`);
65
+ else if (required && !sec.lines.some((l) => /\*\*Rationale\*\*:/.test(l))) problems.push(`\`## ${INTERFACES_SECTION}\` has no **Rationale**: line`);
66
+ else if (required && !spike && !rows.length) problems.push(`\`## ${INTERFACES_SECTION}\` has no boundary row with an anchor (a row of the template's {placeholders} does not count)`);
67
+ const unchecked = rows.filter((r) => !r.seam && /^(?:(?:GET|POST|PUT|PATCH|DELETE)\s+\/|[\w.$]+\s*\(|(?:queue|topic|message|payload|event)\s|\{)/i.test(String(r.signature).replace(/`/g, "").trim())).map((r) => r.boundary);
68
+ return { ok: problems.length === 0, required, slices, hasSection: Boolean(sec), rows: rows.length, problems, unchecked };
69
+ }
70
+
71
+ /** The records of `text` not yet posted on the issue (`comments` are its comment bodies): once per id. */
72
+ export function freshDecisions({ text, issue, comments = [] }) {
73
+ const posted = new Set(comments.map((b) => parseDecisionComment(b, { issue })?.id).filter(Boolean));
74
+ return interfaceDecisions(text, { issue }).filter((d) => !posted.has(d.id));
75
+ }
76
+
77
+ /** The comment body (marker line first) that registers one record. */
78
+ export const decisionComment = (rec) => { const m = renderDecision(rec); return `<!-- ${m.marker} -->\n${m.body}`; };
79
+
80
+ /** Synchronous registration (bootstrap-create): posts each fresh record via `post(body)`, then updates the index. Returns the records posted. */
81
+ export function seedDecisions({ text, issue, repo, comments = [], post, index = { read: readDecisionIndex, write: writeDecisionIndex } }) {
82
+ const fresh = freshDecisions({ text, issue, comments });
83
+ for (const d of fresh) post(decisionComment(d));
84
+ if (fresh.length) index.write(repo, [...index.read(repo), ...fresh]);
85
+ return fresh;
86
+ }
87
+
88
+ /** Writes `<outDir>/<id>.contract.test.mjs` for every row with a machine form, plus seam-check.mjs. Returns {written, skipped}. */
89
+ export function writeContracts({ text, issue, outDir, fs = { mkdirSync, writeFileSync, copyFileSync } }) {
90
+ const recs = interfaceDecisions(text, { issue }), written = [];
91
+ const wanted = recs.filter((r) => r.seam);
92
+ if (wanted.length) {
93
+ fs.mkdirSync(outDir, { recursive: true });
94
+ fs.copyFileSync(SEAM_CHECK, join(outDir, "seam-check.mjs"));
95
+ for (const r of wanted) {
96
+ const file = join(outDir, `${r.id}.contract.test.mjs`);
97
+ fs.writeFileSync(file, renderSeamTest({ v: 1, id: r.id, kind: r.seam.kind, boundary: r.choice.slice(0, 160), auth: r.seam.auth, [r.seam.kind]: r.seam[r.seam.kind], provider: r.seam.provider, consumer: r.seam.consumer }));
98
+ written.push(file);
99
+ }
100
+ }
101
+ return { written, skipped: recs.filter((r) => !r.seam).map((r) => r.id) };
102
+ }
103
+
104
+ const slug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "consumer";
105
+ const REF = /^#?(\d+)$/;
106
+
107
+ /** What a landed `supersedes` decision owes its consumers: [{consumer, issue|null, key}] (`#N` reopens/notifies, a name files an issue). */
108
+ export function consumerNotices(rec) {
109
+ if (!rec?.supersedes || !rec.consumers?.length) return [];
110
+ return rec.consumers.map((c) => { const m = REF.exec(String(c).trim()); return m ? { consumer: `#${m[1]}`, issue: Number(m[1]), key: `${rec.id}:${m[1]}` } : { consumer: String(c), issue: null, key: `${rec.id}:${slug(c)}` }; });
111
+ }
112
+
113
+ const noticeBody = (rec, n, { pr, tag }) => `<!-- ${INTERFACE_CHANGED_MARKER} decision=${rec.id} consumer=${tag} -->\n## Interface changed: ${rec.choice}\n\nDecision \`${rec.id}\` supersedes \`${rec.supersedes}\`${pr ? ` (PR #${pr})` : ""}${rec.issue ? `, recorded on #${rec.issue}` : ""}. ${n.consumer} builds against this interface: re-check it against the new contract${rec.why ? ` (${rec.why})` : ""}.\n\nGoverns: ${(rec.anchors ?? []).map((a) => `\`${a}\``).join(", ")}`;
114
+
115
+ /**
116
+ * Tells the consumers of a superseded interface. `gh(args)` runs gh and resolves stdout. A `#N` consumer that is closed is
117
+ * reopened (best-effort `workflow:merged` removal so it is picked up as work, not as a merge to verify) and every `#N`
118
+ * consumer gets one FORGE:INTERFACE_CHANGED comment; a named consumer gets one new issue. Idempotent: an existing
119
+ * comment/issue carrying the same decision+consumer marker is reused. Returns [{consumer, action, issue?}]; a failed
120
+ * consumer is {action:"failed", error} and never throws.
121
+ */
122
+ export async function notifyConsumers({ rec, pr = null, repo, gh }) {
123
+ const out = [];
124
+ for (const n of consumerNotices(rec)) {
125
+ const tag = n.issue ? `#${n.issue}` : slug(n.consumer), marker = `${INTERFACE_CHANGED_MARKER} decision=${rec.id} consumer=${tag}`;
126
+ try {
127
+ if (n.issue) {
128
+ const v = JSON.parse(String(await gh(["issue", "view", String(n.issue), "-R", repo, "--json", "state,comments"])) || "{}");
129
+ if (String(v.state).toUpperCase() === "CLOSED") {
130
+ await gh(["issue", "reopen", String(n.issue), "-R", repo]);
131
+ try { await gh(["issue", "edit", String(n.issue), "-R", repo, "--remove-label", "workflow:merged"]); } catch { /* the label may not exist */ }
132
+ out.push({ consumer: n.consumer, action: "reopened", issue: n.issue });
133
+ } else out.push({ consumer: n.consumer, action: "notified", issue: n.issue });
134
+ if (!(v.comments ?? []).some((c) => String(c?.body ?? "").includes(marker))) await gh(["issue", "comment", String(n.issue), "-R", repo, "--body", noticeBody(rec, n, { pr, tag })]);
135
+ continue;
136
+ }
137
+ const found = JSON.parse(String(await gh(["issue", "list", "-R", repo, "--state", "all", "--search", `"${marker}" in:body`, "--json", "number", "--limit", "5"])) || "[]");
138
+ if (found.length) { out.push({ consumer: n.consumer, action: "exists", issue: found[0].number }); continue; }
139
+ const url = String(await gh(["issue", "create", "-R", repo, "--title", `Adapt ${n.consumer} to interface change ${rec.id}`.slice(0, 120), "--body", noticeBody(rec, n, { pr, tag })])).trim();
140
+ out.push({ consumer: n.consumer, action: "filed", issue: Number(/\/issues\/(\d+)/.exec(url)?.[1]) || null });
141
+ } catch (e) { out.push({ consumer: n.consumer, action: "failed", error: String(e?.message ?? e).slice(0, 160) }); }
142
+ }
143
+ return out;
144
+ }
145
+
146
+ /** `forgedock interfaces check|register|contract`. Resolves the exit code (1: invalid). */
147
+ export async function interfacesFromCli(argv, deps = {}) {
148
+ const val = (n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : null; };
149
+ const print = deps.print ?? ((t) => console.log(t));
150
+ const usage = "usage: forgedock interfaces check --body-file F [--kind spike|epic] | register --issue N --body-file F [--repo o/r] | contract --issue N --body-file F [--out contracts]";
151
+ const sub = argv[0], file = val("--body-file");
152
+ if (!["check", "register", "contract"].includes(sub) || !file) throw new Error(usage);
153
+ const text = deps.readFile ? deps.readFile(file) : readFileSync(file, "utf8");
154
+ if (sub === "check") {
155
+ const kind = val("--kind") ?? "auto";
156
+ if (!["auto", "spike", "epic"].includes(kind)) throw new Error(usage);
157
+ const r = checkInterfaces(text, { kind });
158
+ for (const p of r.problems) print(`interfaces: ${p}`);
159
+ for (const u of r.unchecked) print(`interfaces: note: "${u}" has a machine-form signature but no provider:/consumer: anchors, so no contract test is generated`);
160
+ if (r.ok) print(`interfaces: ok (${r.slices} slice(s), ${r.rows} boundary row(s))`);
161
+ return r.ok ? 0 : 1;
162
+ }
163
+ const issue = Number(val("--issue"));
164
+ if (!Number.isSafeInteger(issue) || issue < 1) throw new Error(usage);
165
+ if (sub === "contract") {
166
+ const r = writeContracts({ text, issue, outDir: val("--out") ?? "contracts", ...(deps.fs ? { fs: deps.fs } : {}) });
167
+ for (const f of r.written) print(`interfaces: wrote ${f}`);
168
+ if (!r.written.length) print("interfaces: no row has a machine-form signature with provider: and consumer: anchors; nothing generated");
169
+ return 0;
170
+ }
171
+ const repo = val("--repo") ?? deps.repo;
172
+ if (!repo) throw new Error("interfaces register needs the repo: pass --repo owner/repo");
173
+ const gh = deps.gh ?? (async (args, input) => (await import("node:child_process")).execFileSync("gh", args, { encoding: "utf8", input, maxBuffer: 64 * 1024 * 1024 }));
174
+ const comments = JSON.parse(String(await gh(["issue", "view", String(issue), "-R", repo, "--json", "comments"])) || "{}").comments?.map((c) => c?.body) ?? [];
175
+ const index = deps.index ?? { read: readDecisionIndex, write: writeDecisionIndex };
176
+ const fresh = freshDecisions({ text, issue, comments });
177
+ for (const d of fresh) await gh(["issue", "comment", String(issue), "-R", repo, "--body-file", "-"], decisionComment(d));
178
+ if (fresh.length) index.write(repo, [...index.read(repo), ...fresh]);
179
+ print(`interfaces: registered ${fresh.length} decision(s) on #${issue}${fresh.length ? `: ${fresh.map((d) => d.id).join(", ")}` : " (all already present)"}`);
180
+ return 0;
181
+ }
@@ -0,0 +1,192 @@
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 { existsSync, readFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { tmpDir } from "../tests/_tmp.mjs";
8
+ import { sliceCount, checkInterfaces, freshDecisions, seedDecisions, writeContracts, consumerNotices, notifyConsumers, interfacesFromCli, decisionComment } from "./interfaces.mjs";
9
+ import { interfaceDecisions, interfaceRows, withDecisionRows, supersede, normaliseDecision, readDecisionIndex } from "./decisions.mjs";
10
+ import { precheck, applyAmendments } from "./conformance.mjs";
11
+ import { seamFailures } from "./seam.mjs";
12
+
13
+ const TABLE = (rows) => ["| Boundary | Signature or schema | Auth mode | Owner issue | Anchors | Consumers |", "|---|---|---|---|---|---|", ...rows].join("\n");
14
+ const SPIKE = (extra = "") => `## Stack\n**Rationale**: x\n\n## Milestone plan\n1. api\n2. web\n\n${extra}`;
15
+ const EPIC = (extra = "") => `## Goal\nShip search.\n\n## Slices\n- [ ] #11 api\n- [ ] #12 web\n\n${extra}`;
16
+ const IFACE = `## Interfaces\n\n${TABLE(["| web -> api | POST /v1/search | API key only, no session cookie | #11 | `provider:api/`, `consumer:web/` | #12, search-sdk |"])}\n\n**Rationale**: one boundary\n`;
17
+
18
+ describe("Interfaces section validation (#5338)", () => {
19
+ it("counts slices: a spike's numbered Milestone plan, an epic's list items", () => {
20
+ assert.equal(sliceCount(SPIKE()), 2);
21
+ assert.equal(sliceCount(EPIC()), 2);
22
+ assert.equal(sliceCount(`## Slices\n1. one\n2. two\n3. three\n`), 3);
23
+ assert.equal(sliceCount("## Goal\n- [ ] #1 a\n- [ ] #2 b\n"), 2);
24
+ assert.equal(sliceCount("## Goal\nno list"), 0);
25
+ });
26
+ it("a spike or an epic with two or more slices and no Interfaces section fails; one slice, or a section, passes", () => {
27
+ for (const [body, kind] of [[SPIKE(), "spike"], [EPIC(), "epic"]]) {
28
+ const r = checkInterfaces(body, { kind });
29
+ assert.equal(r.ok, false, kind);
30
+ assert.match(r.problems[0], /no `## Interfaces` section: 2 slices/);
31
+ assert.equal(checkInterfaces(body + IFACE, { kind }).ok, true, kind);
32
+ assert.equal(checkInterfaces(body, { kind: "auto" }).ok, false);
33
+ }
34
+ assert.equal(checkInterfaces("## Slices\n- [ ] #1 only\n", { kind: "epic" }).ok, true);
35
+ assert.equal(checkInterfaces("## Goal\nx").required, false);
36
+ });
37
+ it("the section needs a Rationale line, and an epic needs a real boundary row (a placeholder row does not count)", () => {
38
+ assert.match(checkInterfaces(EPIC("## Interfaces\n" + TABLE(["| a -> b | f(x) | key | #1 | `p/` | |"])), { kind: "epic" }).problems[0], /no \*\*Rationale\*\*/);
39
+ const ph = EPIC(`## Interfaces\n${TABLE(["| {web -> api} | {POST /x} | {key} | {issue} | `{provider:a/}` | {#n} |"])}\n\n**Rationale**: r\n`);
40
+ assert.match(checkInterfaces(ph, { kind: "epic" }).problems[0], /no boundary row/);
41
+ assert.equal(checkInterfaces(SPIKE(`## Interfaces\n${TABLE(["| {a} | {b} | {c} | {d} | `{e}` | |"])}\n\n**Rationale**: r\n`), { kind: "spike" }).ok, true, "the spike template ships a placeholder row");
42
+ });
43
+ it("notes a machine-form signature that declares no sides (no contract test can be generated)", () => {
44
+ const body = EPIC(`## Interfaces\n${TABLE(["| a -> b | POST /v1/x | key | #1 | `api/` | |"])}\n\n**Rationale**: r\n`);
45
+ assert.deepEqual(checkInterfaces(body, { kind: "epic" }).unchecked, ["a -> b"]);
46
+ assert.deepEqual(checkInterfaces(EPIC(IFACE), { kind: "epic" }).unchecked, []);
47
+ });
48
+ it("rows are read by header name: a five-column table without Consumers still parses", () => {
49
+ const rows = interfaceRows(`## Interfaces\n| Boundary | Signature or schema | Auth mode | Owner issue | Anchors |\n|--|--|--|--|--|\n| a -> b | refund(id) | key | #3 | \`provider:w/\`, \`consumer:a/\` |\n`);
50
+ assert.equal(rows.length, 1);
51
+ assert.deepEqual(rows[0].consumers, []);
52
+ assert.equal(rows[0].seam.kind, "symbol");
53
+ assert.deepEqual(interfaceRows(EPIC(IFACE))[0].consumers, ["#12", "search-sdk"]);
54
+ });
55
+ });
56
+
57
+ describe("registering a spike or epic's interfaces in the decision register (#5338)", () => {
58
+ const idx = () => { const dir = tmpDir("ifc-"); process.env.FORGEDOCK_DECISIONS_DIR = dir; return dir; };
59
+ it("an epic's Interfaces row and anchored architecture choice are posted once per id and indexed; a lane on the anchors gets the preserve row", () => {
60
+ idx();
61
+ const body = EPIC(`## Auth\n**Rationale**: keys everywhere\n**Anchors**: \`api/auth/\`\n\n${IFACE}`);
62
+ const posts = [];
63
+ const first = seedDecisions({ text: body, issue: 40, repo: "o/r", comments: [], post: (b) => posts.push(b) });
64
+ assert.deepEqual(first.map((d) => d.id), ["i40-1", "i40-2"]);
65
+ assert.match(posts[0], /^<!-- FORGE:DECISION \{/);
66
+ assert.match(posts[1], /Interface web -> api: POST \/v1\/search; auth API key only, no session cookie; owner #11/);
67
+ const again = seedDecisions({ text: body, issue: 40, repo: "o/r", comments: posts, post: (b) => posts.push(b) });
68
+ assert.deepEqual(again, [], "idempotent on resume");
69
+ assert.equal(posts.length, 2);
70
+ const recs = readDecisionIndex("o/r");
71
+ assert.equal(recs.length, 2);
72
+ assert.deepEqual(recs[1].consumers, ["#12", "search-sdk"]);
73
+ assert.equal(recs[1].seam.kind, "route");
74
+ const lane = withDecisionRows({ deliverables: [{ id: "D1", path: "web/app/api/search/route.ts" }], preserve: [] }, recs);
75
+ assert.deepEqual(lane.preserve.map((p) => [p.source, p.decision]), [["decision", "i40-2"]]);
76
+ assert.match(lane.preserve[0].what, /POST \/v1\/search/);
77
+ assert.deepEqual(freshDecisions({ text: body, issue: 40, comments: [decisionComment(first[0])] }).map((d) => d.id), ["i40-2"]);
78
+ });
79
+ it("CLI: check exits 1 for the missing section and 0 with it; register posts via gh once; contract writes the test for machine-form rows", async () => {
80
+ const dir = idx(); const out = [];
81
+ const files = { "epic.md": EPIC(), "ok.md": EPIC(IFACE) };
82
+ const deps = { print: (t) => out.push(t), readFile: (f) => files[f] };
83
+ assert.equal(await interfacesFromCli(["check", "--body-file", "epic.md", "--kind", "epic"], deps), 1);
84
+ assert.match(out.at(-1), /interfaces: no `## Interfaces` section/);
85
+ assert.equal(await interfacesFromCli(["check", "--body-file", "ok.md", "--kind", "epic"], deps), 0);
86
+ const calls = [];
87
+ const gh = async (a, input) => { calls.push([a, input]); return a[1] === "view" ? JSON.stringify({ comments: calls.filter((c) => c[0][1] === "comment").map((c) => ({ body: c[1] })) }) : ""; };
88
+ assert.equal(await interfacesFromCli(["register", "--issue", "40", "--body-file", "ok.md", "--repo", "o/r"], { ...deps, gh }), 0);
89
+ assert.equal(calls.filter((c) => c[0][1] === "comment").length, 1);
90
+ assert.match(out.at(-1), /registered 1 decision\(s\) on #40: i40-1/);
91
+ await interfacesFromCli(["register", "--issue", "40", "--body-file", "ok.md", "--repo", "o/r"], { ...deps, gh });
92
+ assert.equal(calls.filter((c) => c[0][1] === "comment").length, 1, "re-run posts nothing");
93
+ assert.match(out.at(-1), /already present/);
94
+ await assert.rejects(() => interfacesFromCli(["register", "--body-file", "ok.md"], deps), /usage/);
95
+ const o = join(dir, "contracts");
96
+ assert.equal(await interfacesFromCli(["contract", "--issue", "40", "--body-file", "ok.md", "--out", o], deps), 0);
97
+ assert.ok(existsSync(join(o, "seam-check.mjs")) && existsSync(join(o, "i40-1.contract.test.mjs")));
98
+ assert.match(readFileSync(join(o, "i40-1.contract.test.mjs"), "utf8"), /"kind": "route"/);
99
+ assert.deepEqual(writeContracts({ text: EPIC(), issue: 1, outDir: join(dir, "none") }), { written: [], skipped: [] });
100
+ });
101
+ });
102
+
103
+ describe("a superseded interface tells its consumers (#5338)", () => {
104
+ const old = normaliseDecision({ id: "i40-1", choice: "Interface web -> api: POST /v1/search", anchors: ["api/", "web/"], issue: 40, consumers: ["#12", "#13", "search-sdk"] });
105
+ const rec = supersede(old, normaliseDecision({ id: "d41-1", choice: "Interface web -> api: POST /v2/search", why: "v2", anchors: ["api/", "web/"], issue: 41 })).next;
106
+ it("the new record inherits the consumers; none for a decision that supersedes nothing", () => {
107
+ assert.deepEqual(rec.consumers, ["#12", "#13", "search-sdk"]);
108
+ assert.deepEqual(consumerNotices(rec).map((n) => [n.consumer, n.issue]), [["#12", 12], ["#13", 13], ["search-sdk", null]]);
109
+ assert.deepEqual(consumerNotices({ ...rec, supersedes: undefined }), []);
110
+ });
111
+ it("closed consumers are reopened, open ones commented, a named consumer gets one new issue; idempotent on a re-run", async () => {
112
+ const calls = [], comments = { 12: [], 13: [] };
113
+ const gh = async (a) => {
114
+ calls.push(a.join(" "));
115
+ if (a[0] === "issue" && a[1] === "view") return JSON.stringify({ state: a[2] === "12" ? "CLOSED" : "OPEN", comments: (comments[a[2]] ?? []).map((body) => ({ body })) });
116
+ if (a[0] === "issue" && a[1] === "comment") { comments[a[2]].push(a[a.indexOf("--body") + 1]); return ""; }
117
+ if (a[0] === "issue" && a[1] === "list") return JSON.stringify(calls.some((c) => c.startsWith("issue create")) ? [{ number: 99 }] : []);
118
+ if (a[0] === "issue" && a[1] === "create") return "https://github.com/o/r/issues/99\n";
119
+ return "";
120
+ };
121
+ const first = await notifyConsumers({ rec, pr: 77, repo: "o/r", gh });
122
+ assert.deepEqual(first.map((x) => [x.consumer, x.action, x.issue]), [["#12", "reopened", 12], ["#13", "notified", 13], ["search-sdk", "filed", 99]]);
123
+ assert.ok(calls.includes("issue reopen 12 -R o/r") && !calls.includes("issue reopen 13 -R o/r"));
124
+ assert.ok(calls.some((c) => c.startsWith("issue edit 12") && c.includes("--remove-label workflow:merged")));
125
+ assert.match(comments[12][0], /FORGE:INTERFACE_CHANGED decision=d41-1 consumer=#12/);
126
+ assert.match(comments[12][0], /supersedes `i40-1` \(PR #77\)/);
127
+ const second = await notifyConsumers({ rec, pr: 77, repo: "o/r", gh });
128
+ assert.deepEqual(second.map((x) => x.action), ["reopened", "notified", "exists"]);
129
+ assert.equal(comments[12].length, 1, "one notice per consumer");
130
+ assert.equal(calls.filter((c) => c.startsWith("issue create")).length, 1);
131
+ });
132
+ it("a failing consumer is reported, never thrown", async () => {
133
+ const r = await notifyConsumers({ rec, repo: "o/r", gh: async () => { throw new Error("HTTP 500"); } });
134
+ assert.deepEqual(r.map((x) => x.action), ["failed", "failed", "failed"]);
135
+ });
136
+ });
137
+
138
+ describe("replay: the audit's interface mismatches are flagged at lane review, not at release review (#5338)", () => {
139
+ // The spike rows the architecture would have carried (AlterLab Search/Hands): the refund primitive, the web proxy auth
140
+ // mode (#39210, #39569) and the device/city/uule payload (worker BUG-1).
141
+ const spike = `${SPIKE()}## Interfaces\n\n${TABLE([
142
+ "| research -> refund primitive | refund(job_id, amount_micro) | internal | #101 | `provider:worker/refund.py`, `consumer:api/research/` | #102 |",
143
+ "| web proxy -> API | POST /v1/search | API key only, no session cookie or JWT | #103 | `provider:api/routes/`, `consumer:web/app/api/` | #104 |",
144
+ "| API -> worker | queue search.jobs {query, device, city, uule} | internal | #105 | `provider:worker/handlers/`, `consumer:api/search/` | |",
145
+ ])}\n\n**Rationale**: each boundary is a contract\n`;
146
+ const recs = interfaceDecisions(spike, { issue: 100 });
147
+ const base = {
148
+ "worker/refund.py": "async def refund(job_id: str, amount_micro: int) -> None:\n ...\n",
149
+ "api/research/run.py": "await refund(job.id, amount_micro=cost)\n",
150
+ "api/routes/search.py": "@router.post('/v1/search')\nasync def search(): ...\n",
151
+ "web/app/api/search/route.ts": "export async function POST() { return fetch(`${API}/v1/search`, { headers: { 'x-api-key': KEY } }); }\n",
152
+ "worker/handlers/search.py": "def handle(j): return j['query'], j['device'], j['city'], j['uule']\n",
153
+ "api/search/enqueue.py": "enqueue({'query': q, 'device': d, 'city': c, 'uule': u})\n",
154
+ };
155
+ const lane = (changes) => {
156
+ const files = { ...base, ...changes };
157
+ const changed = Object.keys(changes);
158
+ const contract = withDecisionRows({ requirements: [], deliverables: changed.map((p, i) => ({ id: `D${i + 1}`, path: p })), preserve: [] }, recs);
159
+ const seam = seamFailures({ records: recs, changedFiles: changed, list: () => Object.keys(files), read: (p) => files[p] });
160
+ return { contract, seam, pc: precheck({ contract: { ...contract, deliverables: [] }, result: { requirements: [], validation: [], preserve: [] }, changedFiles: changed, ignore: changed, seamFailures: seam }) };
161
+ };
162
+ it("the baseline repo is clean: every seam row has a contract", () => {
163
+ assert.equal(recs.filter((r) => r.seam).length, 3);
164
+ assert.deepEqual(lane({ "worker/refund.py": base["worker/refund.py"] }).seam, []);
165
+ });
166
+ it("refund signature drift: flagged on the lane that changes the primitive, with the row as a preserve item", () => {
167
+ const l = lane({ "worker/refund.py": "async def refund(job_id: str) -> None:\n ...\n" });
168
+ assert.ok(l.contract.preserve.some((p) => p.source === "decision" && /refund\(job_id, amount_micro\)/.test(p.what)));
169
+ assert.deepEqual(l.seam.map((f) => f.kind), ["interface_seam"]);
170
+ assert.match(l.seam[0].detail, /refund\(job_id\) does not match the declared refund\(job_id, amount_micro\)/);
171
+ assert.equal(l.pc.ok, false);
172
+ assert.ok(l.pc.failures.some((f) => f.kind === "interface_seam"));
173
+ });
174
+ it("cookie vs API key: a web proxy that forwards the session cookie to the API-key-only route is flagged at lane review", () => {
175
+ const l = lane({ "web/app/api/search/route.ts": "export async function POST(req) { return fetch(`${API}/v1/search`, { headers: { cookie: req.headers.get('cookie') ?? '' } }); }\n" });
176
+ assert.ok(l.seam.length >= 1);
177
+ assert.match(l.seam[0].detail, /web\/app\/api\/search\/route\.ts:1.*Cookie header/);
178
+ assert.ok(l.pc.failures.some((f) => f.kind === "interface_seam" && f.code === "conformance.preserve_violated"));
179
+ });
180
+ it("dropped payload fields: the handler that stops reading device/city/uule is flagged", () => {
181
+ const l = lane({ "worker/handlers/search.py": "def handle(j): return j['query']\n" });
182
+ assert.deepEqual(l.seam.map((f) => /field "(\w+)"/.exec(f.detail)[1]), ["device", "city", "uule"]);
183
+ });
184
+ it("changing an interface on purpose needs a supersedes decision, which retires the row and the seam check", () => {
185
+ const changes = { "worker/refund.py": "async def refund(job_id: str) -> None:\n ...\n" };
186
+ const files = { ...base, ...changes };
187
+ const a = applyAmendments({ requirements: [{ id: "R1", quote: "q", disposition: "deliver" }], deliverables: [{ id: "D1", path: "worker/refund.py" }], preserve: withDecisionRows({ deliverables: [{ id: "D1", path: "worker/refund.py" }], preserve: [] }, recs).preserve }, [{ kind: "decision", why: "refund is job-scoped now", decision: { choice: "Interface research -> refund: refund(job_id)", anchors: ["worker/refund.py"], supersedes: "i100-1" } }], "q", { baseFiles: Object.keys(files) });
188
+ assert.deepEqual(a.problems, []);
189
+ assert.equal(a.contract.preserve.some((p) => p.decision === "i100-1"), false);
190
+ assert.deepEqual(seamFailures({ records: recs, changedFiles: Object.keys(changes), list: () => Object.keys(files), read: (p) => files[p], superseded: a.decisions.map((d) => d.supersedes).filter(Boolean) }), []);
191
+ });
192
+ });