forgedock 1.59.1 → 1.60.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/engine/outcome-codes.mjs +3 -3
- package/bin/engine-cli.mjs +50 -10
- package/bin/labels.json +5 -0
- package/bin/lean/batch.mjs +21 -2
- package/bin/lean/batch.test.mjs +116 -1
- package/bin/lean/conformance.mjs +12 -5
- package/bin/lean/conformance.test.mjs +30 -2
- package/bin/lean/depcache.mjs +34 -15
- package/bin/lean/depcache.test.mjs +100 -1
- package/bin/lean/design-gate.mjs +15 -10
- package/bin/lean/design-gate.test.mjs +21 -0
- package/bin/lean/effects.mjs +18 -2
- package/bin/lean/execution.mjs +23 -5
- package/bin/lean/execution.test.mjs +81 -1
- package/bin/lean/gatewatch.test.mjs +5 -5
- package/bin/lean/issuewatch-triage.mjs +68 -0
- package/bin/lean/issuewatch-triage.test.mjs +98 -0
- package/bin/lean/issuewatch.mjs +34 -6
- package/bin/lean/issuewatch.test.mjs +11 -0
- package/bin/lean/lanelock.mjs +5 -4
- package/bin/lean/lean.mjs +123 -17
- package/bin/lean/lean.test.mjs +154 -6
- package/bin/lean/orchestrate-cancel.test.mjs +33 -0
- package/bin/lean/orchestrate-hostfallback.test.mjs +41 -0
- package/bin/lean/orchestrate-recovering.test.mjs +42 -0
- package/bin/lean/orchestrate.mjs +23 -10
- package/bin/lean/pagegate.mjs +50 -12
- package/bin/lean/pagegate.test.mjs +38 -1
- package/bin/lean/phaseledger.mjs +65 -2
- package/bin/lean/phaseledger.test.mjs +70 -2
- package/bin/lean/preflight.mjs +5 -2
- package/bin/lean/preflight.test.mjs +7 -0
- package/bin/lean/prompts.mjs +2 -1
- package/bin/lean/recovery.test.mjs +11 -6
- package/bin/lean/release-classify.mjs +143 -0
- package/bin/lean/release-classify.test.mjs +130 -0
- package/bin/lean/release-conductor.mjs +163 -0
- package/bin/lean/release-conductor.test.mjs +194 -0
- package/bin/lean/release-config.mjs +60 -8
- package/bin/lean/release-config.test.mjs +43 -1
- package/bin/lean/release-control.mjs +22 -5
- package/bin/lean/release-control.test.mjs +22 -0
- package/bin/lean/release-credentials.mjs +40 -0
- package/bin/lean/release-credentials.test.mjs +42 -0
- package/bin/lean/release-deploy.mjs +3 -3
- package/bin/lean/release-deploy.test.mjs +8 -0
- package/bin/lean/release-docs.test.mjs +93 -0
- package/bin/lean/release-fence.mjs +2 -0
- package/bin/lean/release-gate.mjs +88 -0
- package/bin/lean/release-gate.test.mjs +116 -0
- package/bin/lean/release-gates.mjs +5 -1
- package/bin/lean/release-ledger.mjs +47 -1
- package/bin/lean/release-ledger.test.mjs +33 -1
- package/bin/lean/release-mergeback.mjs +148 -0
- package/bin/lean/release-mergeback.test.mjs +129 -0
- package/bin/lean/release-p0.mjs +193 -0
- package/bin/lean/release-p0.test.mjs +127 -0
- package/bin/lean/release-plan.mjs +267 -0
- package/bin/lean/release-plan.test.mjs +202 -0
- package/bin/lean/release-preflight.mjs +16 -0
- package/bin/lean/release-regate.mjs +141 -0
- package/bin/lean/release-regate.test.mjs +149 -0
- package/bin/lean/release-review.mjs +5 -3
- package/bin/lean/release-rollback.mjs +277 -0
- package/bin/lean/release-rollback.test.mjs +245 -0
- package/bin/lean/release-snapshot.mjs +48 -9
- package/bin/lean/release-snapshot.test.mjs +43 -1
- package/bin/lean/release-start.mjs +164 -0
- package/bin/lean/release-start.test.mjs +171 -0
- package/bin/lean/release-status.mjs +6 -2
- package/bin/lean/release-train.mjs +159 -0
- package/bin/lean/release-train.test.mjs +139 -0
- package/bin/lean/release.mjs +127 -5
- package/bin/lean/release.test.mjs +80 -0
- package/bin/lean/sandbox-remote.mjs +2 -0
- package/bin/lean/schedd-load.test.mjs +82 -0
- package/bin/lean/schedd.mjs +67 -31
- package/bin/lean/schedd.test.mjs +80 -1
- package/bin/lean/validate-catalog.mjs +94 -0
- package/bin/lean/validate-catalog.test.mjs +42 -0
- package/bin/pool/agent.mjs +4 -1
- package/bin/pool/lane-tools.mjs +115 -0
- package/bin/pool/lane-tools.test.mjs +26 -0
- package/bin/pool/warm.mjs +1 -1
- package/docs/CONFIG.md +225 -1
- package/docs/ISSUE-WATCH.md +1 -0
- package/docs/design/visual-gate.md +10 -0
- package/docs/eval/adversarial-bench.md +1 -0
- package/package.json +5 -2
- package/pool/README.md +2 -0
- package/scripts/bench-adversarial.mjs +4 -0
- package/scripts/bench-lightlane.mjs +2 -1
- package/templates/github-actions/forge-conductor.scopes.json +7 -0
- package/templates/github-actions/forge-conductor.yml +57 -0
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// #5572: docs/CONFIG.md `release` section stays true to release-config.mjs and release.mjs; drift fails CI.
|
|
4
|
+
import { describe, it } from "node:test";
|
|
5
|
+
import assert from "node:assert/strict";
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
7
|
+
import { POLICY_SCHEMA, INIT_PROFILE, DEFERRED_KEYS, parsePolicy } from "./release-config.mjs";
|
|
8
|
+
import { RELEASE_USAGE } from "./release.mjs";
|
|
9
|
+
|
|
10
|
+
const DOC = readFileSync(new URL("../../docs/CONFIG.md", import.meta.url), "utf8");
|
|
11
|
+
const LEAN = readFileSync(new URL("../../devdocs/modules/lean.md", import.meta.url), "utf8");
|
|
12
|
+
|
|
13
|
+
const sectionOf = (text, re) => { const m = re.exec(text); if (!m) return ""; const rest = text.slice(m.index + m[0].length); const end = rest.search(/^## /m); return end < 0 ? rest : rest.slice(0, end); };
|
|
14
|
+
export const releaseSection = (doc) => sectionOf(doc, /^## `release` \(OPTIONAL\)\n/m);
|
|
15
|
+
const subsection = (sec, title) => { const i = sec.indexOf(title); if (i < 0) return ""; const rest = sec.slice(i + title.length); const e = rest.search(/^#{3,4} /m); return e < 0 ? rest : rest.slice(0, e); };
|
|
16
|
+
const policyRef = (sec) => { const i = sec.indexOf("### Policy reference"); if (i < 0) return ""; const rest = sec.slice(i + 3); const e = rest.search(/^### /m); return sec.slice(i, e < 0 ? undefined : i + 3 + e); };
|
|
17
|
+
|
|
18
|
+
/** Dotted key paths of the schema: `<name>` for map keys, `[]` for list items; every named key is a path. */
|
|
19
|
+
export function schemaPaths(schema) {
|
|
20
|
+
const out = [];
|
|
21
|
+
const walk = (n, p) => {
|
|
22
|
+
if (n.t === "object") for (const [k, c] of Object.entries(n.p)) { const q = p ? `${p}.${k}` : k; out.push(q); walk(c, q); }
|
|
23
|
+
else if (n.t === "map") walk(n.v, `${p}.<name>`);
|
|
24
|
+
else if (n.t === "array") walk(n.i, `${p}[]`);
|
|
25
|
+
};
|
|
26
|
+
walk(schema, "");
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
export const documentedPaths = (ref) => [...ref.matchAll(/^\| `([^`]+)` \|/gm)].map((m) => m[1]);
|
|
30
|
+
export function keyDrift(schema, doc) {
|
|
31
|
+
const want = schemaPaths(schema), have = documentedPaths(policyRef(releaseSection(doc)).split("\n#### ")[0]);
|
|
32
|
+
return { undocumented: want.filter((p) => !have.includes(p)), unknown: have.filter((p) => !want.includes(p)) };
|
|
33
|
+
}
|
|
34
|
+
/** Verbs of RELEASE_USAGE: the word after `forgedock release` in each segment, plus the control verbs. */
|
|
35
|
+
export function usageVerbs(usage) {
|
|
36
|
+
const verbs = new Set();
|
|
37
|
+
for (const seg of usage.split(" | ")) {
|
|
38
|
+
const m = /forgedock release ([a-z][a-z0-9-]*)(?: ([a-z|]+)(?: |$))?/.exec(seg);
|
|
39
|
+
if (!m) continue;
|
|
40
|
+
verbs.add(m[1]);
|
|
41
|
+
if (m[1] === "control" && m[2]) m[2].split("|").forEach((v) => verbs.add(v));
|
|
42
|
+
}
|
|
43
|
+
return [...verbs];
|
|
44
|
+
}
|
|
45
|
+
export const undocumentedVerbs = (usage, doc) => { const cli = subsection(policyRef(releaseSection(doc)), "#### CLI reference"); return usageVerbs(usage).filter((v) => !cli.includes(`\`forgedock release ${v}\``) && !new RegExp(`\`${v}\``).test(cli)); };
|
|
46
|
+
const STALE = [/not automated yet/, /`--watch`[^.\n]*has no effect/, /no `rollback` verb yet/];
|
|
47
|
+
export const stalePhrases = (text) => STALE.filter((re) => re.test(text)).map(String);
|
|
48
|
+
const fenced = (sub) => /```yaml\n([\s\S]*?)```/.exec(sub)?.[1] ?? "";
|
|
49
|
+
const deferredList = (sub) => [...sub.matchAll(/^- `([^`]+)`/gm)].map((m) => m[1]);
|
|
50
|
+
const norm = (k) => k.replace(/: /, "=");
|
|
51
|
+
|
|
52
|
+
describe("release docs (#5572)", () => {
|
|
53
|
+
it("every POLICY_SCHEMA key path is documented and every documented key exists", () => {
|
|
54
|
+
const d = keyDrift(POLICY_SCHEMA, DOC);
|
|
55
|
+
assert.deepEqual(d, { undocumented: [], unknown: [] });
|
|
56
|
+
assert.ok(schemaPaths(POLICY_SCHEMA).length > 100);
|
|
57
|
+
});
|
|
58
|
+
it("seeded: a schema key missing from the doc and a documented key missing from the schema both fail", () => {
|
|
59
|
+
const withNew = { ...POLICY_SCHEMA, p: { ...POLICY_SCHEMA.p, zzz_new_key: { t: "string" } } };
|
|
60
|
+
assert.deepEqual(keyDrift(withNew, DOC).undocumented, ["zzz_new_key"]);
|
|
61
|
+
const doc2 = DOC.replace("| `quarantine.max` |", "| `quarantine.bogus` |");
|
|
62
|
+
assert.deepEqual(keyDrift(POLICY_SCHEMA, doc2), { undocumented: ["quarantine.max"], unknown: ["quarantine.bogus"] });
|
|
63
|
+
});
|
|
64
|
+
it("the documented zero-config YAML equals INIT_PROFILE", () => {
|
|
65
|
+
const sub = subsection(policyRef(releaseSection(DOC)), "#### Zero-config profile");
|
|
66
|
+
assert.equal(fenced(sub), INIT_PROFILE);
|
|
67
|
+
assert.deepEqual(parsePolicy(fenced(sub)).policy, parsePolicy(INIT_PROFILE).policy);
|
|
68
|
+
});
|
|
69
|
+
it("the documented deferred keys equal DEFERRED_KEYS and are described as rejected", () => {
|
|
70
|
+
const sub = subsection(policyRef(releaseSection(DOC)), "#### Deferred keys");
|
|
71
|
+
assert.deepEqual(deferredList(sub).map(norm).sort(), DEFERRED_KEYS.map(norm).sort());
|
|
72
|
+
assert.match(sub, /rejected/);
|
|
73
|
+
});
|
|
74
|
+
it("every verb in RELEASE_USAGE is in the CLI reference, with intake and ci budget", () => {
|
|
75
|
+
assert.deepEqual(undocumentedVerbs(RELEASE_USAGE, DOC), []);
|
|
76
|
+
assert.ok(usageVerbs(RELEASE_USAGE).length >= 14);
|
|
77
|
+
const cli = subsection(policyRef(releaseSection(DOC)), "#### CLI reference");
|
|
78
|
+
for (const s of ["forgedock intake", "forgedock ci budget", "controls log", "ci flakes", "ci nightly"]) assert.ok(cli.includes(s), s);
|
|
79
|
+
});
|
|
80
|
+
it("seeded: an undocumented verb fails", () => {
|
|
81
|
+
assert.deepEqual(undocumentedVerbs(`${RELEASE_USAGE} | forgedock release zzzverb [--x]`, DOC), ["zzzverb"]);
|
|
82
|
+
});
|
|
83
|
+
it("stale phrases stay out of the release section and lean.md", () => {
|
|
84
|
+
assert.deepEqual(stalePhrases(releaseSection(DOC)), []);
|
|
85
|
+
assert.deepEqual(stalePhrases(LEAN), []);
|
|
86
|
+
assert.ok(releaseSection(DOC).length > 1000);
|
|
87
|
+
});
|
|
88
|
+
it("seeded: stale phrases are detected", () => {
|
|
89
|
+
assert.equal(stalePhrases("Review and fixes are not automated yet.").length, 1);
|
|
90
|
+
assert.equal(stalePhrases("`--watch` has no effect").length, 1);
|
|
91
|
+
assert.equal(stalePhrases("there is no `rollback` verb yet").length, 1);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
@@ -11,6 +11,8 @@ import { readActive } from "./release-ledger.mjs";
|
|
|
11
11
|
import { holdCheck } from "./release-control.mjs";
|
|
12
12
|
|
|
13
13
|
export const epochTrailer = (epoch) => `Forge-Epoch: ${epoch}`;
|
|
14
|
+
/** Landing-merge trailers of a fast lane (#5570): lane, release id and lease epoch, one per line. */
|
|
15
|
+
export const laneTrailers = ({ lane, release, epoch }) => [`Forge-Lane: ${lane}`, `Forge-Release: ${release}`, ...(epoch != null ? [epochTrailer(epoch)] : [])].join("\n");
|
|
14
16
|
export const epochMarker = (epoch) => `<!-- FORGE:EPOCH ${epoch} -->`;
|
|
15
17
|
|
|
16
18
|
/** @returns {{ok: true, epoch} | {fenced: true, current} | {unreadable: string}} */
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Release gate (#5561, epic #5549, invariants I1/I5): the merge to the default branch depends on the `forge/release-gate`
|
|
5
|
+
* check run produced by a workflow from real CI conclusions, never on an agent-posted GATE_PASS marker. `computeGate` is the
|
|
6
|
+
* pure function that workflow runs; `readReleaseGate` reads the check run (accepted only from the configured app);
|
|
7
|
+
* `mergeGuard` is the MERGING guard. Every function fails closed on unreadable input.
|
|
8
|
+
*/
|
|
9
|
+
import { checkChain } from "./release-snapshot.mjs";
|
|
10
|
+
import { assertRole } from "./release-credentials.mjs";
|
|
11
|
+
|
|
12
|
+
export const GATE_CHECK = "forge/release-gate";
|
|
13
|
+
const PASS_VERDICTS = ["pass", "approve", "approved", "approve for deploy"]; // the last is the review-staging verdict (bin/review-staging.mjs:650)
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Pass only when every required check concluded `success` on exactly `head` (neutral, skipped, missing and other-sha runs do
|
|
17
|
+
* not count) and the review verdict was recorded for `head`.
|
|
18
|
+
* @param {{checks: {name: string, conclusion: string, head?: string, sha?: string}[], required: string[], reviewVerdict: {head: string, verdict: string}, head: string}} p
|
|
19
|
+
* @returns {{pass: boolean, reasons: string[]}}
|
|
20
|
+
*/
|
|
21
|
+
export function computeGate({ checks, required, reviewVerdict, head } = {}) {
|
|
22
|
+
const no = (...reasons) => ({ pass: false, reasons });
|
|
23
|
+
if (typeof head !== "string" || !head) return no("unreadable input: no head sha");
|
|
24
|
+
if (!Array.isArray(checks)) return no("unreadable input: checks");
|
|
25
|
+
if (!Array.isArray(required) || !required.length || required.some((r) => typeof r !== "string" || !r)) return no("unreadable input: no required checks");
|
|
26
|
+
const reasons = [];
|
|
27
|
+
for (const name of required) {
|
|
28
|
+
const runs = checks.filter((c) => c?.name === name && (c.head ?? c.sha) === head);
|
|
29
|
+
if (!runs.length) reasons.push(`${name}: missing on ${head}`);
|
|
30
|
+
else if (!runs.every((c) => c.conclusion === "success")) reasons.push(`${name}: ${runs.find((c) => c.conclusion !== "success").conclusion ?? "unfinished"}, not success`);
|
|
31
|
+
}
|
|
32
|
+
if (!reviewVerdict || typeof reviewVerdict !== "object") reasons.push("review verdict: not recorded");
|
|
33
|
+
else if (reviewVerdict.head !== head) reasons.push(`review verdict is for ${reviewVerdict.head ?? "no head"}, not ${head}`);
|
|
34
|
+
else if (!PASS_VERDICTS.includes(String(reviewVerdict.verdict ?? "").toLowerCase())) reasons.push(`review verdict is ${reviewVerdict.verdict ?? "absent"}`);
|
|
35
|
+
return reasons.length ? { pass: false, reasons } : { pass: true, reasons: [] };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The `forge/release-gate` check run at `head`, accepted only from the configured gate app.
|
|
40
|
+
* @returns {Promise<{ok: true, conclusion: string} | {ok: false, why: string}>}
|
|
41
|
+
*/
|
|
42
|
+
export async function readReleaseGate({ io, repo, head, identity }) {
|
|
43
|
+
if (!identity?.app) return { ok: false, why: "no gate identity configured (credentials.gate_app)" };
|
|
44
|
+
let runs;
|
|
45
|
+
try { runs = JSON.parse(await io.gh(["api", `repos/${repo}/commits/${head}/check-runs`, "--jq", "[.check_runs[] | {name, conclusion, head: .head_sha, app: .app.slug}]"])); } catch (e) { return { ok: false, why: `cannot read check runs: ${String(e?.message ?? e).split("\n")[0]}` }; }
|
|
46
|
+
if (!Array.isArray(runs)) return { ok: false, why: "cannot read check runs: unexpected shape" };
|
|
47
|
+
const mine = runs.filter((c) => c?.name === GATE_CHECK && c.head === head);
|
|
48
|
+
if (!mine.length) return { ok: false, why: `no ${GATE_CHECK} on ${head}` };
|
|
49
|
+
const trusted = mine.filter((c) => c.app === identity.app);
|
|
50
|
+
if (!trusted.length) return { ok: false, why: `${GATE_CHECK} on ${head} was not posted by ${identity.app}` };
|
|
51
|
+
return { ok: true, conclusion: trusted.every((c) => c.conclusion === "success") ? "success" : String(trusted.find((c) => c.conclusion !== "success").conclusion ?? "pending") };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* MERGING guard (I1): plan approval current (hash match, I2), every required check green on the exact head, the gate status
|
|
56
|
+
* exists for that sha and passed, and head == cut sha + recorded picks (`checkChain`, including main-sync).
|
|
57
|
+
* @returns {Promise<{ok: true} | {ok: false, why: string}>}
|
|
58
|
+
*/
|
|
59
|
+
export async function mergeGuard({ io, repo, head, state, policy, staging }) {
|
|
60
|
+
const no = (why) => ({ ok: false, why });
|
|
61
|
+
const plan = state?.plan;
|
|
62
|
+
if (!policy) return no("release policy is unreadable");
|
|
63
|
+
// I2: a recorded plan must be approved at its current hash. No plan recorded (the plan step is a separate change) is accepted only under `plan.approval: auto`.
|
|
64
|
+
if (plan?.hash ? plan.approved_hash !== plan.hash : policy.plan?.approval !== "auto") return no("plan approval is not current (approved hash does not match the plan hash)");
|
|
65
|
+
const required = policy.ci?.required_checks;
|
|
66
|
+
let checks;
|
|
67
|
+
try { checks = JSON.parse(await io.gh(["api", `repos/${repo}/commits/${head}/check-runs`, "--jq", "[.check_runs[] | {name, conclusion, head: .head_sha}]"])); } catch (e) { return no(`cannot read check runs: ${String(e?.message ?? e).split("\n")[0]}`); }
|
|
68
|
+
const rev = state.steps?.review?.result;
|
|
69
|
+
const g = computeGate({ checks, required, reviewVerdict: rev ? { head: rev.head, verdict: rev.verdict } : null, head });
|
|
70
|
+
if (!g.pass) return no(`required checks not green: ${g.reasons.join("; ")}`);
|
|
71
|
+
const gate = await readReleaseGate({ io, repo, head, identity: { app: policy.credentials?.gate_app } });
|
|
72
|
+
if (!gate.ok) return no(gate.why);
|
|
73
|
+
if (gate.conclusion !== "success") return no(`${GATE_CHECK} is ${gate.conclusion}, not success`);
|
|
74
|
+
if (!state.release) return no("no FORGE:RELEASE record to verify the head against");
|
|
75
|
+
const chain = checkChain({ git: io.git, record: state.release, sha: head, staging, exact: true });
|
|
76
|
+
if (!chain.ok) return no(`release head ${head} is not snapshot + recorded cherry-picks: ${chain.why}`);
|
|
77
|
+
return { ok: true };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The sole in-repo writer of the `forge/release-gate` check run (the gate workflow normally posts it): refused unless the context holds the `gate` role (I12).
|
|
82
|
+
* @returns {Promise<{posted: true}>} throws `{refused}` for any other role
|
|
83
|
+
*/
|
|
84
|
+
export async function postReleaseGate({ io, ctx, repo, head, conclusion }) {
|
|
85
|
+
assertRole(ctx, "gate-post");
|
|
86
|
+
await io.gh(["api", `repos/${repo}/check-runs`, "-f", `name=${GATE_CHECK}`, "-f", `head_sha=${head}`, "-f", "status=completed", "-f", `conclusion=${conclusion}`]);
|
|
87
|
+
return { posted: true };
|
|
88
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { computeGate, readReleaseGate, mergeGuard, postReleaseGate, GATE_CHECK } from "./release-gate.mjs";
|
|
6
|
+
|
|
7
|
+
const H = "a".repeat(40), OLD = "b".repeat(40);
|
|
8
|
+
const run = (name, conclusion, head = H) => ({ name, conclusion, head });
|
|
9
|
+
const verdict = { head: H, verdict: "pass" };
|
|
10
|
+
const base = { required: ["ci", "lint"], reviewVerdict: verdict, head: H };
|
|
11
|
+
|
|
12
|
+
describe("computeGate (#5561)", () => {
|
|
13
|
+
const rows = [
|
|
14
|
+
["success", [run("ci", "success"), run("lint", "success")], true],
|
|
15
|
+
["failure", [run("ci", "failure"), run("lint", "success")], false],
|
|
16
|
+
["neutral", [run("ci", "neutral"), run("lint", "success")], false],
|
|
17
|
+
["skipped", [run("ci", "skipped"), run("lint", "success")], false],
|
|
18
|
+
["missing", [run("ci", "success")], false],
|
|
19
|
+
["wrong head", [run("ci", "success", OLD), run("lint", "success")], false],
|
|
20
|
+
["one rerun red", [run("ci", "success"), run("ci", "failure"), run("lint", "success")], false],
|
|
21
|
+
];
|
|
22
|
+
for (const [name, checks, pass] of rows) it(name, () => assert.equal(computeGate({ ...base, checks }).pass, pass));
|
|
23
|
+
const ok = [run("ci", "success"), run("lint", "success")];
|
|
24
|
+
it("stale verdict (other head), failing verdict, no verdict", () => {
|
|
25
|
+
assert.equal(computeGate({ ...base, checks: ok, reviewVerdict: { head: OLD, verdict: "pass" } }).pass, false);
|
|
26
|
+
assert.equal(computeGate({ ...base, checks: ok, reviewVerdict: { head: H, verdict: "blocked" } }).pass, false);
|
|
27
|
+
assert.equal(computeGate({ ...base, checks: ok, reviewVerdict: null }).pass, false);
|
|
28
|
+
});
|
|
29
|
+
it("fails closed on unreadable input", () => {
|
|
30
|
+
for (const bad of [{ checks: "x" }, { checks: ok, required: [] }, { checks: ok, required: undefined }, { checks: ok, head: undefined }, {}]) assert.equal(computeGate({ ...base, ...bad }).pass, false);
|
|
31
|
+
assert.equal(computeGate().pass, false);
|
|
32
|
+
});
|
|
33
|
+
it("I1 fixture matrix: the merging actor (App or human) and check-skip rules never change the result; a skipped required check is not green", () => {
|
|
34
|
+
const matrix = [
|
|
35
|
+
{ actor: "app", conclusion: "success", pass: true },
|
|
36
|
+
{ actor: "app", conclusion: "skipped", pass: false }, // an App-authored merge does not make a check-skip rule count as success
|
|
37
|
+
{ actor: "human", conclusion: "success", pass: true },
|
|
38
|
+
{ actor: "human", conclusion: "skipped", pass: false },
|
|
39
|
+
];
|
|
40
|
+
for (const row of matrix) assert.equal(computeGate({ ...base, checks: [run("ci", row.conclusion), run("lint", "success")] }).pass, row.pass, JSON.stringify(row));
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const ioWith = (checks, extra = {}) => ({ gh: async () => { if (checks instanceof Error) throw checks; return JSON.stringify(checks); }, git: () => "", ...extra });
|
|
45
|
+
|
|
46
|
+
describe("readReleaseGate (#5561)", () => {
|
|
47
|
+
const gate = (conclusion, app) => ({ name: GATE_CHECK, conclusion, head: H, app });
|
|
48
|
+
it("accepts the check run only from the configured app", async () => {
|
|
49
|
+
assert.deepEqual(await readReleaseGate({ io: ioWith([gate("success", "gate-app")]), repo: "o/r", head: H, identity: { app: "gate-app" } }), { ok: true, conclusion: "success" });
|
|
50
|
+
assert.match((await readReleaseGate({ io: ioWith([gate("success", "forge-bot")]), repo: "o/r", head: H, identity: { app: "gate-app" } })).why, /not posted by gate-app/);
|
|
51
|
+
});
|
|
52
|
+
it("refuses when absent for the sha, unreadable or no identity is configured", async () => {
|
|
53
|
+
assert.match((await readReleaseGate({ io: ioWith([]), repo: "o/r", head: H, identity: { app: "a" } })).why, /no forge\/release-gate/);
|
|
54
|
+
assert.match((await readReleaseGate({ io: ioWith(new Error("boom")), repo: "o/r", head: H, identity: { app: "a" } })).why, /cannot read/);
|
|
55
|
+
assert.match((await readReleaseGate({ io: ioWith([gate("success", "a")]), repo: "o/r", head: H, identity: {} })).why, /no gate identity/);
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
describe("mergeGuard I1 actor matrix (#5561)", () => {
|
|
60
|
+
// Documented: the I1 case. Required checks skipped (check-skip rules) or a gate run posted by anyone but the configured App never count, whoever authored the merge.
|
|
61
|
+
const policy = { ci: { required_checks: ["ci"] }, credentials: { gate_app: "gate-app" }, plan: { approval: "auto" } };
|
|
62
|
+
const state = { release: null, steps: { review: { result: { head: H, verdict: "pass" } } } };
|
|
63
|
+
const rows = [
|
|
64
|
+
{ ci: "success", gateApp: "gate-app", expect: /no FORGE:RELEASE record/ }, // gates pass; refused later only for the missing record
|
|
65
|
+
{ ci: "skipped", gateApp: "gate-app", expect: /required checks not green/ },
|
|
66
|
+
{ ci: "success", gateApp: "agent-bot", expect: /not posted by gate-app/ },
|
|
67
|
+
{ ci: "success", gateApp: "someone", expect: /not posted by gate-app/ },
|
|
68
|
+
];
|
|
69
|
+
for (const row of rows) it(`ci ${row.ci}, gate posted by ${row.gateApp}`, async () => {
|
|
70
|
+
const checks = [{ name: "ci", conclusion: row.ci, head: H }, { name: GATE_CHECK, conclusion: "success", head: H, app: row.gateApp }];
|
|
71
|
+
assert.match((await mergeGuard({ io: ioWith(checks), repo: "o/r", head: H, state, policy, staging: "staging" })).why, row.expect);
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
describe("mergeGuard (#5561)", () => {
|
|
76
|
+
const policy = { ci: { required_checks: ["ci"] }, credentials: { gate_app: "gate-app" } };
|
|
77
|
+
const state = (over = {}) => ({ plan: { hash: "h1", approved_hash: "h1" }, release: null, steps: { review: { result: { head: H, verdict: "pass" } } }, ...over });
|
|
78
|
+
const checks = [run("ci", "success"), { name: GATE_CHECK, conclusion: "success", head: H, app: "gate-app" }];
|
|
79
|
+
const call = (o = {}) => mergeGuard({ io: ioWith(o.checks ?? checks), repo: "o/r", head: H, state: o.state ?? state(), policy: "policy" in o ? o.policy : policy, staging: "staging" });
|
|
80
|
+
it("a forged GATE_PASS marker is never sufficient: no check run, refused", async () => {
|
|
81
|
+
const r = await call({ checks: [run("ci", "success")], state: state({ gateMarker: "GATE_PASS" }) });
|
|
82
|
+
assert.match(r.why, /no forge\/release-gate/);
|
|
83
|
+
});
|
|
84
|
+
it("stale approval hash, missing plan, unreadable policy and unreadable checks refuse", async () => {
|
|
85
|
+
assert.match((await call({ state: state({ plan: { hash: "h2", approved_hash: "h1" } }) })).why, /approval is not current/);
|
|
86
|
+
assert.match((await call({ state: state({ plan: undefined }) })).why, /approval is not current/);
|
|
87
|
+
assert.match((await call({ state: state({ plan: undefined }), policy: { ...policy, plan: { approval: "auto" } } })).why, /no FORGE:RELEASE record/); // auto policy: no plan needed, the next guard answers
|
|
88
|
+
assert.match((await call({ policy: null })).why, /policy is unreadable/);
|
|
89
|
+
assert.match((await call({ checks: new Error("x") })).why, /cannot read check runs/);
|
|
90
|
+
});
|
|
91
|
+
it("a required check not green on the head refuses; a green head without a release record refuses", async () => {
|
|
92
|
+
assert.match((await call({ checks: [run("ci", "failure"), checks[1]] })).why, /required checks not green/);
|
|
93
|
+
assert.match((await call()).why, /no FORGE:RELEASE record/);
|
|
94
|
+
});
|
|
95
|
+
it("head moved by one commit refuses via checkChain", async () => {
|
|
96
|
+
const rec = { snapshot: "s".repeat(40), picks: [] };
|
|
97
|
+
const git = (a) => { if (a[0] === "rev-parse") return "t\n"; if (a[0] === "merge-base") throw new Error("not ancestor"); return "\n"; };
|
|
98
|
+
const r = await mergeGuard({ io: { ...ioWith(checks), git }, repo: "o/r", head: H, state: state({ release: rec }), policy, staging: "staging" });
|
|
99
|
+
assert.equal(r.ok, false);
|
|
100
|
+
assert.match(r.why, /not snapshot \+ recorded cherry-picks/);
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
describe("real review verdict and gate posting (#5561)", () => {
|
|
105
|
+
it("the review-staging verdict APPROVE FOR DEPLOY passes computeGate; REQUEST CHANGES does not", () => {
|
|
106
|
+
const base = { checks: [run("ci", "success")], required: ["ci"], head: H };
|
|
107
|
+
assert.equal(computeGate({ ...base, reviewVerdict: { head: H, verdict: "APPROVE FOR DEPLOY" } }).pass, true);
|
|
108
|
+
assert.equal(computeGate({ ...base, reviewVerdict: { head: H, verdict: "REQUEST CHANGES" } }).pass, false);
|
|
109
|
+
});
|
|
110
|
+
it("gate-post is refused for lane and driver roles and allowed for the gate role", async () => {
|
|
111
|
+
const calls = [], io = { gh: async (a) => { calls.push(a); return ""; } };
|
|
112
|
+
for (const credential of ["lane", "driver"]) await assert.rejects(postReleaseGate({ io, ctx: { credential }, repo: "o/r", head: H, conclusion: "success" }), (e) => e.refused === `role ${credential} may not gate-post`);
|
|
113
|
+
assert.equal(calls.length, 0);
|
|
114
|
+
assert.deepEqual(await postReleaseGate({ io, ctx: { credential: "gate" }, repo: "o/r", head: H, conclusion: "success" }), { posted: true });
|
|
115
|
+
});
|
|
116
|
+
});
|
|
@@ -22,6 +22,7 @@ export const TELEMETRY_SCHEMA = "forgedock.release.gate/v1";
|
|
|
22
22
|
export const REPORT_SCHEMA = "forgedock.release.gates/v1";
|
|
23
23
|
export const DEMOTE_MODES = ["warn", "inconclusive"];
|
|
24
24
|
export const SAFETY_DEFAULT = ["migration-immutability", "identity-preflight", "backup-freshness", "health-auto-restore"];
|
|
25
|
+
export const GATE_PATHS_DEFAULT = ["scripts/deploy/**", "scripts/lib/**", "scripts/prod-smoke-test.sh", "**/gate-fixtures/**", "tests/gates/**"];
|
|
25
26
|
export const REQUIRED = ["id", "protects_against", "where", "determinism", "pre_merge_artifact", "version", "mode", "owner", "review_by"];
|
|
26
27
|
const OPTIONAL = ["on_uncertainty", "failure_triggers", "proportionality"];
|
|
27
28
|
const DAY_MS = 86_400_000;
|
|
@@ -71,6 +72,8 @@ export function parseGatesConfig(policy) {
|
|
|
71
72
|
demoteFbRate: Number(g.demote_fb_rate) >= 0 && g.demote_fb_rate != null ? Number(g.demote_fb_rate) : 5,
|
|
72
73
|
demoteWindow: Number.isInteger(g.demote_window) && g.demote_window > 0 ? g.demote_window : 20,
|
|
73
74
|
safety: Array.isArray(g.safety) ? g.safety.map(String) : SAFETY_DEFAULT,
|
|
75
|
+
paths: Array.isArray(g.paths) && g.paths.length ? g.paths.map(String) : GATE_PATHS_DEFAULT, // #5584: the gate-only allowlist
|
|
76
|
+
workflowSteps: Array.isArray(g.workflow_steps) ? g.workflow_steps.map(String) : [],
|
|
74
77
|
};
|
|
75
78
|
}
|
|
76
79
|
|
|
@@ -79,11 +82,12 @@ export const isSafetyGate = (gate, safety = SAFETY_DEFAULT) =>
|
|
|
79
82
|
isUnskippable(String(gate)) || safety.some((s) => gate === s || String(gate).startsWith(`${s}:`) || String(gate).startsWith(`${s}/`));
|
|
80
83
|
|
|
81
84
|
/** One telemetry record, or null for an unknown gate or outcome. A TP/FB class needs a non-empty `evidence`, else `unknown`. */
|
|
82
|
-
export function gateRecord({ gate, outcome, class: cls, evidence, minutes = 0 }) {
|
|
85
|
+
export function gateRecord({ gate, outcome, class: cls, evidence, minutes = 0, gate_sha: gateSha }) {
|
|
83
86
|
if (!gate || !OUTCOMES.includes(outcome)) return null;
|
|
84
87
|
const ev = typeof evidence === "string" ? evidence.trim() : "";
|
|
85
88
|
const r = { gate: String(gate), outcome, class: (cls === "TP" || cls === "FB") && ev ? cls : "unknown", minutes: Number(minutes) > 0 ? Number(minutes) : 0 };
|
|
86
89
|
if (ev) r.evidence = ev;
|
|
90
|
+
if (typeof gateSha === "string" && /^[0-9a-f]{7,64}$/i.test(gateSha)) r.gate_sha = gateSha; // #5584: the gate-script sha that evaluated this gate
|
|
87
91
|
return r;
|
|
88
92
|
}
|
|
89
93
|
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
* Off unless forge.yaml `release.managed` is on; nothing here runs otherwise.
|
|
13
13
|
*/
|
|
14
14
|
import { SECRET_PAIR_RE, SECRET_SHAPE_RE } from "./conformance.mjs";
|
|
15
|
+
import { roleRefusal } from "./release-credentials.mjs";
|
|
15
16
|
|
|
16
17
|
export const LEDGER_PREFIX = "forge-ledger/";
|
|
17
18
|
export const ACTIVE = "_active";
|
|
@@ -46,7 +47,7 @@ const readFile = async ({ io, repo }, branch, path) => {
|
|
|
46
47
|
};
|
|
47
48
|
|
|
48
49
|
/** The driver credential writes the ledger; a lane credential never does (I12). */
|
|
49
|
-
const assertDriver = (ctx) => {
|
|
50
|
+
const assertDriver = (ctx) => { const why = roleRefusal(ctx.credential, "ledger-write"); if (why) throw Object.assign(new Error(`ledger writes need the driver credential (${why})`), { refused: "not-driver" }); };
|
|
50
51
|
|
|
51
52
|
/**
|
|
52
53
|
* One commit of `files` ({path: text}, redacted) on `branch` on top of `parent` (null = orphan, creates the branch).
|
|
@@ -174,3 +175,48 @@ export async function listLedgers({ io, repo }) {
|
|
|
174
175
|
try { refs = (await io.api("GET", `repos/${repo}/git/matching-refs/heads/${LEDGER_PREFIX}`)) ?? []; } catch (e) { if (!isMissing(e)) throw e; }
|
|
175
176
|
return refs.map((r) => String(r.ref).slice(`refs/heads/${LEDGER_PREFIX}`.length)).filter((id) => id !== ACTIVE && ID_RE.test(id));
|
|
176
177
|
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* #5565: one DEPLOYING release at a time. Claims `_active.deploying` for `release`; another release's claim refuses (`{queued}`) unless
|
|
181
|
+
* `preempt`, which takes it over and writes an audit line (`p0-preempt`) to controls.jsonl. @returns {{ok: true, preempted?: string} | {queued: string} | {lost: true}}
|
|
182
|
+
*/
|
|
183
|
+
export async function claimDeploy(ctx, { release, preempt = false, actor = "engine", reason = "", now = Date.now() }) {
|
|
184
|
+
let preempted = null;
|
|
185
|
+
const at = new Date(now).toISOString();
|
|
186
|
+
const r = await updateActive(ctx, ["deploying"], async (active) => {
|
|
187
|
+
const cur = active.deploying;
|
|
188
|
+
if (cur && cur.release !== release) {
|
|
189
|
+
if (!preempt) return { refuse: `release ${cur.release} is DEPLOYING; deploys never overlap (pass --preempt to cancel it)` };
|
|
190
|
+
preempted = cur.release;
|
|
191
|
+
return { patch: { deploying: { release, since: at } }, control: { at, actor, verb: "p0-preempt", release, preempted: cur.release, reason } };
|
|
192
|
+
}
|
|
193
|
+
return { patch: { deploying: { release, since: cur?.since ?? at } } };
|
|
194
|
+
});
|
|
195
|
+
if (r.refused) return { queued: r.refused };
|
|
196
|
+
if (!r.ok) return { lost: true };
|
|
197
|
+
return { ok: true, ...(preempted ? { preempted } : {}) };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Release the DEPLOYING claim when it is still `release`'s. */
|
|
201
|
+
export async function releaseDeploy(ctx, release) {
|
|
202
|
+
return updateActive(ctx, ["deploying"], (active) => (active.deploying?.release === release ? { patch: { deploying: null } } : { refuse: "not the deploying release" }));
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** #5565 (I10): a p0 started while the default branch != live; the divergence is kept in `_active.p0` with an audit line. */
|
|
206
|
+
export async function recordP0Divergence(ctx, rec, now = Date.now()) {
|
|
207
|
+
const at = new Date(now).toISOString();
|
|
208
|
+
return updateActive(ctx, ["p0"], (active) => ({ patch: { p0: { ...(active.p0 ?? {}), [rec.release ?? "-"]: { ...rec, at } } }, control: { at, verb: "p0-divergence", ...rec } }));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** #5566: the merge-back sync of a fast lane (PR, conflicts, target set, validation) kept in `_active.sync` with an audit line. */
|
|
212
|
+
export async function recordSync(ctx, rec, now = Date.now()) {
|
|
213
|
+
const at = new Date(now).toISOString();
|
|
214
|
+
const { milestones, duplicates, ...audit } = rec;
|
|
215
|
+
return updateActive(ctx, ["sync"], () => ({ patch: { sync: { ...rec, at } }, control: { at, verb: "sync", ...audit, milestones: milestones?.length ?? 0, duplicates: duplicates?.length ?? 0 } }));
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** #5570: a landed train wave (lane `train`, state, rolled units, branch, merge sha) kept in `_active.train` so a repo-side check can read it; the service deploy invalidates the rollout record. */
|
|
219
|
+
export async function recordTrain(ctx, rec, now = Date.now()) {
|
|
220
|
+
const at = new Date(now).toISOString();
|
|
221
|
+
return updateActive(ctx, ["train"], (active) => ({ patch: { train: { ...(active.train ?? {}), [rec.release ?? "-"]: { ...rec, lane: "train", rollout_invalidated: true, at } } }, control: { at, verb: "train", lane: "train", release: rec.release ?? null, state: rec.state ?? null, units: rec.units?.length ?? 0, rollout_invalidated: true } }));
|
|
222
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { INIT_PROFILE } from "./release-config.mjs";
|
|
3
4
|
import { describe, it } from "node:test";
|
|
4
5
|
import assert from "node:assert/strict";
|
|
5
6
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
@@ -155,6 +156,7 @@ async function commitHead(g) { // a foreign writer commits on top of the current
|
|
|
155
156
|
describe("release fencing through the job (#5553)", () => {
|
|
156
157
|
const HEAD = "a".repeat(40);
|
|
157
158
|
const mkIo = (g, holder, calls) => ({ holder, print() {}, now: () => 1_700_000_000_000, sleep: async () => {}, runningLanes: async () => [], batches: async () => [], setParallel: async () => {}, api: g.api,
|
|
159
|
+
git: () => INIT_PROFILE, mergeGuard: async () => ({ ok: true }), // the merge guard has its own tests (release-gate.test.mjs, release.test.mjs)
|
|
158
160
|
gh: async (a) => {
|
|
159
161
|
const j = a.join(" ");
|
|
160
162
|
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" }] });
|
|
@@ -171,7 +173,7 @@ describe("release fencing through the job (#5553)", () => {
|
|
|
171
173
|
const out = await go(mkIo(g, "hostA", calls), null, tmpDir("fa-"));
|
|
172
174
|
assert.equal(out.status, "done");
|
|
173
175
|
assert.equal(calls.length, 1);
|
|
174
|
-
assert.deepEqual(calls[0].slice(-2), ["--body",
|
|
176
|
+
assert.deepEqual(calls[0].slice(-2), ["--body", `Forge-Release: ${ID}\nForge-Epoch: 1`]);
|
|
175
177
|
const st = (await readLedger(ctxOf(g), ID)).state;
|
|
176
178
|
assert.deepEqual(st.intents.map((i) => [i.action, i.epoch, i.done]), [["merge", 1, true]]);
|
|
177
179
|
});
|
|
@@ -224,3 +226,33 @@ describe("release fencing through the job (#5553)", () => {
|
|
|
224
226
|
}
|
|
225
227
|
});
|
|
226
228
|
});
|
|
229
|
+
|
|
230
|
+
describe("claimDeploy (#5565)", async () => {
|
|
231
|
+
const { claimDeploy, releaseDeploy } = await import("./release-ledger.mjs");
|
|
232
|
+
it("refuses an overlapping deploy, preempts only on request, releases", async () => {
|
|
233
|
+
const gh = fakeGh();
|
|
234
|
+
const io = { api: gh.api, now: () => gh.now, sleep: async () => {} };
|
|
235
|
+
const ctx = { io, repo: REPO, credential: "driver" };
|
|
236
|
+
assert.equal((await claimDeploy(ctx, { release: "r1" })).ok, true);
|
|
237
|
+
assert.equal((await claimDeploy(ctx, { release: "r1" })).ok, true);
|
|
238
|
+
assert.match((await claimDeploy(ctx, { release: "r2" })).queued, /DEPLOYING/);
|
|
239
|
+
const p = await claimDeploy(ctx, { release: "r2", preempt: true });
|
|
240
|
+
assert.equal(p.preempted, "r1");
|
|
241
|
+
await releaseDeploy(ctx, "r2");
|
|
242
|
+
assert.equal((await claimDeploy(ctx, { release: "r3" })).ok, true);
|
|
243
|
+
});
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
describe("recordSync (#5566)", async () => {
|
|
247
|
+
const { recordSync } = await import("./release-ledger.mjs");
|
|
248
|
+
it("keeps the sync in _active.sync and appends one audit line", async () => {
|
|
249
|
+
const g = fakeGh(), ctx = ctxOf(g);
|
|
250
|
+
const r = await recordSync(ctx, { pr: 7, conflicted: true, target: ["a.js"], milestones: [{ branch: "milestone/x" }], duplicates: [] }, 0);
|
|
251
|
+
assert.equal(r.ok, true);
|
|
252
|
+
assert.equal(r.active.sync.pr, 7);
|
|
253
|
+
const files = g.trees.get(g.commits.get(g.refs.get(ACTIVE)).tree);
|
|
254
|
+
const line = JSON.parse(files["controls.jsonl"].trim());
|
|
255
|
+
assert.equal(line.verb, "sync");
|
|
256
|
+
assert.equal(line.milestones, 1);
|
|
257
|
+
});
|
|
258
|
+
});
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Merge-back after a fast lane (#5566, epic #5549 Phase 4; design 6.7 point 6, risks R3 R4): once a p0 or train has landed on the
|
|
5
|
+
* default branch, sync it back into the integration branch through a sync PR (merge commit, never squash). Staging has no CI by
|
|
6
|
+
* policy, so a conflicted sync must not land unvalidated code: the PR gets the review panel plus a targeted preflight over the
|
|
7
|
+
* recorded target set (every conflict file and every file the lane changed), and `syncBlocksRelease` holds `release start` for
|
|
8
|
+
* lane `release` until it is merged and green. Facts (target set, hunk overlap, stale milestones) are deterministic git/gh reads.
|
|
9
|
+
* Every effect goes through `io` (`git`, `gh`, `api`); with `release.managed` off nothing is read or written.
|
|
10
|
+
*/
|
|
11
|
+
import { DEFAULT_STAGING_BRANCH } from "./lane.mjs";
|
|
12
|
+
import { recordSync } from "./release-ledger.mjs";
|
|
13
|
+
import { setIntake } from "./intake.mjs";
|
|
14
|
+
import { reviewStep } from "./release-review.mjs";
|
|
15
|
+
import { runTargetedPreflight } from "./release-preflight.mjs";
|
|
16
|
+
|
|
17
|
+
export const SYNC_BOUNDS = { pollMs: 10_000, mergePolls: 30 };
|
|
18
|
+
export const HAZARD = "stale-vs-main: this milestone branch predates the sync; a later squash merge of it can drop or re-apply lane changes (squash/ancestry hazard); merge the integration branch into it first";
|
|
19
|
+
const json = (s) => JSON.parse(String(s || "null"));
|
|
20
|
+
const uniq = (a) => [...new Set(a)];
|
|
21
|
+
|
|
22
|
+
/** A sync is blocked until it is merged and green: conflicted, unreviewed, or a preflight that does not cover the target set is unvalidated. */
|
|
23
|
+
export function syncValidated(sync) {
|
|
24
|
+
if (!sync) return false;
|
|
25
|
+
const covered = new Set(sync.preflight?.covered ?? []);
|
|
26
|
+
return !sync.conflicted && sync.preflight?.ok === true && (sync.target ?? []).every((f) => covered.has(f)) && sync.review?.ok === true;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* `release start` for lane `release` is held while a recorded sync is conflicted, unvalidated or unmerged; trains and p0 are never
|
|
31
|
+
* blocked. `state` is the ledger `_active` view (or the sync record itself). @returns {boolean}
|
|
32
|
+
*/
|
|
33
|
+
export function syncBlocksRelease(state, lane = state?.lane ?? "release") {
|
|
34
|
+
if (lane !== "release") return false;
|
|
35
|
+
const sync = state?.sync ?? (state?.target ? state : null);
|
|
36
|
+
if (!sync) return false;
|
|
37
|
+
return !(sync.merged === true && syncValidated(sync));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Old-side line ranges per file from a `-U0` unified diff: `{file: [[start, end], ...]}`. */
|
|
41
|
+
export function diffRanges(diff) {
|
|
42
|
+
const out = {};
|
|
43
|
+
let file = null;
|
|
44
|
+
for (const line of String(diff ?? "").split("\n")) {
|
|
45
|
+
const f = /^\+\+\+ (?:b\/)?(.+)$/.exec(line);
|
|
46
|
+
if (f) { file = f[1] === "/dev/null" ? null : f[1]; continue; }
|
|
47
|
+
const m = /^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/.exec(line);
|
|
48
|
+
if (m && file) { const s = Number(m[1]), n = m[2] === undefined ? 1 : Number(m[2]); (out[file] ??= []).push([s, s + Math.max(n, 1) - 1]); }
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Open PRs whose hunks overlap a lane hunk (same file, intersecting line range). @returns {{pr, files}[]} */
|
|
54
|
+
export function duplicateFixes(laneHunks, prs) {
|
|
55
|
+
const hits = [];
|
|
56
|
+
for (const p of prs) {
|
|
57
|
+
const files = Object.keys(p.hunks ?? {}).filter((f) => (laneHunks[f] ?? []).some(([a, b]) => p.hunks[f].some(([c, d]) => a <= d && c <= b)));
|
|
58
|
+
if (files.length) hits.push({ pr: p.number, files });
|
|
59
|
+
}
|
|
60
|
+
return hits;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Every conflict file and every lane-changed file; recorded on the sync. */
|
|
64
|
+
export const targetSet = ({ conflicts = [], changed = [] }) => uniq([...conflicts, ...changed]).sort();
|
|
65
|
+
|
|
66
|
+
const probe = (io, staging, def) => {
|
|
67
|
+
try { io.git(["merge-tree", "--write-tree", "--name-only", `origin/${staging}`, `origin/${def}`]); return { conflicted: false, files: [] }; } catch (e) {
|
|
68
|
+
const text = `${e?.stdout ?? ""}\n${e?.message ?? ""}`;
|
|
69
|
+
const files = uniq([...text.matchAll(/Merge conflict in (.+)/g)].map((m) => m[1].trim()));
|
|
70
|
+
return { conflicted: true, files };
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/** Open `milestone/<slug>` branches, each marked stale-vs-main with the squash/ancestry hazard. */
|
|
75
|
+
export function staleMilestones(io) {
|
|
76
|
+
let out = ""; try { out = io.git(["ls-remote", "--heads", "origin", "milestone/*"]); } catch { out = ""; }
|
|
77
|
+
return String(out).split("\n").map((l) => /refs\/heads\/(milestone\/\S+)/.exec(l)?.[1]).filter(Boolean).map((branch) => ({ branch, status: "stale-vs-main", note: HAZARD }));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function openOrReuse({ io, repo, def, staging }) {
|
|
81
|
+
const open = json(await io.gh(["pr", "list", "--repo", repo, "--head", def, "--base", staging, "--state", "open", "--json", "number"])) ?? [];
|
|
82
|
+
if (open[0]) return open[0].number;
|
|
83
|
+
const body = `Merge-back of \`${def}\` into \`${staging}\` after a fast lane landed (#5566). Merge with a merge commit; squash is refused. The review panel and a targeted preflight over the recorded target set must pass before it merges.`;
|
|
84
|
+
const out = String(await io.gh(["pr", "create", "--repo", repo, "--base", staging, "--head", def, "--title", `sync: merge ${def} into ${staging}`, "--body", body]));
|
|
85
|
+
return Number(/\/pull\/(\d+)/.exec(out)?.[1]) || null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const defaultReview = async (ctx, pr) => {
|
|
89
|
+
const r = await reviewStep({ ...ctx, state: { ...(ctx.state ?? {}), steps: { "release-pr": { result: { pr } } } }, save: () => {} });
|
|
90
|
+
return { ok: !r?.blocked && !r?.refused && !r?.stopped, verdict: r?.verdict ?? null };
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The SYNCING step. `ctx`: {io, repo, def, staging?, config: {managed, preflight?}, policy?: {merge: {method}}, state?, actor?, release?,
|
|
95
|
+
* review?, preflight?, recordSync?, setIntake?}; `args`: {lane}. Unmanaged: `{skipped: true}` with no io call.
|
|
96
|
+
* @returns {Promise<{skipped?: true, refused?: string, pr, conflicted, target, duplicates, milestones, validated, merged, blocks}>}
|
|
97
|
+
*/
|
|
98
|
+
export async function syncStep(ctx, { lane = "p0" } = {}) {
|
|
99
|
+
if (!ctx.config?.managed) return { skipped: true };
|
|
100
|
+
const { io, repo, def } = ctx;
|
|
101
|
+
const staging = ctx.staging ?? DEFAULT_STAGING_BRANCH;
|
|
102
|
+
const method = ctx.policy?.merge?.method ?? "merge-commit";
|
|
103
|
+
if (method === "squash") return { refused: "merge-back refuses merge.method squash: a squash drops the default branch from the ancestry and re-conflicts the next sync (R4); use merge-commit" };
|
|
104
|
+
const L = { recordSync, setIntake, ...(ctx.ledger ?? {}) };
|
|
105
|
+
const lctx = io.api ? { io, repo, credential: "driver" } : null;
|
|
106
|
+
const record = ctx.recordSync ?? (lctx ? (r) => L.recordSync(lctx, r, io.now?.()) : async () => null);
|
|
107
|
+
const intake = ctx.setIntake ?? (io.api ? (p) => L.setIntake({ io, repo, by: ctx.actor ?? "engine", release: ctx.release ?? null, ...p }) : async () => null);
|
|
108
|
+
|
|
109
|
+
await intake({ paused: true, reason: `merge-back ${def} -> ${staging} (${lane})` });
|
|
110
|
+
try { io.git(["fetch", "--quiet", "origin", staging, def]); } catch { /* best effort */ }
|
|
111
|
+
const p = probe(io, staging, def);
|
|
112
|
+
let changed = [], laneHunks = {};
|
|
113
|
+
try { changed = String(io.git(["diff", "--name-only", `origin/${staging}...origin/${def}`])).split("\n").filter(Boolean); laneHunks = diffRanges(io.git(["diff", "-U0", `origin/${staging}...origin/${def}`])); } catch { /* unreadable: the target keeps the conflict files */ }
|
|
114
|
+
const target = targetSet({ conflicts: p.files, changed });
|
|
115
|
+
const pr = await openOrReuse({ io, repo, def, staging });
|
|
116
|
+
const head = (() => { try { return String(io.git(["rev-parse", `origin/${def}`])).trim(); } catch { return null; } })();
|
|
117
|
+
|
|
118
|
+
const review = await (ctx.review ?? defaultReview)(ctx, pr);
|
|
119
|
+
const pre = await (ctx.preflight ?? runTargetedPreflight)(ctx, { head, pr, target });
|
|
120
|
+
const prs = json(await io.gh(["pr", "list", "--repo", repo, "--base", staging, "--state", "open", "--json", "number,headRefName"])) ?? [];
|
|
121
|
+
const others = [];
|
|
122
|
+
for (const o of prs.filter((x) => x.headRefName !== def && x.number !== pr)) others.push({ number: o.number, hunks: diffRanges(await io.gh(["pr", "diff", String(o.number), "--repo", repo])) });
|
|
123
|
+
const sync = { lane, pr, def, staging, conflicted: p.conflicted, target, review: { ok: !!review?.ok, verdict: review?.verdict ?? null }, preflight: { ok: !!pre?.ok, covered: pre?.covered ?? [], head }, duplicates: duplicateFixes(laneHunks, others), milestones: staleMilestones(io), merged: false };
|
|
124
|
+
sync.validated = syncValidated(sync);
|
|
125
|
+
await record(sync);
|
|
126
|
+
return { ...sync, blocks: syncBlocksRelease({ sync, lane: "release" }) };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Merge a validated sync PR with a merge commit, record it, and release the intake pause. A conflicted or unvalidated sync stays open and paused. */
|
|
130
|
+
export async function finishSync(ctx, sync) {
|
|
131
|
+
if (!ctx.config?.managed) return { skipped: true };
|
|
132
|
+
const { io, repo } = ctx;
|
|
133
|
+
if (!syncValidated(sync)) return { merged: false, why: sync?.conflicted ? "sync is conflicted; resolve it and rerun the preflight" : "sync is unvalidated: review and a preflight covering the target set must be green" };
|
|
134
|
+
const b = { ...SYNC_BOUNDS, ...(ctx.config.syncBounds ?? {}) };
|
|
135
|
+
await io.gh(["pr", "merge", String(sync.pr), "--repo", repo, "--merge"]);
|
|
136
|
+
let state = null;
|
|
137
|
+
for (let i = 0; i < b.mergePolls; i++) {
|
|
138
|
+
state = json(await io.gh(["pr", "view", String(sync.pr), "--repo", repo, "--json", "state"]))?.state;
|
|
139
|
+
if (state === "MERGED") break;
|
|
140
|
+
await io.sleep?.(b.pollMs);
|
|
141
|
+
}
|
|
142
|
+
if (state !== "MERGED") return { merged: false, why: `sync PR #${sync.pr} is ${state ?? "unreadable"}, not merged` };
|
|
143
|
+
const lctx = io.api ? { io, repo, credential: "driver" } : null;
|
|
144
|
+
const done = { ...sync, merged: true };
|
|
145
|
+
await (ctx.recordSync ?? (lctx ? (r) => (ctx.ledger?.recordSync ?? recordSync)(lctx, r, io.now?.()) : async () => null))(done);
|
|
146
|
+
await (ctx.setIntake ?? (io.api ? (p) => (ctx.ledger?.setIntake ?? setIntake)({ io, repo, by: ctx.actor ?? "engine", ...p }) : async () => null))({ paused: false });
|
|
147
|
+
return { merged: true, sync: done };
|
|
148
|
+
}
|