forgedock 1.56.0 → 1.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/config-schema.mjs +1 -1
- package/bin/engine/outcome-codes.mjs +2 -1
- package/bin/engine/phases.mjs +4 -3
- package/bin/engine-cli.mjs +48 -12
- package/bin/forgedock.mjs +52 -3
- package/bin/gc.mjs +43 -6
- package/bin/help-text.mjs +4 -2
- package/bin/lean/batch-health.mjs +5 -1
- package/bin/lean/batch-health.test.mjs +7 -1
- package/bin/lean/batch.mjs +7 -2
- package/bin/lean/batch.test.mjs +45 -0
- package/bin/lean/conformance.e2e.test.mjs +3 -2
- package/bin/lean/conformance.mjs +118 -20
- package/bin/lean/conformance.test.mjs +172 -3
- package/bin/lean/decisions.mjs +98 -1
- package/bin/lean/decisions.test.mjs +30 -1
- package/bin/lean/depcache.mjs +124 -13
- package/bin/lean/depcache.test.mjs +121 -3
- package/bin/lean/design-gate.mjs +144 -0
- package/bin/lean/design-gate.test.mjs +169 -0
- package/bin/lean/effects-cap.test.mjs +17 -0
- package/bin/lean/effects.mjs +58 -13
- package/bin/lean/heavy.mjs +25 -8
- package/bin/lean/hostload.test.mjs +28 -0
- package/bin/lean/intake.mjs +97 -0
- package/bin/lean/intake.test.mjs +105 -0
- package/bin/lean/interfaces.mjs +181 -0
- package/bin/lean/interfaces.test.mjs +192 -0
- package/bin/lean/issuewatch-install.mjs +52 -12
- package/bin/lean/issuewatch-install.test.mjs +50 -0
- package/bin/lean/issuewatch-parity.mjs +16 -3
- package/bin/lean/issuewatch-parity.test.mjs +32 -0
- package/bin/lean/issuewatch-reconcile.mjs +29 -1
- package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
- package/bin/lean/issuewatch.mjs +34 -3
- package/bin/lean/issuewatch.test.mjs +49 -1
- package/bin/lean/lanecheck.test.mjs +15 -4
- package/bin/lean/lean.mjs +110 -24
- package/bin/lean/lean.test.mjs +183 -4
- package/bin/lean/orchestrate-blocked.test.mjs +18 -2
- package/bin/lean/orchestrate-owned.test.mjs +14 -5
- package/bin/lean/orchestrate.mjs +26 -4
- package/bin/lean/orphan-pr.mjs +3 -2
- package/bin/lean/orphan-pr.test.mjs +8 -1
- package/bin/lean/pagegate.mjs +35 -12
- package/bin/lean/pagegate.test.mjs +39 -1
- package/bin/lean/preflight.mjs +35 -1
- package/bin/lean/preflight.test.mjs +27 -1
- package/bin/lean/prompts.mjs +2 -1
- package/bin/lean/reap.test.mjs +39 -0
- package/bin/lean/recovery.test.mjs +28 -3
- package/bin/lean/release-config.mjs +169 -0
- package/bin/lean/release-config.test.mjs +132 -0
- package/bin/lean/release-control.mjs +171 -0
- package/bin/lean/release-control.test.mjs +167 -0
- package/bin/lean/release-deploy.mjs +209 -0
- package/bin/lean/release-deploy.test.mjs +217 -0
- package/bin/lean/release-fence.mjs +50 -0
- package/bin/lean/release-fence.test.mjs +105 -0
- package/bin/lean/release-flakes.mjs +139 -0
- package/bin/lean/release-flakes.test.mjs +116 -0
- package/bin/lean/release-gates.mjs +230 -0
- package/bin/lean/release-gates.test.mjs +146 -0
- package/bin/lean/release-ledger.mjs +176 -0
- package/bin/lean/release-ledger.test.mjs +226 -0
- package/bin/lean/release-minutes.mjs +102 -0
- package/bin/lean/release-minutes.test.mjs +107 -0
- package/bin/lean/release-nightly.mjs +75 -0
- package/bin/lean/release-nightly.test.mjs +48 -0
- package/bin/lean/release-postmerge.mjs +8 -2
- package/bin/lean/release-review.e2e.test.mjs +1 -0
- package/bin/lean/release-review.mjs +54 -7
- package/bin/lean/release-review.test.mjs +76 -7
- package/bin/lean/release-status.mjs +300 -0
- package/bin/lean/release-status.test.mjs +220 -0
- package/bin/lean/release-unitmap.mjs +35 -0
- package/bin/lean/release-unitmap.test.mjs +41 -0
- package/bin/lean/release-verify.mjs +221 -0
- package/bin/lean/release-verify.test.mjs +176 -0
- package/bin/lean/release.mjs +244 -22
- package/bin/lean/release.test.mjs +44 -0
- package/bin/lean/render.mjs +3 -1
- package/bin/lean/run-issue-placement.test.mjs +82 -0
- package/bin/lean/sandbox-remote.mjs +16 -0
- package/bin/lean/schedd.mjs +1 -1
- package/bin/lean/seam.mjs +115 -0
- package/bin/lean/seam.test.mjs +118 -0
- package/bin/lean/selftest-journey.mjs +40 -2
- package/bin/lean/selftest-journey.test.mjs +43 -3
- package/bin/lean/statuscomment.mjs +168 -0
- package/bin/lean/statuscomment.test.mjs +133 -0
- package/bin/lean/ui-quality.mjs +57 -0
- package/bin/lean/ui-quality.test.mjs +55 -0
- package/bin/lean/visual-gate.test.mjs +63 -0
- package/bin/pool/agent.mjs +16 -2
- package/bin/pool/router.mjs +5 -1
- package/bin/review-staging.mjs +5 -3
- package/bin/stats/card.mjs +117 -0
- package/bin/stats/card.test.mjs +109 -0
- package/bin/stats/conformance-outcomes.test.mjs +2 -1
- package/bin/stats/depth.mjs +1 -1
- package/bin/stats/gh-retry.test.mjs +152 -0
- package/bin/stats/github-source.mjs +147 -14
- package/bin/stats/index.mjs +35 -2
- package/bin/stats/stats.test.mjs +31 -3
- package/bin/vendor/js-yaml/LICENSE +21 -0
- package/bin/vendor/js-yaml/PIN.md +7 -0
- package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
- package/commands/design-render-critique-loop.md +2 -0
- package/commands/design.md +2 -0
- package/commands/issue.md +1 -1
- package/commands/milestone.md +1 -1
- package/commands/review-pr-agents/frontend.md +1 -0
- package/commands/review-pr-staging.md +5 -0
- package/docs/CONFIG.md +95 -2
- package/docs/ISSUE-WATCH.md +7 -0
- package/docs/OUTCOME-CODES.md +1 -0
- package/docs/STATS.md +10 -0
- package/docs/design/visual-gate.md +25 -0
- package/docs/eval/adversarial-bench.md +2 -2
- package/docs/eval/corpus/adversarial-v1.json +3 -3
- package/docs/site/start-a-new-project.md +7 -0
- package/docs/spec/forge-protocol-v1.md +31 -0
- package/package.json +1 -1
- package/pool/README.md +2 -0
- package/scripts/acceptance-red-green.sh +15 -1
- package/scripts/acceptance-red-green.test.sh +12 -0
- package/scripts/bench-adversarial.mjs +4 -0
- package/scripts/bench-lightlane.mjs +4 -1
- package/scripts/bootstrap-create.mjs +8 -2
- package/scripts/ci-local/scoping.mjs +19 -0
- package/scripts/ci-local.test.sh +16 -3
- package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
- package/scripts/plan-validate-live.mjs +9 -6
- package/scripts/review-prepare.sh +7 -1
- package/scripts/review-roster.sh +5 -2
- package/scripts/review-roster.test.sh +9 -0
- package/scripts/visual-gate.mjs +64 -0
- package/templates/bootstrap/technical-spike.md +17 -0
- package/templates/contracts/seam-check.mjs +236 -0
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
6
|
+
import { verifyStep, closeIssues, hasVerified, verifiedMarker, soakMinutes, sliBreaches, verifyConfigured, verifyReleaseById, SOAK_MIN } from "./release-verify.mjs";
|
|
7
|
+
import { validatePolicy } from "./release-config.mjs";
|
|
8
|
+
|
|
9
|
+
const SHA = "a".repeat(40);
|
|
10
|
+
const TABLE = { smoke1: { run: "check smoke1", timeout: 5 }, win1: { run: "check win1", for: "7d" } };
|
|
11
|
+
|
|
12
|
+
/** World: `runs` by workflow, `issues` by number {state, body, comments[]}; records every gh call and rehearsed command. */
|
|
13
|
+
function world(o = {}) {
|
|
14
|
+
const w = { runs: {}, issues: { 7: { state: "OPEN", body: "does X [check:smoke1]", comments: [] } }, gh: [], ran: [], logs: {}, rollups: [{ number: 99 }], metrics: undefined, table: TABLE, checkOk: true, ...o };
|
|
15
|
+
const io = {
|
|
16
|
+
print: () => {}, sleep: async () => {}, now: () => 1_000,
|
|
17
|
+
git: (a) => { if (w.table == null) throw new Error("no such file"); return JSON.stringify(w.table); },
|
|
18
|
+
rehearse: async (cmd) => { w.ran.push(cmd); return { ok: w.checkOk, output: "boom" }; },
|
|
19
|
+
gh: async (a) => {
|
|
20
|
+
w.gh.push(a.join(" "));
|
|
21
|
+
if (a[0] === "run" && a[1] === "list") { if (w.unreadable) throw new Error("HTTP 502"); const r = w.runs[a[a.indexOf("--workflow") + 1]]; return JSON.stringify(r ? [r] : []); }
|
|
22
|
+
if (a[0] === "run" && a[1] === "view") return w.logs[a[2]] ?? "";
|
|
23
|
+
if (a[0] === "workflow") { const wf = a[2]; w.runs[wf] ??= w.dispatchRun ?? { databaseId: 50, status: "completed", conclusion: "success" }; return ""; }
|
|
24
|
+
if (a[0] === "issue" && a[1] === "view") { const i = w.issues[a[2]]; if (!i) throw new Error("not found"); return JSON.stringify(i); }
|
|
25
|
+
if (a[0] === "issue" && a[1] === "list") return JSON.stringify(w.rollups);
|
|
26
|
+
if (a[0] === "issue" && a[1] === "comment") { const i = w.issues[a[2]]; if (i) i.comments.push({ body: a[a.indexOf("--body") + 1] }); return ""; }
|
|
27
|
+
if (a[0] === "issue" && (a[1] === "close" || a[1] === "create")) { if (a[1] === "close") w.issues[a[2]].state = "CLOSED"; return ""; }
|
|
28
|
+
throw new Error(`unexpected gh ${a.join(" ")}`);
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
if (w.metrics) io.metrics = w.metrics;
|
|
32
|
+
return { w, io };
|
|
33
|
+
}
|
|
34
|
+
const ok = { databaseId: 5, status: "completed", conclusion: "success" };
|
|
35
|
+
const mk = (io, verify, over = {}) => ({ io, repo: "o/r", def: "main", config: { verify, verifyRisk: "full", deployBounds: { pollMs: 1, runPollMs: 1 } }, state: { id: "r1", repo: "o/r", release: { issues: [7] }, deploy: { merge: SHA, phase: "VERIFYING" } }, save() {}, ...over });
|
|
36
|
+
|
|
37
|
+
describe("release verify (#5562)", () => {
|
|
38
|
+
it("defaults: soak minutes by risk class, overridable; verifyConfigured is off for an empty block", () => {
|
|
39
|
+
assert.deepEqual(SOAK_MIN, { low: 10, medium: 20, full: 30, p0: 15 });
|
|
40
|
+
assert.equal(soakMinutes("p0"), 15); assert.equal(soakMinutes("full", 45), 45); assert.equal(soakMinutes("low", { low: 3 }), 3);
|
|
41
|
+
assert.equal(verifyConfigured({}), false); assert.equal(verifyConfigured({ slis: [] }), false); assert.equal(verifyConfigured({ close_requires: "verified" }), true);
|
|
42
|
+
});
|
|
43
|
+
it("the policy schema accepts the verify layer keys", () => {
|
|
44
|
+
const r = validatePolicy({ schema: 1, verify: { workflow: "v.yml", results: [{ workflow: "smoke.yml", kind: "smoke" }], flags: [{ flag: "F", off_command: "x" }], slis: [], close_requires: "verified" } });
|
|
45
|
+
assert.ok(!JSON.stringify(r).includes("verify."), JSON.stringify(r));
|
|
46
|
+
});
|
|
47
|
+
it("layer 1: green results pass; an unreadable source blocks (I5); a missing run blocks", async () => {
|
|
48
|
+
const v = { results: [{ workflow: "smoke.yml", kind: "smoke" }], close_requires: "deployed" };
|
|
49
|
+
let { w, io } = world({ runs: { "smoke.yml": ok } });
|
|
50
|
+
assert.equal((await verifyStep(mk(io, v), SHA)).verified, true);
|
|
51
|
+
({ w, io } = world({ unreadable: true }));
|
|
52
|
+
assert.match((await verifyStep(mk(io, v), SHA)).reason, /cannot read smoke.yml results \(I5\)/);
|
|
53
|
+
({ io } = world({ runs: {} }));
|
|
54
|
+
assert.match((await verifyStep(mk(io, v), SHA)).reason, /no completed run/);
|
|
55
|
+
});
|
|
56
|
+
it("layer 1: a real smoke failure emits the rollback trigger once", async () => {
|
|
57
|
+
const v = { results: [{ workflow: "smoke.yml", kind: "smoke" }] };
|
|
58
|
+
const { io } = world({ runs: { "smoke.yml": { databaseId: 5, status: "completed", conclusion: "failure" } }, logs: { 5: "assertion failed: /health returned wrong body" } });
|
|
59
|
+
const trig = []; const c = mk(io, v, { rollbackTrigger: (t) => trig.push(t) });
|
|
60
|
+
const r = await verifyStep(c, SHA); const r2 = await verifyStep(c, SHA);
|
|
61
|
+
assert.ok(r.rollback); assert.ok(r2.rollback); assert.equal(trig.length, 1);
|
|
62
|
+
});
|
|
63
|
+
it("smoke identity/transport failure: one re-verify, then hold, never a rollback", async () => {
|
|
64
|
+
const v = { results: [{ workflow: "smoke.yml", kind: "smoke" }] };
|
|
65
|
+
const { w, io } = world({ runs: { "smoke.yml": { databaseId: 5, status: "completed", conclusion: "failure" } }, logs: { 5: "HTTP 401 unauthorized" } });
|
|
66
|
+
const c = mk(io, v), trig = []; c.rollbackTrigger = (t) => trig.push(t);
|
|
67
|
+
const r = await verifyStep(c, SHA);
|
|
68
|
+
assert.equal(r.hold?.label, "needs-agent"); assert.equal(c.state.verify.reverifies, 1); assert.equal(trig.length, 0); assert.equal(r.rollback, undefined);
|
|
69
|
+
assert.equal(w.gh.filter((g) => g.startsWith("run list")).length, 2, "exactly one re-verify read");
|
|
70
|
+
});
|
|
71
|
+
it("a convergence failure with smoke green is released-with-convergence-failures: repair issue, no rollback", async () => {
|
|
72
|
+
const v = { results: [{ workflow: "smoke.yml", kind: "smoke" }, { workflow: "conv.yml", kind: "convergence" }], close_requires: "deployed" };
|
|
73
|
+
const { w, io } = world({ runs: { "smoke.yml": ok, "conv.yml": { databaseId: 6, status: "completed", conclusion: "failure" } } });
|
|
74
|
+
const r = await verifyStep(mk(io, v), SHA);
|
|
75
|
+
assert.equal(r.outcome, "released-with-convergence-failures");
|
|
76
|
+
assert.equal(w.gh.filter((g) => g.startsWith("issue create")).length, 1);
|
|
77
|
+
});
|
|
78
|
+
it("layer 2: the verification workflow is dispatched once through fenced() and its failure triggers rollback", async () => {
|
|
79
|
+
const v = { workflow: "verify.yml", close_requires: "deployed" };
|
|
80
|
+
let { w, io } = world();
|
|
81
|
+
const calls = []; const fence = { lctx: { io: { api: async () => ({ content: Buffer.from(JSON.stringify({ epoch: 3, lease: { holder: "h", epoch: 3 } })).toString("base64") }) }, repo: "o/r" }, lease: { holder: "h", epoch: 3, release: "r" }, now: () => "t", record: async (r) => calls.push(r) };
|
|
82
|
+
const c = mk(io, v, { fence });
|
|
83
|
+
assert.equal((await verifyStep(c, SHA)).verified, true);
|
|
84
|
+
assert.equal(w.gh.filter((g) => g.startsWith("workflow run")).length, 1);
|
|
85
|
+
assert.ok(calls.some((i) => i.action === "dispatch" && i.epoch === 3 && /verify:/.test(i.key)));
|
|
86
|
+
({ w, io } = world({ dispatchRun: { databaseId: 50, status: "completed", conclusion: "failure" } }));
|
|
87
|
+
assert.ok((await verifyStep(mk(io, v), SHA)).rollback);
|
|
88
|
+
});
|
|
89
|
+
it("layer 2: a dispatch intent already recorded is never repeated on resume", async () => {
|
|
90
|
+
const { w, io } = world();
|
|
91
|
+
const c = mk(io, { workflow: "verify.yml" }, { state: { id: "r1", release: { issues: [] }, deploy: { merge: SHA }, intents: [{ action: "dispatch", key: `r1:deploy:0:verify:${SHA}` }] } });
|
|
92
|
+
const r = await verifyStep(c, SHA);
|
|
93
|
+
assert.match(r.reason, /already recorded/); assert.equal(w.gh.filter((g) => g.startsWith("workflow run")).length, 0);
|
|
94
|
+
});
|
|
95
|
+
it("layer 3: an SLI breach in a fixture series emits the rollback trigger; within tolerance passes", async () => {
|
|
96
|
+
const slis = [{ name: "5xx", tolerance: 0.1 }, { name: "success", worse: "lower", tolerance: 0.05 }];
|
|
97
|
+
const series = (cur) => async ({ sli }) => ({ baseline: 100, current: cur[sli.name] });
|
|
98
|
+
let { io } = world({ metrics: series({ "5xx": 150, success: 100 }) });
|
|
99
|
+
const trig = []; const c = mk(io, { slis, close_requires: "deployed" }); c.rollbackTrigger = (t) => trig.push(t);
|
|
100
|
+
const r = await verifyStep(c, SHA);
|
|
101
|
+
assert.match(r.reason, /SLI breach over 30 min: 5xx 150/); assert.equal(trig.length, 1);
|
|
102
|
+
({ io } = world({ metrics: series({ "5xx": 105, success: 97 }) }));
|
|
103
|
+
const ok2 = await verifyStep(mk(io, { slis, close_requires: "deployed" }), SHA);
|
|
104
|
+
assert.equal(ok2.verified, true); assert.match(ok2.sli, /pass \(30 min soak, 2 sli\)/);
|
|
105
|
+
assert.deepEqual(sliBreaches([{ name: "a" }], { a: { baseline: 10, current: 13 } }).map((x) => x.sli), ["a"]);
|
|
106
|
+
});
|
|
107
|
+
it("layer 3: no metric source skips and says so; an unreadable metric blocks (I5)", async () => {
|
|
108
|
+
const v = { slis: [{ name: "5xx" }], close_requires: "deployed" };
|
|
109
|
+
let { io } = world();
|
|
110
|
+
const lines = []; io.print = (l) => lines.push(l);
|
|
111
|
+
const r = await verifyStep(mk(io, v), SHA);
|
|
112
|
+
assert.equal(r.sli, "skipped (no host)"); assert.ok(lines.some((l) => l.includes("sli: skipped (no host)")));
|
|
113
|
+
({ io } = world({ metrics: async () => { throw new Error("prometheus down"); } }));
|
|
114
|
+
assert.match((await verifyStep(mk(io, v), SHA)).reason, /cannot read SLI 5xx \(I5\)/);
|
|
115
|
+
});
|
|
116
|
+
it("layer 4: each check runs once, from the default branch; an unreadable registry blocks; windowed checks become follow-ups", async () => {
|
|
117
|
+
const v = { post_deploy_checks_file: ".forge/post-deploy-checks.json", close_requires: "deployed" };
|
|
118
|
+
let { w, io } = world({ issues: { 7: { state: "OPEN", body: "[check:smoke1] [check:win1]", comments: [] }, 8: { state: "OPEN", body: "[check:smoke1]", comments: [] } } });
|
|
119
|
+
const c = mk(io, v); c.state.release.issues = [7, 8];
|
|
120
|
+
assert.equal((await verifyStep(c, SHA)).verified, true);
|
|
121
|
+
assert.deepEqual(w.ran, ["check smoke1"], "smoke1 runs once for two issues; windowed win1 never runs");
|
|
122
|
+
assert.ok(w.gh.some((g) => g.startsWith("issue comment 99") && g.includes("[check:win1]")));
|
|
123
|
+
({ io } = world({ table: null }));
|
|
124
|
+
assert.match((await verifyStep(mk(io, v), SHA)).reason, /cannot read .* from origin\/main \(I13, I5\)/);
|
|
125
|
+
({ io } = world({ checkOk: false }));
|
|
126
|
+
assert.equal((await verifyStep(mk(io, v), SHA)).hold?.kind, "check");
|
|
127
|
+
});
|
|
128
|
+
it("layer 5: a flag-gated feature is verified off and never activated", async () => {
|
|
129
|
+
const { w, io } = world();
|
|
130
|
+
const r = await verifyStep(mk(io, { flags: [{ flag: "NEW_UI", off_command: "flag-state NEW_UI off" }], close_requires: "deployed" }), SHA);
|
|
131
|
+
assert.equal(r.verified, true); assert.deepEqual(w.ran, ["flag-state NEW_UI off"]);
|
|
132
|
+
const bad = world({ checkOk: false });
|
|
133
|
+
assert.equal((await verifyStep(mk(bad.io, { flags: [{ flag: "NEW_UI", off_command: "x" }] }), SHA)).hold?.kind, "flag");
|
|
134
|
+
});
|
|
135
|
+
it("I19: close is refused without FORGE:VERIFIED naming the deploy sha, allowed with it; deployed mode opts out", async () => {
|
|
136
|
+
const { w, io } = world({ issues: { 7: { state: "OPEN", body: "", comments: [{ body: verifiedMarker("b".repeat(40)) }] } } });
|
|
137
|
+
const c = mk(io, {});
|
|
138
|
+
let r = await closeIssues(c, { issues: [7], sha: SHA });
|
|
139
|
+
assert.equal(r.closed.length, 0); assert.match(r.refused[0].why, /no FORGE:VERIFIED/); assert.ok(!w.gh.some((g) => g.startsWith("issue close")));
|
|
140
|
+
w.issues[7].comments.push({ body: verifiedMarker(SHA) });
|
|
141
|
+
r = await closeIssues(c, { issues: [7], sha: SHA }); assert.deepEqual(r.closed, [7]);
|
|
142
|
+
w.issues[7].state = "OPEN"; w.issues[7].comments = [];
|
|
143
|
+
assert.deepEqual((await closeIssues(c, { issues: [7], sha: SHA, mode: "deployed" })).closed, [7]);
|
|
144
|
+
assert.equal(hasVerified([{ body: "<!-- FORGE:VERIFIED fp=abc123 -->" }], SHA), false);
|
|
145
|
+
});
|
|
146
|
+
it("end to end: verified issue gets the marker comment then closes; resume repeats no dispatch, check or comment", async () => {
|
|
147
|
+
const v = { workflow: "verify.yml", post_deploy_checks_file: "f.json" };
|
|
148
|
+
const { w, io } = world();
|
|
149
|
+
const c = mk(io, v);
|
|
150
|
+
const r = await verifyStep(c, SHA);
|
|
151
|
+
assert.equal(r.verified, true); assert.deepEqual(r.closed, [7]);
|
|
152
|
+
assert.ok(hasVerified(w.issues[7].comments, SHA));
|
|
153
|
+
const before = w.gh.filter((g) => /^(workflow run|issue comment)/.test(g)).length, ran = w.ran.length;
|
|
154
|
+
w.issues[7].state = "OPEN"; await verifyStep(c, SHA);
|
|
155
|
+
assert.equal(w.gh.filter((g) => /^(workflow run|issue comment)/.test(g)).length, before); assert.equal(w.ran.length, ran);
|
|
156
|
+
});
|
|
157
|
+
it("verifyReleaseById refuses before LIVE_CHECK and runs the layers after it", async () => {
|
|
158
|
+
const { io } = world();
|
|
159
|
+
assert.match((await verifyReleaseById({ io, state: { id: "r1", deploy: { phase: "DEPLOYING" } }, save() {}, def: "main", policy: {} })).reason, /LIVE_CHECK/);
|
|
160
|
+
const state = { id: "r1", repo: "o/r", release: { issues: [] }, deploy: { phase: "LIVE", merge: SHA } };
|
|
161
|
+
assert.equal((await verifyReleaseById({ io, state, save() {}, def: "main", policy: { verify: { close_requires: "deployed" } }, lane: "p0" })).verified, true);
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
/** I22 scanner: write verbs against production in a module's source. */
|
|
166
|
+
const WRITE_VERBS = [/\bssh\s/, /\bscp\s/, /\bsystemctl\b/, /\bdocker\s+(run|exec|rm|stop|restart|kill|compose|build|push|cp)\b/, /\b(INSERT\s+INTO|UPDATE\s+\w+\s+SET|DELETE\s+FROM|DROP\s+TABLE|ALTER\s+TABLE|TRUNCATE)\b/i, /\bkubectl\s+(apply|delete|scale|rollout)\b/];
|
|
167
|
+
const writeVerbs = (src) => WRITE_VERBS.filter((re) => re.test(src)).map(String);
|
|
168
|
+
|
|
169
|
+
describe("release verify I22: no write path to production", () => {
|
|
170
|
+
it("the module has no write verbs", () => {
|
|
171
|
+
assert.deepEqual(writeVerbs(readFileSync(new URL("./release-verify.mjs", import.meta.url), "utf8")), []);
|
|
172
|
+
});
|
|
173
|
+
it("the scan fails on a seeded violation", () => {
|
|
174
|
+
for (const bad of ["await sh('ssh prod systemctl restart api')", "run(`docker exec app sh`)", "q('DELETE FROM users')"]) assert.ok(writeVerbs(bad).length, bad);
|
|
175
|
+
});
|
|
176
|
+
});
|
package/bin/lean/release.mjs
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* live in release-review.mjs / release-postmerge.mjs (stubs that block until their parts land). Promotion is opt-in: without
|
|
9
9
|
* `--merge` or forge.yaml `release.auto_merge: true` the job stops at GATE_PASS and prints the merge command.
|
|
10
10
|
*/
|
|
11
|
-
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
|
|
12
12
|
import { execFileSync } from "node:child_process";
|
|
13
13
|
import { homedir } from "node:os";
|
|
14
14
|
import { join } from "node:path";
|
|
@@ -18,12 +18,22 @@ import { ghRunner } from "./issuewatch.mjs";
|
|
|
18
18
|
import { parseForgeYaml } from "../forge-utils.mjs";
|
|
19
19
|
import { reviewStep, fixStep } from "./release-review.mjs";
|
|
20
20
|
import { postMergeStep } from "./release-postmerge.mjs";
|
|
21
|
+
import { deployStep } from "./release-deploy.mjs";
|
|
22
|
+
import { riskClass } from "./release-verify.mjs";
|
|
21
23
|
import { rehearsalStep, parseRehearsalConfig } from "./release-rehearsal.mjs";
|
|
22
|
-
import { budgetReportLine, releaseRuns } from "./ci-budget.mjs";
|
|
24
|
+
import { budgetReportLine, releaseRuns, detectBudget, readCiPolicy } from "./ci-budget.mjs";
|
|
25
|
+
import { parseNightlyConfig, readNightly, blocksRelease, fileNightlyRed } from "./release-nightly.mjs";
|
|
26
|
+
import { parseBudgetConfig, applyOnExceed, waveReport, trailingMedian, historyFromRoot, gateHistoryFromRoot, releaseMinutes } from "./release-minutes.mjs";
|
|
23
27
|
import { cutSnapshot, writeRecord, checkChain, verifyRelease, DEFAULT_PATTERN } from "./release-snapshot.mjs";
|
|
28
|
+
import { createReleaseLedger, writeRelease, readLedger, acquireLease, heartbeat } from "./release-ledger.mjs";
|
|
29
|
+
import { fenced, epochTrailer } from "./release-fence.mjs";
|
|
30
|
+
import { holdCheck, exemptionsSection, VERBS as CONTROL_VERBS } from "./release-control.mjs";
|
|
31
|
+
import { parseFlakeConfig, classifyFailure, planRerun, flakeEntry, recordFlakes, readFlakes } from "./release-flakes.mjs";
|
|
32
|
+
import { readActive } from "./release-ledger.mjs";
|
|
33
|
+
import { statusFromCli, policyFromYaml } from "./release-status.mjs";
|
|
24
34
|
import { hostPreflightStep, markReadyStep, parsePreflightConfig } from "./release-preflight.mjs";
|
|
25
35
|
|
|
26
|
-
export const RELEASE_STEPS = ["preflight", "host-preflight", "release-pr", "review", "fixes", "mark-ready", "rehearsal", "promotion", "post-merge"];
|
|
36
|
+
export const RELEASE_STEPS = ["preflight", "host-preflight", "release-pr", "review", "fixes", "mark-ready", "rehearsal", "promotion", "post-merge", "deploy"];
|
|
27
37
|
const ID_RE = /^r\d{8}-\d{6}-\d+$/;
|
|
28
38
|
const BLOCKED_EXIT = 3;
|
|
29
39
|
|
|
@@ -51,9 +61,51 @@ export function readReleaseConfig(raw) {
|
|
|
51
61
|
let r = {};
|
|
52
62
|
try { r = parseForgeYaml(String(raw ?? ""))?.release ?? {}; } catch { r = {}; }
|
|
53
63
|
const off = (v) => ["false", "off", "no", "0", ""].includes(String(v ?? "").trim().toLowerCase());
|
|
54
|
-
return { autoMerge: !off(r.auto_merge), artifactCheck: r.artifact_check || null, versionSync: !off(r.version_sync), publishWorkflow: r.publish_workflow || null, ...optKeys(r), ...snapshotKeys(r) };
|
|
64
|
+
return { autoMerge: !off(r.auto_merge), artifactCheck: r.artifact_check || null, versionSync: !off(r.version_sync), publishWorkflow: r.publish_workflow || null, ...(r.managed !== undefined && !off(r.managed) ? { managed: true } : {}), ...managedKeys(raw, r), ...freezeKeys(raw, r), ...optKeys(r), ...snapshotKeys(r) };
|
|
55
65
|
}
|
|
56
66
|
|
|
67
|
+
/** `{nightly, budget}` (#5569) only when `release.managed` is on: the forge.yaml `nightly:` and `budget:` blocks. */
|
|
68
|
+
const managedKeys = (raw, r) => {
|
|
69
|
+
if (r.managed === undefined || off2(r.managed)) return {};
|
|
70
|
+
let y = {}; try { y = parseForgeYaml(String(raw ?? "")) ?? {}; } catch { y = {}; }
|
|
71
|
+
return { nightly: parseNightlyConfig(y.nightly), budget: parseBudgetConfig(y.budget) };
|
|
72
|
+
};
|
|
73
|
+
const off2 = (v) => ["false", "off", "no", "0", ""].includes(String(v ?? "").trim().toLowerCase());
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Managed gate before the first step (#5569; there is no APPROVED state, so this is where it applies): a red nightly blocks only
|
|
77
|
+
* `lane: release` (T0-T2 reds and unskippable classes), and a forecast over the month's remaining minutes applies `budget.on_exceed`
|
|
78
|
+
* (p0 never). Every read is best effort: unreadable facts proceed. @returns {{blocked?, reason?, ciMode?}}
|
|
79
|
+
*/
|
|
80
|
+
export async function managedGate({ io, repo, config, lane, root }) {
|
|
81
|
+
if (config.nightly) {
|
|
82
|
+
try {
|
|
83
|
+
const n = await readNightly({ gh: (a) => io.gh(a), repo, cfg: config.nightly, now: io.now() });
|
|
84
|
+
if (n?.reds.length) await fileNightlyRed({ gh: (a) => io.gh(a), repo, reds: n.reds, run: n.run });
|
|
85
|
+
const hit = blocksRelease({ lane, reds: n?.reds ?? [], cfg: config.nightly });
|
|
86
|
+
if (hit.length) return { blocked: true, reason: `nightly is red: ${hit.map((r) => r.name).join(", ")}` };
|
|
87
|
+
} catch { /* best effort */ }
|
|
88
|
+
}
|
|
89
|
+
if (config.budget) {
|
|
90
|
+
try {
|
|
91
|
+
const forecast = trailingMedian(historyFromRoot(root), lane);
|
|
92
|
+
const facts = await detectBudget({ gh: (a) => io.gh(a), repo, policy: config.ciPolicy, now: io.now() });
|
|
93
|
+
const remaining = facts.budget != null && facts.mtd != null ? facts.budget * (1 - (config.ciPolicy?.reservePct ?? 10) / 100) - facts.mtd : null;
|
|
94
|
+
const r = applyOnExceed({ lane, forecast, remaining, cfg: config.budget });
|
|
95
|
+
if (r.action === "hold") return { blocked: true, reason: `budget hold: ${r.why}` };
|
|
96
|
+
if (r.action === "local-first") return { ciMode: "local-first", why: r.why };
|
|
97
|
+
} catch { /* best effort */ }
|
|
98
|
+
}
|
|
99
|
+
return {};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** `{intakeAutoResume, tracker}` only when configured (#5555): forge.yaml `freeze.intake_auto_resume`, `release.tracker`. */
|
|
103
|
+
const freezeKeys = (raw, r) => {
|
|
104
|
+
let f = {}; try { f = parseForgeYaml(String(raw ?? ""))?.freeze ?? {}; } catch { f = {}; }
|
|
105
|
+
const on = f.intake_auto_resume !== undefined && !["false", "off", "no", "0", ""].includes(String(f.intake_auto_resume).trim().toLowerCase());
|
|
106
|
+
return { ...(on ? { intakeAutoResume: true } : {}), ...(r.tracker ? { tracker: r.tracker } : {}) };
|
|
107
|
+
};
|
|
108
|
+
|
|
57
109
|
/** `{mode, branchPattern, fixMode}` only when configured (#5276): mode `snapshot` cuts release/<id>; anything else is `freeze`. */
|
|
58
110
|
const snapshotKeys = (r) => {
|
|
59
111
|
const pick = (v, ok, dflt) => (ok.includes(String(v).trim().toLowerCase()) ? String(v).trim().toLowerCase() : dflt);
|
|
@@ -123,7 +175,7 @@ async function snapshotPrStep(ctx) {
|
|
|
123
175
|
const found = json(await io.gh(["pr", "list", "--repo", repo, "--base", def, "--head", branch, "--state", "open", "--json", "number,headRefOid,url"]))?.[0];
|
|
124
176
|
if (found) return { pr: found.number, head: found.headRefOid, url: found.url, reused: true, branch };
|
|
125
177
|
const list = state.releaseBundle ?? [];
|
|
126
|
-
const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", branch, "--title", `Release: ${branch} -> ${def}`, "--body", bundleBody(list)])).trim();
|
|
178
|
+
const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", branch, "--title", `Release: ${branch} -> ${def}`, "--body", bundleBody(list) + await exemptionBody(ctx)])).trim();
|
|
127
179
|
const n = Number(/\/pull\/(\d+)/.exec(url)?.[1]);
|
|
128
180
|
if (!Number.isSafeInteger(n)) throw new Error(`gh pr create returned no PR url: ${url}`);
|
|
129
181
|
state.steps["release-pr"] = { done: false, result: { pr: n } }; // writeRecord reads the PR number from here
|
|
@@ -138,13 +190,19 @@ async function releasePrStep(ctx) {
|
|
|
138
190
|
const found = json(await io.gh(["pr", "list", "--repo", repo, "--base", def, "--head", staging, "--state", "open", "--json", "number,headRefOid,url"]))?.[0];
|
|
139
191
|
if (found) return { pr: found.number, head: found.headRefOid, url: found.url, reused: true };
|
|
140
192
|
const list = await bundleList({ io, repo, head: staging, base: def });
|
|
141
|
-
const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", staging, "--title", `Release: ${staging} -> ${def}`, "--body", bundleBody(list), ...(ctx.config.preflight ? ["--draft"] : [])])).trim();
|
|
193
|
+
const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", staging, "--title", `Release: ${staging} -> ${def}`, "--body", bundleBody(list) + await exemptionBody(ctx), ...(ctx.config.preflight ? ["--draft"] : [])])).trim();
|
|
142
194
|
const n = Number(/\/pull\/(\d+)/.exec(url)?.[1]);
|
|
143
195
|
if (!Number.isSafeInteger(n)) throw new Error(`gh pr create returned no PR url: ${url}`);
|
|
144
196
|
const v = json(await io.gh(["pr", "view", String(n), "--repo", repo, "--json", "headRefOid"]));
|
|
145
197
|
return { pr: n, head: v?.headRefOid, url, reused: false, bundle: list.length };
|
|
146
198
|
}
|
|
147
199
|
|
|
200
|
+
/** The live operator exemptions as a PR-body section (#5568, I20); "" when unmanaged, none, or `_active` is unreadable. */
|
|
201
|
+
async function exemptionBody({ io, repo, config }) {
|
|
202
|
+
if (!config.managed || !io.api) return "";
|
|
203
|
+
try { return exemptionsSection((await readActive({ io, repo, credential: "driver" })).exemptions, io.now?.()); } catch { return ""; }
|
|
204
|
+
}
|
|
205
|
+
|
|
148
206
|
/** GATE_PASS marker on the PR and the `forge/deploy-gate` conclusion at `head`. */
|
|
149
207
|
export async function gateState({ io, repo, pr, head }) {
|
|
150
208
|
const comments = json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "comments"]))?.comments ?? [];
|
|
@@ -165,16 +223,49 @@ export async function gateState({ io, repo, pr, head }) {
|
|
|
165
223
|
const GATE_POLLS = 12, GATE_POLL_MS = 10_000;
|
|
166
224
|
|
|
167
225
|
/** Re-run the newest gate-marker-check run on `head`: the bot's GATE_PASS comment never triggers it, so the status would stay pending. */
|
|
168
|
-
async function retriggerGate({ io, repo, head }) {
|
|
226
|
+
async function retriggerGate({ io, repo, head, fence }) {
|
|
169
227
|
try {
|
|
170
228
|
const runs = json(await io.gh(["run", "list", "--repo", repo, "--workflow", "gate-marker-check.yml", "--commit", head, "--json", "databaseId", "--limit", "1"])) ?? [];
|
|
171
|
-
if (runs[0]?.databaseId)
|
|
172
|
-
|
|
229
|
+
if (!runs[0]?.databaseId) return null;
|
|
230
|
+
const f = await fenced(fence, { action: "rerun", key: `rerun:${runs[0].databaseId}` }, () => io.gh(["run", "rerun", String(runs[0].databaseId), "--repo", repo]));
|
|
231
|
+
return f.refused ?? null; // #5553: a fenced host stops here
|
|
232
|
+
} catch { return null; /* a run still in progress cannot be rerun, and it re-reads the markers anyway: just wait */ }
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* #5568 (5.5): `rerun --failed` once per job for failed runs on `head` whose failures all carry a known infra signature, inside
|
|
237
|
+
* `ci.rerun_budget_min`; every decision (rerun or not, and why) is recorded in `flakes.json`. Best effort: never throws.
|
|
238
|
+
* @returns {{reran: string[], skipped: object[]}}
|
|
239
|
+
*/
|
|
240
|
+
export async function rerunInfraFlakes({ io, repo, head, fence, policy }) {
|
|
241
|
+
const out = { reran: [], skipped: [] };
|
|
242
|
+
try {
|
|
243
|
+
const cfg = parseFlakeConfig(policy);
|
|
244
|
+
if (!fence?.lctx || !(cfg.rerunBudgetMin > 0)) return out;
|
|
245
|
+
const prior = await readFlakes(fence.lctx), done = prior.filter((f) => f.rerun).map((f) => `${f.sha}:${f.check}`);
|
|
246
|
+
const runs = json(await io.gh(["run", "list", "--repo", repo, "--commit", head, "--status", "failure", "--json", "databaseId,name", "--limit", "20"])) ?? [];
|
|
247
|
+
const at = new Date(io.now?.() ?? Date.now()).toISOString(), entries = [];
|
|
248
|
+
let spentMin = 0;
|
|
249
|
+
for (const r of runs) {
|
|
250
|
+
const log = String(await io.gh(["run", "view", String(r.databaseId), "--repo", repo, "--log-failed"]).catch(() => "")).slice(-20_000);
|
|
251
|
+
const c = classifyFailure(log);
|
|
252
|
+
const [d] = planRerun({ jobs: [{ key: `${head}:${r.name}`, name: r.name, class: c.class }], done, spentMin, budgetMin: cfg.rerunBudgetMin });
|
|
253
|
+
if (d.rerun) {
|
|
254
|
+
const f = await fenced(fence, { action: "rerun", key: `rerun-failed:${r.databaseId}` }, () => io.gh(["run", "rerun", String(r.databaseId), "--repo", repo, "--failed"]));
|
|
255
|
+
if (f.refused) { out.skipped.push({ name: r.name, why: f.refused }); continue; }
|
|
256
|
+
out.reran.push(r.name);
|
|
257
|
+
} else out.skipped.push({ name: r.name, why: d.why });
|
|
258
|
+
entries.push(flakeEntry({ check: r.name, signature: c.signature, kind: c.class === "infra" ? "infra" : "decision", sha: head, runIds: [r.databaseId], at, rerun: d.rerun }));
|
|
259
|
+
}
|
|
260
|
+
await recordFlakes(fence.lctx, entries.filter((e) => e.kind === "infra"));
|
|
261
|
+
} catch { /* best effort */ }
|
|
262
|
+
return out;
|
|
173
263
|
}
|
|
174
264
|
|
|
175
265
|
/** Re-trigger the gate, then poll (bounded) until `forge/deploy-gate` is success or failure; @returns the last gateState. */
|
|
176
|
-
async function awaitGate({ io, repo, pr, head, gate }) {
|
|
177
|
-
await retriggerGate({ io, repo, head });
|
|
266
|
+
async function awaitGate({ io, repo, pr, head, gate, fence }) {
|
|
267
|
+
const refused = await retriggerGate({ io, repo, head, fence });
|
|
268
|
+
if (refused) return { ...gate, fenced: refused };
|
|
178
269
|
for (let i = 0; i < GATE_POLLS && gate.deployGate !== "success" && gate.deployGate !== "failure"; i++) {
|
|
179
270
|
await io.sleep(GATE_POLL_MS);
|
|
180
271
|
gate = await gateState({ io, repo, pr, head });
|
|
@@ -196,15 +287,22 @@ async function promotionStep(ctx) {
|
|
|
196
287
|
}
|
|
197
288
|
let gate = await gateState({ io, repo, pr, head });
|
|
198
289
|
if (gate.marker !== "pass") return { stopped: true, why: `no FORGE:GATE_PASS on #${pr} (last marker: ${gate.marker ?? "none"})`, head };
|
|
199
|
-
if (gate.deployGate !== "success" && gate.deployGate !== "failure") gate = await awaitGate({ io, repo, pr, head, gate });
|
|
290
|
+
if (gate.deployGate !== "success" && gate.deployGate !== "failure") gate = await awaitGate({ io, repo, pr, head, gate, fence: ctx.fence });
|
|
291
|
+
if (gate.fenced) return { refused: gate.fenced, head };
|
|
292
|
+
if (gate.deployGate === "failure" && ctx.config.managed && io.git) { // #5568: policy loaded lazily (release-config imports this module)
|
|
293
|
+
const { readPolicy } = await import("./release-config.mjs");
|
|
294
|
+
const policy = readPolicy({ io, defaultBranch: ctx.def }).policy;
|
|
295
|
+
await rerunInfraFlakes({ io, repo, head, fence: ctx.fence, policy });
|
|
296
|
+
}
|
|
200
297
|
const cmd = `gh pr merge ${pr} --repo ${repo} --merge --match-head-commit ${head}`;
|
|
201
298
|
if (!opts.merge && !ctx.config.autoMerge) { io.print(`GATE_PASS on #${pr}. Merge when ready:\n ${cmd}`); return { stopped: true, why: "GATE_PASS; promotion is opt-in (--merge or release.auto_merge)", cmd, head, gate }; }
|
|
202
299
|
if (gate.deployGate !== "success") return { stopped: true, why: `forge/deploy-gate is ${gate.deployGate ?? "absent"}, not success${gate.deployGate === "failure" ? "" : ` after ${GATE_POLLS} polls`}`, head, gate };
|
|
203
|
-
await io.gh(["pr", "merge", String(pr), "--repo", repo, "--merge", "--match-head-commit", head]);
|
|
300
|
+
const f = await fenced(ctx.fence, { action: "merge", key: `merge:${pr}:${head}` }, (epoch) => io.gh(["pr", "merge", String(pr), "--repo", repo, "--merge", "--match-head-commit", head, ...(epoch != null ? ["--body", epochTrailer(epoch)] : [])]));
|
|
301
|
+
if (f.refused) return { refused: f.refused, head, gate };
|
|
204
302
|
return { merged: true, head, gate };
|
|
205
303
|
}
|
|
206
304
|
|
|
207
|
-
const OPTIONAL_STEPS = ["host-preflight", "mark-ready"];
|
|
305
|
+
const OPTIONAL_STEPS = ["host-preflight", "mark-ready", "deploy"];
|
|
208
306
|
|
|
209
307
|
const STEP_FNS = {
|
|
210
308
|
preflight: preflightStep,
|
|
@@ -216,6 +314,7 @@ const STEP_FNS = {
|
|
|
216
314
|
rehearsal: (ctx) => rehearsalStep(ctx),
|
|
217
315
|
promotion: promotionStep,
|
|
218
316
|
"post-merge": (ctx) => postMergeStep(ctx),
|
|
317
|
+
deploy: (ctx) => deployStep(ctx),
|
|
219
318
|
};
|
|
220
319
|
|
|
221
320
|
/** The step table with `over` replacing steps by name (tests stub the steps that need a real repo). */
|
|
@@ -228,14 +327,44 @@ export const withStubs = (over = {}) => ({ ...STEP_FNS, ...over });
|
|
|
228
327
|
*/
|
|
229
328
|
export async function runRelease({ io, repo, opts = {}, config = {}, branches = {}, root, id, steps = STEP_FNS, mounts }) {
|
|
230
329
|
const rel = openRelease(root, id, mounts);
|
|
231
|
-
|
|
330
|
+
// #5550: managed releases read the ledger first (it is authoritative; the local file is a cache); off = no ledger call at all.
|
|
331
|
+
const lctx = config.managed && io.api ? { io, repo, credential: "driver" } : null;
|
|
332
|
+
const led = lctx ? await readLedger(lctx, id) : null;
|
|
333
|
+
if (led?.rejected) return { id, status: "refused", step: "ledger", reason: `ledger of ${id} rejected: ${led.rejected}` };
|
|
334
|
+
let ledgerHead = led?.head ?? null;
|
|
335
|
+
const mirror = async (s) => { // best effort: a lost race means another writer owns the release, which stops this run
|
|
336
|
+
const r = ledgerHead ? await writeRelease(lctx, id, s, ledgerHead) : await createReleaseLedger(lctx, id, s);
|
|
337
|
+
if (r.ok) ledgerHead = r.sha; else throw new Error(`release ${id}: ledger write lost the race (another writer holds the release)`);
|
|
338
|
+
};
|
|
339
|
+
const state = led?.state ?? rel.load() ?? { v: 1, id, repo, startedAt: new Date(io.now()).toISOString(), steps: {}, held: [] };
|
|
232
340
|
state.opts = { merge: !!(opts.merge || state.opts?.merge) };
|
|
341
|
+
if (lctx) {
|
|
342
|
+
state.lane = opts.lane || state.lane || "release";
|
|
343
|
+
if (!Object.values(state.steps).some((x) => x?.done)) {
|
|
344
|
+
const g = await managedGate({ io, repo, config, lane: state.lane, root });
|
|
345
|
+
if (g.blocked) return { id, status: "blocked", step: "gate", reason: g.reason };
|
|
346
|
+
if (g.ciMode) { state.ciMode = g.ciMode; io.print?.(`release ${id}: ${g.why}; host checks run before paid CI`); }
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const holder = io.holder ?? `host-${process.pid}`;
|
|
350
|
+
const takeLease = async () => { // #5553: the epoch fences every irreversible effect; the release PR carries the heartbeat comment
|
|
351
|
+
const l = await acquireLease(lctx, { holder, release: id, issue: state.steps["release-pr"].result.pr, ttlS: config.leaseTtlS ?? 120, now: io.now() });
|
|
352
|
+
if (!l.ok) return l.refused ?? "lease lost the race";
|
|
353
|
+
const record = async (rec) => { const a = (state.intents ??= []); const i = a.findIndex((x) => x.key === rec.key); if (i < 0) a.push(rec); else a[i] = rec; ctx.save(); await mirror(state); };
|
|
354
|
+
ctx.fence = { lctx, lease: l.lease, record, now: () => new Date(io.now()).toISOString() };
|
|
355
|
+
return null;
|
|
356
|
+
};
|
|
233
357
|
const ctx = { io, repo, opts: state.opts, config, state, staging: branches.staging || DEFAULT_STAGING_BRANCH, def: branches.default || "main", git: io.git, save: () => rel.save(state) };
|
|
234
358
|
ctx.save();
|
|
235
359
|
let out;
|
|
236
360
|
try {
|
|
237
361
|
for (const step of RELEASE_STEPS) {
|
|
238
362
|
if (state.steps[step]?.done) continue;
|
|
363
|
+
if (lctx && !ctx.fence && state.steps["release-pr"]?.done) { const why = await takeLease(); if (why) { out = { id, status: "refused", step: "lease", reason: why }; break; } }
|
|
364
|
+
if (ctx.fence) { // #5556 (I24): a hold stops the run before the next step; an unreadable _active already ends it above
|
|
365
|
+
const held = await holdCheck(lctx, id).catch(() => null);
|
|
366
|
+
if (held) { out = { id, status: "refused", step, reason: held }; break; }
|
|
367
|
+
}
|
|
239
368
|
const result = await steps[step](ctx);
|
|
240
369
|
if (result?.refused) { out = { id, status: "refused", step, reason: result.refused }; break; }
|
|
241
370
|
if (result?.blocked) { out = { id, status: "blocked", step, reason: result.reason }; break; }
|
|
@@ -243,13 +372,32 @@ export async function runRelease({ io, repo, opts = {}, config = {}, branches =
|
|
|
243
372
|
if (result?.stopped) { state.steps[step] = { done: false, at: new Date(io.now()).toISOString(), result }; out = { id, status: "stopped", step, reason: result.why }; break; }
|
|
244
373
|
state.steps[step] = { done: true, at: new Date(io.now()).toISOString(), result };
|
|
245
374
|
ctx.save();
|
|
375
|
+
if (lctx) await mirror(state);
|
|
376
|
+
if (lctx && !ctx.fence && step === "release-pr") { const why = await takeLease(); if (why) { out = { id, status: "refused", step: "lease", reason: why }; break; } }
|
|
377
|
+
if (ctx.fence) { // an unreadable _active ends the run too (I5): the next irreversible step would refuse anyway
|
|
378
|
+
const hb = await heartbeat(lctx, ctx.fence.lease).catch((e) => ({ unreadable: e.message }));
|
|
379
|
+
if (hb.fenced || hb.unreadable) { out = { id, status: "refused", step, reason: hb.fenced ? "fenced: another host took over the release lease" : `cannot read _active (${hb.unreadable})` }; break; }
|
|
380
|
+
}
|
|
246
381
|
}
|
|
247
382
|
out ??= { id, status: "done" };
|
|
248
383
|
} finally {
|
|
249
384
|
// A stop at GATE_PASS ends the release hold as well: nothing else is waiting on the batches.
|
|
250
385
|
await restoreBatches(ctx);
|
|
251
386
|
}
|
|
387
|
+
if (lctx) { // #5569: Actions minutes of this release (sum of ceil per job), mirrored to the ledger below
|
|
388
|
+
try { const m = await releaseMinutes({ gh: (a) => io.gh(a), repo, sinceMs: Date.parse(state.startedAt) }); if (m) state.minutes = { runs: m.runs, total: m.minutes }; } catch { /* best effort */ }
|
|
389
|
+
}
|
|
390
|
+
{ // #5583: with a catalogue, the deploy-telemetry JSON lines of this release (FORGE_GATE_TELEMETRY file) are kept next to state.minutes; no catalogue, no write
|
|
391
|
+
const tf = process.env.FORGE_GATE_TELEMETRY;
|
|
392
|
+
try {
|
|
393
|
+
if (tf && existsSync(tf) && existsSync(join(process.cwd(), ".forge/gates.yaml"))) {
|
|
394
|
+
const recs = (await import("./release-gates.mjs")).parseTelemetry(readFileSync(tf, "utf8"));
|
|
395
|
+
if (recs.length) state.gates = [...(state.gates ?? []), ...recs];
|
|
396
|
+
}
|
|
397
|
+
} catch { /* best effort */ }
|
|
398
|
+
}
|
|
252
399
|
state.status = out.status; ctx.save();
|
|
400
|
+
if (lctx) await mirror(state);
|
|
253
401
|
return out;
|
|
254
402
|
}
|
|
255
403
|
|
|
@@ -260,7 +408,11 @@ export function realReleaseIo({ env = process.env, exec = execFileSync, print =
|
|
|
260
408
|
const mine = (b, repo) => { const r = b.readPlan()?.repo; return !r || r === repo; };
|
|
261
409
|
const unfinished = (repo) => listBatches(root).map((id) => openBatch(root, id)).filter((b) => !b.readReport() && mine(b, repo));
|
|
262
410
|
return {
|
|
263
|
-
gh: (args) => gh(args), print,
|
|
411
|
+
gh: (args) => gh(args), print,
|
|
412
|
+
api: (method, path, body) => { // JSON in and out for the ledger (#5550); the error carries the HTTP status
|
|
413
|
+
try { return JSON.parse(String(exec("gh", ["api", "-X", method, path, ...(body ? ["--input", "-"] : [])], { encoding: "utf8", input: body ? JSON.stringify(body) : undefined, maxBuffer: 64 << 20, stdio: ["pipe", "pipe", "pipe"] })) || "null"); }
|
|
414
|
+
catch (e) { throw Object.assign(new Error(`gh api ${method} ${path} failed: ${String(e?.stderr ?? e?.message ?? e).split("\n")[0]}`), { status: Number(/HTTP (\d{3})/.exec(String(e?.stderr ?? ""))?.[1]) || undefined }); }
|
|
415
|
+
}, now: () => Date.now(),
|
|
264
416
|
git: (args, { env: extra, input } = {}) => exec("git", args, { cwd, encoding: "utf8", input, env: { ...env, ...extra }, maxBuffer: 64 << 20, stdio: ["pipe", "pipe", "pipe"] }),
|
|
265
417
|
sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
266
418
|
run: async (cmd) => { try { exec("sh", ["-c", cmd], { stdio: "ignore", timeout: 120_000 }); return { ok: true }; } catch { return { ok: false }; } },
|
|
@@ -280,31 +432,92 @@ export function realReleaseIo({ env = process.env, exec = execFileSync, print =
|
|
|
280
432
|
}
|
|
281
433
|
|
|
282
434
|
const flag = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
|
|
283
|
-
export const RELEASE_USAGE = "usage: forgedock release [--repo owner/repo] [--merge] [--watch] [--resume <id>] | forgedock release verify <sha> [--repo owner/repo]";
|
|
435
|
+
export const RELEASE_USAGE = "usage: forgedock release [--repo owner/repo] [--merge] [--watch] [--resume <id>] | forgedock release verify <sha | release id> [--repo owner/repo] | forgedock release status [<id>] [--watch] [--interval s] [--json] | forgedock release explain <id | #issue | PR> [--json] | forgedock release check-config [--ref <git ref>] | forgedock release init | forgedock release control <hold|resume|cancel|lane|exempt|freeze|unfreeze> ... --reason <text> [--repo owner/repo] [--json] (the verbs also work as `forgedock release <verb>`) | forgedock release gates [check [--base <ref>] | demote] [--since 30d] [--json] | forgedock release gates record <release-id> --file <jsonl> | forgedock release report";
|
|
284
436
|
|
|
285
437
|
/** `forgedock release ...`; @returns the process exit code (0 done or stopped at GATE_PASS, 1 refused, 3 blocked on a manual step). */
|
|
286
438
|
export async function releaseFromCli(argv, deps = {}) {
|
|
287
439
|
const cwd = deps.cwd ?? process.cwd(), env = deps.env ?? process.env;
|
|
288
440
|
const io = deps.io ?? realReleaseIo({ env, cwd });
|
|
441
|
+
if (argv[0] === "report") { // #5569: monthly model vs measured minutes of the first 3 managed waves
|
|
442
|
+
let y = {}; try { y = parseForgeYaml(readFileSync(join(cwd, "forge.yaml"), "utf8")) ?? {}; } catch { /* defaults */ }
|
|
443
|
+
for (const l of waveReport(historyFromRoot(releaseRoot(env)), parseBudgetConfig(y.budget)).lines) io.print(l);
|
|
444
|
+
return 0;
|
|
445
|
+
}
|
|
446
|
+
if (argv[0] === "verify" && ID_RE.test(String(argv[1] ?? ""))) { // #5562: a release id re-runs the deploy verification; a sha keeps the snapshot-chain check
|
|
447
|
+
const { verifyReleaseById } = await import("./release-verify.mjs");
|
|
448
|
+
const { readPolicy } = await import("./release-config.mjs");
|
|
449
|
+
const def = readBranches(cwd).default || "main", rel = openRelease(releaseRoot(env), argv[1]), state = rel.load();
|
|
450
|
+
if (!state) throw new Error(`no release ${argv[1]} in ${releaseRoot(env)}`);
|
|
451
|
+
const r = await verifyReleaseById({ io, state, save: () => rel.save(state), def, policy: readPolicy({ io, defaultBranch: def, cwd }).policy, lane: flag(argv, "--lane") ?? state.lane });
|
|
452
|
+
return r.verified ? 0 : BLOCKED_EXIT;
|
|
453
|
+
}
|
|
454
|
+
if (argv[0] === "gates") { // #5583: catalogue, telemetry report, admission check; release-gates is loaded lazily
|
|
455
|
+
const g = await import("./release-gates.mjs");
|
|
456
|
+
const { readPolicy } = await import("./release-config.mjs");
|
|
457
|
+
const defaultBranch = readBranches(cwd).default || "main", root = releaseRoot(env);
|
|
458
|
+
if (argv[1] === "record") { // merge a deploy-telemetry JSON-lines file into the release state; no catalogue, no write
|
|
459
|
+
const id = argv[2], file = flag(argv, "--file");
|
|
460
|
+
if (!id || !file || !existsSync(join(cwd, g.GATES_PATH))) { io.print(`release gates record: needs <release-id>, --file and ${g.GATES_PATH}`); return 1; }
|
|
461
|
+
const rel = openRelease(root, id), st = rel.load();
|
|
462
|
+
if (!st) { io.print(`release gates record: no release ${id}`); return 1; }
|
|
463
|
+
const recs = g.parseTelemetry(readFileSync(file, "utf8"));
|
|
464
|
+
rel.save({ ...st, gates: [...(st.gates ?? []), ...recs] });
|
|
465
|
+
io.print(`release gates record: ${recs.length} record(s) into ${id}`);
|
|
466
|
+
return 0;
|
|
467
|
+
}
|
|
468
|
+
const policy = readPolicy({ io, defaultBranch, cwd }).policy;
|
|
469
|
+
const repo = flag(argv, "--repo") ?? (argv[1] === "demote" ? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner : undefined);
|
|
470
|
+
return g.gatesFromCli(argv.slice(1), { io, cwd, defaultBranch, policy, repo, history: gateHistoryFromRoot(root) });
|
|
471
|
+
}
|
|
289
472
|
if (argv[0] === "verify") return verifyFromCli(argv.slice(1), { io, cwd });
|
|
290
|
-
|
|
473
|
+
if (argv[0] === "status" || argv[0] === "explain") return statusCli(argv, { io, cwd, env, deps });
|
|
474
|
+
if (argv[0] === "check-config" || argv[0] === "init") { // #5551: policy file, loaded lazily (release-config imports this module)
|
|
475
|
+
const { checkConfigFromCli, initFromCli } = await import("./release-config.mjs");
|
|
476
|
+
return (argv[0] === "init" ? initFromCli : checkConfigFromCli)(argv.slice(1), { io, cwd });
|
|
477
|
+
}
|
|
478
|
+
const cv = argv[0] === "control" ? argv[1] : argv[0]; // #5556: one implementation, the bare verbs are aliases
|
|
479
|
+
if (CONTROL_VERBS.includes(cv)) {
|
|
480
|
+
const { controlFromCli } = await import("./release-control.mjs");
|
|
481
|
+
const { readPolicy } = await import("./release-config.mjs");
|
|
482
|
+
const policy = readPolicy({ io, defaultBranch: readBranches(cwd).default || "main", cwd }).policy;
|
|
483
|
+
return controlFromCli(cv, argv.slice(argv[0] === "control" ? 2 : 1), { io, policy, actor: deps.actor, host: deps.host });
|
|
484
|
+
}
|
|
485
|
+
if (argv[0] === "control") throw new Error(`unknown control verb ${argv[1] ?? ""}; ${RELEASE_USAGE}`);
|
|
486
|
+
const unknown = argv.filter((a, i) => a.startsWith("--") && !["--repo", "--merge", "--watch", "--resume", "--lane", "--interval"].includes(a) && !(argv[i - 1] === "--resume" || argv[i - 1] === "--repo" || argv[i - 1] === "--lane" || argv[i - 1] === "--interval"));
|
|
291
487
|
if (unknown.length) throw new Error(`unknown option ${unknown[0]}; ${RELEASE_USAGE}`);
|
|
488
|
+
if (argv.includes("--watch")) { // the bare flag delegates to the status loop (#5554)
|
|
489
|
+
const pick = (f) => (flag(argv, f) ? [f, flag(argv, f)] : []);
|
|
490
|
+
return statusCli(["status", ...(flag(argv, "--resume") ? [flag(argv, "--resume")] : []), "--watch", ...pick("--repo"), ...pick("--interval")], { io, cwd, env, deps });
|
|
491
|
+
}
|
|
292
492
|
const root = releaseRoot(env);
|
|
293
493
|
const resume = flag(argv, "--resume");
|
|
294
494
|
let id = resume ?? newReleaseId(io.now());
|
|
295
495
|
let repo = flag(argv, "--repo");
|
|
496
|
+
let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* no forge.yaml: defaults */ }
|
|
497
|
+
const config = readReleaseConfig(raw);
|
|
498
|
+
if (config.managed) config.ciPolicy = readCiPolicy(cwd);
|
|
499
|
+
if (config.managed) { // #5560: deploy stages come from the default-branch policy only (I13)
|
|
500
|
+
const { readPolicy } = await import("./release-config.mjs");
|
|
501
|
+
const pol = readPolicy({ io, defaultBranch: readBranches(cwd).default || "main", cwd }).policy;
|
|
502
|
+
if (pol?.deploy) config.deploy = pol.deploy;
|
|
503
|
+
config.deployPipeline = pol?.lanes?.[flag(argv, "--lane")]?.pipeline ?? "full"; // service/hotfix lanes dispatch with unit inputs
|
|
504
|
+
if (pol?.verify) { // #5562: verification layers; risk class picks the soak minutes
|
|
505
|
+
config.verify = pol.verify;
|
|
506
|
+
config.verifyRisk = riskClass(flag(argv, "--lane"), config.deployPipeline);
|
|
507
|
+
config.verifySoak = pol.lanes?.[flag(argv, "--lane")]?.soak_min;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
296
510
|
if (resume) {
|
|
297
511
|
const st = openRelease(root, resume).load();
|
|
298
|
-
if (!st) throw new Error(`no release ${resume} in ${root}`);
|
|
299
|
-
repo ??= st
|
|
512
|
+
if (!st && !config.managed) throw new Error(`no release ${resume} in ${root}`); // managed: the ledger may hold it (another host)
|
|
513
|
+
repo ??= st?.repo;
|
|
300
514
|
}
|
|
301
515
|
repo ??= JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
|
|
302
|
-
let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* no forge.yaml: defaults */ }
|
|
303
516
|
const budget = async (since) => { // #5278: the Actions-minutes line (and any auto switch to local-first); never fails the job
|
|
304
517
|
try { io.print(await budgetReportLine({ cwd, repo, gh: (a) => io.gh(a), now: io.now(), release: since ? await releaseRuns({ gh: (a) => io.gh(a), repo, sinceMs: since }) : null })); } catch { /* best effort */ }
|
|
305
518
|
};
|
|
306
519
|
await budget(null);
|
|
307
|
-
const r = await runRelease({ io, repo, opts: { merge: argv.includes("--merge")
|
|
520
|
+
const r = await runRelease({ io, repo, opts: { merge: argv.includes("--merge"), lane: flag(argv, "--lane") }, config, branches: readBranches(cwd), root, id, mounts: deps.mounts });
|
|
308
521
|
const line = r.status === "done" ? `release ${id}: done` : `release ${id}: ${r.status} at ${r.step}: ${r.reason} (resume: forgedock release --resume ${id})`;
|
|
309
522
|
io.print(line);
|
|
310
523
|
try { await budget(Date.parse(openRelease(root, id).load()?.startedAt) || null); } catch { /* best effort */ }
|
|
@@ -321,3 +534,12 @@ async function verifyFromCli(argv, { io, cwd }) {
|
|
|
321
534
|
io.print(r.ok ? `release verify ${full}: ok (snapshot + ${r.picks} cherry-pick(s), PR #${r.pr})` : `release verify ${full}: FAILED: ${r.why}`);
|
|
322
535
|
return r.ok ? 0 : 1;
|
|
323
536
|
}
|
|
537
|
+
|
|
538
|
+
/** `release status|explain` (#5554): read-only; the local cache and the gate read are handed to release-status.mjs. */
|
|
539
|
+
function statusCli(argv, { io, cwd, env, deps }) {
|
|
540
|
+
let raw = ""; try { raw = readFileSync(join(cwd, "forge.yaml"), "utf8"); } catch { /* defaults */ }
|
|
541
|
+
const root = releaseRoot(env);
|
|
542
|
+
const local = { load: (id) => (ID_RE.test(String(id)) ? openRelease(root, id).load() : null), ids: () => { try { return readdirSync(root).filter((d) => ID_RE.test(d)); } catch { return []; } } };
|
|
543
|
+
const { policy, watch } = policyFromYaml(raw);
|
|
544
|
+
return statusFromCli(argv, { io, config: readReleaseConfig(raw), local, gateState, watch: deps.watch ?? watch, policy: deps.policy ?? policy, maxPolls: deps.maxPolls });
|
|
545
|
+
}
|