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.
- package/bin/config-schema.mjs +1 -1
- package/bin/engine/outcome-codes.mjs +2 -1
- package/bin/engine/phases.mjs +4 -3
- package/bin/engine-cli.mjs +48 -12
- package/bin/forgedock.mjs +52 -3
- package/bin/gc.mjs +43 -6
- package/bin/help-text.mjs +4 -2
- package/bin/lean/batch-health.mjs +5 -1
- package/bin/lean/batch-health.test.mjs +7 -1
- package/bin/lean/batch.mjs +7 -2
- package/bin/lean/batch.test.mjs +45 -0
- package/bin/lean/conformance.e2e.test.mjs +3 -2
- package/bin/lean/conformance.mjs +118 -20
- package/bin/lean/conformance.test.mjs +172 -3
- package/bin/lean/decisions.mjs +98 -1
- package/bin/lean/decisions.test.mjs +30 -1
- package/bin/lean/depcache.mjs +124 -13
- package/bin/lean/depcache.test.mjs +121 -3
- package/bin/lean/design-gate.mjs +144 -0
- package/bin/lean/design-gate.test.mjs +169 -0
- package/bin/lean/effects-cap.test.mjs +17 -0
- package/bin/lean/effects.mjs +58 -13
- package/bin/lean/heavy.mjs +25 -8
- package/bin/lean/hostload.test.mjs +28 -0
- package/bin/lean/intake.mjs +97 -0
- package/bin/lean/intake.test.mjs +105 -0
- package/bin/lean/interfaces.mjs +181 -0
- package/bin/lean/interfaces.test.mjs +192 -0
- package/bin/lean/issuewatch-install.mjs +52 -12
- package/bin/lean/issuewatch-install.test.mjs +50 -0
- package/bin/lean/issuewatch-parity.mjs +16 -3
- package/bin/lean/issuewatch-parity.test.mjs +32 -0
- package/bin/lean/issuewatch-reconcile.mjs +29 -1
- package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
- package/bin/lean/issuewatch.mjs +34 -3
- package/bin/lean/issuewatch.test.mjs +49 -1
- package/bin/lean/lanecheck.test.mjs +15 -4
- package/bin/lean/lean.mjs +110 -24
- package/bin/lean/lean.test.mjs +183 -4
- package/bin/lean/orchestrate-blocked.test.mjs +18 -2
- package/bin/lean/orchestrate-owned.test.mjs +14 -5
- package/bin/lean/orchestrate.mjs +26 -4
- package/bin/lean/orphan-pr.mjs +3 -2
- package/bin/lean/orphan-pr.test.mjs +8 -1
- package/bin/lean/pagegate.mjs +35 -12
- package/bin/lean/pagegate.test.mjs +39 -1
- package/bin/lean/preflight.mjs +35 -1
- package/bin/lean/preflight.test.mjs +27 -1
- package/bin/lean/prompts.mjs +2 -1
- package/bin/lean/reap.test.mjs +39 -0
- package/bin/lean/recovery.test.mjs +28 -3
- package/bin/lean/release-config.mjs +169 -0
- package/bin/lean/release-config.test.mjs +132 -0
- package/bin/lean/release-control.mjs +171 -0
- package/bin/lean/release-control.test.mjs +167 -0
- package/bin/lean/release-deploy.mjs +209 -0
- package/bin/lean/release-deploy.test.mjs +217 -0
- package/bin/lean/release-fence.mjs +50 -0
- package/bin/lean/release-fence.test.mjs +105 -0
- package/bin/lean/release-flakes.mjs +139 -0
- package/bin/lean/release-flakes.test.mjs +116 -0
- package/bin/lean/release-gates.mjs +230 -0
- package/bin/lean/release-gates.test.mjs +146 -0
- package/bin/lean/release-ledger.mjs +176 -0
- package/bin/lean/release-ledger.test.mjs +226 -0
- package/bin/lean/release-minutes.mjs +102 -0
- package/bin/lean/release-minutes.test.mjs +107 -0
- package/bin/lean/release-nightly.mjs +75 -0
- package/bin/lean/release-nightly.test.mjs +48 -0
- package/bin/lean/release-postmerge.mjs +8 -2
- package/bin/lean/release-review.e2e.test.mjs +1 -0
- package/bin/lean/release-review.mjs +54 -7
- package/bin/lean/release-review.test.mjs +76 -7
- package/bin/lean/release-status.mjs +300 -0
- package/bin/lean/release-status.test.mjs +220 -0
- package/bin/lean/release-unitmap.mjs +35 -0
- package/bin/lean/release-unitmap.test.mjs +41 -0
- package/bin/lean/release-verify.mjs +221 -0
- package/bin/lean/release-verify.test.mjs +176 -0
- package/bin/lean/release.mjs +244 -22
- package/bin/lean/release.test.mjs +44 -0
- package/bin/lean/render.mjs +3 -1
- package/bin/lean/run-issue-placement.test.mjs +82 -0
- package/bin/lean/sandbox-remote.mjs +16 -0
- package/bin/lean/schedd.mjs +1 -1
- package/bin/lean/seam.mjs +115 -0
- package/bin/lean/seam.test.mjs +118 -0
- package/bin/lean/selftest-journey.mjs +40 -2
- package/bin/lean/selftest-journey.test.mjs +43 -3
- package/bin/lean/statuscomment.mjs +168 -0
- package/bin/lean/statuscomment.test.mjs +133 -0
- package/bin/lean/ui-quality.mjs +57 -0
- package/bin/lean/ui-quality.test.mjs +55 -0
- package/bin/lean/visual-gate.test.mjs +63 -0
- package/bin/pool/agent.mjs +16 -2
- package/bin/pool/router.mjs +5 -1
- package/bin/review-staging.mjs +5 -3
- package/bin/stats/card.mjs +117 -0
- package/bin/stats/card.test.mjs +109 -0
- package/bin/stats/conformance-outcomes.test.mjs +2 -1
- package/bin/stats/depth.mjs +1 -1
- package/bin/stats/gh-retry.test.mjs +152 -0
- package/bin/stats/github-source.mjs +147 -14
- package/bin/stats/index.mjs +35 -2
- package/bin/stats/stats.test.mjs +31 -3
- package/bin/vendor/js-yaml/LICENSE +21 -0
- package/bin/vendor/js-yaml/PIN.md +7 -0
- package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
- package/commands/design-render-critique-loop.md +2 -0
- package/commands/design.md +2 -0
- package/commands/issue.md +1 -1
- package/commands/milestone.md +1 -1
- package/commands/review-pr-agents/frontend.md +1 -0
- package/commands/review-pr-staging.md +5 -0
- package/docs/CONFIG.md +95 -2
- package/docs/ISSUE-WATCH.md +7 -0
- package/docs/OUTCOME-CODES.md +1 -0
- package/docs/STATS.md +10 -0
- package/docs/design/visual-gate.md +25 -0
- package/docs/eval/adversarial-bench.md +2 -2
- package/docs/eval/corpus/adversarial-v1.json +3 -3
- package/docs/site/start-a-new-project.md +7 -0
- package/docs/spec/forge-protocol-v1.md +31 -0
- package/package.json +1 -1
- package/pool/README.md +2 -0
- package/scripts/acceptance-red-green.sh +15 -1
- package/scripts/acceptance-red-green.test.sh +12 -0
- package/scripts/bench-adversarial.mjs +4 -0
- package/scripts/bench-lightlane.mjs +4 -1
- package/scripts/bootstrap-create.mjs +8 -2
- package/scripts/ci-local/scoping.mjs +19 -0
- package/scripts/ci-local.test.sh +16 -3
- package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
- package/scripts/plan-validate-live.mjs +9 -6
- package/scripts/review-prepare.sh +7 -1
- package/scripts/review-roster.sh +5 -2
- package/scripts/review-roster.test.sh +9 -0
- package/scripts/visual-gate.mjs +64 -0
- package/templates/bootstrap/technical-spike.md +17 -0
- package/templates/contracts/seam-check.mjs +236 -0
|
@@ -0,0 +1,226 @@
|
|
|
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 { createReleaseLedger, writeRelease, readLedger, updateActive, acquireLease, heartbeat, acceptWrite, redactDeep, ACTIVE, ACTIVE_RETRIES } from "./release-ledger.mjs";
|
|
7
|
+
import { runRelease, withStubs, RELEASE_STEPS } from "./release.mjs";
|
|
8
|
+
|
|
9
|
+
const REPO = "o/r", ID = "r20261112-101500-42", DISK = [{ mount: "/", type: "ext4" }];
|
|
10
|
+
const err = (status, m) => Object.assign(new Error(m ?? `HTTP ${status}`), { status });
|
|
11
|
+
|
|
12
|
+
/** In-memory GitHub: refs, commits (tree = file map), comments. `meta` tunes the author the next commits get. */
|
|
13
|
+
function fakeGh(meta = {}) {
|
|
14
|
+
const refs = new Map(), commits = new Map(), trees = new Map(), comments = new Map();
|
|
15
|
+
const g = { refs, commits, trees, comments, calls: [], meta: { id: 1, verified: true, ...meta }, now: 1_000_000, hooks: {} };
|
|
16
|
+
let n = 0;
|
|
17
|
+
g.api = async (method, path, body) => {
|
|
18
|
+
g.calls.push(`${method} ${path}`);
|
|
19
|
+
await g.hooks.before?.(method, path);
|
|
20
|
+
let m;
|
|
21
|
+
if ((m = /git\/ref\/heads\/(.+)$/.exec(path))) { if (!refs.has(m[1])) throw err(404); return { object: { sha: refs.get(m[1]) } }; }
|
|
22
|
+
if ((m = /git\/commits\/(\w+)$/.exec(path))) return { tree: { sha: commits.get(m[1]).tree } };
|
|
23
|
+
if (method === "POST" && /git\/trees$/.test(path)) { const files = { ...(trees.get(body.base_tree) ?? {}) }; for (const e of body.tree) files[e.path] = e.content; const sha = `t${++n}`; trees.set(sha, files); return { sha }; }
|
|
24
|
+
if (method === "POST" && /git\/commits$/.test(path)) { const sha = `c${++n}`; commits.set(sha, { tree: body.tree, parents: body.parents, author: g.meta.id, verified: g.meta.verified }); return { sha }; }
|
|
25
|
+
if (method === "POST" && /git\/refs$/.test(path)) { const b = body.ref.replace("refs/heads/", ""); if (refs.has(b)) throw err(422, "Reference already exists"); refs.set(b, body.sha); return {}; }
|
|
26
|
+
if (method === "PATCH" && (m = /git\/refs\/heads\/(.+)$/.exec(path))) { if (commits.get(body.sha).parents[0] !== refs.get(m[1]) || body.force) throw err(422, "Update is not a fast forward"); refs.set(m[1], body.sha); return {}; }
|
|
27
|
+
if ((m = /contents\/([^?]+)\?ref=(.+)$/.exec(path))) { const f = trees.get(commits.get(refs.get(decodeURIComponent(m[2]))).tree)[m[1]]; if (f === undefined) throw err(404); return { content: Buffer.from(f).toString("base64") }; }
|
|
28
|
+
if ((m = /\/commits\/(\w+)$/.exec(path))) { const c = commits.get(m[1]); return { author: { id: c.author, login: `u${c.author}` }, commit: { verification: { verified: c.verified } } }; }
|
|
29
|
+
if (method === "POST" && /issues\/\d+\/comments$/.test(path)) { const id = ++n; comments.set(id, { body: body.body, updated_at: new Date(g.now).toISOString() }); return { id }; }
|
|
30
|
+
if (method === "PATCH" && (m = /issues\/comments\/(\d+)$/.exec(path))) { comments.set(Number(m[1]), { body: body.body, updated_at: new Date(g.now).toISOString() }); return {}; }
|
|
31
|
+
if ((m = /issues\/comments\/(\d+)$/.exec(path))) { if (!comments.has(Number(m[1]))) throw err(404); return comments.get(Number(m[1])); }
|
|
32
|
+
throw new Error(`unrouted ${method} ${path}`);
|
|
33
|
+
};
|
|
34
|
+
return g;
|
|
35
|
+
}
|
|
36
|
+
const ctxOf = (g, credential = "driver") => ({ io: { api: g.api }, repo: REPO, credential });
|
|
37
|
+
const POLICY = { allowlist: [1], driverIds: [1] };
|
|
38
|
+
|
|
39
|
+
describe("release ledger (#5550)", () => {
|
|
40
|
+
it("createReleaseLedger makes an orphan branch; a second create loses; the head is read back", async () => {
|
|
41
|
+
const g = fakeGh(), c = ctxOf(g);
|
|
42
|
+
const a = await createReleaseLedger(c, ID, { v: 1, id: ID, steps: {} });
|
|
43
|
+
assert.ok(a.ok);
|
|
44
|
+
assert.deepEqual(g.commits.get(a.sha).parents, []);
|
|
45
|
+
assert.ok((await createReleaseLedger(c, ID, { v: 1 })).lost);
|
|
46
|
+
assert.deepEqual((await readLedger(c, ID, POLICY)).state, { v: 1, id: ID, steps: {} });
|
|
47
|
+
assert.equal(await readLedger(c, "r20261112-101500-43"), null);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("writeRelease is compare-and-swap: a stale head loses", async () => {
|
|
51
|
+
const g = fakeGh(), c = ctxOf(g);
|
|
52
|
+
const a = await createReleaseLedger(c, ID, { n: 1 });
|
|
53
|
+
assert.ok((await writeRelease(c, ID, { n: 2 }, a.sha)).ok);
|
|
54
|
+
assert.ok((await writeRelease(c, ID, { n: 3 }, a.sha)).lost);
|
|
55
|
+
assert.equal((await readLedger(c, ID)).state.n, 2);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it("I6: two drivers race for the lease, exactly one wins", async () => {
|
|
59
|
+
const g = fakeGh(), c = ctxOf(g);
|
|
60
|
+
const out = await Promise.all(["hostA", "hostB"].map((holder) => acquireLease(c, { holder, release: ID, issue: 9, now: g.now })));
|
|
61
|
+
assert.equal(out.filter((r) => r.ok).length, 1);
|
|
62
|
+
const loser = out.find((r) => !r.ok);
|
|
63
|
+
assert.match(loser.refused, /lease held by/);
|
|
64
|
+
const win = out.find((r) => r.ok).lease;
|
|
65
|
+
assert.equal(win.epoch, 1);
|
|
66
|
+
assert.equal(win.expires, g.now + 120_000); // #5553: {holder, epoch, expires}
|
|
67
|
+
assert.ok(win.commentId);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("a lease whose heartbeat comment is older than the ttl is taken over with a higher epoch", async () => {
|
|
71
|
+
const g = fakeGh(), c = ctxOf(g);
|
|
72
|
+
assert.ok((await acquireLease(c, { holder: "A", release: ID, issue: 9, ttlS: 60, now: g.now })).ok);
|
|
73
|
+
assert.match((await acquireLease(c, { holder: "B", release: ID, issue: 9, now: g.now + 30_000 })).refused, /held by A/);
|
|
74
|
+
const t = await acquireLease(c, { holder: "B", release: ID, issue: 9, now: g.now + 61_000 });
|
|
75
|
+
assert.equal(t.lease.epoch, 2);
|
|
76
|
+
assert.equal(t.lease.holder, "B");
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it("heartbeat edits the FORGE:LEASE comment and makes no commit; a superseded holder is fenced", async () => {
|
|
80
|
+
const g = fakeGh(), c = ctxOf(g);
|
|
81
|
+
const { lease } = await acquireLease(c, { holder: "A", release: ID, issue: 9, ttlS: 60, now: g.now });
|
|
82
|
+
const commitsBefore = g.commits.size;
|
|
83
|
+
g.now += 10_000;
|
|
84
|
+
assert.ok((await heartbeat(c, lease)).ok);
|
|
85
|
+
assert.equal(g.commits.size, commitsBefore);
|
|
86
|
+
assert.match(g.comments.get(lease.commentId).body, /FORGE:LEASE/);
|
|
87
|
+
assert.equal(g.comments.get(lease.commentId).updated_at, new Date(g.now).toISOString());
|
|
88
|
+
await acquireLease(c, { holder: "B", release: ID, issue: 9, now: g.now + 61_000 });
|
|
89
|
+
assert.ok((await heartbeat(c, lease)).fenced);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it("updateActive is key-scoped, appends controls.jsonl, and retries a lost race up to 5 times", async () => {
|
|
93
|
+
const g = fakeGh(), c = ctxOf(g);
|
|
94
|
+
const r = await updateActive(c, ["pause"], () => ({ patch: { pause: true, epoch: 99 }, control: { verb: "pause" } }));
|
|
95
|
+
assert.deepEqual(r.active, { pause: true }); // epoch is not an owned key
|
|
96
|
+
await updateActive(c, ["pause"], () => ({ patch: { pause: false }, control: { verb: "resume" } }));
|
|
97
|
+
assert.equal(g.trees.get(g.commits.get(g.refs.get(ACTIVE)).tree)["controls.jsonl"].trim().split("\n").length, 2);
|
|
98
|
+
// one lost race then success
|
|
99
|
+
let lose = 1;
|
|
100
|
+
g.hooks.before = async (m, p) => { if (lose > 0 && m === "PATCH" && p.includes("git/refs")) { lose--; g.refs.set(ACTIVE, (await (async () => { const s = await commitHead(g); return s; })())); } };
|
|
101
|
+
const ok = await updateActive(c, ["holds"], () => ({ patch: { holds: ["x"] } }));
|
|
102
|
+
assert.ok(ok.ok);
|
|
103
|
+
// always losing: stops at the bound
|
|
104
|
+
let attempts = 0;
|
|
105
|
+
g.hooks.before = async (m, p) => { if (m === "PATCH" && p.includes("git/refs")) { attempts++; g.refs.set(ACTIVE, await commitHead(g)); } };
|
|
106
|
+
const bad = await updateActive(c, ["holds"], () => ({ patch: { holds: ["y"] } }));
|
|
107
|
+
assert.deepEqual(bad, { lost: true, attempts: ACTIVE_RETRIES });
|
|
108
|
+
assert.equal(attempts, ACTIVE_RETRIES);
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it("forged writes are rejected: lane credential, unverified commit, non-allowlisted actor", async () => {
|
|
112
|
+
const g = fakeGh();
|
|
113
|
+
await assert.rejects(() => createReleaseLedger(ctxOf(g, "lane"), ID, {}), /driver credential/);
|
|
114
|
+
assert.equal(g.refs.size, 0);
|
|
115
|
+
const c = ctxOf(g);
|
|
116
|
+
g.meta.verified = false; await createReleaseLedger(c, ID, { a: 1 });
|
|
117
|
+
assert.match((await readLedger(c, ID, POLICY)).rejected, /unverified/);
|
|
118
|
+
const g2 = fakeGh({ id: 7 }); await createReleaseLedger(ctxOf(g2), ID, { a: 1 });
|
|
119
|
+
assert.match((await readLedger(ctxOf(g2), ID, POLICY)).rejected, /not allowlisted/);
|
|
120
|
+
const g3 = fakeGh({ id: 2 }); await createReleaseLedger(ctxOf(g3), ID, { a: 1 });
|
|
121
|
+
assert.match((await readLedger(ctxOf(g3), ID, { allowlist: [1, 2], driverIds: [1] })).rejected, /not the driver credential/);
|
|
122
|
+
assert.ok(acceptWrite({ author: { id: 1 }, commit: { verification: { verified: true } } }, POLICY).ok);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it("I21: seeded secret-shaped strings never reach a commit", async () => {
|
|
126
|
+
const g = fakeGh(), c = ctxOf(g);
|
|
127
|
+
const tok = "ghp_" + "a".repeat(30);
|
|
128
|
+
await createReleaseLedger(c, ID, { note: `pushed with ${tok}`, env: { API_KEY: "hunter2hunter2" }, line: "GITHUB_TOKEN=abc123def456" });
|
|
129
|
+
await updateActive(c, ["pause"], () => ({ patch: { pause: tok }, control: { why: `Bearer ${"z".repeat(20)}` } }));
|
|
130
|
+
assert.ok(g.trees.size >= 2);
|
|
131
|
+
for (const files of g.trees.values()) assert.doesNotMatch(JSON.stringify(files), /ghp_a|hunter2|abc123def456|zzzzzzzzzz/);
|
|
132
|
+
assert.deepEqual(redactDeep({ TOKEN: "x" }), { TOKEN: "[redacted]" });
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it("kill -9 resume: a second host continues the release from the ledger, not its own disk", async () => {
|
|
136
|
+
const g = fakeGh(), seen = [];
|
|
137
|
+
const mkIo = () => ({ print() {}, now: () => 1_700_000_000_000, runningLanes: async () => [], batches: async () => [], setParallel: async () => {}, gh: async () => { throw new Error("no gh"); }, api: g.api });
|
|
138
|
+
const step = (name, die) => async () => { if (die) throw new Error("kill -9"); seen.push(name); return {}; };
|
|
139
|
+
const all = (dieAt) => ({ preflight: step("preflight"), "host-preflight": async () => ({ skipped: true }), deploy: async () => ({ skipped: true }), "release-pr": async () => { if (dieAt === "release-pr") throw new Error("kill -9"); seen.push("release-pr"); return { pr: 7 }; }, review: step("review"), fixes: step("fixes"), "mark-ready": async () => ({ skipped: true }), rehearsal: async () => ({ skipped: true }), promotion: step("promotion"), "post-merge": step("post-merge") });
|
|
140
|
+
const run = (io, dieAt, root) => runRelease({ io, repo: REPO, root, mounts: DISK, id: ID, opts: {}, config: { managed: true }, branches: {}, steps: all(dieAt) });
|
|
141
|
+
await assert.rejects(() => run(mkIo(), "release-pr", tmpDir("ledgerA-")), /kill -9/);
|
|
142
|
+
assert.deepEqual(seen, ["preflight"]);
|
|
143
|
+
const out = await run(mkIo(), null, tmpDir("ledgerB-")); // host B: empty disk
|
|
144
|
+
assert.equal(out.status, "done");
|
|
145
|
+
assert.deepEqual(seen, ["preflight", "release-pr", "review", "fixes", "promotion", "post-merge"]);
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
async function commitHead(g) { // a foreign writer commits on top of the current head: the next ref update loses
|
|
150
|
+
const sha = `foreign${g.commits.size}`;
|
|
151
|
+
g.commits.set(sha, { tree: g.commits.get(g.refs.get(ACTIVE)).tree, parents: [g.refs.get(ACTIVE)], author: 1, verified: true });
|
|
152
|
+
return sha;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
describe("release fencing through the job (#5553)", () => {
|
|
156
|
+
const HEAD = "a".repeat(40);
|
|
157
|
+
const mkIo = (g, holder, calls) => ({ holder, print() {}, now: () => 1_700_000_000_000, sleep: async () => {}, runningLanes: async () => [], batches: async () => [], setParallel: async () => {}, api: g.api,
|
|
158
|
+
gh: async (a) => {
|
|
159
|
+
const j = a.join(" ");
|
|
160
|
+
if (a[0] === "pr" && a[1] === "view") return JSON.stringify({ state: calls.some((c) => c[1] === "merge") ? "MERGED" : "OPEN", mergeCommit: calls.some((c) => c[1] === "merge") ? { oid: "m".repeat(40) } : null, headRefOid: HEAD, comments: [{ body: "FORGE:GATE_PASS" }] });
|
|
161
|
+
if (a[0] === "api") return JSON.stringify([{ name: "forge/deploy-gate", conclusion: "success" }]);
|
|
162
|
+
if (a[0] === "pr" && a[1] === "merge") { calls.push(a); return ""; }
|
|
163
|
+
throw new Error(`unexpected gh ${j}`);
|
|
164
|
+
} });
|
|
165
|
+
const skip = async () => ({ skipped: true }), ok = async () => ({});
|
|
166
|
+
const steps = (over = {}) => withStubs({ preflight: ok, "host-preflight": skip, "release-pr": async () => ({ pr: 7 }), review: ok, fixes: ok, "mark-ready": skip, rehearsal: skip, "post-merge": ok, ...over });
|
|
167
|
+
const go = (io, st, root) => runRelease({ io, repo: REPO, root, mounts: DISK, id: ID, opts: { merge: true }, config: { managed: true }, branches: { staging: "staging", default: "main" }, steps: st ?? steps() });
|
|
168
|
+
|
|
169
|
+
it("the job takes the lease after release-pr and the merge carries the Forge-Epoch trailer and a write-ahead intent", async () => {
|
|
170
|
+
const g = fakeGh(), calls = [];
|
|
171
|
+
const out = await go(mkIo(g, "hostA", calls), null, tmpDir("fa-"));
|
|
172
|
+
assert.equal(out.status, "done");
|
|
173
|
+
assert.equal(calls.length, 1);
|
|
174
|
+
assert.deepEqual(calls[0].slice(-2), ["--body", "Forge-Epoch: 1"]);
|
|
175
|
+
const st = (await readLedger(ctxOf(g), ID)).state;
|
|
176
|
+
assert.deepEqual(st.intents.map((i) => [i.action, i.epoch, i.done]), [["merge", 1, true]]);
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it("I7 zombie: a host paused after takeover wakes and is refused; no merge is issued", async () => {
|
|
180
|
+
const g = fakeGh(), calls = [];
|
|
181
|
+
let takeover = false;
|
|
182
|
+
const zombie = steps({ review: async () => { // host A "pauses" here; host B takes the lease over while it sleeps
|
|
183
|
+
g.now += 600_000; takeover = (await acquireLease(ctxOf(g), { holder: "hostB", release: ID, issue: 7, now: g.now })).ok; return {}; } });
|
|
184
|
+
const out = await go(mkIo(g, "hostA", calls), zombie, tmpDir("fz-"));
|
|
185
|
+
assert.ok(takeover);
|
|
186
|
+
assert.equal(out.status, "refused");
|
|
187
|
+
assert.match(out.reason, /fenced/);
|
|
188
|
+
assert.equal(calls.length, 0);
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
it("I5: when _active cannot be read, the merge is not issued", async () => {
|
|
192
|
+
const g = fakeGh(), calls = [];
|
|
193
|
+
const io = mkIo(g, "hostA", calls);
|
|
194
|
+
let armed = false;
|
|
195
|
+
const base = g.api;
|
|
196
|
+
io.api = async (m, path, b) => { if (armed && /contents\/active\.json/.test(path)) throw new Error("network partition"); return base(m, path, b); };
|
|
197
|
+
const out = await go(io, steps({ review: async () => { armed = true; return {}; } }), tmpDir("fp-"));
|
|
198
|
+
assert.equal(out.status, "refused");
|
|
199
|
+
assert.match(out.reason, /cannot read _active/);
|
|
200
|
+
assert.equal(calls.length, 0);
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
it("kill -9 at the step boundary after the merge: the resumed run does not merge again", async () => {
|
|
204
|
+
const g = fakeGh(), calls = [];
|
|
205
|
+
const die = steps({ "post-merge": async () => { throw new Error("kill -9"); } });
|
|
206
|
+
await assert.rejects(() => go(mkIo(g, "hostA", calls), die, tmpDir("fk1-")), /kill -9/);
|
|
207
|
+
assert.equal(calls.length, 1);
|
|
208
|
+
const out = await go(mkIo(g, "hostA", calls), null, tmpDir("fk2-")); // same host or another: the PR is observed MERGED
|
|
209
|
+
assert.equal(out.status, "done");
|
|
210
|
+
assert.equal(calls.length, 1);
|
|
211
|
+
});
|
|
212
|
+
it("kill -9 at every step boundary: the resumed run repeats no completed step and merges exactly once", async () => {
|
|
213
|
+
for (const dieAt of RELEASE_STEPS) {
|
|
214
|
+
const g = fakeGh(), calls = [], ran = [];
|
|
215
|
+
const track = (name, fn) => async (...a) => { if (name === dieAt && !ran.includes(`die:${name}`)) { ran.push(`die:${name}`); throw new Error("kill -9"); } ran.push(name); return fn(...a); };
|
|
216
|
+
const base = { preflight: ok, "host-preflight": skip, "release-pr": async () => ({ pr: 7 }), review: ok, fixes: ok, "mark-ready": skip, rehearsal: skip, "post-merge": ok, deploy: skip };
|
|
217
|
+
const wrapped = withStubs(Object.fromEntries(Object.entries(withStubs(base)).map(([k, fn]) => [k, track(k, fn)])));
|
|
218
|
+
await assert.rejects(() => go(mkIo(g, "hostA", calls), wrapped, tmpDir("fe1-")), /kill -9/, dieAt);
|
|
219
|
+
const out = await go(mkIo(g, "hostB", calls), wrapped, tmpDir("fe2-")); // another host, empty disk
|
|
220
|
+
assert.equal(out.status, "done", dieAt);
|
|
221
|
+
assert.equal(calls.length, 1, `${dieAt}: one merge`);
|
|
222
|
+
const done = ran.filter((r) => !r.startsWith("die:") && !["host-preflight", "mark-ready", "rehearsal", "deploy"].includes(r)); // unconfigured steps leave no trace and may re-run
|
|
223
|
+
assert.equal(new Set(done).size, done.length, `${dieAt}: no step ran twice (${done})`);
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
});
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Actions minutes per release (#5569, epic #5549 5.8): minutes = sum of ceil(job minutes) from the jobs API (billable_ms is 0 on
|
|
5
|
+
* some repos, so it is ignored), recorded in the release state (mirrored to the ledger when managed); the forecast is the lane's
|
|
6
|
+
* trailing median; `budget.on_exceed` (local-first | hold | proceed) is applied at the gate before the release starts. p0 is never
|
|
7
|
+
* blocked (I14). The monthly model report and its 25% check are pure. Used only when `release.managed`.
|
|
8
|
+
*/
|
|
9
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
|
|
12
|
+
export const ON_EXCEED = Object.freeze(["local-first", "hold", "proceed"]);
|
|
13
|
+
export const MODEL_TOLERANCE = 0.25;
|
|
14
|
+
const json = (s) => { try { return JSON.parse(String(s)); } catch { return null; } };
|
|
15
|
+
|
|
16
|
+
/** forge.yaml `budget:` -> {onExceed, ignore}; junk falls back to local-first. `ignore: true` (lane config `budget: ignore`) never blocks. */
|
|
17
|
+
export function parseBudgetConfig(sec) {
|
|
18
|
+
const s = sec && typeof sec === "object" ? sec : {};
|
|
19
|
+
const v = String(s.on_exceed ?? "").trim().toLowerCase();
|
|
20
|
+
return { onExceed: ON_EXCEED.includes(v) ? v : "local-first", modelPerRelease: Number(s.model_release_minutes) > 0 ? Number(s.model_release_minutes) : 500, ignore: String(s.ignore ?? "").trim().toLowerCase() === "true" };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Sum of ceil(minutes) over the jobs of a jobs-API payload (jobs without both timestamps count 0). */
|
|
24
|
+
export function jobMinutes(payload) {
|
|
25
|
+
let total = 0;
|
|
26
|
+
for (const j of payload?.jobs ?? []) {
|
|
27
|
+
const ms = Date.parse(j.completed_at) - Date.parse(j.started_at);
|
|
28
|
+
if (ms > 0) total += Math.ceil(ms / 60_000);
|
|
29
|
+
}
|
|
30
|
+
return total;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Minutes of the runs created since `sinceMs` (optionally one branch), from the jobs API; null when the runs are unreadable. */
|
|
34
|
+
export async function releaseMinutes({ gh, repo, sinceMs, branch = null }) {
|
|
35
|
+
const q = `repos/${repo}/actions/runs?per_page=100&created=>=${new Date(sinceMs).toISOString()}${branch ? `&branch=${encodeURIComponent(branch)}` : ""}`;
|
|
36
|
+
const runs = json(await gh(["api", q]))?.workflow_runs;
|
|
37
|
+
if (!Array.isArray(runs)) return null;
|
|
38
|
+
let minutes = 0;
|
|
39
|
+
for (const r of runs) minutes += jobMinutes(json(await gh(["api", `repos/${repo}/actions/runs/${r.id}/jobs?per_page=100`])));
|
|
40
|
+
return { runs: runs.length, minutes };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Records `{lane, minutes}` of the finished releases kept under `root` (the local cache of the ledger states); the array's non-enumerable `gates` property carries the #5583 gate records (see gateHistoryFromRoot). */
|
|
44
|
+
export function historyFromRoot(root) {
|
|
45
|
+
if (!existsSync(root)) return Object.defineProperty([], "gates", { value: [], enumerable: false });
|
|
46
|
+
const out = [];
|
|
47
|
+
for (const id of readdirSync(root)) {
|
|
48
|
+
try { const s = JSON.parse(readFileSync(join(root, id, "state.json"), "utf8")); if (s?.minutes?.total > 0) out.push({ lane: s.lane ?? "release", minutes: s.minutes.total }); } catch { /* skip */ }
|
|
49
|
+
}
|
|
50
|
+
return Object.defineProperty(out, "gates", { value: gateHistoryFromRoot(root), enumerable: false });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Gate telemetry records (#5583) of the releases kept under `root`, oldest release first, each with `release` and `at`; [] when none. */
|
|
54
|
+
export function gateHistoryFromRoot(root) {
|
|
55
|
+
if (!existsSync(root)) return [];
|
|
56
|
+
const out = [];
|
|
57
|
+
for (const id of readdirSync(root).sort()) {
|
|
58
|
+
try { const s = JSON.parse(readFileSync(join(root, id, "state.json"), "utf8")); for (const g of Array.isArray(s?.gates) ? s.gates : []) out.push({ ...g, release: id, at: s.startedAt }); } catch { /* skip */ }
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Median of the last `n` records of `lane`; null with no history. */
|
|
64
|
+
export function trailingMedian(records, lane = "release", n = 5) {
|
|
65
|
+
const v = records.filter((r) => (r.lane ?? "release") === lane).slice(-n).map((r) => r.minutes).sort((a, b) => a - b);
|
|
66
|
+
if (!v.length) return null;
|
|
67
|
+
const m = v.length >> 1;
|
|
68
|
+
return v.length % 2 ? v[m] : (v[m - 1] + v[m]) / 2;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The action at the gate: `proceed` when p0, budget ignored, forecast unknown or it fits `remaining`; else the configured `onExceed`.
|
|
73
|
+
* @returns {{action: "proceed"|"local-first"|"hold", why}}
|
|
74
|
+
*/
|
|
75
|
+
export function applyOnExceed({ lane = "release", forecast, remaining, cfg }) {
|
|
76
|
+
if (lane === "p0" || cfg?.ignore) return { action: "proceed", why: lane === "p0" ? "p0 is never blocked by budget" : "budget ignored" };
|
|
77
|
+
if (forecast == null || remaining == null) return { action: "proceed", why: "no forecast or budget known" };
|
|
78
|
+
if (forecast <= remaining) return { action: "proceed", why: `forecast ${forecast} min within ${Math.round(remaining)} min left` };
|
|
79
|
+
return { action: cfg?.onExceed ?? "local-first", why: `forecast ${forecast} min exceeds ${Math.round(remaining)} min left` };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** True when the measured minutes are within `tol` of the model's (the 25% exit criterion of 5.8). */
|
|
83
|
+
export const withinTolerance = (model, measured, tol = MODEL_TOLERANCE) => model > 0 && Math.abs(measured - model) / model <= tol;
|
|
84
|
+
|
|
85
|
+
/** Monthly model report: items [{name, model, measured}] -> {lines, model, measured, within}; measured-less items are shown as `n/a`. */
|
|
86
|
+
export function monthlyModel(items) {
|
|
87
|
+
const done = items.filter((i) => i.measured != null);
|
|
88
|
+
const model = items.reduce((a, i) => a + i.model, 0), measured = done.reduce((a, i) => a + i.measured, 0);
|
|
89
|
+
const comparable = done.reduce((a, i) => a + i.model, 0);
|
|
90
|
+
return {
|
|
91
|
+
lines: items.map((i) => `${i.name}: model ${i.model} min, measured ${i.measured ?? "n/a"}`),
|
|
92
|
+
model, measured, within: done.length > 0 && withinTolerance(comparable, measured),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Report over the first 3 recorded releases (the managed waves of 5.8): model = `model_release_minutes` each (default 500) vs measured. */
|
|
97
|
+
export function waveReport(records, cfg = parseBudgetConfig(null)) {
|
|
98
|
+
const waves = records.filter((r) => (r.lane ?? "release") === "release").slice(0, 3);
|
|
99
|
+
const m = monthlyModel(waves.map((w, i) => ({ name: `release wave ${i + 1}`, model: cfg.modelPerRelease, measured: w.minutes })));
|
|
100
|
+
const verdict = waves.length < 3 ? `${waves.length}/3 waves measured` : m.within ? "within 25% of the model" : "OUTSIDE 25% of the model: tune budget.on_exceed and the nightly cadence";
|
|
101
|
+
return { ...m, waves: waves.length, lines: [...m.lines, `total: model ${m.model} min, measured ${m.measured} min (${verdict})`] };
|
|
102
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
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 { mkdirSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
8
|
+
import { parseBudgetConfig, jobMinutes, releaseMinutes, trailingMedian, applyOnExceed, withinTolerance, monthlyModel, historyFromRoot, waveReport } from "./release-minutes.mjs";
|
|
9
|
+
import { runRelease, readReleaseConfig, newReleaseId, releaseFromCli } from "./release.mjs";
|
|
10
|
+
|
|
11
|
+
const job = (s, e) => ({ started_at: `2026-11-12T10:00:${s}Z`, completed_at: `2026-11-12T10:0${e}`, billable_ms: 0 });
|
|
12
|
+
const T = (m, s = "00") => ({ started_at: "2026-11-12T10:00:00Z", completed_at: `2026-11-12T10:${String(m).padStart(2, "0")}:${s}Z` });
|
|
13
|
+
|
|
14
|
+
describe("release minutes (#5569)", () => {
|
|
15
|
+
it("sums ceil per job and ignores billable_ms and unfinished jobs", () => {
|
|
16
|
+
assert.equal(jobMinutes({ jobs: [T(1, "01"), T(2, "00"), { started_at: "2026-11-12T10:00:00Z", completed_at: null }] }), 2 + 2);
|
|
17
|
+
assert.equal(jobMinutes(null), 0);
|
|
18
|
+
});
|
|
19
|
+
it("sums the jobs of every run since the release started", async () => {
|
|
20
|
+
const gh = async (a) => /\/jobs/.test(a[1]) ? JSON.stringify({ jobs: [T(1, "30")] }) : JSON.stringify({ workflow_runs: [{ id: 1 }, { id: 2 }] });
|
|
21
|
+
assert.deepEqual(await releaseMinutes({ gh, repo: "o/r", sinceMs: 0 }), { runs: 2, minutes: 4 });
|
|
22
|
+
assert.equal(await releaseMinutes({ gh: async () => "x", repo: "o/r", sinceMs: 0 }), null);
|
|
23
|
+
});
|
|
24
|
+
it("trailing median is per lane over the last n", () => {
|
|
25
|
+
const rec = [{ lane: "release", minutes: 900 }, { lane: "release", minutes: 500 }, { lane: "release", minutes: 600 }, { lane: "train", minutes: 90 }];
|
|
26
|
+
assert.equal(trailingMedian(rec, "release"), 600);
|
|
27
|
+
assert.equal(trailingMedian(rec, "train"), 90);
|
|
28
|
+
assert.equal(trailingMedian(rec, "p0"), null);
|
|
29
|
+
assert.equal(trailingMedian([{ minutes: 1 }, { minutes: 3 }], "release"), 2);
|
|
30
|
+
});
|
|
31
|
+
it("on_exceed matrix; p0 and ignore never block", () => {
|
|
32
|
+
const base = { forecast: 600, remaining: 100 };
|
|
33
|
+
for (const v of ["local-first", "hold", "proceed"]) assert.equal(applyOnExceed({ ...base, cfg: parseBudgetConfig({ on_exceed: v }) }).action, v);
|
|
34
|
+
assert.equal(parseBudgetConfig({ on_exceed: "bogus" }).onExceed, "local-first");
|
|
35
|
+
assert.equal(applyOnExceed({ ...base, lane: "p0", cfg: parseBudgetConfig({ on_exceed: "hold" }) }).action, "proceed");
|
|
36
|
+
assert.equal(applyOnExceed({ ...base, cfg: parseBudgetConfig({ on_exceed: "hold", ignore: "true" }) }).action, "proceed");
|
|
37
|
+
assert.equal(applyOnExceed({ forecast: 50, remaining: 100, cfg: parseBudgetConfig({ on_exceed: "hold" }) }).action, "proceed");
|
|
38
|
+
assert.equal(applyOnExceed({ forecast: null, remaining: 100, cfg: parseBudgetConfig({ on_exceed: "hold" }) }).action, "proceed");
|
|
39
|
+
});
|
|
40
|
+
it("25% tolerance and the monthly report", () => {
|
|
41
|
+
assert.equal(withinTolerance(100, 125), true); assert.equal(withinTolerance(100, 126), false); assert.equal(withinTolerance(0, 1), false);
|
|
42
|
+
const m = monthlyModel([{ name: "trains", model: 2700, measured: 3000 }, { name: "releases", model: 7500, measured: null }]);
|
|
43
|
+
assert.equal(m.model, 10200); assert.equal(m.measured, 3000); assert.equal(m.within, true);
|
|
44
|
+
assert.match(m.lines[1], /measured n\/a/);
|
|
45
|
+
});
|
|
46
|
+
it("reads recorded minutes from the release cache", () => {
|
|
47
|
+
const root = tmpDir("rm");
|
|
48
|
+
mkdirSync(join(root, "a")); writeFileSync(join(root, "a", "state.json"), JSON.stringify({ lane: "release", minutes: { total: 480 } }));
|
|
49
|
+
mkdirSync(join(root, "b")); writeFileSync(join(root, "b", "state.json"), "{}");
|
|
50
|
+
assert.deepEqual(historyFromRoot(root), [{ lane: "release", minutes: 480 }]);
|
|
51
|
+
assert.deepEqual(historyFromRoot(join(root, "none")), []);
|
|
52
|
+
});
|
|
53
|
+
it("historyFromRoot carries the gate records on a non-enumerable gates property (#5583)", () => {
|
|
54
|
+
const root = tmpDir("rm");
|
|
55
|
+
mkdirSync(join(root, "a")); writeFileSync(join(root, "a", "state.json"), JSON.stringify({ minutes: { total: 5 }, startedAt: "t", gates: [{ gate: "g", outcome: "fail", class: "FB", minutes: 2 }] }));
|
|
56
|
+
const h = historyFromRoot(root);
|
|
57
|
+
assert.deepEqual(h, [{ lane: "release", minutes: 5 }]);
|
|
58
|
+
assert.deepEqual(h.gates.map((g) => [g.gate, g.release]), [["g", "a"]]);
|
|
59
|
+
assert.deepEqual(historyFromRoot(join(root, "none")).gates, []);
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
describe("release report (#5569)", () => {
|
|
64
|
+
it("compares the first 3 waves with the model and says when it is outside 25%", () => {
|
|
65
|
+
const rec = (...m) => m.map((minutes) => ({ lane: "release", minutes }));
|
|
66
|
+
assert.match(waveReport(rec(480, 520, 560)).lines.at(-1), /within 25%/);
|
|
67
|
+
assert.match(waveReport(rec(900, 900, 900)).lines.at(-1), /OUTSIDE 25%/);
|
|
68
|
+
assert.match(waveReport(rec(500)).lines.at(-1), /1\/3 waves/);
|
|
69
|
+
});
|
|
70
|
+
it("`forgedock release report` prints it", async () => {
|
|
71
|
+
const root = tmpDir("rep"), cwd = tmpDir("repcwd"), out = [];
|
|
72
|
+
mkdirSync(join(root, "a")); writeFileSync(join(root, "a", "state.json"), JSON.stringify({ minutes: { total: 500 } }));
|
|
73
|
+
const code = await releaseFromCli(["report"], { cwd, env: { FORGEDOCK_RELEASE_DIR: root }, io: { print: (l) => out.push(l) } });
|
|
74
|
+
assert.equal(code, 0); assert.match(out.join("\n"), /release wave 1: model 500 min, measured 500/);
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
describe("runRelease managed gate (#5569)", () => {
|
|
79
|
+
const mkIo = (over = {}) => {
|
|
80
|
+
const calls = [], printed = [];
|
|
81
|
+
const api = async (m, p) => { calls.push(`${m} ${p}`); if (m === "GET" && /git\/ref\/heads/.test(p)) { const e = new Error("HTTP 404"); e.status = 404; throw e; } if (m === "GET") return { tree: { sha: "t" } }; return { sha: "s" }; };
|
|
82
|
+
return { calls, printed, now: () => 1_700_000_000_000, print: (l) => printed.push(l), api, git: () => "", sleep: async () => {}, runningLanes: async () => [], batches: async () => [], setParallel: async () => {},
|
|
83
|
+
gh: async (a) => { calls.push(a.join(" ")); if (over.gh) { const r = over.gh(a); if (r !== undefined) return r; } return "[]"; }, ...over.io };
|
|
84
|
+
};
|
|
85
|
+
const stub = { preflight: async () => ({ skipped: true }) };
|
|
86
|
+
const steps = new Proxy({}, { get: () => async () => ({ skipped: true }) });
|
|
87
|
+
const red = (a) => /workflows/.test(a[1] ?? "") ? JSON.stringify({ workflow_runs: [{ id: 1, created_at: new Date(1_700_000_000_000 - 3600_000).toISOString() }] })
|
|
88
|
+
: /runs\/1\/jobs/.test(a[1] ?? "") ? JSON.stringify({ jobs: [{ name: "T1 unit", conclusion: "failure" }] })
|
|
89
|
+
: a[0] === "issue" && a[1] === "list" ? "[]" : a[0] === "issue" ? "https://github.com/o/r/issues/5" : undefined;
|
|
90
|
+
const cfg = (extra = "") => readReleaseConfig(`release:\n managed: true\nnightly:\n workflow: nightly.yml\n${extra}`);
|
|
91
|
+
|
|
92
|
+
it("a red T1 nightly blocks a release, files nightly-red, and never blocks p0", async () => {
|
|
93
|
+
const io = mkIo({ gh: red });
|
|
94
|
+
const r = await runRelease({ io, repo: "o/r", config: cfg(), root: tmpDir("g1"), id: newReleaseId(), steps, opts: {} });
|
|
95
|
+
assert.equal(r.status, "blocked"); assert.equal(r.step, "gate"); assert.match(r.reason, /T1 unit/);
|
|
96
|
+
assert.ok(io.calls.some((c) => /^issue create .*nightly-red/.test(c)));
|
|
97
|
+
const p0 = await runRelease({ io: mkIo({ gh: red }), repo: "o/r", config: cfg(), root: tmpDir("g2"), id: newReleaseId(), steps, opts: { lane: "p0" } });
|
|
98
|
+
assert.notEqual(p0.status, "blocked", JSON.stringify(p0)); assert.notEqual(p0.step, "gate"); // the stubbed API does not model staging's lease (#5553), so p0 may stop there
|
|
99
|
+
assert.ok(!io.calls.some((c) => /git\/refs/.test(c)), "a blocked gate writes no ledger");
|
|
100
|
+
});
|
|
101
|
+
it("managed off makes no nightly or minutes call", async () => {
|
|
102
|
+
const io = mkIo({ gh: red });
|
|
103
|
+
const r = await runRelease({ io, repo: "o/r", config: readReleaseConfig("nightly:\n workflow: nightly.yml\n"), root: tmpDir("g3"), id: newReleaseId(), steps, opts: {} });
|
|
104
|
+
assert.equal(r.status, "done");
|
|
105
|
+
assert.deepEqual(io.calls, []);
|
|
106
|
+
});
|
|
107
|
+
});
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Nightly results for managed releases (#5569, epic #5549 5.6): read the latest nightly run on the integration branch
|
|
5
|
+
* (T0-T2 daily, T3-T4 weekly), file or refresh one `nightly-red` issue, and decide whether a red blocks a release.
|
|
6
|
+
* Only `lane: release` is ever blocked, and only by T0-T2 reds or unskippable classes; T3/T4, train and p0 never.
|
|
7
|
+
* Pure functions plus `gh`-injected reads; no model call. forge.yaml `nightly:` block, used only when `release.managed`.
|
|
8
|
+
*/
|
|
9
|
+
export const NIGHTLY_LABEL = "nightly-red";
|
|
10
|
+
const json = (s) => { try { return JSON.parse(String(s)); } catch { return null; } };
|
|
11
|
+
const off = (v) => ["false", "off", "no", "0"].includes(String(v ?? "").trim().toLowerCase());
|
|
12
|
+
const list = (v) => String(v ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
|
|
13
|
+
const hours = (v, d) => { const n = Number(v); return Number.isFinite(n) && n > 0 ? n : d; };
|
|
14
|
+
|
|
15
|
+
/** forge.yaml `nightly:` -> null when unset, else {branch, workflow, blockRelease, t0t2Hours, t3t4Hours, unskippable, t3, t4}. */
|
|
16
|
+
export function parseNightlyConfig(sec) {
|
|
17
|
+
if (!sec || typeof sec !== "object" || (!sec.workflow && !sec.branch)) return null;
|
|
18
|
+
return {
|
|
19
|
+
branch: String(sec.branch || "staging"), workflow: String(sec.workflow || "nightly.yml"),
|
|
20
|
+
blockRelease: !off(sec.block_release ?? "true"),
|
|
21
|
+
t0t2Hours: hours(sec.t0_t2_hours, 24), t3t4Hours: hours(sec.t3_t4_hours, 168),
|
|
22
|
+
unskippable: list(sec.unskippable), t3: list(sec.t3_jobs), t4: list(sec.t4_jobs),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Tier 0-4 of a job: a leading `T<n>`, else a configured t3_jobs/t4_jobs substring, else T2 (unclassified counts as blocking-eligible). */
|
|
27
|
+
export function classifyTier(name, cfg = {}) {
|
|
28
|
+
const n = String(name ?? "").toLowerCase();
|
|
29
|
+
const m = /^t([0-4])\b/.exec(n);
|
|
30
|
+
if (m) return Number(m[1]);
|
|
31
|
+
if ((cfg.t4 ?? []).some((p) => n.includes(p))) return 4;
|
|
32
|
+
if ((cfg.t3 ?? []).some((p) => n.includes(p))) return 3;
|
|
33
|
+
return 2;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const RED = new Set(["failure", "timed_out", "startup_failure"]);
|
|
37
|
+
const ageH = (iso, now) => (now - Date.parse(iso)) / 3_600_000;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Latest completed nightly runs -> {run, stale, reds:[{name, tier, run}]}. T0-T2 reds come from the newest run (stale when older than
|
|
41
|
+
* 2x t0_t2_hours); T3-T4 reds from the newest run inside t3_t4_hours that has a T3/T4 job. null when the runs are unreadable.
|
|
42
|
+
*/
|
|
43
|
+
export async function readNightly({ gh, repo, cfg, now = Date.now() }) {
|
|
44
|
+
const runs = json(await gh(["api", `repos/${repo}/actions/workflows/${cfg.workflow}/runs?branch=${encodeURIComponent(cfg.branch)}&status=completed&per_page=20`]))?.workflow_runs;
|
|
45
|
+
if (!Array.isArray(runs)) return null;
|
|
46
|
+
if (!runs.length) return { run: null, stale: true, reds: [] };
|
|
47
|
+
const jobsOf = async (r) => json(await gh(["api", `repos/${repo}/actions/runs/${r.id}/jobs?per_page=100`]))?.jobs ?? [];
|
|
48
|
+
const reds = [];
|
|
49
|
+
const first = runs[0];
|
|
50
|
+
for (const j of await jobsOf(first)) if (classifyTier(j.name, cfg) <= 2 && RED.has(j.conclusion)) reds.push({ name: j.name, tier: classifyTier(j.name, cfg), run: first.id });
|
|
51
|
+
for (const r of runs) {
|
|
52
|
+
if (ageH(r.created_at, now) > cfg.t3t4Hours) break;
|
|
53
|
+
const high = (await jobsOf(r)).filter((j) => classifyTier(j.name, cfg) >= 3);
|
|
54
|
+
if (!high.length) continue;
|
|
55
|
+
for (const j of high) if (RED.has(j.conclusion)) reds.push({ name: j.name, tier: classifyTier(j.name, cfg), run: r.id });
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
return { run: first.id, stale: ageH(first.created_at, now) > cfg.t0t2Hours * 2, reds };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The reds that stop `lane`: only `release` is ever blocked, by T0-T2 reds or a job matching `unskippable` (never when block_release is off). */
|
|
62
|
+
export function blocksRelease({ lane = "release", reds = [], cfg }) {
|
|
63
|
+
if (lane !== "release" || !cfg?.blockRelease) return [];
|
|
64
|
+
return reds.filter((r) => r.tier <= 2 || cfg.unskippable.some((p) => r.name.toLowerCase().includes(p)));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** One open `nightly-red` issue: created on the first red, its body edited afterwards. @returns {{issue, created}|null} null when nothing is red. */
|
|
68
|
+
export async function fileNightlyRed({ gh, repo, reds, run }) {
|
|
69
|
+
if (!reds.length) return null;
|
|
70
|
+
const body = `<!-- FORGE:NIGHTLY -->\nNightly run ${run ?? "?"} is red:\n${reds.map((r) => `- T${r.tier}: ${r.name} (run ${r.run})`).join("\n")}\n`;
|
|
71
|
+
const open = json(await gh(["issue", "list", "--repo", repo, "--label", NIGHTLY_LABEL, "--state", "open", "--json", "number", "--limit", "1"])) ?? [];
|
|
72
|
+
if (open[0]) { await gh(["issue", "edit", String(open[0].number), "--repo", repo, "--body", body]); return { issue: open[0].number, created: false }; }
|
|
73
|
+
const url = String(await gh(["issue", "create", "--repo", repo, "--label", NIGHTLY_LABEL, "--title", `nightly-red: ${reds.length} red job(s) on the integration branch`, "--body", body])).trim();
|
|
74
|
+
return { issue: Number(/(\d+)$/.exec(url)?.[1]) || null, created: true };
|
|
75
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
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 { parseNightlyConfig, classifyTier, readNightly, blocksRelease, fileNightlyRed } from "./release-nightly.mjs";
|
|
6
|
+
|
|
7
|
+
const cfg = parseNightlyConfig({ workflow: "nightly.yml", branch: "staging", t3_jobs: "hands e2e", t4_jobs: "trivy", unskippable: "migration" });
|
|
8
|
+
const NOW = Date.parse("2026-11-12T12:00:00Z");
|
|
9
|
+
const hAgo = (h) => new Date(NOW - h * 3_600_000).toISOString();
|
|
10
|
+
|
|
11
|
+
describe("nightly (#5569)", () => {
|
|
12
|
+
it("config is null when unset and has the 24h/168h defaults", () => {
|
|
13
|
+
assert.equal(parseNightlyConfig(undefined), null);
|
|
14
|
+
assert.equal(cfg.t0t2Hours, 24); assert.equal(cfg.t3t4Hours, 168); assert.equal(cfg.blockRelease, true);
|
|
15
|
+
});
|
|
16
|
+
it("classifies tiers by prefix, then config, else T2", () => {
|
|
17
|
+
assert.equal(classifyTier("T1 unit api", cfg), 1);
|
|
18
|
+
assert.equal(classifyTier("Hands e2e", cfg), 3);
|
|
19
|
+
assert.equal(classifyTier("Trivy scan", cfg), 4);
|
|
20
|
+
assert.equal(classifyTier("lint", cfg), 2);
|
|
21
|
+
});
|
|
22
|
+
it("blocks only a release, only by T0-T2 or unskippable reds, never T3/T4", () => {
|
|
23
|
+
const reds = [{ name: "T1 unit", tier: 1 }, { name: "Hands e2e", tier: 3 }, { name: "migration safety", tier: 3 }];
|
|
24
|
+
assert.deepEqual(blocksRelease({ lane: "release", reds, cfg }).map((r) => r.name), ["T1 unit", "migration safety"]);
|
|
25
|
+
assert.deepEqual(blocksRelease({ lane: "release", reds: [reds[1]], cfg }), []);
|
|
26
|
+
assert.deepEqual(blocksRelease({ lane: "train", reds, cfg }), []);
|
|
27
|
+
assert.deepEqual(blocksRelease({ lane: "p0", reds, cfg }), []);
|
|
28
|
+
assert.deepEqual(blocksRelease({ lane: "release", reds, cfg: { ...cfg, blockRelease: false } }), []);
|
|
29
|
+
});
|
|
30
|
+
it("reads T0-T2 from the newest run and T3/T4 from the newest weekly run", async () => {
|
|
31
|
+
const jobs = { 1: [{ name: "T1 unit", conclusion: "failure" }, { name: "lint", conclusion: "success" }], 2: [{ name: "Hands e2e", conclusion: "failure" }] };
|
|
32
|
+
const gh = async (a) => /workflows/.test(a[1]) ? JSON.stringify({ workflow_runs: [{ id: 1, created_at: hAgo(2) }, { id: 2, created_at: hAgo(30) }] }) : JSON.stringify({ jobs: jobs[/runs\/(\d)/.exec(a[1])[1]] });
|
|
33
|
+
const n = await readNightly({ gh, repo: "o/r", cfg, now: NOW });
|
|
34
|
+
assert.deepEqual(n.reds.map((r) => [r.name, r.tier, r.run]), [["T1 unit", 1, 1], ["Hands e2e", 3, 2]]);
|
|
35
|
+
assert.equal(n.stale, false);
|
|
36
|
+
assert.equal(await readNightly({ gh: async () => "x", repo: "o/r", cfg, now: NOW }), null);
|
|
37
|
+
});
|
|
38
|
+
it("files one nightly-red issue and edits it afterwards; green files nothing", async () => {
|
|
39
|
+
const calls = []; let open = [];
|
|
40
|
+
const gh = async (a) => { calls.push(a.slice(0, 2).join(" ")); if (a[1] === "list") return JSON.stringify(open); if (a[1] === "create") return "https://github.com/o/r/issues/77"; return ""; };
|
|
41
|
+
const reds = [{ name: "T1 unit", tier: 1, run: 1 }];
|
|
42
|
+
assert.equal(await fileNightlyRed({ gh, repo: "o/r", reds: [], run: 1 }), null);
|
|
43
|
+
assert.deepEqual(await fileNightlyRed({ gh, repo: "o/r", reds, run: 1 }), { issue: 77, created: true });
|
|
44
|
+
open = [{ number: 77 }];
|
|
45
|
+
assert.deepEqual(await fileNightlyRed({ gh, repo: "o/r", reds, run: 2 }), { issue: 77, created: false });
|
|
46
|
+
assert.deepEqual(calls, ["issue list", "issue create", "issue list", "issue edit"]);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import { cleanupSnapshot } from "./release-snapshot.mjs";
|
|
12
|
+
import { fenced } from "./release-fence.mjs";
|
|
13
|
+
import { buildDispatchArgs } from "./release-control.mjs";
|
|
12
14
|
|
|
13
15
|
const BOUNDS = {
|
|
14
16
|
publishPolls: 6, publishPollMs: 10_000, // wait for a run to appear (bot merges never trigger one)
|
|
@@ -43,7 +45,8 @@ async function publishRun(ctx, sha, b) {
|
|
|
43
45
|
let run = await poll(io, b.publishPolls, b.publishPollMs, look);
|
|
44
46
|
let dispatched = false;
|
|
45
47
|
if (!run) {
|
|
46
|
-
await
|
|
48
|
+
const f = await fenced(ctx.fence, { action: "dispatch", key: `dispatch:${sha}` }, (epoch) => io.gh(buildDispatchArgs({ workflow, repo, ref: ctx.def, inputs: epoch != null ? { forge_epoch: epoch } : {} })));
|
|
49
|
+
if (f.refused) return { err: `dispatch ${f.refused}` };
|
|
47
50
|
dispatched = true;
|
|
48
51
|
run = await poll(io, b.publishPolls, b.publishPollMs, look);
|
|
49
52
|
if (!run) return { err: `no ${workflow} run for ${sha.slice(0, 8)} after a dispatch on ${ctx.def}; check the Actions tab, then resume` };
|
|
@@ -103,7 +106,10 @@ async function versionSync(ctx, sha, b) {
|
|
|
103
106
|
pr = { number: n };
|
|
104
107
|
}
|
|
105
108
|
const warn = (why) => ({ pr: pr.number, merged: false, warning: `version-sync PR #${pr.number} ${why}; merge it by hand so ${staging} reaches ${version}` });
|
|
106
|
-
try {
|
|
109
|
+
try {
|
|
110
|
+
const f = await fenced(ctx.fence, { action: "merge", key: `sync-merge:${pr.number}` }, () => io.gh(["pr", "merge", String(pr.number), "--repo", repo, "--merge", "--auto"]));
|
|
111
|
+
if (f.refused) return { err: `version-sync merge ${f.refused}` };
|
|
112
|
+
} catch (e) { return warn(`could not enable auto-merge (${String(e.message).split("\n")[0]})`); }
|
|
107
113
|
const end = await poll(io, b.autoPolls, b.autoPollMs, async () => {
|
|
108
114
|
const st = json(await io.gh(["pr", "view", String(pr.number), "--repo", repo, "--json", "state"]))?.state;
|
|
109
115
|
return st === "MERGED" || st === "CLOSED" ? st : null;
|
|
@@ -35,6 +35,7 @@ function world() {
|
|
|
35
35
|
readFile: () => "brief",
|
|
36
36
|
markLaunched: (_f, domains) => { w.launched = domains; },
|
|
37
37
|
saveTestGate: () => "/sd/gate.txt",
|
|
38
|
+
testGatePlan: async () => ({ clusters: 1, skill: "test-gate" }),
|
|
38
39
|
runAgent: async ({ role }) => { w.agents.push(role); return { text: "FORGE:TEST_GATE:RESULT=PASS" }; },
|
|
39
40
|
finalize: async () => ({ code: 0, lines: [], data: { head: sha(w.head), notes: ["- nit"], toFile: w.fixed ? [] : [{ title: "leak", severity: "HIGH" }] } }),
|
|
40
41
|
fileIssue: async ({ item }) => { w.issues.push(item.title); return 100 + w.issues.length; },
|