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,230 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Deploy-gate catalogue, false-block telemetry and admission checklist (#5583, epic #5549 N4, rule R8).
|
|
5
|
+
* `.forge/gates.yaml` (committed, read from a git ref) lists the gates; each run records `{gate, outcome, class, minutes}`
|
|
6
|
+
* (class TP|FB needs an evidence field, else `unknown`) into the release state (`state.gates`). A gate whose FB rate over the
|
|
7
|
+
* last `gates.demote_window` runs exceeds `gates.demote_fb_rate` percent is demoted to warn through `runControl("demote")`
|
|
8
|
+
* with an expiry and an issue, unless it is on the safety allowlist. `release gates` reports runs/fails/FB share/minutes
|
|
9
|
+
* (FB share = FB runs / runs, the same rate the demotion uses). No catalogue file: every entry point is a no-op, zero writes.
|
|
10
|
+
*/
|
|
11
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { load, JSON_SCHEMA } from "../vendor/js-yaml/js-yaml.mjs";
|
|
14
|
+
import { isUnskippable } from "./release-flakes.mjs";
|
|
15
|
+
import { readActive } from "./release-ledger.mjs";
|
|
16
|
+
|
|
17
|
+
export const GATES_PATH = ".forge/gates.yaml";
|
|
18
|
+
export const GATE_MODES = ["block", "skip", "rollback", "freeze", "warn", "red"];
|
|
19
|
+
export const OUTCOMES = ["pass", "fail", "inconclusive", "skip"];
|
|
20
|
+
export const GATE_CLASSES = ["TP", "FB", "unknown"];
|
|
21
|
+
export const TELEMETRY_SCHEMA = "forgedock.release.gate/v1";
|
|
22
|
+
export const REPORT_SCHEMA = "forgedock.release.gates/v1";
|
|
23
|
+
export const DEMOTE_MODES = ["warn", "inconclusive"];
|
|
24
|
+
export const SAFETY_DEFAULT = ["migration-immutability", "identity-preflight", "backup-freshness", "health-auto-restore"];
|
|
25
|
+
export const REQUIRED = ["id", "protects_against", "where", "determinism", "pre_merge_artifact", "version", "mode", "owner", "review_by"];
|
|
26
|
+
const OPTIONAL = ["on_uncertainty", "failure_triggers", "proportionality"];
|
|
27
|
+
const DAY_MS = 86_400_000;
|
|
28
|
+
|
|
29
|
+
/** @returns {string[]} findings for a parsed catalogue `{schema: 1, gates: [...]}`; empty when valid. */
|
|
30
|
+
export function validateCatalogue(cat) {
|
|
31
|
+
if (!cat || typeof cat !== "object" || Array.isArray(cat)) return ["gates: expected a mapping"];
|
|
32
|
+
const out = [];
|
|
33
|
+
for (const k of Object.keys(cat)) if (k !== "schema" && k !== "gates") out.push(`${k}: unknown key`);
|
|
34
|
+
if (cat.schema !== 1) out.push("schema: required and must be 1");
|
|
35
|
+
if (!Array.isArray(cat.gates)) return [...out, "gates: expected a list"];
|
|
36
|
+
const seen = new Set();
|
|
37
|
+
cat.gates.forEach((g, i) => {
|
|
38
|
+
const at = `gates[${i}]`;
|
|
39
|
+
if (!g || typeof g !== "object" || Array.isArray(g)) return void out.push(`${at}: expected a mapping`);
|
|
40
|
+
for (const k of Object.keys(g)) if (!REQUIRED.includes(k) && !OPTIONAL.includes(k)) out.push(`${at}.${k}: unknown key`);
|
|
41
|
+
for (const k of REQUIRED) if (g[k] === undefined || g[k] === null || String(g[k]).trim() === "") out.push(`${at}.${k}: required`);
|
|
42
|
+
if (g.mode !== undefined && !GATE_MODES.includes(g.mode)) out.push(`${at}.mode: ${JSON.stringify(g.mode)} is not one of ${GATE_MODES.join("|")}`);
|
|
43
|
+
if (g.review_by != null && !/^\d{4}-\d{2}-\d{2}$/.test(String(g.review_by))) out.push(`${at}.review_by: expected YYYY-MM-DD`);
|
|
44
|
+
if (g.id != null) { if (seen.has(g.id)) out.push(`${at}.id: duplicate ${g.id}`); seen.add(g.id); }
|
|
45
|
+
});
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** @returns {{catalogue}|{error}} */
|
|
50
|
+
export function parseCatalogue(text) {
|
|
51
|
+
try { return { catalogue: load(String(text), { schema: JSON_SCHEMA }) }; } catch (e) { return { error: String(e?.message ?? e).split("\n")[0] }; }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The catalogue text at `ref` (`git show`), or null when the file is absent there. */
|
|
55
|
+
export function catalogueAt(io, ref) {
|
|
56
|
+
try { return String(io.git(["show", `${ref}:${GATES_PATH}`])); } catch { return null; }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Findings for the catalogue at `ref`; null when there is none (nothing to validate, nothing written). */
|
|
60
|
+
export function catalogueFindings(io, ref) {
|
|
61
|
+
const text = catalogueAt(io, ref);
|
|
62
|
+
if (text === null) return null;
|
|
63
|
+
const { catalogue, error } = parseCatalogue(text);
|
|
64
|
+
return error ? [`parse: ${error}`] : validateCatalogue(catalogue);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** `gates.*` of the release policy: percent threshold, run window, safety allowlist (defaults + the unskippable classes). */
|
|
68
|
+
export function parseGatesConfig(policy) {
|
|
69
|
+
const g = policy?.gates ?? {};
|
|
70
|
+
return {
|
|
71
|
+
demoteFbRate: Number(g.demote_fb_rate) >= 0 && g.demote_fb_rate != null ? Number(g.demote_fb_rate) : 5,
|
|
72
|
+
demoteWindow: Number.isInteger(g.demote_window) && g.demote_window > 0 ? g.demote_window : 20,
|
|
73
|
+
safety: Array.isArray(g.safety) ? g.safety.map(String) : SAFETY_DEFAULT,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Safety-allowlisted gates are never demoted: the `gates.safety` entries and every unskippable class. */
|
|
78
|
+
export const isSafetyGate = (gate, safety = SAFETY_DEFAULT) =>
|
|
79
|
+
isUnskippable(String(gate)) || safety.some((s) => gate === s || String(gate).startsWith(`${s}:`) || String(gate).startsWith(`${s}/`));
|
|
80
|
+
|
|
81
|
+
/** 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 }) {
|
|
83
|
+
if (!gate || !OUTCOMES.includes(outcome)) return null;
|
|
84
|
+
const ev = typeof evidence === "string" ? evidence.trim() : "";
|
|
85
|
+
const r = { gate: String(gate), outcome, class: (cls === "TP" || cls === "FB") && ev ? cls : "unknown", minutes: Number(minutes) > 0 ? Number(minutes) : 0 };
|
|
86
|
+
if (ev) r.evidence = ev;
|
|
87
|
+
return r;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The JSON line a repo's `deploy-telemetry` job prints (documented in docs/CONFIG.md). */
|
|
91
|
+
export const telemetryLine = (rec) => JSON.stringify({ schema: TELEMETRY_SCHEMA, ...rec });
|
|
92
|
+
|
|
93
|
+
/** Records from JSON lines (telemetry lines or bare records); lines that are not records are skipped. */
|
|
94
|
+
export function parseTelemetry(text) {
|
|
95
|
+
const out = [];
|
|
96
|
+
for (const line of String(text).split("\n")) {
|
|
97
|
+
try { const r = gateRecord(JSON.parse(line)); if (r) out.push(r); } catch { /* not a record */ }
|
|
98
|
+
}
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** `30d` / `12h` -> ms; null when malformed. */
|
|
103
|
+
export function parseSince(s) {
|
|
104
|
+
const m = /^(\d+)([hd])$/.exec(String(s ?? ""));
|
|
105
|
+
return m ? Number(m[1]) * (m[2] === "d" ? DAY_MS : 3_600_000) : null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Per-gate counts of `records` (`at` filtered by `sinceMs`): `{gate, runs, fails, fb, fb_share, minutes}`, sorted by gate. */
|
|
109
|
+
export function summarize(records, { sinceMs = null, now = Date.now() } = {}) {
|
|
110
|
+
const by = new Map();
|
|
111
|
+
for (const r of records) {
|
|
112
|
+
if (sinceMs != null && !(Date.parse(r.at) >= now - sinceMs)) continue;
|
|
113
|
+
const s = by.get(r.gate) ?? { gate: r.gate, runs: 0, fails: 0, fb: 0, minutes: 0 };
|
|
114
|
+
s.runs++; s.minutes += r.minutes ?? 0;
|
|
115
|
+
if (r.outcome === "fail") s.fails++;
|
|
116
|
+
if (r.class === "FB") s.fb++;
|
|
117
|
+
by.set(r.gate, s);
|
|
118
|
+
}
|
|
119
|
+
return [...by.values()].sort((a, b) => a.gate.localeCompare(b.gate)).map((s) => ({ ...s, fb_share: s.runs ? Math.round((s.fb / s.runs) * 1000) / 10 : 0 }));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Text lines (one table row per gate) or the JSON document of a summary. */
|
|
123
|
+
export function formatGatesReport(rows, { json = false } = {}) {
|
|
124
|
+
if (json) return [JSON.stringify({ schema: REPORT_SCHEMA, gates: rows })];
|
|
125
|
+
if (!rows.length) return ["release gates: no gate records"];
|
|
126
|
+
return ["gate\truns\tfails\tfb\tfb_share\tminutes", ...rows.map((r) => `${r.gate}\t${r.runs}\t${r.fails}\t${r.fb}\t${r.fb_share}%\t${r.minutes}`)];
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const liveDemotion = (e, now) => e && Date.parse(e.until) > now;
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Gates to demote: the last `demoteWindow` records of the gate hold FB runs above `demoteFbRate` percent (a full window is
|
|
133
|
+
* needed, so two early runs never decide), the gate is not on the safety allowlist and is not already demoted.
|
|
134
|
+
* `records` are in run order. @returns {{gate, runs, fb, rate}[]}
|
|
135
|
+
*/
|
|
136
|
+
export function planDemotions(records, cfg, { gateModes = {}, now = Date.now() } = {}) {
|
|
137
|
+
const by = new Map();
|
|
138
|
+
for (const r of records) by.set(r.gate, [...(by.get(r.gate) ?? []), r]);
|
|
139
|
+
const out = [];
|
|
140
|
+
for (const [gate, rs] of by) {
|
|
141
|
+
const win = rs.slice(-cfg.demoteWindow);
|
|
142
|
+
if (win.length < cfg.demoteWindow || isSafetyGate(gate, cfg.safety) || liveDemotion(gateModes[gate], now)) continue;
|
|
143
|
+
const fb = win.filter((r) => r.class === "FB").length;
|
|
144
|
+
if (fb * 100 > cfg.demoteFbRate * win.length) out.push({ gate, runs: win.length, fb, rate: Math.round((fb / win.length) * 1000) / 10 });
|
|
145
|
+
}
|
|
146
|
+
return out.sort((a, b) => a.gate.localeCompare(b.gate));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The mode a gate runs in now: its catalogue mode unless a live demotion lowers it. */
|
|
150
|
+
export const effectiveGateMode = (gate, mode, gateModes, now = Date.now()) => (liveDemotion(gateModes?.[gate], now) ? gateModes[gate].mode : mode);
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Demote every planned gate: file one issue, then `runControl("demote")` (audited, with expiry). @returns {{gate, ok, issue?, error?}[]}
|
|
154
|
+
* `run` defaults to release-control's `runControl`.
|
|
155
|
+
*/
|
|
156
|
+
export async function applyDemotions({ io, repo, policy, records, now = Date.now(), days = 14, run }) {
|
|
157
|
+
const cfg = parseGatesConfig(policy);
|
|
158
|
+
const lctx = { io, repo, credential: "driver" };
|
|
159
|
+
const active = await readActive(lctx);
|
|
160
|
+
const plan = planDemotions(records, cfg, { gateModes: active.gateModes ?? {}, now });
|
|
161
|
+
const runControl = run ?? (await import("./release-control.mjs")).runControl;
|
|
162
|
+
const out = [];
|
|
163
|
+
for (const p of plan) {
|
|
164
|
+
const why = `false-block rate ${p.rate}% (${p.fb} of the last ${p.runs} runs) exceeds ${cfg.demoteFbRate}%`;
|
|
165
|
+
const url = String(await io.gh(["issue", "create", "--repo", repo, "--title", `gate ${p.gate} demoted to warn: ${why}`,
|
|
166
|
+
"--body", `Gate \`${p.gate}\` was demoted to warn for ${days}d by the false-block policy (#5583): ${why}.\nRe-promote with \`forgedock release promote ${p.gate} --fixture <ref> --reason <text>\` once a fixture reproduces the false block.`])).trim();
|
|
167
|
+
const issue = /(\d+)$/.exec(url)?.[1];
|
|
168
|
+
if (!issue) { out.push({ gate: p.gate, ok: false, error: "could not file the issue" }); continue; }
|
|
169
|
+
const r = await runControl("demote", [p.gate, "--mode", "warn", "--issue", issue, "--until", `${days}d`, "--reason", why], { io, repo, policy, now });
|
|
170
|
+
out.push(r.ok ? { gate: p.gate, ok: true, issue: Number(issue) } : { gate: p.gate, ok: false, issue: Number(issue), error: r.error });
|
|
171
|
+
}
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const ANSWERS = [
|
|
176
|
+
["pre_merge_artifact", (g) => String(g.pre_merge_artifact ?? "").trim() !== "", "pre_merge_artifact (a fixture)"],
|
|
177
|
+
["version", (g) => String(g.version ?? "").trim() !== "", "version it runs"],
|
|
178
|
+
["on_uncertainty", (g) => g.on_uncertainty === "inconclusive", "on_uncertainty: inconclusive (not fail)"],
|
|
179
|
+
["failure_triggers", (g) => String(g.failure_triggers ?? "").trim() !== "" && String(g.proportionality ?? "").trim() !== "", "failure_triggers and proportionality (what failure triggers and why that is proportional)"],
|
|
180
|
+
["owner", (g) => String(g.owner ?? "").trim() !== "" && String(g.review_by ?? "").trim() !== "", "owner and review_by"],
|
|
181
|
+
];
|
|
182
|
+
|
|
183
|
+
/** Admission checklist: every gate added or changed in `head` against `base` must carry the five answers. @returns {string[]} findings */
|
|
184
|
+
export function admission(base, head) {
|
|
185
|
+
const was = new Map((base?.gates ?? []).map((g) => [g?.id, JSON.stringify(g)]));
|
|
186
|
+
const out = [];
|
|
187
|
+
for (const g of head?.gates ?? []) {
|
|
188
|
+
if (!g || was.get(g.id) === JSON.stringify(g)) continue;
|
|
189
|
+
for (const [, ok, label] of ANSWERS) if (!ok(g)) out.push(`gate ${g.id}: ${was.has(g.id) ? "changed" : "added"} without ${label}`);
|
|
190
|
+
}
|
|
191
|
+
return out;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* `forgedock release gates [--since 30d] [--json]` | `gates check [--base <ref>]` | `gates demote [--repo R]`.
|
|
198
|
+
* `ctx`: {io, cwd, defaultBranch, history: gate records with `at` in run order, policy, repo}. @returns the exit code.
|
|
199
|
+
* Without `.forge/gates.yaml` (on the ref, or in the worktree for `check`) nothing is read or written and the exit is 0.
|
|
200
|
+
*/
|
|
201
|
+
export async function gatesFromCli(argv, ctx) {
|
|
202
|
+
const { io, cwd = process.cwd(), defaultBranch = "main", history = [], policy = null } = ctx;
|
|
203
|
+
const sub = argv[0] && !argv[0].startsWith("--") ? argv[0] : "report";
|
|
204
|
+
const base = flagOf(argv, "--base") ?? `origin/${defaultBranch}`;
|
|
205
|
+
if (sub === "check") {
|
|
206
|
+
const file = join(cwd, GATES_PATH);
|
|
207
|
+
if (!existsSync(file)) { io.print(`release gates check: no ${GATES_PATH}; nothing to check`); return 0; }
|
|
208
|
+
const head = parseCatalogue(readFileSync(file, "utf8"));
|
|
209
|
+
const findings = head.error ? [`parse: ${head.error}`] : validateCatalogue(head.catalogue);
|
|
210
|
+
if (!findings.length) {
|
|
211
|
+
const was = catalogueAt(io, base);
|
|
212
|
+
findings.push(...admission(was === null ? null : parseCatalogue(was).catalogue, head.catalogue));
|
|
213
|
+
}
|
|
214
|
+
findings.forEach((f) => io.print(`release gates check: ${f}`));
|
|
215
|
+
io.print(findings.length ? `release gates check: FAILED (${findings.length})` : "release gates check: ok");
|
|
216
|
+
return findings.length ? 1 : 0;
|
|
217
|
+
}
|
|
218
|
+
if (!existsSync(join(cwd, GATES_PATH)) && catalogueAt(io, base) === null) { io.print(`release gates: no ${GATES_PATH}; nothing to do`); return 0; }
|
|
219
|
+
if (sub === "demote") {
|
|
220
|
+
const res = await applyDemotions({ io, repo: ctx.repo, policy, records: history, now: io.now?.() });
|
|
221
|
+
res.forEach((r) => io.print(r.ok ? `release gates: demoted ${r.gate} (issue #${r.issue})` : `release gates: ${r.gate}: ${r.error}`));
|
|
222
|
+
if (!res.length) io.print("release gates: no gate to demote");
|
|
223
|
+
return res.every((r) => r.ok) ? 0 : 1;
|
|
224
|
+
}
|
|
225
|
+
const since = flagOf(argv, "--since");
|
|
226
|
+
const sinceMs = since == null ? null : parseSince(since);
|
|
227
|
+
if (since != null && sinceMs == null) { io.print(`release gates: --since must be <N>d or <N>h, got ${since}`); return 1; }
|
|
228
|
+
formatGatesReport(summarize(history, { sinceMs, now: io.now?.() }), { json: argv.includes("--json") }).forEach((l) => io.print(l));
|
|
229
|
+
return 0;
|
|
230
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
8
|
+
import {
|
|
9
|
+
validateCatalogue, parseCatalogue, gateRecord, telemetryLine, parseTelemetry, summarize, formatGatesReport, planDemotions, applyDemotions,
|
|
10
|
+
parseGatesConfig, isSafetyGate, admission, gatesFromCli, effectiveGateMode, REQUIRED,
|
|
11
|
+
} from "./release-gates.mjs";
|
|
12
|
+
import { runControl } from "./release-control.mjs";
|
|
13
|
+
|
|
14
|
+
const GATE = { id: "g1", protects_against: "#12", where: "deploy.yml", determinism: "high", pre_merge_artifact: "fixtures/g1.json", version: "v1", mode: "block", owner: "ops", review_by: "2027-01-01", on_uncertainty: "inconclusive", failure_triggers: "blocks deploy", proportionality: "one deploy at risk" };
|
|
15
|
+
const cat = (...gates) => ({ schema: 1, gates });
|
|
16
|
+
const T0 = Date.parse("2026-11-01T00:00:00Z");
|
|
17
|
+
const runs = (gate, n, fb, at = "2026-11-01T00:00:00Z") => Array.from({ length: n }, (_, i) => ({ gate, outcome: i < fb ? "fail" : "pass", class: i < fb ? "FB" : "unknown", minutes: 2, at }));
|
|
18
|
+
|
|
19
|
+
describe("catalogue schema", () => {
|
|
20
|
+
it("accepts a valid catalogue", () => assert.deepEqual(validateCatalogue(cat(GATE)), []));
|
|
21
|
+
it("reports each missing field", () => {
|
|
22
|
+
for (const k of REQUIRED) { const { [k]: _, ...g } = GATE; assert.match(validateCatalogue(cat(g)).join(), new RegExp(`${k}: required`)); }
|
|
23
|
+
});
|
|
24
|
+
it("rejects a bad mode, unknown key, duplicate id and bad date", () => {
|
|
25
|
+
assert.match(validateCatalogue(cat({ ...GATE, mode: "nope" })).join(), /mode: "nope" is not one of block\|skip\|rollback\|freeze\|warn\|red/);
|
|
26
|
+
assert.match(validateCatalogue(cat({ ...GATE, extra: 1 })).join(), /extra: unknown key/);
|
|
27
|
+
assert.match(validateCatalogue(cat(GATE, GATE)).join(), /duplicate g1/);
|
|
28
|
+
assert.match(validateCatalogue(cat({ ...GATE, review_by: "soon" })).join(), /review_by/);
|
|
29
|
+
assert.match(validateCatalogue({ gates: [] }).join(), /schema/);
|
|
30
|
+
});
|
|
31
|
+
it("parses yaml", () => assert.deepEqual(validateCatalogue(parseCatalogue("schema: 1\ngates: []\n").catalogue), []));
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
describe("telemetry", () => {
|
|
35
|
+
it("a class without evidence is unknown; with evidence it is kept", () => {
|
|
36
|
+
assert.equal(gateRecord({ gate: "g", outcome: "fail", class: "FB", minutes: 3 }).class, "unknown");
|
|
37
|
+
assert.equal(gateRecord({ gate: "g", outcome: "fail", class: "FB", evidence: "run 9: rerun green" }).class, "FB");
|
|
38
|
+
assert.equal(gateRecord({ gate: "g", outcome: "boom" }), null);
|
|
39
|
+
});
|
|
40
|
+
it("emits and re-reads the documented json line", () => {
|
|
41
|
+
const rec = gateRecord({ gate: "g", outcome: "pass", minutes: 4 });
|
|
42
|
+
assert.deepEqual(JSON.parse(telemetryLine(rec)), { schema: "forgedock.release.gate/v1", gate: "g", outcome: "pass", class: "unknown", minutes: 4 });
|
|
43
|
+
assert.deepEqual(parseTelemetry(`noise\n${telemetryLine(rec)}\n`), [rec]);
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
describe("demotion", () => {
|
|
48
|
+
const cfg = parseGatesConfig({ gates: { demote_fb_rate: 5, demote_window: 100 } });
|
|
49
|
+
it("defaults to 5% over 20 runs", () => assert.deepEqual([parseGatesConfig(null).demoteFbRate, parseGatesConfig(null).demoteWindow], [5, 20]));
|
|
50
|
+
it("6% is demoted, 5% is not, an allowlisted gate at 50% never is", () => {
|
|
51
|
+
assert.deepEqual(planDemotions(runs("a", 100, 6), cfg).map((p) => p.gate), ["a"]);
|
|
52
|
+
assert.deepEqual(planDemotions(runs("a", 100, 5), cfg), []);
|
|
53
|
+
assert.deepEqual(planDemotions(runs("backup-freshness", 100, 50), cfg), []);
|
|
54
|
+
assert.deepEqual(planDemotions(runs("migration:x", 100, 50), cfg), []);
|
|
55
|
+
assert.deepEqual(planDemotions(runs("a", 99, 50), cfg), [], "an incomplete window never decides");
|
|
56
|
+
});
|
|
57
|
+
it("only the last window counts, and a live demotion is not repeated", () => {
|
|
58
|
+
assert.deepEqual(planDemotions([...runs("a", 50, 50), ...runs("a", 100, 0)], cfg), []);
|
|
59
|
+
const live = { a: { until: new Date(T0 + 1e9).toISOString(), mode: "warn" } };
|
|
60
|
+
assert.deepEqual(planDemotions(runs("a", 100, 9), cfg, { gateModes: live, now: T0 }), []);
|
|
61
|
+
assert.equal(effectiveGateMode("a", "block", live, T0), "warn");
|
|
62
|
+
assert.equal(effectiveGateMode("a", "block", live, T0 + 2e9), "block");
|
|
63
|
+
});
|
|
64
|
+
it("applyDemotions files an issue and records an audited, expiring demotion; promotion without fixture is refused", async () => {
|
|
65
|
+
const state = { files: {}, controls: "", issues: [], active: { epoch: 1, lease: null } };
|
|
66
|
+
const io = {
|
|
67
|
+
now: () => T0,
|
|
68
|
+
gh: async (a) => { state.issues.push(a); return "https://github.com/o/r/issues/42\n"; },
|
|
69
|
+
api: async (m, p, body) => {
|
|
70
|
+
if (m === "GET" && /git\/ref\/heads\/_active$/.test(p)) return { object: { sha: "h" } };
|
|
71
|
+
if (m === "GET" && /contents\/active\.json/.test(p)) return { content: Buffer.from(JSON.stringify(state.active)).toString("base64") };
|
|
72
|
+
if (m === "GET" && /contents\/controls\.jsonl/.test(p)) return { content: Buffer.from(state.controls).toString("base64") };
|
|
73
|
+
if (m === "GET" && /git\/commits\//.test(p)) return { tree: { sha: "t" } };
|
|
74
|
+
if (m === "POST" && /git\/trees/.test(p)) { for (const t of body.tree) state.files[t.path] = t.content; return { sha: "t1" }; }
|
|
75
|
+
if (m === "POST" && /git\/commits/.test(p)) return { sha: "c1" };
|
|
76
|
+
if (m === "PATCH" && /git\/refs/.test(p)) { state.active = JSON.parse(state.files["active.json"]); state.controls = state.files["controls.jsonl"]; return {}; }
|
|
77
|
+
throw new Error(`unrouted ${m} ${p}`);
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
const policy = { gates: { demote_fb_rate: 5, demote_window: 100 } };
|
|
81
|
+
const res = await applyDemotions({ io, repo: "o/r", policy, records: [...runs("a", 100, 6), ...runs("backup-freshness", 100, 50)], now: T0 });
|
|
82
|
+
assert.deepEqual(res, [{ gate: "a", ok: true, issue: 42 }]);
|
|
83
|
+
assert.equal(state.issues.length, 1);
|
|
84
|
+
assert.equal(state.active.gateModes.a.mode, "warn");
|
|
85
|
+
assert.ok(Date.parse(state.active.gateModes.a.until) > T0);
|
|
86
|
+
assert.match(state.controls, /"verb":"demote"/);
|
|
87
|
+
const refused = await runControl("promote", ["a", "--reason", "x"], { io, repo: "o/r", now: T0 });
|
|
88
|
+
assert.equal(refused.ok, false);
|
|
89
|
+
assert.match(refused.error, /fixture/);
|
|
90
|
+
assert.ok(state.active.gateModes.a);
|
|
91
|
+
assert.equal(isSafetyGate("identity-preflight"), true);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
describe("admission checklist", () => {
|
|
96
|
+
it("fails an added gate missing any of the five answers, passes with them", () => {
|
|
97
|
+
assert.deepEqual(admission(cat(), cat(GATE)), []);
|
|
98
|
+
const drops = [["pre_merge_artifact"], ["version"], ["on_uncertainty"], ["failure_triggers"], ["proportionality"], ["owner"], ["review_by"]];
|
|
99
|
+
for (const [k] of drops) { const { [k]: _, ...g } = GATE; assert.equal(admission(cat(), cat(g)).length, 1, k); }
|
|
100
|
+
assert.equal(admission(cat(), cat({ ...GATE, on_uncertainty: "fail" })).length, 1);
|
|
101
|
+
});
|
|
102
|
+
it("only added or changed entries are checked", () => {
|
|
103
|
+
const old = { id: "old", mode: "block" };
|
|
104
|
+
assert.deepEqual(admission(cat(old), cat(old)), []);
|
|
105
|
+
assert.match(admission(cat(old), cat({ ...old, mode: "warn" })).join(), /changed without/);
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
describe("report and cli", () => {
|
|
110
|
+
const history = [...runs("a", 4, 1, "2026-10-30T00:00:00Z"), ...runs("b", 2, 0, "2026-10-30T00:00:00Z"), ...runs("a", 3, 0, "2026-08-01T00:00:00Z")];
|
|
111
|
+
const rows = summarize(history, { sinceMs: 30 * 86_400_000, now: T0 });
|
|
112
|
+
it("reproduces hand-computed counts", () => {
|
|
113
|
+
assert.deepEqual(rows, [{ gate: "a", runs: 4, fails: 1, fb: 1, minutes: 8, fb_share: 25 }, { gate: "b", runs: 2, fails: 0, fb: 0, minutes: 4, fb_share: 0 }]);
|
|
114
|
+
});
|
|
115
|
+
it("text and json goldens", () => {
|
|
116
|
+
assert.deepEqual(formatGatesReport(rows), ["gate\truns\tfails\tfb\tfb_share\tminutes", "a\t4\t1\t1\t25%\t8", "b\t2\t0\t0\t0%\t4"]);
|
|
117
|
+
assert.equal(formatGatesReport(rows, { json: true })[0], '{"schema":"forgedock.release.gates/v1","gates":[{"gate":"a","runs":4,"fails":1,"fb":1,"minutes":8,"fb_share":25},{"gate":"b","runs":2,"fails":0,"fb":0,"minutes":4,"fb_share":0}]}');
|
|
118
|
+
});
|
|
119
|
+
const mk = (git) => { const io = { out: [], calls: [], now: () => T0, print(l) { this.out.push(l); }, git, gh: async (a) => { io.calls.push(a); return ""; }, api: async (...a) => { io.calls.push(a); return {}; } }; return io; };
|
|
120
|
+
it("with no catalogue every subcommand is a no-op with zero writes", async () => {
|
|
121
|
+
const cwd = tmpDir("gates-");
|
|
122
|
+
const io = mk(() => { throw new Error("absent"); });
|
|
123
|
+
for (const argv of [[], ["check"], ["demote"], ["--json"]]) assert.equal(await gatesFromCli(argv, { io, cwd, history: runs("a", 100, 50), repo: "o/r" }), 0);
|
|
124
|
+
assert.deepEqual(io.calls, []);
|
|
125
|
+
});
|
|
126
|
+
it("check compares the worktree catalogue with the base ref", async () => {
|
|
127
|
+
const cwd = tmpDir("gates-");
|
|
128
|
+
mkdirSync(join(cwd, ".forge"));
|
|
129
|
+
const { id, ...noId } = GATE; void noId;
|
|
130
|
+
const { owner: _o, ...noOwner } = GATE;
|
|
131
|
+
const yaml = (g) => `schema: 1\ngates:\n - ${JSON.stringify(g)}\n`;
|
|
132
|
+
const base = mk(() => "schema: 1\ngates: []\n");
|
|
133
|
+
writeFileSync(join(cwd, ".forge/gates.yaml"), yaml(noOwner));
|
|
134
|
+
assert.equal(await gatesFromCli(["check", "--base", "origin/main"], { io: base, cwd }), 1);
|
|
135
|
+
assert.match(base.out.join("\n"), /owner/);
|
|
136
|
+
writeFileSync(join(cwd, ".forge/gates.yaml"), yaml(GATE));
|
|
137
|
+
const ok = mk(() => "schema: 1\ngates: []\n");
|
|
138
|
+
assert.equal(await gatesFromCli(["check"], { io: ok, cwd }), 0);
|
|
139
|
+
});
|
|
140
|
+
it("report prints from history when a catalogue exists", async () => {
|
|
141
|
+
const io = mk(() => "schema: 1\ngates: []\n");
|
|
142
|
+
assert.equal(await gatesFromCli(["--since", "30d", "--json"], { io, history }), 0);
|
|
143
|
+
assert.equal(JSON.parse(io.out[0]).gates.length, 2);
|
|
144
|
+
assert.equal(await gatesFromCli(["--since", "zz"], { io, history }), 1);
|
|
145
|
+
});
|
|
146
|
+
});
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Release ledger on GitHub (#5550, epic #5549 Phase 0): the durable, cross-host record of a release. One orphan branch
|
|
5
|
+
* `forge-ledger/<release-id>` per release (`state.json`, single writer = the lease holder) plus one control branch
|
|
6
|
+
* `forge-ledger/_active` (`active.json`: lease, epoch, intake pause, holds, counters; `controls.jsonl`: append-only audit).
|
|
7
|
+
* Writes are Git Data API commits whose ref update is NOT forced: a non-fast-forward (HTTP 422) is a lost race, which is
|
|
8
|
+
* the compare-and-swap. `_active` is multi-writer, so `updateActive` is a key-scoped read-modify-write with up to 5 retries.
|
|
9
|
+
* The heartbeat is an edit of the `FORGE:LEASE` comment on the tracking issue, never a commit. Every value is redacted
|
|
10
|
+
* before it is written (I21); a head commit is trusted only from an allowlisted, GitHub-verified driver actor (I12).
|
|
11
|
+
* Every effect goes through `io.api(method, path, body?)` (parsed JSON; throws with `.status`), so it is unit-testable.
|
|
12
|
+
* Off unless forge.yaml `release.managed` is on; nothing here runs otherwise.
|
|
13
|
+
*/
|
|
14
|
+
import { SECRET_PAIR_RE, SECRET_SHAPE_RE } from "./conformance.mjs";
|
|
15
|
+
|
|
16
|
+
export const LEDGER_PREFIX = "forge-ledger/";
|
|
17
|
+
export const ACTIVE = "_active";
|
|
18
|
+
export const ACTIVE_RETRIES = 5;
|
|
19
|
+
export const LEASE_MARKER = "FORGE:LEASE";
|
|
20
|
+
const ID_RE = /^r\d{8}-\d{6}-\d+$/;
|
|
21
|
+
const SECRET_KEY_RE = /TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|CREDENTIAL/i;
|
|
22
|
+
const REDACTED = "[redacted]";
|
|
23
|
+
|
|
24
|
+
export const ledgerBranch = (id) => {
|
|
25
|
+
if (id !== ACTIVE && !ID_RE.test(String(id ?? ""))) throw new Error(`invalid release id ${JSON.stringify(id)}`);
|
|
26
|
+
return `${LEDGER_PREFIX}${id}`;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** `value` with every secret-shaped string (and the value of every secret-named key) replaced; never mutates. */
|
|
30
|
+
export function redactDeep(value) {
|
|
31
|
+
if (typeof value === "string") return value.replace(SECRET_PAIR_RE, `$1${REDACTED}`).replace(SECRET_SHAPE_RE, REDACTED);
|
|
32
|
+
if (Array.isArray(value)) return value.map(redactDeep);
|
|
33
|
+
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, SECRET_KEY_RE.test(k) && typeof v === "string" ? REDACTED : redactDeep(v)]));
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const isLost = (e) => e?.status === 422 || /HTTP 422|not a fast.forward|already exists/i.test(String(e?.message ?? e));
|
|
38
|
+
const isMissing = (e) => e?.status === 404 || /HTTP 404|Not Found/i.test(String(e?.message ?? e));
|
|
39
|
+
const refPath = (b) => `heads/${b}`;
|
|
40
|
+
|
|
41
|
+
const headOf = async ({ io, repo }, branch) => {
|
|
42
|
+
try { return (await io.api("GET", `repos/${repo}/git/ref/${refPath(branch)}`))?.object?.sha ?? null; } catch (e) { if (isMissing(e)) return null; throw e; }
|
|
43
|
+
};
|
|
44
|
+
const readFile = async ({ io, repo }, branch, path) => {
|
|
45
|
+
try { const r = await io.api("GET", `repos/${repo}/contents/${path}?ref=${encodeURIComponent(branch)}`); return Buffer.from(r.content ?? "", "base64").toString("utf8"); } catch (e) { if (isMissing(e)) return null; throw e; }
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/** The driver credential writes the ledger; a lane credential never does (I12). */
|
|
49
|
+
const assertDriver = (ctx) => { if (ctx.credential !== "driver") throw Object.assign(new Error("ledger writes need the driver credential"), { refused: "not-driver" }); };
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* One commit of `files` ({path: text}, redacted) on `branch` on top of `parent` (null = orphan, creates the branch).
|
|
53
|
+
* @returns {{ok: true, sha: string} | {lost: true}} lost when the ref moved (or exists): the caller re-reads and decides.
|
|
54
|
+
*/
|
|
55
|
+
export async function commitFiles(ctx, branch, files, message, parent) {
|
|
56
|
+
assertDriver(ctx);
|
|
57
|
+
const { io, repo } = ctx;
|
|
58
|
+
const base = parent ? (await io.api("GET", `repos/${repo}/git/commits/${parent}`)).tree.sha : undefined;
|
|
59
|
+
const tree = await io.api("POST", `repos/${repo}/git/trees`, { ...(base ? { base_tree: base } : {}), tree: Object.entries(files).map(([path, text]) => ({ path, mode: "100644", type: "blob", content: String(redactDeep(text)) })) });
|
|
60
|
+
const commit = await io.api("POST", `repos/${repo}/git/commits`, { message: String(redactDeep(message)), tree: tree.sha, parents: parent ? [parent] : [] });
|
|
61
|
+
try {
|
|
62
|
+
if (parent) await io.api("PATCH", `repos/${repo}/git/refs/${refPath(branch)}`, { sha: commit.sha, force: false });
|
|
63
|
+
else await io.api("POST", `repos/${repo}/git/refs`, { ref: `refs/${refPath(branch)}`, sha: commit.sha });
|
|
64
|
+
} catch (e) { if (isLost(e)) return { lost: true }; throw e; }
|
|
65
|
+
return { ok: true, sha: commit.sha };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const json = (o) => JSON.stringify(redactDeep(o), null, 2) + "\n";
|
|
69
|
+
|
|
70
|
+
/** Create `forge-ledger/<id>` with the first state; `{lost}` when the release already has a ledger. */
|
|
71
|
+
export const createReleaseLedger = (ctx, id, state) => commitFiles(ctx, ledgerBranch(id), { "state.json": json(state) }, `ledger: create ${id}`, null);
|
|
72
|
+
|
|
73
|
+
/** Write the next state of release `id` on top of `head` (the sha the caller read); `{lost}` means another writer moved it. */
|
|
74
|
+
export const writeRelease = (ctx, id, state, head) => commitFiles(ctx, ledgerBranch(id), { "state.json": json(state) }, `ledger: ${id} ${state.status ?? "update"}`, head);
|
|
75
|
+
|
|
76
|
+
/** True when `info` (GET repos/R/commits/<sha>) was authored by an allowlisted driver actor and is GitHub-verified. */
|
|
77
|
+
export function acceptWrite(info, policy = {}) {
|
|
78
|
+
const id = info?.author?.id;
|
|
79
|
+
if (!info?.commit?.verification?.verified) return { ok: false, reason: "unverified commit" };
|
|
80
|
+
if (id == null || !(policy.allowlist ?? []).includes(id)) return { ok: false, reason: `actor ${info?.author?.login ?? id} is not allowlisted` };
|
|
81
|
+
if (!(policy.driverIds ?? []).includes(id)) return { ok: false, reason: `actor ${info?.author?.login ?? id} is not the driver credential` };
|
|
82
|
+
return { ok: true };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** `{state, head}` of release `id`, `null` when it has no ledger, `{rejected}` when the head commit fails `acceptWrite`. */
|
|
86
|
+
export async function readLedger(ctx, id, policy) {
|
|
87
|
+
const branch = ledgerBranch(id), head = await headOf(ctx, branch);
|
|
88
|
+
if (!head) return null;
|
|
89
|
+
if (policy) {
|
|
90
|
+
const verdict = acceptWrite(await ctx.io.api("GET", `repos/${ctx.repo}/commits/${head}`), policy);
|
|
91
|
+
if (!verdict.ok) return { rejected: verdict.reason, head };
|
|
92
|
+
}
|
|
93
|
+
const text = await readFile(ctx, branch, "state.json");
|
|
94
|
+
try { return { state: JSON.parse(text), head }; } catch { return { rejected: "state.json unreadable", head }; }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Key-scoped read-modify-write of `_active`: `fn(active)` returns `{patch}` (only keys in `owned` are applied, others are
|
|
99
|
+
* ignored), optionally `control` (one line appended to controls.jsonl) or `{refuse}`. A lost race re-reads and re-applies,
|
|
100
|
+
* up to ACTIVE_RETRIES attempts.
|
|
101
|
+
* @returns {{ok: true, active, sha} | {refused: string} | {lost: true, attempts: number}}
|
|
102
|
+
*/
|
|
103
|
+
export async function updateActive(ctx, owned, fn) {
|
|
104
|
+
for (let attempt = 1; attempt <= ACTIVE_RETRIES; attempt++) {
|
|
105
|
+
const head = await headOf(ctx, ACTIVE);
|
|
106
|
+
const cur = head ? JSON.parse((await readFile(ctx, ACTIVE, "active.json")) ?? "{}") : {};
|
|
107
|
+
const out = await fn(cur);
|
|
108
|
+
if (out?.refuse) return { refused: out.refuse };
|
|
109
|
+
const next = { ...cur };
|
|
110
|
+
for (const [k, v] of Object.entries(out?.patch ?? {})) if (owned.includes(k)) next[k] = v;
|
|
111
|
+
const files = { "active.json": json(next), ...(out?.files ?? {}) };
|
|
112
|
+
if (out?.control) files["controls.jsonl"] = `${(head ? (await readFile(ctx, ACTIVE, "controls.jsonl")) ?? "" : "")}${JSON.stringify(redactDeep(out.control))}\n`;
|
|
113
|
+
const r = await commitFiles(ctx, ACTIVE, files, `ledger: _active ${Object.keys(out?.patch ?? {}).join(",") || "control"}`, head);
|
|
114
|
+
if (r.ok) return { ok: true, active: next, sha: r.sha };
|
|
115
|
+
}
|
|
116
|
+
return { lost: true, attempts: ACTIVE_RETRIES };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const leaseBody = (l) => `<!-- ${LEASE_MARKER} -->\nholder: ${l.holder}\nepoch: ${l.epoch}\nrelease: ${l.release}\n${l.expires ? `expires: ${new Date(l.expires).toISOString()}\n` : ""}`;
|
|
120
|
+
|
|
121
|
+
/** Parsed `_active/active.json`; throws when it cannot be read (a fence must treat that as "no irreversible action", I5). */
|
|
122
|
+
export async function readActive(ctx) {
|
|
123
|
+
const text = await readFile(ctx, ACTIVE, "active.json");
|
|
124
|
+
if (text == null) throw new Error("_active has no active.json");
|
|
125
|
+
return JSON.parse(text);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Take the lease for release `release` as `holder`: refused while another holder's `FORGE:LEASE` comment (on `issue`) was
|
|
130
|
+
* edited within `ttlS`; each takeover bumps the epoch. The CAS lives in `updateActive`, so of two racing drivers one wins.
|
|
131
|
+
* @returns {{ok: true, lease} | {refused: string} | {lost: true}}
|
|
132
|
+
*/
|
|
133
|
+
export async function acquireLease(ctx, { holder, release, issue, ttlS = 120, now = Date.now() }) {
|
|
134
|
+
const r = await updateActive(ctx, ["lease", "epoch"], async (active) => {
|
|
135
|
+
const l = active.lease;
|
|
136
|
+
if (l && l.holder !== holder && l.commentId) {
|
|
137
|
+
let c = null; try { c = await ctx.io.api("GET", `repos/${ctx.repo}/issues/comments/${l.commentId}`); } catch (e) { if (!isMissing(e)) throw e; }
|
|
138
|
+
if (c && now - Date.parse(c.updated_at) < (l.ttlS ?? ttlS) * 1000) return { refuse: `lease held by ${l.holder} (epoch ${l.epoch})` };
|
|
139
|
+
}
|
|
140
|
+
const epoch = (active.epoch ?? 0) + 1;
|
|
141
|
+
return { patch: { epoch, lease: { holder, release, issue, ttlS, epoch, expires: now + ttlS * 1000, commentId: l?.holder === holder ? l.commentId : undefined } }, control: { at: new Date(now).toISOString(), verb: "lease", holder, release, epoch } };
|
|
142
|
+
});
|
|
143
|
+
if (!r.ok) return r;
|
|
144
|
+
let lease = r.active.lease;
|
|
145
|
+
if (!lease.commentId) { // the heartbeat comment is made once per takeover, then only edited
|
|
146
|
+
const c = await ctx.io.api("POST", `repos/${ctx.repo}/issues/${issue}/comments`, { body: leaseBody(lease) });
|
|
147
|
+
const set = await updateActive(ctx, ["lease"], (a) => (a.lease?.holder === holder && a.lease.epoch === lease.epoch ? { patch: { lease: { ...a.lease, commentId: c.id } } } : { refuse: "lease lost" }));
|
|
148
|
+
if (!set.ok) return set;
|
|
149
|
+
lease = set.active.lease;
|
|
150
|
+
}
|
|
151
|
+
return { ok: true, lease };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Heartbeat: edit the FORGE:LEASE comment (no commit). `{fenced}` when the lease is no longer this holder's epoch. */
|
|
155
|
+
export async function heartbeat(ctx, lease) {
|
|
156
|
+
const active = JSON.parse((await readFile(ctx, ACTIVE, "active.json")) ?? "{}");
|
|
157
|
+
if (active.lease?.holder !== lease.holder || active.lease?.epoch !== lease.epoch) return { fenced: true };
|
|
158
|
+
await ctx.io.api("PATCH", `repos/${ctx.repo}/issues/comments/${active.lease.commentId}`, { body: leaseBody(lease) });
|
|
159
|
+
return { ok: true };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Read-only `_active` ({lease, epoch, holds, intake, ..., controls[]}: active.json plus the parsed lines of controls.jsonl; `{controls: []}` when the branch or a key is missing). */
|
|
163
|
+
export async function readActiveView(ctx) {
|
|
164
|
+
let active = {};
|
|
165
|
+
try { active = JSON.parse((await readFile(ctx, ACTIVE, "active.json")) ?? "{}") ?? {}; } catch { active = {}; }
|
|
166
|
+
const controls = [];
|
|
167
|
+
for (const line of String((await readFile(ctx, ACTIVE, "controls.jsonl")) ?? "").split("\n")) { try { if (line.trim()) controls.push(JSON.parse(line)); } catch { /* skip a bad line */ } }
|
|
168
|
+
return { ...active, controls };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Release ids that have a ledger branch (never `_active`). */
|
|
172
|
+
export async function listLedgers({ io, repo }) {
|
|
173
|
+
let refs = [];
|
|
174
|
+
try { refs = (await io.api("GET", `repos/${repo}/git/matching-refs/heads/${LEDGER_PREFIX}`)) ?? []; } catch (e) { if (!isMissing(e)) throw e; }
|
|
175
|
+
return refs.map((r) => String(r.ref).slice(`refs/heads/${LEDGER_PREFIX}`.length)).filter((id) => id !== ACTIVE && ID_RE.test(id));
|
|
176
|
+
}
|