forgedock 1.55.1 → 1.57.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 (133) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine/phases.mjs +4 -3
  4. package/bin/engine-cli.mjs +58 -10
  5. package/bin/forgedock.mjs +52 -3
  6. package/bin/gc.mjs +43 -6
  7. package/bin/help-text.mjs +3 -1
  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 +88 -17
  14. package/bin/lean/conformance.test.mjs +98 -3
  15. package/bin/lean/decisions.mjs +86 -1
  16. package/bin/lean/decisions.test.mjs +21 -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 +12 -2
  32. package/bin/lean/issuewatch-parity.test.mjs +26 -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 +80 -25
  39. package/bin/lean/lean.test.mjs +149 -3
  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 +125 -0
  44. package/bin/lean/orphan-pr.test.mjs +145 -0
  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 +25 -0
  52. package/bin/lean/release-config.mjs +158 -0
  53. package/bin/lean/release-config.test.mjs +109 -0
  54. package/bin/lean/release-control.mjs +148 -0
  55. package/bin/lean/release-control.test.mjs +143 -0
  56. package/bin/lean/release-fence.mjs +50 -0
  57. package/bin/lean/release-fence.test.mjs +105 -0
  58. package/bin/lean/release-flakes.mjs +139 -0
  59. package/bin/lean/release-flakes.test.mjs +116 -0
  60. package/bin/lean/release-ledger.mjs +160 -0
  61. package/bin/lean/release-ledger.test.mjs +226 -0
  62. package/bin/lean/release-minutes.mjs +92 -0
  63. package/bin/lean/release-minutes.test.mjs +99 -0
  64. package/bin/lean/release-nightly.mjs +75 -0
  65. package/bin/lean/release-nightly.test.mjs +48 -0
  66. package/bin/lean/release-postmerge.mjs +45 -21
  67. package/bin/lean/release-review.e2e.test.mjs +1 -0
  68. package/bin/lean/release-review.mjs +54 -7
  69. package/bin/lean/release-review.test.mjs +76 -7
  70. package/bin/lean/release-unitmap.mjs +35 -0
  71. package/bin/lean/release-unitmap.test.mjs +41 -0
  72. package/bin/lean/release.mjs +177 -19
  73. package/bin/lean/release.test.mjs +80 -16
  74. package/bin/lean/render.mjs +3 -1
  75. package/bin/lean/run-issue-placement.test.mjs +82 -0
  76. package/bin/lean/sandbox-remote.mjs +16 -0
  77. package/bin/lean/schedd.mjs +1 -1
  78. package/bin/lean/seam.mjs +115 -0
  79. package/bin/lean/seam.test.mjs +118 -0
  80. package/bin/lean/selftest-journey.mjs +40 -2
  81. package/bin/lean/selftest-journey.test.mjs +43 -3
  82. package/bin/lean/statuscomment.mjs +168 -0
  83. package/bin/lean/statuscomment.test.mjs +133 -0
  84. package/bin/lean/ui-quality.mjs +57 -0
  85. package/bin/lean/ui-quality.test.mjs +55 -0
  86. package/bin/lean/visual-gate.test.mjs +63 -0
  87. package/bin/pool/agent.mjs +16 -2
  88. package/bin/pool/router.mjs +5 -1
  89. package/bin/review-staging.mjs +8 -5
  90. package/bin/stats/card.mjs +117 -0
  91. package/bin/stats/card.test.mjs +109 -0
  92. package/bin/stats/conformance-outcomes.test.mjs +2 -1
  93. package/bin/stats/depth.mjs +1 -1
  94. package/bin/stats/gh-retry.test.mjs +152 -0
  95. package/bin/stats/github-source.mjs +147 -14
  96. package/bin/stats/index.mjs +35 -2
  97. package/bin/stats/stats.test.mjs +31 -3
  98. package/bin/vendor/js-yaml/LICENSE +21 -0
  99. package/bin/vendor/js-yaml/PIN.md +7 -0
  100. package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
  101. package/commands/design-render-critique-loop.md +2 -0
  102. package/commands/design.md +2 -0
  103. package/commands/incident-response.md +4 -0
  104. package/commands/issue.md +1 -1
  105. package/commands/milestone.md +1 -1
  106. package/commands/pipeline-status.md +13 -0
  107. package/commands/review-pr-agents/frontend.md +1 -0
  108. package/commands/review-pr-staging.md +5 -0
  109. package/docs/CONFIG.md +75 -1
  110. package/docs/ISSUE-WATCH.md +7 -0
  111. package/docs/OUTCOME-CODES.md +1 -0
  112. package/docs/STATS.md +10 -0
  113. package/docs/design/visual-gate.md +25 -0
  114. package/docs/eval/adversarial-bench.md +2 -2
  115. package/docs/eval/corpus/adversarial-v1.json +3 -3
  116. package/docs/site/start-a-new-project.md +7 -0
  117. package/docs/spec/forge-protocol-v1.md +31 -0
  118. package/package.json +1 -1
  119. package/pool/README.md +2 -0
  120. package/scripts/acceptance-red-green.sh +15 -1
  121. package/scripts/acceptance-red-green.test.sh +12 -0
  122. package/scripts/bench-adversarial.mjs +4 -0
  123. package/scripts/bench-lightlane.mjs +4 -1
  124. package/scripts/bootstrap-create.mjs +8 -2
  125. package/scripts/ci-local.test.sh +3 -3
  126. package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
  127. package/scripts/plan-validate-live.mjs +9 -6
  128. package/scripts/review-prepare.sh +7 -1
  129. package/scripts/review-roster.sh +5 -2
  130. package/scripts/review-roster.test.sh +9 -0
  131. package/scripts/visual-gate.mjs +64 -0
  132. package/templates/bootstrap/technical-spike.md +17 -0
  133. package/templates/contracts/seam-check.mjs +236 -0
