forgedock 1.56.0 → 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 (131) 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 +46 -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 +72 -21
  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 +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 +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 +8 -2
  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 +40 -0
  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 +5 -3
  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/issue.md +1 -1
  104. package/commands/milestone.md +1 -1
  105. package/commands/review-pr-agents/frontend.md +1 -0
  106. package/commands/review-pr-staging.md +5 -0
  107. package/docs/CONFIG.md +75 -1
  108. package/docs/ISSUE-WATCH.md +7 -0
  109. package/docs/OUTCOME-CODES.md +1 -0
  110. package/docs/STATS.md +10 -0
  111. package/docs/design/visual-gate.md +25 -0
  112. package/docs/eval/adversarial-bench.md +2 -2
  113. package/docs/eval/corpus/adversarial-v1.json +3 -3
  114. package/docs/site/start-a-new-project.md +7 -0
  115. package/docs/spec/forge-protocol-v1.md +31 -0
  116. package/package.json +1 -1
  117. package/pool/README.md +2 -0
  118. package/scripts/acceptance-red-green.sh +15 -1
  119. package/scripts/acceptance-red-green.test.sh +12 -0
  120. package/scripts/bench-adversarial.mjs +4 -0
  121. package/scripts/bench-lightlane.mjs +4 -1
  122. package/scripts/bootstrap-create.mjs +8 -2
  123. package/scripts/ci-local.test.sh +3 -3
  124. package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
  125. package/scripts/plan-validate-live.mjs +9 -6
  126. package/scripts/review-prepare.sh +7 -1
  127. package/scripts/review-roster.sh +5 -2
  128. package/scripts/review-roster.test.sh +9 -0
  129. package/scripts/visual-gate.mjs +64 -0
  130. package/templates/bootstrap/technical-spike.md +17 -0
  131. package/templates/contracts/seam-check.mjs +236 -0
