forgedock 1.57.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/engine/outcome-codes.mjs +1 -1
- package/bin/engine-cli.mjs +2 -2
- package/bin/help-text.mjs +1 -1
- package/bin/lean/conformance.mjs +30 -3
- package/bin/lean/conformance.test.mjs +74 -0
- package/bin/lean/decisions.mjs +12 -0
- package/bin/lean/decisions.test.mjs +9 -0
- package/bin/lean/issuewatch-parity.mjs +4 -1
- package/bin/lean/issuewatch-parity.test.mjs +6 -0
- package/bin/lean/lean.mjs +41 -6
- package/bin/lean/lean.test.mjs +34 -1
- package/bin/lean/recovery.test.mjs +3 -3
- package/bin/lean/release-config.mjs +18 -7
- package/bin/lean/release-config.test.mjs +23 -0
- package/bin/lean/release-control.mjs +26 -3
- package/bin/lean/release-control.test.mjs +24 -0
- package/bin/lean/release-deploy.mjs +209 -0
- package/bin/lean/release-deploy.test.mjs +217 -0
- package/bin/lean/release-gates.mjs +230 -0
- package/bin/lean/release-gates.test.mjs +146 -0
- package/bin/lean/release-ledger.mjs +16 -0
- package/bin/lean/release-ledger.test.mjs +3 -3
- package/bin/lean/release-minutes.mjs +12 -2
- package/bin/lean/release-minutes.test.mjs +8 -0
- package/bin/lean/release-status.mjs +300 -0
- package/bin/lean/release-status.test.mjs +220 -0
- package/bin/lean/release-verify.mjs +221 -0
- package/bin/lean/release-verify.test.mjs +176 -0
- package/bin/lean/release.mjs +70 -6
- package/bin/lean/release.test.mjs +5 -1
- package/docs/CONFIG.md +20 -1
- package/package.json +1 -1
- package/scripts/ci-local/scoping.mjs +19 -0
- package/scripts/ci-local.test.sh +13 -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
|
+
});
|
|
@@ -158,3 +158,19 @@ export async function heartbeat(ctx, lease) {
|
|
|
158
158
|
await ctx.io.api("PATCH", `repos/${ctx.repo}/issues/comments/${active.lease.commentId}`, { body: leaseBody(lease) });
|
|
159
159
|
return { ok: true };
|
|
160
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
|
+
}
|
|
@@ -136,7 +136,7 @@ describe("release ledger (#5550)", () => {
|
|
|
136
136
|
const g = fakeGh(), seen = [];
|
|
137
137
|
const mkIo = () => ({ print() {}, now: () => 1_700_000_000_000, runningLanes: async () => [], batches: async () => [], setParallel: async () => {}, gh: async () => { throw new Error("no gh"); }, api: g.api });
|
|
138
138
|
const step = (name, die) => async () => { if (die) throw new Error("kill -9"); seen.push(name); return {}; };
|
|
139
|
-
const all = (dieAt) => ({ preflight: step("preflight"), "host-preflight": async () => ({ skipped: true }), "release-pr": async () => { if (dieAt === "release-pr") throw new Error("kill -9"); seen.push("release-pr"); return { pr: 7 }; }, review: step("review"), fixes: step("fixes"), "mark-ready": async () => ({ skipped: true }), rehearsal: async () => ({ skipped: true }), promotion: step("promotion"), "post-merge": step("post-merge") });
|
|
139
|
+
const all = (dieAt) => ({ preflight: step("preflight"), "host-preflight": async () => ({ skipped: true }), deploy: async () => ({ skipped: true }), "release-pr": async () => { if (dieAt === "release-pr") throw new Error("kill -9"); seen.push("release-pr"); return { pr: 7 }; }, review: step("review"), fixes: step("fixes"), "mark-ready": async () => ({ skipped: true }), rehearsal: async () => ({ skipped: true }), promotion: step("promotion"), "post-merge": step("post-merge") });
|
|
140
140
|
const run = (io, dieAt, root) => runRelease({ io, repo: REPO, root, mounts: DISK, id: ID, opts: {}, config: { managed: true }, branches: {}, steps: all(dieAt) });
|
|
141
141
|
await assert.rejects(() => run(mkIo(), "release-pr", tmpDir("ledgerA-")), /kill -9/);
|
|
142
142
|
assert.deepEqual(seen, ["preflight"]);
|
|
@@ -213,13 +213,13 @@ describe("release fencing through the job (#5553)", () => {
|
|
|
213
213
|
for (const dieAt of RELEASE_STEPS) {
|
|
214
214
|
const g = fakeGh(), calls = [], ran = [];
|
|
215
215
|
const track = (name, fn) => async (...a) => { if (name === dieAt && !ran.includes(`die:${name}`)) { ran.push(`die:${name}`); throw new Error("kill -9"); } ran.push(name); return fn(...a); };
|
|
216
|
-
const base = { preflight: ok, "host-preflight": skip, "release-pr": async () => ({ pr: 7 }), review: ok, fixes: ok, "mark-ready": skip, rehearsal: skip, "post-merge": ok };
|
|
216
|
+
const base = { preflight: ok, "host-preflight": skip, "release-pr": async () => ({ pr: 7 }), review: ok, fixes: ok, "mark-ready": skip, rehearsal: skip, "post-merge": ok, deploy: skip };
|
|
217
217
|
const wrapped = withStubs(Object.fromEntries(Object.entries(withStubs(base)).map(([k, fn]) => [k, track(k, fn)])));
|
|
218
218
|
await assert.rejects(() => go(mkIo(g, "hostA", calls), wrapped, tmpDir("fe1-")), /kill -9/, dieAt);
|
|
219
219
|
const out = await go(mkIo(g, "hostB", calls), wrapped, tmpDir("fe2-")); // another host, empty disk
|
|
220
220
|
assert.equal(out.status, "done", dieAt);
|
|
221
221
|
assert.equal(calls.length, 1, `${dieAt}: one merge`);
|
|
222
|
-
const done = ran.filter((r) => !r.startsWith("die:") && !["host-preflight", "mark-ready", "rehearsal"].includes(r)); // unconfigured steps leave no trace and may re-run
|
|
222
|
+
const done = ran.filter((r) => !r.startsWith("die:") && !["host-preflight", "mark-ready", "rehearsal", "deploy"].includes(r)); // unconfigured steps leave no trace and may re-run
|
|
223
223
|
assert.equal(new Set(done).size, done.length, `${dieAt}: no step ran twice (${done})`);
|
|
224
224
|
}
|
|
225
225
|
});
|
|
@@ -40,13 +40,23 @@ export async function releaseMinutes({ gh, repo, sinceMs, branch = null }) {
|
|
|
40
40
|
return { runs: runs.length, minutes };
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
/** Records `{lane, minutes}` of the finished releases kept under `root` (the local cache of the ledger states). */
|
|
43
|
+
/** Records `{lane, minutes}` of the finished releases kept under `root` (the local cache of the ledger states); the array's non-enumerable `gates` property carries the #5583 gate records (see gateHistoryFromRoot). */
|
|
44
44
|
export function historyFromRoot(root) {
|
|
45
|
-
if (!existsSync(root)) return [];
|
|
45
|
+
if (!existsSync(root)) return Object.defineProperty([], "gates", { value: [], enumerable: false });
|
|
46
46
|
const out = [];
|
|
47
47
|
for (const id of readdirSync(root)) {
|
|
48
48
|
try { const s = JSON.parse(readFileSync(join(root, id, "state.json"), "utf8")); if (s?.minutes?.total > 0) out.push({ lane: s.lane ?? "release", minutes: s.minutes.total }); } catch { /* skip */ }
|
|
49
49
|
}
|
|
50
|
+
return Object.defineProperty(out, "gates", { value: gateHistoryFromRoot(root), enumerable: false });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Gate telemetry records (#5583) of the releases kept under `root`, oldest release first, each with `release` and `at`; [] when none. */
|
|
54
|
+
export function gateHistoryFromRoot(root) {
|
|
55
|
+
if (!existsSync(root)) return [];
|
|
56
|
+
const out = [];
|
|
57
|
+
for (const id of readdirSync(root).sort()) {
|
|
58
|
+
try { const s = JSON.parse(readFileSync(join(root, id, "state.json"), "utf8")); for (const g of Array.isArray(s?.gates) ? s.gates : []) out.push({ ...g, release: id, at: s.startedAt }); } catch { /* skip */ }
|
|
59
|
+
}
|
|
50
60
|
return out;
|
|
51
61
|
}
|
|
52
62
|
|
|
@@ -50,6 +50,14 @@ describe("release minutes (#5569)", () => {
|
|
|
50
50
|
assert.deepEqual(historyFromRoot(root), [{ lane: "release", minutes: 480 }]);
|
|
51
51
|
assert.deepEqual(historyFromRoot(join(root, "none")), []);
|
|
52
52
|
});
|
|
53
|
+
it("historyFromRoot carries the gate records on a non-enumerable gates property (#5583)", () => {
|
|
54
|
+
const root = tmpDir("rm");
|
|
55
|
+
mkdirSync(join(root, "a")); writeFileSync(join(root, "a", "state.json"), JSON.stringify({ minutes: { total: 5 }, startedAt: "t", gates: [{ gate: "g", outcome: "fail", class: "FB", minutes: 2 }] }));
|
|
56
|
+
const h = historyFromRoot(root);
|
|
57
|
+
assert.deepEqual(h, [{ lane: "release", minutes: 5 }]);
|
|
58
|
+
assert.deepEqual(h.gates.map((g) => [g.gate, g.release]), [["g", "a"]]);
|
|
59
|
+
assert.deepEqual(historyFromRoot(join(root, "none")).gates, []);
|
|
60
|
+
});
|
|
53
61
|
});
|
|
54
62
|
|
|
55
63
|
describe("release report (#5569)", () => {
|