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.
- package/bin/config-schema.mjs +1 -1
- package/bin/engine/outcome-codes.mjs +1 -0
- package/bin/engine/phases.mjs +4 -3
- package/bin/engine-cli.mjs +46 -10
- package/bin/forgedock.mjs +52 -3
- package/bin/gc.mjs +43 -6
- package/bin/help-text.mjs +3 -1
- 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 +88 -17
- package/bin/lean/conformance.test.mjs +98 -3
- package/bin/lean/decisions.mjs +86 -1
- package/bin/lean/decisions.test.mjs +21 -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 +12 -2
- package/bin/lean/issuewatch-parity.test.mjs +26 -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 +72 -21
- package/bin/lean/lean.test.mjs +149 -3
- 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 +25 -0
- package/bin/lean/release-config.mjs +158 -0
- package/bin/lean/release-config.test.mjs +109 -0
- package/bin/lean/release-control.mjs +148 -0
- package/bin/lean/release-control.test.mjs +143 -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-ledger.mjs +160 -0
- package/bin/lean/release-ledger.test.mjs +226 -0
- package/bin/lean/release-minutes.mjs +92 -0
- package/bin/lean/release-minutes.test.mjs +99 -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-unitmap.mjs +35 -0
- package/bin/lean/release-unitmap.test.mjs +41 -0
- package/bin/lean/release.mjs +177 -19
- package/bin/lean/release.test.mjs +40 -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 +75 -1
- 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.test.sh +3 -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,160 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Release ledger on GitHub (#5550, epic #5549 Phase 0): the durable, cross-host record of a release. One orphan branch
|
|
5
|
+
* `forge-ledger/<release-id>` per release (`state.json`, single writer = the lease holder) plus one control branch
|
|
6
|
+
* `forge-ledger/_active` (`active.json`: lease, epoch, intake pause, holds, counters; `controls.jsonl`: append-only audit).
|
|
7
|
+
* Writes are Git Data API commits whose ref update is NOT forced: a non-fast-forward (HTTP 422) is a lost race, which is
|
|
8
|
+
* the compare-and-swap. `_active` is multi-writer, so `updateActive` is a key-scoped read-modify-write with up to 5 retries.
|
|
9
|
+
* The heartbeat is an edit of the `FORGE:LEASE` comment on the tracking issue, never a commit. Every value is redacted
|
|
10
|
+
* before it is written (I21); a head commit is trusted only from an allowlisted, GitHub-verified driver actor (I12).
|
|
11
|
+
* Every effect goes through `io.api(method, path, body?)` (parsed JSON; throws with `.status`), so it is unit-testable.
|
|
12
|
+
* Off unless forge.yaml `release.managed` is on; nothing here runs otherwise.
|
|
13
|
+
*/
|
|
14
|
+
import { SECRET_PAIR_RE, SECRET_SHAPE_RE } from "./conformance.mjs";
|
|
15
|
+
|
|
16
|
+
export const LEDGER_PREFIX = "forge-ledger/";
|
|
17
|
+
export const ACTIVE = "_active";
|
|
18
|
+
export const ACTIVE_RETRIES = 5;
|
|
19
|
+
export const LEASE_MARKER = "FORGE:LEASE";
|
|
20
|
+
const ID_RE = /^r\d{8}-\d{6}-\d+$/;
|
|
21
|
+
const SECRET_KEY_RE = /TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|CREDENTIAL/i;
|
|
22
|
+
const REDACTED = "[redacted]";
|
|
23
|
+
|
|
24
|
+
export const ledgerBranch = (id) => {
|
|
25
|
+
if (id !== ACTIVE && !ID_RE.test(String(id ?? ""))) throw new Error(`invalid release id ${JSON.stringify(id)}`);
|
|
26
|
+
return `${LEDGER_PREFIX}${id}`;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** `value` with every secret-shaped string (and the value of every secret-named key) replaced; never mutates. */
|
|
30
|
+
export function redactDeep(value) {
|
|
31
|
+
if (typeof value === "string") return value.replace(SECRET_PAIR_RE, `$1${REDACTED}`).replace(SECRET_SHAPE_RE, REDACTED);
|
|
32
|
+
if (Array.isArray(value)) return value.map(redactDeep);
|
|
33
|
+
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, SECRET_KEY_RE.test(k) && typeof v === "string" ? REDACTED : redactDeep(v)]));
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const isLost = (e) => e?.status === 422 || /HTTP 422|not a fast.forward|already exists/i.test(String(e?.message ?? e));
|
|
38
|
+
const isMissing = (e) => e?.status === 404 || /HTTP 404|Not Found/i.test(String(e?.message ?? e));
|
|
39
|
+
const refPath = (b) => `heads/${b}`;
|
|
40
|
+
|
|
41
|
+
const headOf = async ({ io, repo }, branch) => {
|
|
42
|
+
try { return (await io.api("GET", `repos/${repo}/git/ref/${refPath(branch)}`))?.object?.sha ?? null; } catch (e) { if (isMissing(e)) return null; throw e; }
|
|
43
|
+
};
|
|
44
|
+
const readFile = async ({ io, repo }, branch, path) => {
|
|
45
|
+
try { const r = await io.api("GET", `repos/${repo}/contents/${path}?ref=${encodeURIComponent(branch)}`); return Buffer.from(r.content ?? "", "base64").toString("utf8"); } catch (e) { if (isMissing(e)) return null; throw e; }
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/** The driver credential writes the ledger; a lane credential never does (I12). */
|
|
49
|
+
const assertDriver = (ctx) => { if (ctx.credential !== "driver") throw Object.assign(new Error("ledger writes need the driver credential"), { refused: "not-driver" }); };
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* One commit of `files` ({path: text}, redacted) on `branch` on top of `parent` (null = orphan, creates the branch).
|
|
53
|
+
* @returns {{ok: true, sha: string} | {lost: true}} lost when the ref moved (or exists): the caller re-reads and decides.
|
|
54
|
+
*/
|
|
55
|
+
export async function commitFiles(ctx, branch, files, message, parent) {
|
|
56
|
+
assertDriver(ctx);
|
|
57
|
+
const { io, repo } = ctx;
|
|
58
|
+
const base = parent ? (await io.api("GET", `repos/${repo}/git/commits/${parent}`)).tree.sha : undefined;
|
|
59
|
+
const tree = await io.api("POST", `repos/${repo}/git/trees`, { ...(base ? { base_tree: base } : {}), tree: Object.entries(files).map(([path, text]) => ({ path, mode: "100644", type: "blob", content: String(redactDeep(text)) })) });
|
|
60
|
+
const commit = await io.api("POST", `repos/${repo}/git/commits`, { message: String(redactDeep(message)), tree: tree.sha, parents: parent ? [parent] : [] });
|
|
61
|
+
try {
|
|
62
|
+
if (parent) await io.api("PATCH", `repos/${repo}/git/refs/${refPath(branch)}`, { sha: commit.sha, force: false });
|
|
63
|
+
else await io.api("POST", `repos/${repo}/git/refs`, { ref: `refs/${refPath(branch)}`, sha: commit.sha });
|
|
64
|
+
} catch (e) { if (isLost(e)) return { lost: true }; throw e; }
|
|
65
|
+
return { ok: true, sha: commit.sha };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const json = (o) => JSON.stringify(redactDeep(o), null, 2) + "\n";
|
|
69
|
+
|
|
70
|
+
/** Create `forge-ledger/<id>` with the first state; `{lost}` when the release already has a ledger. */
|
|
71
|
+
export const createReleaseLedger = (ctx, id, state) => commitFiles(ctx, ledgerBranch(id), { "state.json": json(state) }, `ledger: create ${id}`, null);
|
|
72
|
+
|
|
73
|
+
/** Write the next state of release `id` on top of `head` (the sha the caller read); `{lost}` means another writer moved it. */
|
|
74
|
+
export const writeRelease = (ctx, id, state, head) => commitFiles(ctx, ledgerBranch(id), { "state.json": json(state) }, `ledger: ${id} ${state.status ?? "update"}`, head);
|
|
75
|
+
|
|
76
|
+
/** True when `info` (GET repos/R/commits/<sha>) was authored by an allowlisted driver actor and is GitHub-verified. */
|
|
77
|
+
export function acceptWrite(info, policy = {}) {
|
|
78
|
+
const id = info?.author?.id;
|
|
79
|
+
if (!info?.commit?.verification?.verified) return { ok: false, reason: "unverified commit" };
|
|
80
|
+
if (id == null || !(policy.allowlist ?? []).includes(id)) return { ok: false, reason: `actor ${info?.author?.login ?? id} is not allowlisted` };
|
|
81
|
+
if (!(policy.driverIds ?? []).includes(id)) return { ok: false, reason: `actor ${info?.author?.login ?? id} is not the driver credential` };
|
|
82
|
+
return { ok: true };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** `{state, head}` of release `id`, `null` when it has no ledger, `{rejected}` when the head commit fails `acceptWrite`. */
|
|
86
|
+
export async function readLedger(ctx, id, policy) {
|
|
87
|
+
const branch = ledgerBranch(id), head = await headOf(ctx, branch);
|
|
88
|
+
if (!head) return null;
|
|
89
|
+
if (policy) {
|
|
90
|
+
const verdict = acceptWrite(await ctx.io.api("GET", `repos/${ctx.repo}/commits/${head}`), policy);
|
|
91
|
+
if (!verdict.ok) return { rejected: verdict.reason, head };
|
|
92
|
+
}
|
|
93
|
+
const text = await readFile(ctx, branch, "state.json");
|
|
94
|
+
try { return { state: JSON.parse(text), head }; } catch { return { rejected: "state.json unreadable", head }; }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Key-scoped read-modify-write of `_active`: `fn(active)` returns `{patch}` (only keys in `owned` are applied, others are
|
|
99
|
+
* ignored), optionally `control` (one line appended to controls.jsonl) or `{refuse}`. A lost race re-reads and re-applies,
|
|
100
|
+
* up to ACTIVE_RETRIES attempts.
|
|
101
|
+
* @returns {{ok: true, active, sha} | {refused: string} | {lost: true, attempts: number}}
|
|
102
|
+
*/
|
|
103
|
+
export async function updateActive(ctx, owned, fn) {
|
|
104
|
+
for (let attempt = 1; attempt <= ACTIVE_RETRIES; attempt++) {
|
|
105
|
+
const head = await headOf(ctx, ACTIVE);
|
|
106
|
+
const cur = head ? JSON.parse((await readFile(ctx, ACTIVE, "active.json")) ?? "{}") : {};
|
|
107
|
+
const out = await fn(cur);
|
|
108
|
+
if (out?.refuse) return { refused: out.refuse };
|
|
109
|
+
const next = { ...cur };
|
|
110
|
+
for (const [k, v] of Object.entries(out?.patch ?? {})) if (owned.includes(k)) next[k] = v;
|
|
111
|
+
const files = { "active.json": json(next), ...(out?.files ?? {}) };
|
|
112
|
+
if (out?.control) files["controls.jsonl"] = `${(head ? (await readFile(ctx, ACTIVE, "controls.jsonl")) ?? "" : "")}${JSON.stringify(redactDeep(out.control))}\n`;
|
|
113
|
+
const r = await commitFiles(ctx, ACTIVE, files, `ledger: _active ${Object.keys(out?.patch ?? {}).join(",") || "control"}`, head);
|
|
114
|
+
if (r.ok) return { ok: true, active: next, sha: r.sha };
|
|
115
|
+
}
|
|
116
|
+
return { lost: true, attempts: ACTIVE_RETRIES };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const leaseBody = (l) => `<!-- ${LEASE_MARKER} -->\nholder: ${l.holder}\nepoch: ${l.epoch}\nrelease: ${l.release}\n${l.expires ? `expires: ${new Date(l.expires).toISOString()}\n` : ""}`;
|
|
120
|
+
|
|
121
|
+
/** Parsed `_active/active.json`; throws when it cannot be read (a fence must treat that as "no irreversible action", I5). */
|
|
122
|
+
export async function readActive(ctx) {
|
|
123
|
+
const text = await readFile(ctx, ACTIVE, "active.json");
|
|
124
|
+
if (text == null) throw new Error("_active has no active.json");
|
|
125
|
+
return JSON.parse(text);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Take the lease for release `release` as `holder`: refused while another holder's `FORGE:LEASE` comment (on `issue`) was
|
|
130
|
+
* edited within `ttlS`; each takeover bumps the epoch. The CAS lives in `updateActive`, so of two racing drivers one wins.
|
|
131
|
+
* @returns {{ok: true, lease} | {refused: string} | {lost: true}}
|
|
132
|
+
*/
|
|
133
|
+
export async function acquireLease(ctx, { holder, release, issue, ttlS = 120, now = Date.now() }) {
|
|
134
|
+
const r = await updateActive(ctx, ["lease", "epoch"], async (active) => {
|
|
135
|
+
const l = active.lease;
|
|
136
|
+
if (l && l.holder !== holder && l.commentId) {
|
|
137
|
+
let c = null; try { c = await ctx.io.api("GET", `repos/${ctx.repo}/issues/comments/${l.commentId}`); } catch (e) { if (!isMissing(e)) throw e; }
|
|
138
|
+
if (c && now - Date.parse(c.updated_at) < (l.ttlS ?? ttlS) * 1000) return { refuse: `lease held by ${l.holder} (epoch ${l.epoch})` };
|
|
139
|
+
}
|
|
140
|
+
const epoch = (active.epoch ?? 0) + 1;
|
|
141
|
+
return { patch: { epoch, lease: { holder, release, issue, ttlS, epoch, expires: now + ttlS * 1000, commentId: l?.holder === holder ? l.commentId : undefined } }, control: { at: new Date(now).toISOString(), verb: "lease", holder, release, epoch } };
|
|
142
|
+
});
|
|
143
|
+
if (!r.ok) return r;
|
|
144
|
+
let lease = r.active.lease;
|
|
145
|
+
if (!lease.commentId) { // the heartbeat comment is made once per takeover, then only edited
|
|
146
|
+
const c = await ctx.io.api("POST", `repos/${ctx.repo}/issues/${issue}/comments`, { body: leaseBody(lease) });
|
|
147
|
+
const set = await updateActive(ctx, ["lease"], (a) => (a.lease?.holder === holder && a.lease.epoch === lease.epoch ? { patch: { lease: { ...a.lease, commentId: c.id } } } : { refuse: "lease lost" }));
|
|
148
|
+
if (!set.ok) return set;
|
|
149
|
+
lease = set.active.lease;
|
|
150
|
+
}
|
|
151
|
+
return { ok: true, lease };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Heartbeat: edit the FORGE:LEASE comment (no commit). `{fenced}` when the lease is no longer this holder's epoch. */
|
|
155
|
+
export async function heartbeat(ctx, lease) {
|
|
156
|
+
const active = JSON.parse((await readFile(ctx, ACTIVE, "active.json")) ?? "{}");
|
|
157
|
+
if (active.lease?.holder !== lease.holder || active.lease?.epoch !== lease.epoch) return { fenced: true };
|
|
158
|
+
await ctx.io.api("PATCH", `repos/${ctx.repo}/issues/comments/${active.lease.commentId}`, { body: leaseBody(lease) });
|
|
159
|
+
return { ok: true };
|
|
160
|
+
}
|
|
@@ -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 }), "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 };
|
|
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"].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,92 @@
|
|
|
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). */
|
|
44
|
+
export function historyFromRoot(root) {
|
|
45
|
+
if (!existsSync(root)) return [];
|
|
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 out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Median of the last `n` records of `lane`; null with no history. */
|
|
54
|
+
export function trailingMedian(records, lane = "release", n = 5) {
|
|
55
|
+
const v = records.filter((r) => (r.lane ?? "release") === lane).slice(-n).map((r) => r.minutes).sort((a, b) => a - b);
|
|
56
|
+
if (!v.length) return null;
|
|
57
|
+
const m = v.length >> 1;
|
|
58
|
+
return v.length % 2 ? v[m] : (v[m - 1] + v[m]) / 2;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The action at the gate: `proceed` when p0, budget ignored, forecast unknown or it fits `remaining`; else the configured `onExceed`.
|
|
63
|
+
* @returns {{action: "proceed"|"local-first"|"hold", why}}
|
|
64
|
+
*/
|
|
65
|
+
export function applyOnExceed({ lane = "release", forecast, remaining, cfg }) {
|
|
66
|
+
if (lane === "p0" || cfg?.ignore) return { action: "proceed", why: lane === "p0" ? "p0 is never blocked by budget" : "budget ignored" };
|
|
67
|
+
if (forecast == null || remaining == null) return { action: "proceed", why: "no forecast or budget known" };
|
|
68
|
+
if (forecast <= remaining) return { action: "proceed", why: `forecast ${forecast} min within ${Math.round(remaining)} min left` };
|
|
69
|
+
return { action: cfg?.onExceed ?? "local-first", why: `forecast ${forecast} min exceeds ${Math.round(remaining)} min left` };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** True when the measured minutes are within `tol` of the model's (the 25% exit criterion of 5.8). */
|
|
73
|
+
export const withinTolerance = (model, measured, tol = MODEL_TOLERANCE) => model > 0 && Math.abs(measured - model) / model <= tol;
|
|
74
|
+
|
|
75
|
+
/** Monthly model report: items [{name, model, measured}] -> {lines, model, measured, within}; measured-less items are shown as `n/a`. */
|
|
76
|
+
export function monthlyModel(items) {
|
|
77
|
+
const done = items.filter((i) => i.measured != null);
|
|
78
|
+
const model = items.reduce((a, i) => a + i.model, 0), measured = done.reduce((a, i) => a + i.measured, 0);
|
|
79
|
+
const comparable = done.reduce((a, i) => a + i.model, 0);
|
|
80
|
+
return {
|
|
81
|
+
lines: items.map((i) => `${i.name}: model ${i.model} min, measured ${i.measured ?? "n/a"}`),
|
|
82
|
+
model, measured, within: done.length > 0 && withinTolerance(comparable, measured),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Report over the first 3 recorded releases (the managed waves of 5.8): model = `model_release_minutes` each (default 500) vs measured. */
|
|
87
|
+
export function waveReport(records, cfg = parseBudgetConfig(null)) {
|
|
88
|
+
const waves = records.filter((r) => (r.lane ?? "release") === "release").slice(0, 3);
|
|
89
|
+
const m = monthlyModel(waves.map((w, i) => ({ name: `release wave ${i + 1}`, model: cfg.modelPerRelease, measured: w.minutes })));
|
|
90
|
+
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";
|
|
91
|
+
return { ...m, waves: waves.length, lines: [...m.lines, `total: model ${m.model} min, measured ${m.measured} min (${verdict})`] };
|
|
92
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
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
|
+
});
|
|
54
|
+
|
|
55
|
+
describe("release report (#5569)", () => {
|
|
56
|
+
it("compares the first 3 waves with the model and says when it is outside 25%", () => {
|
|
57
|
+
const rec = (...m) => m.map((minutes) => ({ lane: "release", minutes }));
|
|
58
|
+
assert.match(waveReport(rec(480, 520, 560)).lines.at(-1), /within 25%/);
|
|
59
|
+
assert.match(waveReport(rec(900, 900, 900)).lines.at(-1), /OUTSIDE 25%/);
|
|
60
|
+
assert.match(waveReport(rec(500)).lines.at(-1), /1\/3 waves/);
|
|
61
|
+
});
|
|
62
|
+
it("`forgedock release report` prints it", async () => {
|
|
63
|
+
const root = tmpDir("rep"), cwd = tmpDir("repcwd"), out = [];
|
|
64
|
+
mkdirSync(join(root, "a")); writeFileSync(join(root, "a", "state.json"), JSON.stringify({ minutes: { total: 500 } }));
|
|
65
|
+
const code = await releaseFromCli(["report"], { cwd, env: { FORGEDOCK_RELEASE_DIR: root }, io: { print: (l) => out.push(l) } });
|
|
66
|
+
assert.equal(code, 0); assert.match(out.join("\n"), /release wave 1: model 500 min, measured 500/);
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
describe("runRelease managed gate (#5569)", () => {
|
|
71
|
+
const mkIo = (over = {}) => {
|
|
72
|
+
const calls = [], printed = [];
|
|
73
|
+
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" }; };
|
|
74
|
+
return { calls, printed, now: () => 1_700_000_000_000, print: (l) => printed.push(l), api, git: () => "", sleep: async () => {}, runningLanes: async () => [], batches: async () => [], setParallel: async () => {},
|
|
75
|
+
gh: async (a) => { calls.push(a.join(" ")); if (over.gh) { const r = over.gh(a); if (r !== undefined) return r; } return "[]"; }, ...over.io };
|
|
76
|
+
};
|
|
77
|
+
const stub = { preflight: async () => ({ skipped: true }) };
|
|
78
|
+
const steps = new Proxy({}, { get: () => async () => ({ skipped: true }) });
|
|
79
|
+
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() }] })
|
|
80
|
+
: /runs\/1\/jobs/.test(a[1] ?? "") ? JSON.stringify({ jobs: [{ name: "T1 unit", conclusion: "failure" }] })
|
|
81
|
+
: a[0] === "issue" && a[1] === "list" ? "[]" : a[0] === "issue" ? "https://github.com/o/r/issues/5" : undefined;
|
|
82
|
+
const cfg = (extra = "") => readReleaseConfig(`release:\n managed: true\nnightly:\n workflow: nightly.yml\n${extra}`);
|
|
83
|
+
|
|
84
|
+
it("a red T1 nightly blocks a release, files nightly-red, and never blocks p0", async () => {
|
|
85
|
+
const io = mkIo({ gh: red });
|
|
86
|
+
const r = await runRelease({ io, repo: "o/r", config: cfg(), root: tmpDir("g1"), id: newReleaseId(), steps, opts: {} });
|
|
87
|
+
assert.equal(r.status, "blocked"); assert.equal(r.step, "gate"); assert.match(r.reason, /T1 unit/);
|
|
88
|
+
assert.ok(io.calls.some((c) => /^issue create .*nightly-red/.test(c)));
|
|
89
|
+
const p0 = await runRelease({ io: mkIo({ gh: red }), repo: "o/r", config: cfg(), root: tmpDir("g2"), id: newReleaseId(), steps, opts: { lane: "p0" } });
|
|
90
|
+
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
|
|
91
|
+
assert.ok(!io.calls.some((c) => /git\/refs/.test(c)), "a blocked gate writes no ledger");
|
|
92
|
+
});
|
|
93
|
+
it("managed off makes no nightly or minutes call", async () => {
|
|
94
|
+
const io = mkIo({ gh: red });
|
|
95
|
+
const r = await runRelease({ io, repo: "o/r", config: readReleaseConfig("nightly:\n workflow: nightly.yml\n"), root: tmpDir("g3"), id: newReleaseId(), steps, opts: {} });
|
|
96
|
+
assert.equal(r.status, "done");
|
|
97
|
+
assert.deepEqual(io.calls, []);
|
|
98
|
+
});
|
|
99
|
+
});
|