@@ -0,0 +1,143 @@
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 { runControl, controlFromCli, buildDispatchArgs, holdCheck, exemptionsSection, CONTROL_SCHEMA } from "./release-control.mjs";
6
+ import { fenced } from "./release-fence.mjs";
7
+
8
+ // A tiny in-memory GitHub: _active branch (active.json + controls.jsonl) and one release ledger.
9
+ function world({ active = { epoch: 1, lease: { holder: "A", epoch: 1, release: "r20260101-000000-1", issue: 9 } }, state = null } = {}) {
10
+ const w = { active, controls: "", comments: [], vars: [], gh: [], files: {}, sha: 0 };
11
+ w.io = {
12
+ now: () => 1_700_000_000_000, print: (l) => (w.out ??= []).push(l),
13
+ gh: async (a) => { w.gh.push(a); if (a[0] === "repo") return JSON.stringify({ nameWithOwner: "o/r" }); if (a[0] === "variable") w.vars.push(a); if (a[0] === "issue" && a[1] === "view") return a[2] === "404" ? "" : JSON.stringify({ number: Number(a[2]), state: "OPEN", labels: [{ name: "flake" }] }); return ""; },
14
+ api: async (method, path, body) => {
15
+ if (method === "GET" && /git\/ref\/heads\/_active$/.test(path)) return { object: { sha: "h0" } };
16
+ if (method === "GET" && /contents\/active\.json/.test(path)) return { content: Buffer.from(JSON.stringify(w.active)).toString("base64") };
17
+ if (method === "GET" && /contents\/controls\.jsonl/.test(path)) return { content: Buffer.from(w.controls).toString("base64") };
18
+ if (method === "GET" && /git\/commits\//.test(path)) return { tree: { sha: "t0" } };
19
+ if (method === "POST" && /git\/trees/.test(path)) { for (const t of body.tree) w.files[t.path] = t.content; return { sha: "t1" }; }
20
+ if (method === "POST" && /git\/commits/.test(path)) return { sha: `c${++w.sha}` };
21
+ if (method === "PATCH" && /git\/refs/.test(path)) { w.active = JSON.parse(w.files["active.json"]); w.controls = w.files["controls.jsonl"] ?? w.controls; return {}; }
22
+ if (method === "POST" && /issues\/\d+\/comments/.test(path)) { w.comments.push(body.body); return { id: w.comments.length }; }
23
+ throw new Error(`unrouted ${method} ${path}`);
24
+ },
25
+ };
26
+ return w;
27
+ }
28
+ const RID = "r20260101-000000-1";
29
+ const base = (w, extra = {}) => ({ io: w.io, repo: "o/r", actor: "op", host: "h1", now: 1_700_000_000_000, ...extra });
30
+
31
+ describe("release control (#5556)", () => {
32
+ it("every mutation needs --reason (I15)", async () => {
33
+ const w = world();
34
+ for (const [v, a] of [["hold", [RID]], ["resume", [RID]], ["cancel", [RID]], ["lane", ["#1", "--force", "p0"]], ["exempt", ["lint", "--mode", "skip", "--issue", "3", "--until", "2h"]], ["freeze", []], ["unfreeze", []]]) {
35
+ const r = await runControl(v, a, base(w, { policy: { deploy: { freeze_variable: "DEPLOY_FREEZE" } } }));
36
+ assert.equal(r.ok, false, v); assert.match(r.error, /--reason is required/);
37
+ }
38
+ assert.equal(w.comments.length, 0);
39
+ });
40
+
41
+ it("exempt of an unskippable class (migration) is rejected; so is a policy-added one", async () => {
42
+ const w = world();
43
+ const a = ["--mode", "skip", "--issue", "3", "--until", "2h", "--reason", "x"];
44
+ assert.match((await runControl("exempt", ["migration", ...a], base(w))).error, /unskippable/);
45
+ for (const c of ["security", "rollback", "backup-restore", "secrets"]) assert.equal((await runControl("exempt", [c, ...a], base(w))).ok, false);
46
+ assert.equal((await runControl("exempt", ["custom", ...a], base(w, { policy: { ci: { unskippable: ["custom"] } } }))).ok, false);
47
+ assert.equal(w.controls, "");
48
+ });
49
+
50
+ it("exempt: mode ttl caps, required issue, trusted actor", async () => {
51
+ const w = world();
52
+ const ok = ["lint", "--mode", "skip", "--issue", "3", "--until", "24h", "--reason", "flaky"];
53
+ assert.match((await runControl("exempt", ["lint", "--mode", "skip", "--issue", "3", "--until", "25h", "--reason", "r"], base(w))).error, /at most 24h/);
54
+ assert.match((await runControl("exempt", ["lint", "--mode", "quarantine", "--issue", "3", "--until", "15d", "--reason", "r"], base(w))).error, /at most 336h/);
55
+ assert.match((await runControl("exempt", ["lint", "--mode", "skip", "--until", "1h", "--reason", "r"], base(w))).error, /--issue/);
56
+ assert.match((await runControl("exempt", ok, base(w, { policy: { trust: { actors: ["boss"] } } }))).error, /not trusted/);
57
+ assert.equal((await runControl("exempt", ["lint", "--mode", "quarantine", "--issue", "3", "--until", "14d", "--reason", "r"], base(w))).ok, true);
58
+ assert.equal((await runControl("exempt", ok, base(w, { policy: { trust: { actors: ["op"] } } }))).ok, true);
59
+ });
60
+
61
+ it("exempt without an existing issue is refused (#5568)", async () => {
62
+ const w = world();
63
+ const r = await runControl("exempt", ["lint", "--mode", "skip", "--issue", "404", "--until", "2h", "--reason", "x"], base(w));
64
+ assert.equal(r.ok, false); assert.match(r.error, /does not exist/);
65
+ assert.equal(w.controls, "");
66
+ });
67
+
68
+ it("quarantine is refused at the cap and without a flake-labelled issue, and a live one shows in the PR body (#5568)", async () => {
69
+ const at = new Date(1_700_000_000_000).toISOString(), until = new Date(1_700_000_000_000 + 3_600_000).toISOString();
70
+ const full = Object.fromEntries(Array.from({ length: 2 }, (_, i) => [`t${i}`, { mode: "quarantine", issue: "3", at, until }]));
71
+ const w = world({ active: { epoch: 1, lease: { holder: "A", epoch: 1, release: RID, issue: 9 }, exemptions: full } });
72
+ const a = ["--mode", "quarantine", "--issue", "3", "--until", "1d", "--reason", "x"];
73
+ assert.match((await runControl("exempt", ["new", ...a], base(w, { policy: { quarantine: { max: 2 } } }))).error, /cap 2/);
74
+ const gh = w.io.gh;
75
+ w.io.gh = async (x) => (x[0] === "issue" ? JSON.stringify({ number: 3, state: "OPEN", labels: [] }) : gh(x));
76
+ assert.match((await runControl("exempt", ["new", ...a], base(w))).error, /labelled flake/);
77
+ w.io.gh = gh;
78
+ const ok = await runControl("exempt", ["new", ...a], base(w));
79
+ assert.equal(ok.ok, true);
80
+ assert.match(exemptionsSection(w.active.exemptions, 1_700_000_000_000), /FORGE:EXEMPT[\s\S]*`new` \(quarantine\)/);
81
+ assert.equal(exemptionsSection({}, 0), "");
82
+ });
83
+
84
+ it("a mutation appends the audit line and posts a FORGE:CONTROL comment", async () => {
85
+ const w = world();
86
+ const r = await runControl("hold", [RID, "--reason", "pause for incident"], base(w));
87
+ assert.equal(r.schema, CONTROL_SCHEMA); assert.equal(r.ok, true);
88
+ const line = JSON.parse(w.controls.trim().split("\n").pop());
89
+ assert.deepEqual({ ...line, after: undefined }, { at: "2023-11-14T22:13:20.000Z", actor: "op", host: "h1", verb: "hold", reason: "pause for incident", before: null, after: undefined, epoch: 1 });
90
+ assert.equal(line.after.reason, "pause for incident");
91
+ assert.match(w.comments[0], /FORGE:CONTROL/);
92
+ assert.equal(w.active.holds[RID].actor, "op");
93
+ });
94
+
95
+ it("hold is obeyed: fenced() refuses every irreversible action; resume lifts it", async () => {
96
+ const w = world();
97
+ const fence = { lctx: { io: w.io, repo: "o/r", credential: "driver" }, lease: w.active.lease, now: () => "t", record: async () => {} };
98
+ let ran = 0;
99
+ assert.equal((await fenced(fence, { action: "merge", key: "k" }, async () => { ran++; })).ok, true);
100
+ await runControl("hold", [RID, "--reason", "r"], base(w));
101
+ assert.match(await holdCheck(fence.lctx, RID), /held/);
102
+ const r = await fenced(fence, { action: "merge", key: "k2" }, async () => { ran++; });
103
+ assert.match(r.refused, /held/); assert.equal(ran, 1);
104
+ await runControl("resume", [RID, "--reason", "done"], base(w));
105
+ assert.equal((await fenced(fence, { action: "merge", key: "k3" }, async () => { ran++; })).ok, true);
106
+ assert.equal(ran, 2);
107
+ });
108
+
109
+ it("cancel is refused once MERGED", async () => {
110
+ const w = world();
111
+ const orig = w.io.api;
112
+ w.io.api = async (m, p, b) => (/forge-ledger%2F|contents\/state\.json/.test(p) && m === "GET" && /state\.json/.test(p)
113
+ ? { content: Buffer.from(JSON.stringify({ v: 1, id: RID, steps: { promotion: { done: true, result: { merged: true } } } })).toString("base64") } : orig(m, p, b));
114
+ const r = await runControl("cancel", [RID, "--reason", "r"], base(w));
115
+ assert.equal(r.ok, false); assert.match(r.error, /MERGED|no ledger/);
116
+ });
117
+
118
+ it("lane force and freeze/unfreeze (the repo's own variable)", async () => {
119
+ const w = world();
120
+ assert.equal((await runControl("lane", ["#4", "#5", "--force", "exclude", "--reason", "r"], base(w))).ok, true);
121
+ assert.equal(w.active.lanes["4"].force, "exclude");
122
+ assert.match((await runControl("lane", ["#4", "--force", "bogus", "--reason", "r"], base(w))).error, /--force/);
123
+ assert.match((await runControl("freeze", ["--reason", "r"], base(w))).error, /freeze_variable/);
124
+ const policy = { deploy: { freeze_variable: "DEPLOY_FREEZE" } };
125
+ assert.equal((await runControl("freeze", ["--reason", "r"], base(w, { policy }))).ok, true);
126
+ assert.deepEqual(w.vars[0], ["variable", "set", "DEPLOY_FREEZE", "--repo", "o/r", "--body", "1"]);
127
+ assert.equal((await runControl("unfreeze", ["--reason", "r"], base(w, { policy }))).ok, true);
128
+ assert.equal(w.vars[1][1], "delete");
129
+ });
130
+
131
+ it("I26: a dispatch with override_freeze or acknowledge_hotfix_revert is rejected", () => {
132
+ assert.throws(() => buildDispatchArgs({ workflow: "p.yml", repo: "o/r", ref: "main", inputs: { override_freeze: "true" } }), /break-glass/);
133
+ assert.throws(() => buildDispatchArgs({ workflow: "p.yml", repo: "o/r", ref: "main", inputs: { acknowledge_hotfix_revert: "1" } }), /break-glass/);
134
+ assert.deepEqual(buildDispatchArgs({ workflow: "p.yml", repo: "o/r", ref: "main", inputs: { forge_epoch: 2 } }), ["workflow", "run", "p.yml", "--repo", "o/r", "--ref", "main", "-f", "forge_epoch=2"]);
135
+ });
136
+
137
+ it("CLI: --json prints the stable schema; --repo is accepted; exit 1 on a refusal", async () => {
138
+ const w = world();
139
+ assert.equal(await controlFromCli("hold", [RID, "--repo", "o/r", "--reason", "r", "--json"], { io: w.io, actor: "op", host: "h" }), 0);
140
+ assert.equal(JSON.parse(w.out[0]).schema, CONTROL_SCHEMA);
141
+ assert.equal(await controlFromCli("hold", [RID, "--json"], { io: w.io }), 1);
142
+ });
143
+ });
@@ -0,0 +1,50 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Lease-epoch fencing (#5553, epic #5549 Phase 0, invariants I5/I7): every irreversible release action (merge, workflow
5
+ * dispatch, rerun, rollback, flag flip, intake release) re-reads `forge-ledger/_active`, aborts unless the lease is still this
6
+ * driver's epoch, records a write-ahead intent naming the epoch, re-checks immediately before acting, and hands the epoch to
7
+ * the effect so it travels with the action (`Forge-Epoch` merge trailer, `forge_epoch` dispatch input, comment marker).
8
+ * A host that cannot read `_active` performs nothing. Without a fence (unmanaged release) the effect just runs.
9
+ */
10
+ import { readActive } from "./release-ledger.mjs";
11
+ import { holdCheck } from "./release-control.mjs";
12
+
13
+ export const epochTrailer = (epoch) => `Forge-Epoch: ${epoch}`;
14
+ export const epochMarker = (epoch) => `<!-- FORGE:EPOCH ${epoch} -->`;
15
+
16
+ /** @returns {{ok: true, epoch} | {fenced: true, current} | {unreadable: string}} */
17
+ export async function fenceCheck(ctx, lease) {
18
+ let active;
19
+ try { active = await readActive(ctx); } catch (e) { return { unreadable: String(e?.message ?? e) }; }
20
+ if (active?.lease?.holder !== lease.holder || active?.lease?.epoch !== lease.epoch) return { fenced: true, current: active?.epoch ?? null };
21
+ return { ok: true, epoch: lease.epoch };
22
+ }
23
+
24
+ /** fenceCheck, then the hold flag of the lease's release (#5556, I24): `{refused}` or null. */
25
+ async function gate(ctx, lease) {
26
+ const c = await fenceCheck(ctx, lease);
27
+ if (!c.ok) return refusal(c, lease);
28
+ try { const h = await holdCheck(ctx, lease.release); return h ? `refused: ${h}` : null; } catch (e) { return refusal({ unreadable: String(e?.message ?? e) }, lease); }
29
+ }
30
+
31
+ const refusal = (c, lease) => (c.unreadable ? `refused: cannot read _active (${c.unreadable})` : `refused: fenced (epoch ${lease.epoch} is not current, ${c.current ?? "unknown"} is)`);
32
+
33
+ /**
34
+ * Run `effect(epoch)` only while `fence` ({lctx, lease, record, now}) is the current lease. `record` persists the intent before
35
+ * the effect (and its completion after). No fence: `effect(null)`.
36
+ * @returns {{ok: true, value} | {refused: string}} an effect error propagates
37
+ */
38
+ export async function fenced(fence, { action, key }, effect) {
39
+ if (!fence) return { ok: true, value: await effect(null) };
40
+ const { lctx, lease } = fence;
41
+ let why = await gate(lctx, lease);
42
+ if (why) return { refused: why };
43
+ const intent = { key, action, epoch: lease.epoch, holder: lease.holder, at: fence.now() };
44
+ await fence.record(intent);
45
+ why = await gate(lctx, lease); // the window between the first read and the intent write is where a takeover can slip in
46
+ if (why) return { refused: why };
47
+ const value = await effect(lease.epoch);
48
+ await fence.record({ ...intent, done: true });
49
+ return { ok: true, value };
50
+ }
@@ -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 { readFileSync } from "node:fs";
6
+ import { postMergeStep } from "./release-postmerge.mjs";
7
+ import { fenceCheck, fenced, epochTrailer, epochMarker } from "./release-fence.mjs";
8
+
9
+ const mkCtx = (active) => ({ repo: "o/r", credential: "driver", io: { api: async (_m, path) => {
10
+ if (!/contents\/active\.json\?ref=_active$/.test(path)) throw new Error(`unrouted ${path}`);
11
+ if (active.get() instanceof Error) throw active.get();
12
+ return { content: Buffer.from(JSON.stringify(active.get())).toString("base64") };
13
+ } } });
14
+ const cell = (v) => ({ v, get() { return this.v; } });
15
+ const act = (holder, epoch) => ({ epoch, lease: { holder, epoch } });
16
+ const LEASE = { holder: "A", epoch: 1 };
17
+ const mkFence = (active, rec = []) => ({ lctx: mkCtx(active), lease: LEASE, now: () => "t", record: async (r) => { rec.push(r); } });
18
+
19
+ describe("release fence (#5553)", () => {
20
+ it("fenceCheck: ok for the current lease, fenced after a takeover, unreadable when _active cannot be read", async () => {
21
+ const a = cell(act("A", 1)), ctx = mkCtx(a);
22
+ assert.deepEqual(await fenceCheck(ctx, LEASE), { ok: true, epoch: 1 });
23
+ a.v = act("B", 2);
24
+ assert.deepEqual(await fenceCheck(ctx, LEASE), { fenced: true, current: 2 });
25
+ a.v = new Error("HTTP 503");
26
+ assert.match((await fenceCheck(ctx, LEASE)).unreadable, /503/);
27
+ });
28
+
29
+ it("the intent is written before the effect, names the epoch, and the effect receives it", async () => {
30
+ const order = [], a = cell(act("A", 1)), f = mkFence(a);
31
+ f.record = async (r) => { order.push(`record:${r.action}:${r.epoch}:${!!r.done}`); };
32
+ const r = await fenced(f, { action: "merge", key: "k" }, async (e) => { order.push(`effect:${e}`); return "v"; });
33
+ assert.deepEqual(r, { ok: true, value: "v" });
34
+ assert.deepEqual(order, ["record:merge:1:false", "effect:1", "record:merge:1:true"]);
35
+ });
36
+
37
+ it("zombie: after a takeover the effect and the intent are never run", async () => {
38
+ const rec = [], a = cell(act("B", 2));
39
+ let ran = 0;
40
+ const r = await fenced(mkFence(a, rec), { action: "dispatch", key: "k" }, async () => { ran++; });
41
+ assert.match(r.refused, /fenced/);
42
+ assert.equal(ran, 0);
43
+ assert.equal(rec.length, 0);
44
+ });
45
+
46
+ it("a takeover that slips in between the first read and the intent write is caught by the re-check", async () => {
47
+ const a = cell(act("A", 1)), f = mkFence(a);
48
+ f.record = async () => { a.v = act("B", 2); };
49
+ let ran = 0;
50
+ assert.match((await fenced(f, { action: "merge", key: "k" }, async () => { ran++; })).refused, /fenced/);
51
+ assert.equal(ran, 0);
52
+ });
53
+
54
+ it("I5: an unreadable _active performs no irreversible action", async () => {
55
+ let ran = 0;
56
+ const r = await fenced(mkFence(cell(new Error("partition"))), { action: "rerun", key: "k" }, async () => { ran++; });
57
+ assert.match(r.refused, /cannot read _active/);
58
+ assert.equal(ran, 0);
59
+ });
60
+
61
+ it("#5556 I24: a held release performs no irreversible action", async () => {
62
+ let ran = 0;
63
+ const a = cell({ ...act("A", 1), holds: { r1: { reason: "incident" } } });
64
+ const f = mkFence(a); f.lease = { holder: "A", epoch: 1, release: "r1" };
65
+ const r = await fenced(f, { action: "merge", key: "k" }, async () => { ran++; });
66
+ assert.match(r.refused, /held \(incident\)/);
67
+ assert.equal(ran, 0);
68
+ });
69
+
70
+ it("without a fence (unmanaged release) the effect just runs with no epoch", async () => {
71
+ assert.deepEqual(await fenced(null, { action: "merge", key: "k" }, async (e) => e), { ok: true, value: null });
72
+ });
73
+
74
+ it("the epoch carriers", () => {
75
+ assert.equal(epochTrailer(3), "Forge-Epoch: 3");
76
+ assert.equal(epochMarker(3), "<!-- FORGE:EPOCH 3 -->");
77
+ });
78
+
79
+ it("publish.yml accepts forge_epoch and rejects a stale one as its first step", () => {
80
+ const y = readFileSync(new URL("../../.github/workflows/publish.yml", import.meta.url), "utf8");
81
+ assert.match(y, /workflow_dispatch:[^\n]*\n\s+inputs:\n\s+forge_epoch:/);
82
+ assert.match(y, / steps:\n - name: Reject a stale forge_epoch/);
83
+ assert.match(y, /ref=_active/);
84
+ });
85
+
86
+ it("post-merge dispatch carries forge_epoch; a fenced host dispatches nothing", async () => {
87
+ const run = async (active) => {
88
+ const calls = []; let listed = 0;
89
+ const io = { print() {}, sleep: async () => {}, gh: async (a) => {
90
+ calls.push(a);
91
+ if (a[0] === "pr" && a[1] === "view") return JSON.stringify({ state: "MERGED", mergeCommit: { oid: "m".repeat(40) } });
92
+ if (a[0] === "run" && a[1] === "list") return JSON.stringify(++listed <= 2 ? [] : [{ databaseId: 5, status: "completed", conclusion: "success" }]);
93
+ return "";
94
+ } };
95
+ const ctx = { io, repo: "o/r", def: "main", staging: "staging", config: { postMerge: { publishPolls: 2, runPolls: 2 } }, state: { steps: { "release-pr": { result: { pr: 7 } } } }, fence: mkFence(cell(active)) };
96
+ return { out: await postMergeStep(ctx), calls };
97
+ };
98
+ const good = await run(act("A", 1));
99
+ assert.equal(good.out.published, true);
100
+ assert.deepEqual(good.calls.find((a) => a[0] === "workflow").slice(-2), ["-f", "forge_epoch=1"]);
101
+ const zombie = await run(act("B", 2));
102
+ assert.equal(zombie.out.blocked, true);
103
+ assert.equal(zombie.calls.some((a) => a[0] === "workflow"), false);
104
+ });
105
+ });
@@ -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
+ });