forgedock 1.57.0 → 1.59.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 +37 -5
- package/bin/lean/conformance.test.mjs +93 -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 +44 -8
- package/bin/lean/lean.test.mjs +37 -4
- package/bin/lean/prompts.mjs +1 -1
- package/bin/lean/recovery.test.mjs +3 -3
- package/bin/lean/release-config.mjs +19 -8
- package/bin/lean/release-config.test.mjs +31 -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-fixloop.mjs +108 -0
- package/bin/lean/release-fixloop.test.mjs +80 -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-preflight.mjs +22 -0
- package/bin/lean/release-preflight.test.mjs +18 -2
- package/bin/lean/release-review.e2e.test.mjs +3 -2
- package/bin/lean/release-review.mjs +114 -31
- package/bin/lean/release-review.test.mjs +107 -20
- package/bin/lean/release-snapshot.mjs +32 -1
- package/bin/lean/release-snapshot.test.mjs +18 -1
- 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 +77 -7
- 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,108 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* One-round CI fix loop of `forgedock release` (#5567, epic #5549 5.2/5.3, I16). Pure functions, no model call, no I/O of their
|
|
5
|
+
* own: the findings collector (every failed CI job, review finding and guard failure on one head, flake-classified), the brief
|
|
6
|
+
* compiler (grouped by the violated property, deterministic), the round counter keyed by head sha, and the second-push policy
|
|
7
|
+
* (a mechanical revert or an infra-flake rerun, once; anything else is HELD with an owner ask). `fixStep` in
|
|
8
|
+
* `release-review.mjs` drives them through its seam.
|
|
9
|
+
*/
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import { classifyFailure } from "./release-flakes.mjs";
|
|
12
|
+
|
|
13
|
+
export const ReleaseFixloopDEFAULT_MAX_ROUNDS = 1;
|
|
14
|
+
const LOG_TAIL = 400;
|
|
15
|
+
const uniq = (a) => [...new Set(a)];
|
|
16
|
+
const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
17
|
+
|
|
18
|
+
/** policy `ci.fix` -> {maxRounds, coStart, fullRunWorkflow}; defaults: one round, no co-start, no uncached full run. */
|
|
19
|
+
export function parseFixConfig(fix) {
|
|
20
|
+
const n = Number(fix?.max_rounds ?? fix?.maxRounds); // accepts the policy form and an already parsed one
|
|
21
|
+
const wf = [fix?.full_run_workflow, fix?.fullRunWorkflow].find((x) => typeof x === "string" && x.trim())?.trim() ?? null;
|
|
22
|
+
return { maxRounds: Number.isInteger(n) && n >= 1 ? n : ReleaseFixloopDEFAULT_MAX_ROUNDS, coStart: fix?.co_start === true || fix?.coStart === true || Boolean(wf), fullRunWorkflow: wf };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* One record of everything wrong at `head`. `jobs`: [{name, conclusion, log?, inputHash?}] of the finished CI jobs (only failed ones
|
|
27
|
+
* are kept), `findings`: review findings [{id?, title, severity?, property?, wave?: boolean, blocking?: boolean}], `guards`:
|
|
28
|
+
* [{name, why}]. Sorted so a fixed input gives a fixed record.
|
|
29
|
+
*/
|
|
30
|
+
export function collectFindings({ head, jobs = [], findings = [], guards = [] }) {
|
|
31
|
+
const ci = jobs
|
|
32
|
+
.filter((j) => j.conclusion === "failure")
|
|
33
|
+
.map((j) => ({ name: j.name, ...classifyFailure(j.log), inputHash: j.inputHash ?? null, tail: String(j.log ?? "").slice(-LOG_TAIL) }))
|
|
34
|
+
.sort((a, b) => byText(a.name, b.name));
|
|
35
|
+
const review = findings
|
|
36
|
+
.map((f) => ({ id: f.id ?? null, title: String(f.title ?? f.id ?? "finding"), severity: String(f.severity ?? "").toUpperCase() || null, property: f.property ?? f.invariant ?? f.category ?? null, inWave: f.wave !== false, blocking: f.blocking !== false && /^(CRITICAL|HIGH)$/i.test(String(f.severity ?? "")) }))
|
|
37
|
+
.sort((a, b) => byText(a.title, b.title) || byText(String(a.id), String(b.id)));
|
|
38
|
+
const gs = guards.map((g) => ({ name: g.name, why: String(g.why ?? "") })).sort((a, b) => byText(a.name, b.name));
|
|
39
|
+
return { head, ci, review, guards: gs };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Findings that block this round: blocking, in-wave review findings; every failed CI job; every guard failure. */
|
|
43
|
+
export const blockingOf = (rec) => ({ ci: rec.ci, review: rec.review.filter((f) => f.blocking && f.inWave), guards: rec.guards });
|
|
44
|
+
/** Findings that never block: non-blocking or outside the wave. They become issues for the next plan and are never merged after READY (I16). */
|
|
45
|
+
export const deferredOf = (rec) => rec.review.filter((f) => !(f.blocking && f.inWave));
|
|
46
|
+
/** True when every failed CI job carries a known infra signature and nothing else is wrong. */
|
|
47
|
+
export const onlyInfraFlakes = (rec) => rec.ci.length > 0 && rec.ci.every((j) => j.class === "infra") && !blockingOf(rec).review.length && !rec.guards.length;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The fix brief: findings grouped by the property they violate (a CI job is `ci:<name>`, a guard `guard:<name>`), one
|
|
51
|
+
* sibling-sweep instruction, the CI-equivalent local commands and the checks that will rerun. Deterministic for a fixed input.
|
|
52
|
+
*/
|
|
53
|
+
export function compileBrief(rec, { commands = [], rerunChecks = [] } = {}) {
|
|
54
|
+
const groups = new Map();
|
|
55
|
+
const add = (prop, line) => groups.set(prop, [...(groups.get(prop) ?? []), line]);
|
|
56
|
+
const b = blockingOf(rec);
|
|
57
|
+
for (const f of b.review) add(f.property ?? "unclassified", `${f.severity ?? "finding"}: ${f.title}`);
|
|
58
|
+
for (const j of b.ci) add(`ci:${j.name}`, j.tail ? `failed: ${j.tail.replace(/\s+/g, " ").trim()}` : "failed");
|
|
59
|
+
for (const g of b.guards) add(`guard:${g.name}`, g.why || "failed");
|
|
60
|
+
const out = [`Fix everything below in ONE commit series on the wave branch, at head ${rec.head}. One push; there is no second round.`, ""];
|
|
61
|
+
for (const prop of [...groups.keys()].sort(byText)) {
|
|
62
|
+
out.push(`## Invariant: ${prop}`, ...uniq(groups.get(prop)).sort(byText).map((l) => `- ${l}`), "");
|
|
63
|
+
}
|
|
64
|
+
out.push("## Sibling sweep", "For each invariant above, search the whole change for other places that break the same property and fix those too; do not fix only the instances named.", "");
|
|
65
|
+
const cmds = uniq(commands);
|
|
66
|
+
out.push("## Run locally first (CI-equivalent; all must be green before you push)", ...(cmds.length ? cmds.map((c) => `- \`${c}\``) : ["- (no preflight.commands configured)"]), "");
|
|
67
|
+
const checks = uniq(rerunChecks).sort(byText);
|
|
68
|
+
out.push("## Checks that will rerun", ...(checks.length ? checks.map((c) => `- ${c}`) : ["- (none recorded)"]), "");
|
|
69
|
+
return out.join("\n");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Stable hash of a job's inputs: a rerun is requested only for jobs whose hash differs from the one that last ran. */
|
|
73
|
+
export const inputHash = (...parts) => createHash("sha256").update(parts.map(String).join("\0")).digest("hex").slice(0, 16);
|
|
74
|
+
/** Names of the jobs to rerun after the fix push: `now` and `before` map job name -> input hash; unchanged jobs are not requested. */
|
|
75
|
+
export const jobsToRerun = (now, before = {}) => Object.keys(now).filter((n) => before[n] !== now[n]).sort(byText);
|
|
76
|
+
|
|
77
|
+
/** Fix rounds already spent for `head`: the counter is keyed by head sha and a fix push links the new head to its parent. */
|
|
78
|
+
export const roundsAt = (state, head) => state?.fixloop?.heads?.[head]?.rounds ?? 0;
|
|
79
|
+
/** Link the head a push produced to its parent; `kind` is set for a second push (`revert`|`rerun`), `failedBefore` the failing check names at `from`. */
|
|
80
|
+
export function recordRound(state, { from, to, kind = null, failedBefore = null }) {
|
|
81
|
+
const fl = (state.fixloop ??= { heads: {} });
|
|
82
|
+
fl.heads[to] = { parent: from, rounds: roundsAt(state, from) + 1, ...(kind ? { second: kind } : {}), ...(failedBefore ? { failedBefore } : {}) };
|
|
83
|
+
}
|
|
84
|
+
/** The second push already used on this head's line, if any. */
|
|
85
|
+
export const secondPushOf = (state, head) => state?.fixloop?.heads?.[head]?.second ?? null;
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* May the loop push again (the round budget is spent or the first fix did not clear the head)? Only (a) a mechanical revert of the
|
|
89
|
+
* round-1 commit or (b) an infra-flake rerun with no code change, each once; anything else is HELD with an owner ask.
|
|
90
|
+
* `lastPush` is what the previous second push was, if any. No model adjudicates whether the fix caused the failure: a revert is
|
|
91
|
+
* chosen only when a check fails now that was not failing before the fix (a set difference by check name).
|
|
92
|
+
* @returns {{action: "revert"|"rerun"}|{action: "hold", ask: string}}
|
|
93
|
+
*/
|
|
94
|
+
export function secondPush({ rec, failedBefore = null, lastPush = null, maxRounds = ReleaseFixloopDEFAULT_MAX_ROUNDS, rounds }) {
|
|
95
|
+
const ask = (why) => ({ action: "hold", ask: `Owner: ${why} The one-round fix budget (ci.fix.max_rounds=${maxRounds}, ${rounds} used) is spent; decide the next step, then resume the release.` });
|
|
96
|
+
if (lastPush) return ask(`a second push (${lastPush}) was already used on this head.`);
|
|
97
|
+
if (onlyInfraFlakes(rec)) return { action: "rerun" };
|
|
98
|
+
const regressed = failedBefore ? rec.ci.filter((j) => !failedBefore.includes(j.name)) : [];
|
|
99
|
+
if (regressed.length) return { action: "revert" };
|
|
100
|
+
const left = [...rec.ci.map((j) => `ci:${j.name}`), ...blockingOf(rec).review.map((f) => f.title), ...rec.guards.map((g) => `guard:${g.name}`)];
|
|
101
|
+
return ask(`still failing after the fix and not an infra flake or a regression from it: ${left.slice(0, 5).join("; ") || "no failure recorded"}.`);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Mark the release HELD through the control path (best effort: the returned blocked result stops the run either way). */
|
|
105
|
+
export async function holdForOwner(ctx, ask) {
|
|
106
|
+
try { await ctx.hold?.(ask); } catch { /* the blocked result below still stops the job */ }
|
|
107
|
+
return { blocked: true, held: true, reason: ask };
|
|
108
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
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 { parseFixConfig, collectFindings, blockingOf, deferredOf, compileBrief, inputHash, jobsToRerun, roundsAt, recordRound, secondPush, secondPushOf, holdForOwner } from "./release-fixloop.mjs";
|
|
6
|
+
|
|
7
|
+
const HEAD = "a".repeat(40);
|
|
8
|
+
const input = () => ({
|
|
9
|
+
head: HEAD,
|
|
10
|
+
jobs: [{ name: "unit", conclusion: "failure", log: "AssertionError: x" }, { name: "lint", conclusion: "success" }, { name: "e2e", conclusion: "failure", log: "ECONNRESET" }],
|
|
11
|
+
findings: [{ title: "SQL injection", severity: "HIGH", property: "input-validation" }, { title: "Other path injection", severity: "CRITICAL", property: "input-validation" }, { title: "nit", severity: "LOW" }, { title: "elsewhere", severity: "HIGH", wave: false }],
|
|
12
|
+
guards: [{ name: "devdocs", why: "dossier stale" }],
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
describe("release-fixloop (#5567)", () => {
|
|
16
|
+
it("collects failed jobs (flake-classified), findings and guards into one record", () => {
|
|
17
|
+
const rec = collectFindings(input());
|
|
18
|
+
assert.deepEqual(rec.ci.map((j) => [j.name, j.class]).map(([n, c]) => [n, c === "infra"]), [["e2e", true], ["unit", false]]);
|
|
19
|
+
assert.equal(rec.guards.length, 1);
|
|
20
|
+
assert.equal(blockingOf(rec).review.length, 2);
|
|
21
|
+
});
|
|
22
|
+
it("non-blocking and out-of-wave findings never block; they are deferred to the next plan", () => {
|
|
23
|
+
const d = deferredOf(collectFindings(input())).map((f) => f.title);
|
|
24
|
+
assert.deepEqual(d.sort(), ["elsewhere", "nit"]);
|
|
25
|
+
});
|
|
26
|
+
it("brief groups by invariant, has the sibling sweep, commands and rerun checks, and is deterministic", () => {
|
|
27
|
+
const a = compileBrief(collectFindings(input()), { commands: ["npm test"], rerunChecks: ["unit", "e2e"] });
|
|
28
|
+
const rev = input(); rev.findings.reverse(); rev.jobs.reverse();
|
|
29
|
+
const b = compileBrief(collectFindings(rev), { commands: ["npm test"], rerunChecks: ["e2e", "unit"] });
|
|
30
|
+
assert.equal(a, b);
|
|
31
|
+
assert.match(a, /## Invariant: input-validation\n- CRITICAL: Other path injection\n- HIGH: SQL injection/);
|
|
32
|
+
assert.match(a, /## Sibling sweep/);
|
|
33
|
+
assert.match(a, /`npm test`/);
|
|
34
|
+
assert.match(a, /## Checks that will rerun\n- e2e\n- unit/);
|
|
35
|
+
assert.ok(!a.includes("LOW"), "non-blocking finding is not in the brief");
|
|
36
|
+
});
|
|
37
|
+
it("max_rounds defaults to 1; the counter is keyed by head sha", () => {
|
|
38
|
+
assert.equal(parseFixConfig(undefined).maxRounds, 1);
|
|
39
|
+
assert.equal(parseFixConfig({ max_rounds: 3 }).maxRounds, 3);
|
|
40
|
+
const st = {};
|
|
41
|
+
assert.equal(roundsAt(st, HEAD), 0);
|
|
42
|
+
recordRound(st, { from: HEAD, to: "b".repeat(40) });
|
|
43
|
+
assert.equal(roundsAt(st, "b".repeat(40)), 1);
|
|
44
|
+
assert.equal(roundsAt(st, HEAD), 0);
|
|
45
|
+
});
|
|
46
|
+
it("second push: infra-only -> rerun once; regression -> revert; anything else -> HELD with an owner ask (no model)", () => {
|
|
47
|
+
const flake = collectFindings({ head: HEAD, jobs: [{ name: "e2e", conclusion: "failure", log: "ECONNRESET" }] });
|
|
48
|
+
assert.deepEqual(secondPush({ rec: flake, rounds: 1 }), { action: "rerun" });
|
|
49
|
+
assert.equal(secondPush({ rec: flake, lastPush: "rerun", rounds: 1 }).action, "hold");
|
|
50
|
+
const real = collectFindings({ head: HEAD, jobs: [{ name: "unit", conclusion: "failure", log: "AssertionError" }] });
|
|
51
|
+
assert.deepEqual(secondPush({ rec: real, failedBefore: ["lint"], rounds: 1 }), { action: "revert" });
|
|
52
|
+
const held = secondPush({ rec: real, failedBefore: ["unit"], rounds: 1 });
|
|
53
|
+
assert.equal(held.action, "hold");
|
|
54
|
+
assert.match(held.ask, /^Owner: /);
|
|
55
|
+
});
|
|
56
|
+
it("secondPushOf reads the recorded second push; reruns are limited to jobs whose input hash changed", () => {
|
|
57
|
+
const st = {}; recordRound(st, { from: HEAD, to: HEAD, kind: "rerun" });
|
|
58
|
+
assert.equal(secondPushOf(st, HEAD), "rerun");
|
|
59
|
+
assert.deepEqual(jobsToRerun({ a: inputHash("1"), b: inputHash("2") }, { a: inputHash("1"), b: inputHash("x") }), ["b"]);
|
|
60
|
+
});
|
|
61
|
+
it("holdForOwner marks HELD through ctx.hold and returns a blocked result", async () => {
|
|
62
|
+
let ask = null;
|
|
63
|
+
const r = await holdForOwner({ hold: async (a) => { ask = a; } }, "Owner: x");
|
|
64
|
+
assert.equal(ask, "Owner: x");
|
|
65
|
+
assert.deepEqual(r, { blocked: true, held: true, reason: "Owner: x" });
|
|
66
|
+
});
|
|
67
|
+
it("unmanaged (no ctx.hold): a hold writes nothing and still stops the job", async () => {
|
|
68
|
+
assert.deepEqual(await holdForOwner({}, "Owner: y"), { blocked: true, held: true, reason: "Owner: y" });
|
|
69
|
+
});
|
|
70
|
+
it("replay of a recorded findings fixture ends in one round or a recorded hold", () => {
|
|
71
|
+
const rec = collectFindings(input());
|
|
72
|
+
const d = secondPush({ rec, failedBefore: ["unit", "e2e"], rounds: 1 });
|
|
73
|
+
assert.equal(d.action, "hold", "same failures as before the fix, mixed with a real failure: neither revert nor rerun");
|
|
74
|
+
assert.match(d.ask, /^Owner: .*ci:unit.*max_rounds=1/);
|
|
75
|
+
const flakeOnly = collectFindings({ head: HEAD, jobs: [{ name: "e2e", conclusion: "failure", log: "ECONNRESET" }] });
|
|
76
|
+
assert.equal(secondPush({ rec: flakeOnly, failedBefore: ["e2e"], rounds: 1 }).action, "rerun");
|
|
77
|
+
const regress = collectFindings({ head: HEAD, jobs: [{ name: "unit", conclusion: "failure", log: "x" }, { name: "e2e", conclusion: "failure", log: "y" }] });
|
|
78
|
+
assert.equal(secondPush({ rec: regress, failedBefore: ["unit"], rounds: 1 }).action, "revert");
|
|
79
|
+
});
|
|
80
|
+
});
|
|
@@ -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
|
});
|