@@ -0,0 +1,139 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Flake policy for managed releases (#5568, epic #5549 5.5, I15/I20/I29, R2). Pure functions plus `gh`-injected reads; no model call.
5
+ * Flips and infra signatures go to `flakes.json` (on `_active`); an infra flake is rerun once per job inside `ci.rerun_budget_min`;
6
+ * a repeated flake files one `flake` issue, and only then may a test be quarantined (expiring, capped, never an unskippable class).
7
+ */
8
+ import { createHash } from "node:crypto";
9
+ import { readActive, updateActive } from "./release-ledger.mjs";
10
+
11
+ export const FLAKE_LABEL = "flake";
12
+ export const FLAKE_MARKER = "FORGE:FLAKE";
13
+ export const UNSKIPPABLE_CLASSES = ["migration", "security", "rollback", "backup-restore", "secrets"];
14
+ const DAY_MS = 86_400_000;
15
+ const json = (s) => { try { return JSON.parse(String(s)); } catch { return null; } };
16
+ const num = (v, d) => { const n = Number(v); return Number.isFinite(n) && n > 0 ? n : d; };
17
+
18
+ /** Known infra signatures (artifact upload outage, runner cancel, Postgres init race, apt/network). */
19
+ export const INFRA_SIGNATURES = [
20
+ ["artifact-upload", /artifact.*(upload|storage)|upload-artifact|unable to upload/i],
21
+ ["runner-cancel", /runner.*(lost communication|shutdown|received a shutdown signal)|operation was canceled|the job was canceled/i],
22
+ ["postgres-init", /pg_isready|database system is starting up|connection refused.*5432|postgres.*(not ready|init)/i],
23
+ ["network", /ETIMEDOUT|ECONNRESET|EAI_AGAIN|apt-get.*(failed|unable)|temporary failure in name resolution|could not resolve host|502 bad gateway|503 service unavailable/i],
24
+ ];
25
+
26
+ /** forge.yaml policy -> {rerunBudgetMin, quarantineAfter, windowDays, quarantineDays, quarantineMax, unskippable}. */
27
+ export function parseFlakeConfig(policy) {
28
+ const ci = policy?.ci ?? {}, f = ci.flake ?? {}, q = policy?.quarantine ?? {};
29
+ return {
30
+ rerunBudgetMin: num(ci.rerun_budget_min, 0), quarantineAfter: num(f.quarantine_after, 3), windowDays: num(f.window_days, 14),
31
+ quarantineDays: num(q.days, 14), quarantineMax: num(q.max, 15), unskippable: [...UNSKIPPABLE_CLASSES, ...(Array.isArray(ci.unskippable) ? ci.unskippable : [])],
32
+ };
33
+ }
34
+
35
+ /** True when `check` is, or is under (`class:x`, `class/x`), an unskippable class; the one matcher for exempt and quarantine. */
36
+ export const isUnskippable = (check, classes = UNSKIPPABLE_CLASSES) => classes.some((c) => check === c || check.startsWith(`${c}:`) || check.startsWith(`${c}/`));
37
+
38
+ /** @returns {{class: "infra"|"unknown", signature: string|null}} from failure text (log tail or annotations). */
39
+ export function classifyFailure(text) {
40
+ const hit = INFRA_SIGNATURES.find(([, re]) => re.test(String(text ?? "")));
41
+ return hit ? { class: "infra", signature: hit[0] } : { class: "unknown", signature: null };
42
+ }
43
+ export const signatureHash = (check, test, signature) => createHash("sha256").update([check, test ?? "", signature ?? ""].join("\0")).digest("hex").slice(0, 16);
44
+
45
+ /** Same-SHA flips in `runs` [{sha, check, test?, conclusion, id, at}]: a check that failed and then passed on one sha. */
46
+ export function detectSameShaFlip(runs) {
47
+ const by = new Map();
48
+ for (const r of [...runs].sort((a, b) => Date.parse(a.at) - Date.parse(b.at))) {
49
+ const k = `${r.sha}\0${r.check}\0${r.test ?? ""}`, g = by.get(k) ?? { fail: [], flipped: false, r };
50
+ if (r.conclusion === "failure") g.fail.push(r); else if (r.conclusion === "success" && g.fail.length) g.flipped = true;
51
+ g.runs = [...(g.runs ?? []), r.id]; by.set(k, g);
52
+ }
53
+ return [...by.values()].filter((g) => g.flipped).map((g) => ({ check: g.r.check, test: g.r.test ?? null, sha: g.r.sha, run_ids: g.runs }));
54
+ }
55
+
56
+ /** One `flakes.json` entry. */
57
+ export const flakeEntry = ({ check, test = null, signature = null, kind, sha = null, runIds = [], at, rerun = false }) =>
58
+ ({ check, test, signature, signature_hash: signatureHash(check, test, signature), kind, sha, run_ids: runIds, at, ...(rerun ? { rerun: true } : {}) });
59
+
60
+ /** Append entries to `flakes.json` and the `_active` `flakes` key in one commit. */
61
+ export async function recordFlakes(lctx, entries, now = Date.now()) {
62
+ if (!entries.length) return { ok: true, recorded: 0 };
63
+ const r = await updateActive(lctx, ["flakes"], (a) => {
64
+ const flakes = [...(a.flakes ?? []), ...entries];
65
+ return { patch: { flakes }, files: { "flakes.json": `${JSON.stringify({ updated: new Date(now).toISOString(), flakes }, null, 2)}\n` } };
66
+ });
67
+ return r.ok ? { ok: true, recorded: entries.length } : { ok: false, error: r.refused ?? "lost the race recording flakes" };
68
+ }
69
+
70
+ /**
71
+ * Which failed jobs to `rerun --failed`: infra class only, once per job (`done` = keys of jobs already rerun), and only while the
72
+ * minutes already spent stay inside `ci.rerun_budget_min`. Every job gets a decision, so a skipped rerun is never silent.
73
+ * @param {{jobs: {key, name, class, minutes?}[], done?: Set|string[], spentMin?: number, budgetMin: number}} p
74
+ */
75
+ export function planRerun({ jobs, done = [], spentMin = 0, budgetMin }) {
76
+ const seen = new Set(done);
77
+ let spent = spentMin;
78
+ return jobs.map((j) => {
79
+ if (j.class !== "infra") return { ...j, rerun: false, why: "not an infra flake" };
80
+ if (seen.has(j.key)) return { ...j, rerun: false, why: "already rerun once" };
81
+ const cost = j.minutes ?? 0;
82
+ if (!(budgetMin > 0) || spent + cost > budgetMin) return { ...j, rerun: false, why: `ci.rerun_budget_min ${budgetMin} exhausted (${spent} spent)` };
83
+ spent += cost; seen.add(j.key);
84
+ return { ...j, rerun: true, why: "infra flake, first rerun" };
85
+ });
86
+ }
87
+
88
+ const targetOf = (f) => f.test ? `${f.check}:${f.test}` : f.check;
89
+
90
+ /** Targets with >= quarantine_after flips inside window_days: [{target, check, test, count, evidence}]. Infra reruns do not count as flips. */
91
+ export function repeatedFlakes(flakes, cfg, now = Date.now()) {
92
+ const groups = new Map();
93
+ for (const f of flakes ?? []) {
94
+ if (f.kind !== "flip" && f.kind !== "test") continue;
95
+ if (now - Date.parse(f.at) > cfg.windowDays * DAY_MS) continue;
96
+ const g = groups.get(targetOf(f)) ?? { target: targetOf(f), check: f.check, test: f.test ?? null, count: 0, evidence: [] };
97
+ g.count++; g.evidence.push(...(f.run_ids ?? [])); groups.set(g.target, g);
98
+ }
99
+ return [...groups.values()].filter((g) => g.count >= cfg.quarantineAfter);
100
+ }
101
+
102
+ const markerFor = (target) => `<!-- ${FLAKE_MARKER} target=${target} -->`;
103
+
104
+ /** The open `flake` issue of `target`, else a new one (label `flake`, evidence). @returns {{issue, created}|null} null for an unskippable target. */
105
+ export async function fileFlakeIssue({ gh, repo, target, evidence = [], count = 0, owner = null, cfg }) {
106
+ if (isUnskippable(target, cfg?.unskippable)) return null;
107
+ const mark = markerFor(target);
108
+ const open = json(await gh(["issue", "list", "--repo", repo, "--label", FLAKE_LABEL, "--state", "open", "--json", "number,body", "--limit", "100"])) ?? [];
109
+ const found = open.find((i) => String(i.body ?? "").includes(mark));
110
+ if (found) return { issue: found.number, created: false };
111
+ const body = `${mark}\nRepeated flake: \`${target}\` flipped ${count} time(s) inside the window.${owner ? `\nOwner: ${owner}` : ""}\nRuns: ${evidence.join(", ") || "none"}\n`;
112
+ const url = String(await gh(["issue", "create", "--repo", repo, "--label", FLAKE_LABEL, "--title", `flake: ${target} is flaky`, "--body", body])).trim();
113
+ return { issue: Number(/(\d+)$/.exec(url)?.[1]) || null, created: true };
114
+ }
115
+
116
+ /** An exemption is live until `until`; a quarantine also lapses `quarantine.days` after it was recorded (fail closed: blocking again). */
117
+ export function isLive(e, cfg, now = Date.now()) {
118
+ if (!e || !(Date.parse(e.until) > now)) return false;
119
+ return e.mode !== "quarantine" || now - Date.parse(e.at) <= cfg.quarantineDays * DAY_MS;
120
+ }
121
+ export const activeQuarantines = (exemptions, cfg, now = Date.now()) => Object.entries(exemptions ?? {}).filter(([, e]) => e?.mode === "quarantine" && isLive(e, cfg, now)).map(([k]) => k);
122
+
123
+ /**
124
+ * May `target` be quarantined? Refused for an unskippable class, without an existing open `flake` issue, or at the cap.
125
+ * @returns {{ok: true} | {ok: false, why: string}}
126
+ */
127
+ export function canQuarantine({ target, exemptions, issueLabels = [], issueOpen = true, cfg, now = Date.now() }) {
128
+ if (isUnskippable(target, cfg.unskippable)) return { ok: false, why: `${target} is an unskippable class and can never be quarantined` };
129
+ if (!issueOpen || !issueLabels.includes(FLAKE_LABEL)) return { ok: false, why: `quarantine needs an open issue labelled ${FLAKE_LABEL} (file it first)` };
130
+ const live = activeQuarantines(exemptions, cfg, now);
131
+ if (live.length >= cfg.quarantineMax && !live.includes(target)) return { ok: false, why: `quarantine cap ${cfg.quarantineMax} reached` };
132
+ return { ok: true };
133
+ }
134
+
135
+ /** I29: a run that needed an in-runner retry or a rerun (a `FLAKE:` annotation) never writes a cache marker. */
136
+ export const shouldWriteMarker = ({ retried = false, flakeAnnotated = false, rerun = false, passed = true } = {}) => passed && !retried && !flakeAnnotated && !rerun;
137
+
138
+ /** Live flakes ledger from `_active` (empty when unreadable). */
139
+ export async function readFlakes(lctx) { try { return (await readActive(lctx)).flakes ?? []; } catch { return []; } }
@@ -0,0 +1,116 @@
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 { parseFlakeConfig, classifyFailure, detectSameShaFlip, flakeEntry, planRerun, repeatedFlakes, fileFlakeIssue, canQuarantine, activeQuarantines, shouldWriteMarker, isUnskippable, recordFlakes, UNSKIPPABLE_CLASSES } from "./release-flakes.mjs";
6
+ import { rerunInfraFlakes } from "./release.mjs";
7
+
8
+ const NOW = Date.parse("2026-11-12T00:00:00Z"), DAY = 86_400_000;
9
+ const cfg = parseFlakeConfig({ ci: { rerun_budget_min: 30 } });
10
+
11
+ describe("release flakes (#5568)", () => {
12
+ it("defaults and overrides", () => {
13
+ assert.deepEqual([cfg.quarantineAfter, cfg.windowDays, cfg.quarantineDays, cfg.quarantineMax], [3, 14, 14, 15]);
14
+ assert.equal(parseFlakeConfig({ quarantine: { days: 7, max: 2 }, ci: { unskippable: ["x"] } }).unskippable.includes("x"), true);
15
+ });
16
+
17
+ it("records a same-SHA fail-then-pass flip but not a plain failure or a different sha", () => {
18
+ const r = (sha, conclusion, id, at) => ({ sha, check: "unit", conclusion, id, at });
19
+ const flips = detectSameShaFlip([r("a", "failure", 1, "2026-11-01T00:00:00Z"), r("a", "success", 2, "2026-11-01T01:00:00Z"), r("b", "failure", 3, "2026-11-02T00:00:00Z"), r("c", "failure", 4, "2026-11-02T00:00:00Z"), r("d", "success", 5, "2026-11-02T00:00:00Z")]);
20
+ assert.deepEqual(flips, [{ check: "unit", test: null, sha: "a", run_ids: [1, 2] }]);
21
+ });
22
+
23
+ it("infra signatures are classified and hashed stably", () => {
24
+ assert.deepEqual(classifyFailure("Error: pg_isready: no response"), { class: "infra", signature: "postgres-init" });
25
+ assert.equal(classifyFailure("Unable to upload artifact").class, "infra");
26
+ assert.equal(classifyFailure("AssertionError: 1 !== 2").class, "unknown");
27
+ assert.equal(flakeEntry({ check: "c", signature: "s", kind: "infra", at: "t" }).signature_hash, flakeEntry({ check: "c", signature: "s", kind: "infra", at: "u" }).signature_hash);
28
+ });
29
+
30
+ it("rerun: once per job, infra only, inside the budget, every job decided", () => {
31
+ const jobs = [{ key: "a", class: "infra", minutes: 10 }, { key: "b", class: "unknown" }, { key: "c", class: "infra", minutes: 10 }, { key: "d", class: "infra", minutes: 50 }];
32
+ const p = planRerun({ jobs, done: ["c"], spentMin: 5, budgetMin: 30 });
33
+ assert.deepEqual(p.map((d) => d.rerun), [true, false, false, false]);
34
+ assert.match(p[3].why, /rerun_budget_min/); assert.match(p[2].why, /once/);
35
+ assert.equal(planRerun({ jobs: [jobs[0]], budgetMin: 0 })[0].rerun, false);
36
+ });
37
+
38
+ it("repeated flakes inside the window file one flake issue (deduped)", async () => {
39
+ const at = (d) => new Date(NOW - d * DAY).toISOString();
40
+ const fl = [1, 2, 3].map((d) => flakeEntry({ check: "e2e", test: "t1", kind: "flip", at: at(d), runIds: [d] })).concat(flakeEntry({ check: "e2e", test: "old", kind: "flip", at: at(40) }));
41
+ const rep = repeatedFlakes(fl, cfg, NOW);
42
+ assert.equal(rep.length, 1); assert.equal(rep[0].target, "e2e:t1");
43
+ const issues = []; const calls = [];
44
+ const gh = async (a) => { calls.push(a); if (a[1] === "list") return JSON.stringify(issues); issues.push({ number: 7, body: a[a.indexOf("--body") + 1] }); return "https://github.com/o/r/issues/7"; };
45
+ const first = await fileFlakeIssue({ gh, repo: "o/r", ...rep[0], cfg });
46
+ assert.deepEqual(first, { issue: 7, created: true }); assert.ok(calls.at(-1).includes("flake"));
47
+ assert.deepEqual(await fileFlakeIssue({ gh, repo: "o/r", ...rep[0], cfg }), { issue: 7, created: false });
48
+ assert.equal(await fileFlakeIssue({ gh, repo: "o/r", target: "migration:x", cfg }), null);
49
+ });
50
+
51
+ it("quarantine needs the flake issue, respects the cap and never takes unskippable classes", () => {
52
+ const base = { target: "e2e:t1", exemptions: {}, issueLabels: ["flake"], cfg, now: NOW };
53
+ assert.equal(canQuarantine(base).ok, true);
54
+ assert.match(canQuarantine({ ...base, issueLabels: [] }).why, /flake/);
55
+ assert.equal(canQuarantine({ ...base, issueOpen: false }).ok, false);
56
+ for (const c of UNSKIPPABLE_CLASSES) assert.equal(canQuarantine({ ...base, target: `${c}:x` }).ok, false, c);
57
+ const live = (i) => [`t${i}`, { mode: "quarantine", at: new Date(NOW - DAY).toISOString(), until: new Date(NOW + DAY).toISOString() }];
58
+ const full = Object.fromEntries(Array.from({ length: 15 }, (_, i) => live(i)));
59
+ assert.match(canQuarantine({ ...base, exemptions: full }).why, /cap 15/);
60
+ assert.equal(canQuarantine({ ...base, target: "t3", exemptions: full }).ok, true);
61
+ assert.equal(isUnskippable("migration"), true);
62
+ });
63
+
64
+ it("a quarantine is blocking again at its 14 day expiry, or at `until`", () => {
65
+ const q = (ageD, untilD) => ({ x: { mode: "quarantine", at: new Date(NOW - ageD * DAY).toISOString(), until: new Date(NOW + untilD * DAY).toISOString() } });
66
+ assert.deepEqual(activeQuarantines(q(1, 5), cfg, NOW), ["x"]);
67
+ assert.deepEqual(activeQuarantines(q(15, 5), cfg, NOW), []);
68
+ assert.deepEqual(activeQuarantines(q(1, -1), cfg, NOW), []);
69
+ });
70
+
71
+ it("a retry-pass run writes no cache marker (I29)", () => {
72
+ assert.equal(shouldWriteMarker({ passed: true }), true);
73
+ for (const k of ["retried", "flakeAnnotated", "rerun"]) assert.equal(shouldWriteMarker({ passed: true, [k]: true }), false, k);
74
+ assert.equal(shouldWriteMarker({ passed: false }), false);
75
+ });
76
+
77
+ it("recordFlakes commits flakes.json with active.json", async () => {
78
+ const files = {};
79
+ const io = { api: async (m, p, b) => {
80
+ if (m === "GET" && /git\/ref\/heads/.test(p)) return { object: { sha: "h" } };
81
+ if (m === "GET" && /contents\/active\.json/.test(p)) return { content: Buffer.from("{}").toString("base64") };
82
+ if (m === "GET") return { tree: { sha: "t" } };
83
+ if (/git\/trees/.test(p)) { for (const t of b.tree) files[t.path] = t.content; return { sha: "t1" }; }
84
+ return { sha: "c1" };
85
+ } };
86
+ const r = await recordFlakes({ io, repo: "o/r", credential: "driver" }, [flakeEntry({ check: "c", kind: "infra", at: "t" })]);
87
+ assert.equal(r.ok, true);
88
+ assert.equal(JSON.parse(files["flakes.json"]).flakes.length, 1); assert.ok(files["active.json"]);
89
+ });
90
+
91
+ it("rerunInfraFlakes reruns an infra-failed run once, skips a real failure, records the flake", async () => {
92
+ const calls = [], files = {};
93
+ const logs = { 1: "Unable to upload artifact", 2: "AssertionError" };
94
+ const active = { epoch: 1, lease: { holder: "A", epoch: 1, release: "r1" } };
95
+ const api = async (m, p, b) => {
96
+ if (m === "GET" && /git\/ref\/heads/.test(p)) return { object: { sha: "h" } };
97
+ if (m === "GET" && /contents\/active\.json/.test(p)) return { content: Buffer.from(JSON.stringify(active)).toString("base64") };
98
+ if (m === "GET") return { tree: { sha: "t" } };
99
+ if (/git\/trees/.test(p)) { for (const t of b.tree) files[t.path] = t.content; return { sha: "t1" }; }
100
+ return { sha: "c1" };
101
+ };
102
+ const io = { now: () => NOW, api, gh: async (a) => {
103
+ calls.push(a);
104
+ if (a[1] === "list") return JSON.stringify([{ databaseId: 1, name: "unit" }, { databaseId: 2, name: "lint" }]);
105
+ if (a[1] === "view") return logs[a[2]];
106
+ return "";
107
+ } };
108
+ const fence = { lctx: { io, repo: "o/r", credential: "driver" }, lease: { holder: "A", epoch: 1, release: "r1" }, record: async () => {}, now: () => "t" };
109
+ const r = await rerunInfraFlakes({ io, repo: "o/r", head: "abc", fence, policy: { ci: { rerun_budget_min: 30 } } });
110
+ assert.deepEqual(r.reran, ["unit"]); assert.equal(r.skipped[0].name, "lint");
111
+ assert.deepEqual(calls.filter((c) => c[1] === "rerun"), [["run", "rerun", "1", "--repo", "o/r", "--failed"]]);
112
+ assert.equal(JSON.parse(files["flakes.json"]).flakes[0].signature, "artifact-upload");
113
+ const none = await rerunInfraFlakes({ io, repo: "o/r", head: "abc", fence, policy: {} });
114
+ assert.deepEqual(none, { reran: [], skipped: [] }); // no ci.rerun_budget_min: no rerun
115
+ });
116
+ });
@@ -0,0 +1,160 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Release ledger on GitHub (#5550, epic #5549 Phase 0): the durable, cross-host record of a release. One orphan branch
5
+ * `forge-ledger/<release-id>` per release (`state.json`, single writer = the lease holder) plus one control branch
6
+ * `forge-ledger/_active` (`active.json`: lease, epoch, intake pause, holds, counters; `controls.jsonl`: append-only audit).
7
+ * Writes are Git Data API commits whose ref update is NOT forced: a non-fast-forward (HTTP 422) is a lost race, which is
8
+ * the compare-and-swap. `_active` is multi-writer, so `updateActive` is a key-scoped read-modify-write with up to 5 retries.
9
+ * The heartbeat is an edit of the `FORGE:LEASE` comment on the tracking issue, never a commit. Every value is redacted
10
+ * before it is written (I21); a head commit is trusted only from an allowlisted, GitHub-verified driver actor (I12).
11
+ * Every effect goes through `io.api(method, path, body?)` (parsed JSON; throws with `.status`), so it is unit-testable.
12
+ * Off unless forge.yaml `release.managed` is on; nothing here runs otherwise.
13
+ */
14
+ import { SECRET_PAIR_RE, SECRET_SHAPE_RE } from "./conformance.mjs";
15
+
16
+ export const LEDGER_PREFIX = "forge-ledger/";
17
+ export const ACTIVE = "_active";
18
+ export const ACTIVE_RETRIES = 5;
19
+ export const LEASE_MARKER = "FORGE:LEASE";
20
+ const ID_RE = /^r\d{8}-\d{6}-\d+$/;
21
+ const SECRET_KEY_RE = /TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|CREDENTIAL/i;
22
+ const REDACTED = "[redacted]";
23
+
24
+ export const ledgerBranch = (id) => {
25
+ if (id !== ACTIVE && !ID_RE.test(String(id ?? ""))) throw new Error(`invalid release id ${JSON.stringify(id)}`);
26
+ return `${LEDGER_PREFIX}${id}`;
27
+ };
28
+
29
+ /** `value` with every secret-shaped string (and the value of every secret-named key) replaced; never mutates. */
30
+ export function redactDeep(value) {
31
+ if (typeof value === "string") return value.replace(SECRET_PAIR_RE, `$1${REDACTED}`).replace(SECRET_SHAPE_RE, REDACTED);
32
+ if (Array.isArray(value)) return value.map(redactDeep);
33
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, SECRET_KEY_RE.test(k) && typeof v === "string" ? REDACTED : redactDeep(v)]));
34
+ return value;
35
+ }
36
+
37
+ const isLost = (e) => e?.status === 422 || /HTTP 422|not a fast.forward|already exists/i.test(String(e?.message ?? e));
38
+ const isMissing = (e) => e?.status === 404 || /HTTP 404|Not Found/i.test(String(e?.message ?? e));
39
+ const refPath = (b) => `heads/${b}`;
40
+
41
+ const headOf = async ({ io, repo }, branch) => {
42
+ try { return (await io.api("GET", `repos/${repo}/git/ref/${refPath(branch)}`))?.object?.sha ?? null; } catch (e) { if (isMissing(e)) return null; throw e; }
43
+ };
44
+ const readFile = async ({ io, repo }, branch, path) => {
45
+ try { const r = await io.api("GET", `repos/${repo}/contents/${path}?ref=${encodeURIComponent(branch)}`); return Buffer.from(r.content ?? "", "base64").toString("utf8"); } catch (e) { if (isMissing(e)) return null; throw e; }
46
+ };
47
+
48
+ /** The driver credential writes the ledger; a lane credential never does (I12). */
49
+ const assertDriver = (ctx) => { if (ctx.credential !== "driver") throw Object.assign(new Error("ledger writes need the driver credential"), { refused: "not-driver" }); };
50
+
51
+ /**
52
+ * One commit of `files` ({path: text}, redacted) on `branch` on top of `parent` (null = orphan, creates the branch).
53
+ * @returns {{ok: true, sha: string} | {lost: true}} lost when the ref moved (or exists): the caller re-reads and decides.
54
+ */
55
+ export async function commitFiles(ctx, branch, files, message, parent) {
56
+ assertDriver(ctx);
57
+ const { io, repo } = ctx;
58
+ const base = parent ? (await io.api("GET", `repos/${repo}/git/commits/${parent}`)).tree.sha : undefined;
59
+ const tree = await io.api("POST", `repos/${repo}/git/trees`, { ...(base ? { base_tree: base } : {}), tree: Object.entries(files).map(([path, text]) => ({ path, mode: "100644", type: "blob", content: String(redactDeep(text)) })) });
60
+ const commit = await io.api("POST", `repos/${repo}/git/commits`, { message: String(redactDeep(message)), tree: tree.sha, parents: parent ? [parent] : [] });
61
+ try {
62
+ if (parent) await io.api("PATCH", `repos/${repo}/git/refs/${refPath(branch)}`, { sha: commit.sha, force: false });
63
+ else await io.api("POST", `repos/${repo}/git/refs`, { ref: `refs/${refPath(branch)}`, sha: commit.sha });
64
+ } catch (e) { if (isLost(e)) return { lost: true }; throw e; }
65
+ return { ok: true, sha: commit.sha };
66
+ }
67
+
68
+ const json = (o) => JSON.stringify(redactDeep(o), null, 2) + "\n";
69
+
70
+ /** Create `forge-ledger/<id>` with the first state; `{lost}` when the release already has a ledger. */
71
+ export const createReleaseLedger = (ctx, id, state) => commitFiles(ctx, ledgerBranch(id), { "state.json": json(state) }, `ledger: create ${id}`, null);
72
+
73
+ /** Write the next state of release `id` on top of `head` (the sha the caller read); `{lost}` means another writer moved it. */
74
+ export const writeRelease = (ctx, id, state, head) => commitFiles(ctx, ledgerBranch(id), { "state.json": json(state) }, `ledger: ${id} ${state.status ?? "update"}`, head);
75
+
76
+ /** True when `info` (GET repos/R/commits/<sha>) was authored by an allowlisted driver actor and is GitHub-verified. */
77
+ export function acceptWrite(info, policy = {}) {
78
+ const id = info?.author?.id;
79
+ if (!info?.commit?.verification?.verified) return { ok: false, reason: "unverified commit" };
80
+ if (id == null || !(policy.allowlist ?? []).includes(id)) return { ok: false, reason: `actor ${info?.author?.login ?? id} is not allowlisted` };
81
+ if (!(policy.driverIds ?? []).includes(id)) return { ok: false, reason: `actor ${info?.author?.login ?? id} is not the driver credential` };
82
+ return { ok: true };
83
+ }
84
+
85
+ /** `{state, head}` of release `id`, `null` when it has no ledger, `{rejected}` when the head commit fails `acceptWrite`. */
86
+ export async function readLedger(ctx, id, policy) {
87
+ const branch = ledgerBranch(id), head = await headOf(ctx, branch);
88
+ if (!head) return null;
89
+ if (policy) {
90
+ const verdict = acceptWrite(await ctx.io.api("GET", `repos/${ctx.repo}/commits/${head}`), policy);
91
+ if (!verdict.ok) return { rejected: verdict.reason, head };
92
+ }
93
+ const text = await readFile(ctx, branch, "state.json");
94
+ try { return { state: JSON.parse(text), head }; } catch { return { rejected: "state.json unreadable", head }; }
95
+ }
96
+
97
+ /**
98
+ * Key-scoped read-modify-write of `_active`: `fn(active)` returns `{patch}` (only keys in `owned` are applied, others are
99
+ * ignored), optionally `control` (one line appended to controls.jsonl) or `{refuse}`. A lost race re-reads and re-applies,
100
+ * up to ACTIVE_RETRIES attempts.
101
+ * @returns {{ok: true, active, sha} | {refused: string} | {lost: true, attempts: number}}
102
+ */
103
+ export async function updateActive(ctx, owned, fn) {
104
+ for (let attempt = 1; attempt <= ACTIVE_RETRIES; attempt++) {
105
+ const head = await headOf(ctx, ACTIVE);
106
+ const cur = head ? JSON.parse((await readFile(ctx, ACTIVE, "active.json")) ?? "{}") : {};
107
+ const out = await fn(cur);
108
+ if (out?.refuse) return { refused: out.refuse };
109
+ const next = { ...cur };
110
+ for (const [k, v] of Object.entries(out?.patch ?? {})) if (owned.includes(k)) next[k] = v;
111
+ const files = { "active.json": json(next), ...(out?.files ?? {}) };
112
+ if (out?.control) files["controls.jsonl"] = `${(head ? (await readFile(ctx, ACTIVE, "controls.jsonl")) ?? "" : "")}${JSON.stringify(redactDeep(out.control))}\n`;
113
+ const r = await commitFiles(ctx, ACTIVE, files, `ledger: _active ${Object.keys(out?.patch ?? {}).join(",") || "control"}`, head);
114
+ if (r.ok) return { ok: true, active: next, sha: r.sha };
115
+ }
116
+ return { lost: true, attempts: ACTIVE_RETRIES };
117
+ }
118
+
119
+ const leaseBody = (l) => `<!-- ${LEASE_MARKER} -->\nholder: ${l.holder}\nepoch: ${l.epoch}\nrelease: ${l.release}\n${l.expires ? `expires: ${new Date(l.expires).toISOString()}\n` : ""}`;
120
+
121
+ /** Parsed `_active/active.json`; throws when it cannot be read (a fence must treat that as "no irreversible action", I5). */
122
+ export async function readActive(ctx) {
123
+ const text = await readFile(ctx, ACTIVE, "active.json");
124
+ if (text == null) throw new Error("_active has no active.json");
125
+ return JSON.parse(text);
126
+ }
127
+
128
+ /**
129
+ * Take the lease for release `release` as `holder`: refused while another holder's `FORGE:LEASE` comment (on `issue`) was
130
+ * edited within `ttlS`; each takeover bumps the epoch. The CAS lives in `updateActive`, so of two racing drivers one wins.
131
+ * @returns {{ok: true, lease} | {refused: string} | {lost: true}}
132
+ */
133
+ export async function acquireLease(ctx, { holder, release, issue, ttlS = 120, now = Date.now() }) {
134
+ const r = await updateActive(ctx, ["lease", "epoch"], async (active) => {
135
+ const l = active.lease;
136
+ if (l && l.holder !== holder && l.commentId) {
137
+ let c = null; try { c = await ctx.io.api("GET", `repos/${ctx.repo}/issues/comments/${l.commentId}`); } catch (e) { if (!isMissing(e)) throw e; }
138
+ if (c && now - Date.parse(c.updated_at) < (l.ttlS ?? ttlS) * 1000) return { refuse: `lease held by ${l.holder} (epoch ${l.epoch})` };
139
+ }
140
+ const epoch = (active.epoch ?? 0) + 1;
141
+ return { patch: { epoch, lease: { holder, release, issue, ttlS, epoch, expires: now + ttlS * 1000, commentId: l?.holder === holder ? l.commentId : undefined } }, control: { at: new Date(now).toISOString(), verb: "lease", holder, release, epoch } };
142
+ });
143
+ if (!r.ok) return r;
144
+ let lease = r.active.lease;
145
+ if (!lease.commentId) { // the heartbeat comment is made once per takeover, then only edited
146
+ const c = await ctx.io.api("POST", `repos/${ctx.repo}/issues/${issue}/comments`, { body: leaseBody(lease) });
147
+ const set = await updateActive(ctx, ["lease"], (a) => (a.lease?.holder === holder && a.lease.epoch === lease.epoch ? { patch: { lease: { ...a.lease, commentId: c.id } } } : { refuse: "lease lost" }));
148
+ if (!set.ok) return set;
149
+ lease = set.active.lease;
150
+ }
151
+ return { ok: true, lease };
152
+ }
153
+
154
+ /** Heartbeat: edit the FORGE:LEASE comment (no commit). `{fenced}` when the lease is no longer this holder's epoch. */
155
+ export async function heartbeat(ctx, lease) {
156
+ const active = JSON.parse((await readFile(ctx, ACTIVE, "active.json")) ?? "{}");
157
+ if (active.lease?.holder !== lease.holder || active.lease?.epoch !== lease.epoch) return { fenced: true };
158
+ await ctx.io.api("PATCH", `repos/${ctx.repo}/issues/comments/${active.lease.commentId}`, { body: leaseBody(lease) });
159
+ return { ok: true };
160
+ }