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.
Files changed (44) hide show
  1. package/bin/engine/outcome-codes.mjs +1 -1
  2. package/bin/engine-cli.mjs +2 -2
  3. package/bin/help-text.mjs +1 -1
  4. package/bin/lean/conformance.mjs +37 -5
  5. package/bin/lean/conformance.test.mjs +93 -0
  6. package/bin/lean/decisions.mjs +12 -0
  7. package/bin/lean/decisions.test.mjs +9 -0
  8. package/bin/lean/issuewatch-parity.mjs +4 -1
  9. package/bin/lean/issuewatch-parity.test.mjs +6 -0
  10. package/bin/lean/lean.mjs +44 -8
  11. package/bin/lean/lean.test.mjs +37 -4
  12. package/bin/lean/prompts.mjs +1 -1
  13. package/bin/lean/recovery.test.mjs +3 -3
  14. package/bin/lean/release-config.mjs +19 -8
  15. package/bin/lean/release-config.test.mjs +31 -0
  16. package/bin/lean/release-control.mjs +26 -3
  17. package/bin/lean/release-control.test.mjs +24 -0
  18. package/bin/lean/release-deploy.mjs +209 -0
  19. package/bin/lean/release-deploy.test.mjs +217 -0
  20. package/bin/lean/release-fixloop.mjs +108 -0
  21. package/bin/lean/release-fixloop.test.mjs +80 -0
  22. package/bin/lean/release-gates.mjs +230 -0
  23. package/bin/lean/release-gates.test.mjs +146 -0
  24. package/bin/lean/release-ledger.mjs +16 -0
  25. package/bin/lean/release-ledger.test.mjs +3 -3
  26. package/bin/lean/release-minutes.mjs +12 -2
  27. package/bin/lean/release-minutes.test.mjs +8 -0
  28. package/bin/lean/release-preflight.mjs +22 -0
  29. package/bin/lean/release-preflight.test.mjs +18 -2
  30. package/bin/lean/release-review.e2e.test.mjs +3 -2
  31. package/bin/lean/release-review.mjs +114 -31
  32. package/bin/lean/release-review.test.mjs +107 -20
  33. package/bin/lean/release-snapshot.mjs +32 -1
  34. package/bin/lean/release-snapshot.test.mjs +18 -1
  35. package/bin/lean/release-status.mjs +300 -0
  36. package/bin/lean/release-status.test.mjs +220 -0
  37. package/bin/lean/release-verify.mjs +221 -0
  38. package/bin/lean/release-verify.test.mjs +176 -0
  39. package/bin/lean/release.mjs +77 -7
  40. package/bin/lean/release.test.mjs +5 -1
  41. package/docs/CONFIG.md +20 -1
  42. package/package.json +1 -1
  43. package/scripts/ci-local/scoping.mjs +19 -0
  44. package/scripts/ci-local.test.sh +13 -0
@@ -12,6 +12,7 @@ import { createHash } from "node:crypto";
12
12
  import { load, JSON_SCHEMA } from "../vendor/js-yaml/js-yaml.mjs";
13
13
  import { readReleaseConfig } from "./release.mjs";
14
14
  import { readBranches } from "./lane.mjs";
15
+ import { catalogueFindings } from "./release-gates.mjs";
15
16
 
16
17
  export const POLICY_PATH = ".forge/release.yaml";
17
18
  export const DEFERRED_KEYS = ["plan.auto_if", "retention_days", "ci.forbid_per_issue_steps", "couplings[].refine", "ci.provider=command", "risk.weights"];
@@ -44,12 +45,13 @@ export const POLICY_SCHEMA = obj({
44
45
  plan: obj({ approval: en("wait", "auto", "auto-if"), skip_labels: list(), require_design_gate: B, max_issues: N, stale_snapshot_s: N }),
45
46
  lanes: { t: "map", v: obj({ pipeline: S, ci_tier: S, approval: S, budget: S, base: en("live", "integration", "default"), units_max: N, max_risk: en("low", "medium", "high"), train_max_issues: N, train_max_units: N, soak_min: { t: "any" }, flag_policy: en("require", "warn", "off"), requires: list() }) },
46
47
  merge: obj({ approval: en("confirm", "with-plan", "auto"), method: en("merge-commit", "squash", "rebase"), trailers: list() }),
47
- ci: obj({ provider: en("github-actions", "command"), required_checks: ANY, selection: ANY, rerun_budget_min: N, fix: ANY, flake: obj({ quarantine_after: N, window_days: N }), unskippable: list(), tiers: { t: "map", v: obj({ jobs: list() }) }, nightly: ANY, budget: ANY }),
48
+ ci: obj({ provider: en("github-actions", "command"), required_checks: ANY, selection: ANY, rerun_budget_min: N, fix: obj({ max_rounds: I, co_start: B, full_run_workflow: S }), flake: obj({ quarantine_after: N, window_days: N }), unskippable: list(), tiers: { t: "map", v: obj({ jobs: list() }) }, nightly: ANY, budget: ANY }),
48
49
  preflight: obj({ commands: list(), timeout_s: N, blocking: B }),
49
- deploy: obj({ live_release_command: S, freeze_variable: S, concurrency_group: S, start_timeout_s: N, stage_timeout_s: ANY, recovery: ANY, pipelines: { t: "map", v: PIPELINE } }),
50
- verify: obj({ slis: list(ANY), post_deploy_checks_file: S, close_requires: en("verified", "deployed") }),
50
+ deploy: obj({ live_release_command: S, freeze_variable: S, concurrency_group: S, start_timeout_s: N, stage_timeout_s: N, expected_digests_command: S, recovery: obj({ rerun_max: I, max_attempts: I, signatures: list() }), pipelines: { t: "map", v: PIPELINE } }),
51
+ verify: obj({ workflow: S, results: list(obj({ workflow: S, kind: en("smoke", "edge", "convergence") })), flags: list(obj({ flag: S, off_command: S })), slis: list(ANY), post_deploy_checks_file: S, close_requires: en("verified", "deployed") }),
51
52
  rollback: obj({ triggers: list(), ladder: list(), refuse_across: list(), open_revert_pr: B }),
52
53
  quarantine: obj({ days: N, max: N }),
54
+ gates: obj({ demote_fb_rate: N, demote_window: I, safety: list() }),
53
55
  controls: obj({ intake: ANY, conductor: ANY, exempt: ANY }),
54
56
  });
55
57
 
@@ -135,16 +137,25 @@ export function readPolicy({ io, defaultBranch, cwd = process.cwd(), ref }) {
135
137
  return { source: "file", policy: findings.length ? null : policy, findings, sha: createHash("sha256").update(text).digest("hex") };
136
138
  }
137
139
 
140
+ const GATES_PATH_LABEL = ".forge/gates.yaml";
138
141
  const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
139
142
 
140
143
  /** `forgedock release check-config [--ref <git ref>]`: exit 0 valid (or file absent: flat keys), 1 on any finding. */
141
144
  export function checkConfigFromCli(argv, { io, cwd = process.cwd() }) {
142
145
  const defaultBranch = readBranches(cwd).default || "main";
143
- const r = readPolicy({ io, defaultBranch, cwd, ref: flagOf(argv, "--ref") });
144
- if (r.source === "forge.yaml") { io.print(`release check-config: no ${POLICY_PATH} on origin/${defaultBranch}; using forge.yaml release.* keys`); return 0; }
145
- r.findings.forEach((f) => io.print(`release check-config: ${f}`));
146
- io.print(r.findings.length ? `release check-config: FAILED (${r.findings.length})` : `release check-config: ok (sha256 ${r.sha.slice(0, 12)})`);
147
- return r.findings.length ? 1 : 0;
146
+ const ref = flagOf(argv, "--ref");
147
+ const gf = catalogueFindings(io, ref ?? `origin/${defaultBranch}`); // #5583: .forge/gates.yaml, validated when present
148
+ const gatesLines = () => (gf ?? []).map((f) => `release check-config: ${GATES_PATH_LABEL}: ${f}`);
149
+ const r = readPolicy({ io, defaultBranch, cwd, ref });
150
+ if (r.source === "forge.yaml") {
151
+ io.print(`release check-config: no ${POLICY_PATH} on origin/${defaultBranch}; using forge.yaml release.* keys`);
152
+ gatesLines().forEach((l) => io.print(l));
153
+ return gf?.length ? 1 : 0;
154
+ }
155
+ const findings = [...r.findings, ...(gf ?? []).map((f) => `${GATES_PATH_LABEL}: ${f}`)];
156
+ findings.forEach((f) => io.print(`release check-config: ${f}`));
157
+ io.print(findings.length ? `release check-config: FAILED (${findings.length})` : `release check-config: ok (sha256 ${r.sha.slice(0, 12)})`);
158
+ return findings.length ? 1 : 0;
148
159
  }
149
160
 
150
161
  /** `forgedock release init`: writes the zero-config profile (7.4) to `.forge/release.yaml` and nothing else; never overwrites. */
@@ -47,6 +47,14 @@ describe("validate", () => {
47
47
  });
48
48
  });
49
49
 
50
+ describe("ci.fix (#5567)", () => {
51
+ it("accepts max_rounds, co_start and full_run_workflow; rejects unknown keys and a non-integer max_rounds", () => {
52
+ assert.deepEqual(check(OK.replace("ci:\n", "ci:\n fix: {max_rounds: 1, co_start: true, full_run_workflow: full.yml}\n")), []);
53
+ assert.match(check(OK.replace("ci:\n", "ci:\n fix: {bogus: 1}\n")).join(), /bogus: unknown key/);
54
+ assert.notDeepEqual(check(OK.replace("ci:\n", "ci:\n fix: {max_rounds: x}\n")), []);
55
+ });
56
+ });
57
+
50
58
  describe("I23 deferred keys are rejected", () => {
51
59
  const cases = {
52
60
  "plan.auto_if": "plan: {auto_if: x}\n", "retention_days": "retention_days: 30\n", "ci.forbid_per_issue_steps": "ci: {forbid_per_issue_steps: true}\n",
@@ -106,4 +114,27 @@ describe("CLI", () => {
106
114
  assert.deepEqual(check(`${OK} flake: {quarantine_after: 3, window_days: 14}\nquarantine: {days: 14, max: 15}\n`.replace("ci:\n tiers: {T3: {jobs: [e2e]}}\n flake", "ci:\n tiers: {T3: {jobs: [e2e]}}\n flake")), []);
107
115
  assert.notDeepEqual(check(`${OK}quarantine: {max: x}\n`), []);
108
116
  });
117
+ it("accepts the verification layer keys and rejects a bad result kind (#5562)", () => {
118
+ assert.deepEqual(check(`${OK}verify:\n workflow: verify.yml\n close_requires: verified\n results: [{workflow: smoke.yml, kind: smoke}]\n flags: [{flag: F, off_command: x}]\n`), []);
119
+ assert.notDeepEqual(check(`${OK}verify:\n results: [{workflow: s.yml, kind: nope}]\n`), []);
120
+ });
121
+ });
122
+
123
+ describe("gates catalogue and policy (#5583)", () => {
124
+ const GATE = `schema: 1\ngates:\n - {id: g1, protects_against: "#1", where: deploy, determinism: high, pre_merge_artifact: f.json, version: v1, mode: block, owner: me, review_by: 2027-01-01}\n`;
125
+ const gio = (files) => ({ printed: [], print(l) { this.printed.push(l); }, git(a) { const t = files[a[1].split(":").slice(1).join(":")]; if (t === undefined) throw new Error("missing"); return t; } });
126
+ it("accepts the gates policy keys and rejects a wrong type", () => {
127
+ assert.deepEqual(check(OK + "gates: {demote_fb_rate: 5, demote_window: 20, safety: [a]}\n"), []);
128
+ assert.match(check(OK + "gates: {demote_window: 2.5}\n").join(), /demote_window/);
129
+ });
130
+ it("check-config reports catalogue errors, passes a valid one, ignores an absent one", () => {
131
+ const bad = gio({ ".forge/gates.yaml": GATE.replace("mode: block", "mode: nope"), [POLICY_PATH]: OK });
132
+ assert.equal(checkConfigFromCli([], { io: bad }), 1);
133
+ assert.match(bad.printed.join("\n"), /gates\.yaml: gates\[0\]\.mode/);
134
+ const good = gio({ ".forge/gates.yaml": GATE, [POLICY_PATH]: OK });
135
+ assert.equal(checkConfigFromCli([], { io: good }), 0);
136
+ const none = gio({ [POLICY_PATH]: OK });
137
+ assert.equal(checkConfigFromCli([], { io: none }), 0);
138
+ assert.doesNotMatch(none.printed.join("\n"), /gates/);
139
+ });
109
140
  });
@@ -10,15 +10,17 @@
10
10
  */
11
11
  import { hostname } from "node:os";
12
12
  import { readActive, readLedger, updateActive } from "./release-ledger.mjs";
13
+ import { isSafetyGate, parseGatesConfig, DEMOTE_MODES } from "./release-gates.mjs";
13
14
  import { UNSKIPPABLE_CLASSES, isUnskippable, parseFlakeConfig, canQuarantine } from "./release-flakes.mjs";
14
15
 
15
16
  export const CONTROL_SCHEMA = "forgedock.release.control/v1";
16
17
  export const CONTROL_MARKER = "FORGE:CONTROL";
17
- export const VERBS = ["hold", "resume", "cancel", "lane", "exempt", "freeze", "unfreeze"];
18
+ export const VERBS = ["hold", "resume", "cancel", "lane", "exempt", "freeze", "unfreeze", "demote", "promote"];
18
19
  export { UNSKIPPABLE_CLASSES as UNSKIPPABLE };
19
20
  export const EXEMPT_MAX_H = { skip: 24, quarantine: 14 * 24 };
20
21
  export const LANES = ["train", "release", "p0", "exclude"];
21
- const OWNED = ["holds", "cancelled", "lanes", "exemptions", "freeze"];
22
+ const OWNED = ["holds", "cancelled", "lanes", "exemptions", "freeze", "gateModes"];
23
+ export const DEMOTE_MAX_H = 30 * 24;
22
24
  const BREAK_GLASS = /^(override_freeze|acknowledge_hotfix_revert|override_.*|acknowledge_.*)$/;
23
25
 
24
26
  /** Argv of `gh workflow run`; rejects a break-glass input (I26). */
@@ -44,7 +46,7 @@ export async function holdCheck(lctx, id) {
44
46
  }
45
47
 
46
48
  const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
47
- const FLAGS = ["--repo", "--reason", "--mode", "--issue", "--until", "--force"];
49
+ const FLAGS = ["--repo", "--reason", "--mode", "--issue", "--until", "--force", "--fixture"];
48
50
  const positionals = (argv) => argv.filter((a, i) => !a.startsWith("--") && !FLAGS.includes(argv[i - 1]));
49
51
  const ttlHours = (s) => { const m = /^(\d+)([hd])$/.exec(String(s ?? "")); return m ? Number(m[1]) * (m[2] === "d" ? 24 : 1) : null; };
50
52
 
@@ -113,6 +115,27 @@ export async function runControl(verb, argv, ctx) {
113
115
  }
114
116
  return { patch: { exemptions: { ...(a.exemptions ?? {}), [check]: entry } }, before: a.exemptions?.[check] ?? null, after: entry };
115
117
  };
118
+ } else if (verb === "demote" || verb === "promote") { // #5583: false-block policy on a deploy gate, same audited path
119
+ const gate = pos[0];
120
+ if (!gate) return fail(`${verb}: gate id required`);
121
+ if (verb === "demote") {
122
+ const mode = flagOf(argv, "--mode"), issue = flagOf(argv, "--issue"), hours = ttlHours(flagOf(argv, "--until"));
123
+ if (!DEMOTE_MODES.includes(mode)) return fail(`demote: --mode must be ${DEMOTE_MODES.join(" or ")}`);
124
+ if (!/^#?\d+$/.test(issue ?? "")) return fail("demote: --issue N is required");
125
+ if (hours == null) return fail("demote: --until <Nh|Nd> is required");
126
+ if (hours > DEMOTE_MAX_H) return fail(`demote: expires in at most ${DEMOTE_MAX_H}h (got ${hours}h)`);
127
+ if (isSafetyGate(gate, parseGatesConfig(policy).safety)) return fail(`demote: ${gate} is on the safety allowlist and is never demoted`);
128
+ const entry = { mode, issue: String(issue).replace("#", ""), reason, actor, at, until: new Date((ctx.now ?? Date.now()) + hours * 3_600_000).toISOString() };
129
+ apply = (a) => ({ patch: { gateModes: { ...(a.gateModes ?? {}), [gate]: entry } }, before: a.gateModes?.[gate] ?? null, after: entry });
130
+ } else {
131
+ const fixture = flagOf(argv, "--fixture");
132
+ if (!fixture || !fixture.trim() || fixture.startsWith("--")) return fail("promote: --fixture <ref> is required (re-promotion needs a fixture reference)");
133
+ apply = (a) => {
134
+ if (!a.gateModes?.[gate]) return { refuse: `promote: ${gate} is not demoted` };
135
+ const next = { ...a.gateModes }; delete next[gate];
136
+ return { patch: { gateModes: next }, before: a.gateModes[gate], after: { promoted: true, fixture } };
137
+ };
138
+ }
116
139
  } else { // freeze | unfreeze: the repo's own deploy variable (6.4), not a second mechanism
117
140
  const name = policy?.deploy?.freeze_variable;
118
141
  if (!name) return fail(`${verb}: policy deploy.freeze_variable is not set`);
@@ -141,3 +141,27 @@ describe("release control (#5556)", () => {
141
141
  assert.equal(await controlFromCli("hold", [RID, "--json"], { io: w.io }), 1);
142
142
  });
143
143
  });
144
+
145
+ describe("demote / promote (#5583)", () => {
146
+ const dem = (g, extra = []) => [g, "--mode", "warn", "--issue", "7", "--until", "14d", "--reason", "fb", ...extra];
147
+ it("demote records an expiry and an audit line; promote needs a fixture", async () => {
148
+ const w = world();
149
+ const r = await runControl("demote", dem("smoke"), base(w));
150
+ assert.equal(r.ok, true);
151
+ assert.equal(r.entry.verb, "demote");
152
+ assert.equal(w.active.gateModes.smoke.until, new Date(1_700_000_000_000 + 14 * 86_400_000).toISOString());
153
+ assert.match(w.controls, /"verb":"demote"/);
154
+ const no = await runControl("promote", ["smoke", "--reason", "ok"], base(w));
155
+ assert.match(no.error, /--fixture/);
156
+ assert.ok(w.active.gateModes.smoke);
157
+ assert.equal((await runControl("promote", ["smoke", "--fixture", "tests/f.json", "--reason", "ok"], base(w))).ok, true);
158
+ assert.equal(w.active.gateModes.smoke, undefined);
159
+ });
160
+ it("refuses a safety-allowlisted or unskippable gate, a bad mode and a long expiry", async () => {
161
+ const w = world();
162
+ for (const g of ["backup-freshness", "migration", "secrets:x"]) assert.match((await runControl("demote", dem(g), base(w))).error, /safety allowlist/);
163
+ assert.match((await runControl("demote", ["g", "--mode", "skip", "--issue", "7", "--until", "1d", "--reason", "r"], base(w))).error, /--mode/);
164
+ assert.match((await runControl("demote", ["g", "--mode", "warn", "--issue", "7", "--until", "90d", "--reason", "r"], base(w))).error, /at most/);
165
+ assert.match((await runControl("promote", ["g", "--fixture", "f", "--reason", "r"], base(w))).error, /not demoted/);
166
+ });
167
+ });
@@ -0,0 +1,209 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Deploy stages of `forgedock release` (#5560, epic #5549 Phase 3): MERGED -> DEPLOYING -> LIVE_CHECK -> RECOVERING -> VERIFYING -> LIVE (verification layers, FORGE:VERIFIED and close-after-verified live in release-verify.mjs, #5562).
5
+ * Off unless the policy has `deploy.pipelines` (`ctx.config.deploy`): without it the step is `{skipped}` and leaves no trace.
6
+ * Every step is observe -> decide -> fenced act -> verify, and progress lives in `state.deploy`, so a resume re-observes GitHub
7
+ * (the run, the live record, the freeze variable) before it acts and repeats no dispatch or rerun. Waits are bounded and end in
8
+ * `{blocked}`, never a throw. The engine never sets a break-glass input and never reruns a deploy while a freeze is set (I26);
9
+ * a run that concluded `success` while live is not the merge sha (or the expected digests) is a failed deploy (I28); no deploy
10
+ * starts without a recorded rollback target (I9). Rationale: devdocs/decisions/5560-release-deploy.md.
11
+ */
12
+ import { fenced } from "./release-fence.mjs";
13
+ import { buildDispatchArgs } from "./release-control.mjs";
14
+ import { INFRA_SIGNATURES } from "./release-flakes.mjs";
15
+ import { verifyStep, verifyConfigured } from "./release-verify.mjs";
16
+
17
+ export const BOUNDS = { pollMs: 10_000, runPollMs: 20_000, defaultStageS: 3600, rerunMax: 2, maxAttempts: 3 };
18
+ const json = (s) => JSON.parse(String(s || "null"));
19
+ const blocked = (reason) => ({ blocked: true, reason });
20
+ const tail = (s, n = 400) => String(s ?? "").trim().slice(-n);
21
+
22
+ /** `{sha, images}` from the live-release command output: JSON `{sha, images|units: {unit: digest}}` or a bare sha. */
23
+ export function parseLiveRelease(out) {
24
+ const t = String(out ?? "").trim();
25
+ if (!t) return null;
26
+ if (t.startsWith("{")) { try { const o = JSON.parse(t); return o?.sha ? { sha: String(o.sha), images: o.images ?? o.units ?? {} } : null; } catch { return null; } }
27
+ const sha = t.split(/\s+/)[0];
28
+ return /^[0-9a-f]{7,64}$/i.test(sha) ? { sha, images: {} } : null;
29
+ }
30
+
31
+ const sameSha = (a, b) => !!a && !!b && (a.startsWith(b) || b.startsWith(a));
32
+
33
+ /** LIVE_CHECK (I28): the digests decide when expected ones are recorded, else the sha. */
34
+ export function liveMatches(live, mergeSha, expected) {
35
+ if (!live) return false;
36
+ const units = Object.entries(expected ?? {});
37
+ return units.length ? units.every(([u, d]) => live.images?.[u] === d) : sameSha(live.sha, mergeSha);
38
+ }
39
+
40
+ async function readTarget(io, cmd) {
41
+ if (!cmd) return null;
42
+ const r = await io.rehearse(cmd, { timeout: 120_000 });
43
+ return r?.ok ? parseLiveRelease(r.output) : null;
44
+ }
45
+
46
+ /** The freeze variable's value ("" when unset or unreadable-as-absent). A gh failure means unset: `gh variable get` exits non-zero for a missing variable. */
47
+ async function freezeValue(io, repo, name) {
48
+ if (!name) return "";
49
+ try { return String(await io.gh(["variable", "get", name, "--repo", repo])).trim(); } catch { return ""; }
50
+ }
51
+
52
+ /** The newest run for `(workflow, sha)`; a `skipped` run (a push the workflow chose not to run) is expected and not a run. */
53
+ async function latestRun({ io, repo, workflow, sha }) {
54
+ const runs = json(await io.gh(["run", "list", "--repo", repo, "--workflow", workflow, "--commit", sha, "--json", "databaseId,status,conclusion", "--limit", "5"])) ?? [];
55
+ return runs.find((r) => r.conclusion !== "skipped") ?? null;
56
+ }
57
+
58
+ /** A cancelled run is a concurrency-group supersede (expected) when the workflow has a newer run. */
59
+ async function superseded({ io, repo, workflow }, run) {
60
+ const runs = json(await io.gh(["run", "list", "--repo", repo, "--workflow", workflow, "--json", "databaseId,status", "--limit", "10"])) ?? [];
61
+ return runs.some((r) => r.databaseId > run.databaseId);
62
+ }
63
+
64
+ async function poll(io, polls, ms, fn) {
65
+ for (let i = 0; i < polls; i++) {
66
+ const v = await fn();
67
+ if (v) return v;
68
+ if (i < polls - 1) await io.sleep(ms);
69
+ }
70
+ return null;
71
+ }
72
+
73
+ /** Intent key `(release, step, epoch, what)`: one irreversible action per epoch, named in the write-ahead intent (R10). */
74
+ const idemKey = (ctx, what) => `${ctx.fence?.lease?.release ?? ctx.state.id ?? "-"}:deploy:${ctx.fence?.lease?.epoch ?? 0}:${what}`;
75
+
76
+ /** A dispatch (fenced, write-ahead intent) and the run it makes; observe first so a crashed driver never dispatches twice. */
77
+ export async function runFor(ctx, { workflow, sha, inputs, key, startPolls, b }) {
78
+ const { io, repo } = ctx;
79
+ const look = () => latestRun({ io, repo, workflow, sha });
80
+ let run = await poll(io, startPolls, b.pollMs, look);
81
+ if (run) return { run, dispatched: false };
82
+ if ((ctx.state.intents ?? []).some((i) => i.action === "dispatch" && String(i.key).endsWith(`:${key}`))) { // a dispatch intent (any epoch, done or not) may have taken effect: wait for its run, never repeat it (I7)
83
+ run = await poll(io, Math.max(startPolls, Math.ceil((ctx.config.deploy?.start_timeout_s ?? 60) * 1000 / b.pollMs)), b.pollMs, look);
84
+ return run ? { run, dispatched: false } : { err: `a ${workflow} dispatch for ${sha.slice(0, 8)} was already recorded but no run appeared; check the Actions tab, then resume (never redispatched)` };
85
+ }
86
+ const f = await fenced(ctx.fence, { action: "dispatch", key: idemKey(ctx, key) }, (epoch) => io.gh(buildDispatchArgs({ workflow, repo, ref: ctx.def, inputs: { ...inputs, ...(epoch != null ? { forge_epoch: epoch } : {}) } })));
87
+ if (f.refused) return { err: `dispatch ${f.refused}` };
88
+ run = await poll(io, startPolls, b.pollMs, look);
89
+ return run ? { run, dispatched: true } : { err: `no ${workflow} run for ${sha.slice(0, 8)} after a dispatch on ${ctx.def}; check the Actions tab, then resume` };
90
+ }
91
+
92
+ export async function finished(ctx, workflow, sha, polls, b) {
93
+ const { io, repo } = ctx;
94
+ return poll(io, polls, b.runPollMs, async () => { const r = await latestRun({ io, repo, workflow, sha }); return r?.status === "completed" ? r : null; });
95
+ }
96
+
97
+ /** transient: shared infra signatures (release-flakes) or configured ones; migration: a rehearsal-class failure; else a deterministic build failure. */
98
+ export function classifyDeploy(log, sigs) {
99
+ if (INFRA_SIGNATURES.some(([, re]) => re.test(log)) || (sigs ?? []).some((s) => { try { return new RegExp(s, "i").test(log); } catch { return log.includes(s); } })) return "transient";
100
+ return /migrat/i.test(log) ? "migration" : "deterministic";
101
+ }
102
+
103
+ const hold = (reason, kind) => ({ blocked: `${reason} (owner ask: decide rollback or fix; label needs-agent when no host is attached)`, hold: { kind, label: "needs-agent" } });
104
+
105
+ /**
106
+ * Recovery (6.5): one action at a time, bounded. @returns {{rerun: true}|{blocked: string}}
107
+ * No rerun while a freeze is set (I26); only a failed run with a configured transient log signature is rerun.
108
+ */
109
+ async function recover(ctx, d, run, why, freezeNow, b, workflow) {
110
+ const { io, repo, state } = ctx;
111
+ const st = state.deploy, rec = d.recovery ?? {};
112
+ const rerunMax = rec.rerun_max ?? b.rerunMax, maxAttempts = rec.max_attempts ?? b.maxAttempts;
113
+ if (freezeNow) return { blocked: `${why}; ${d.freeze_variable} is set, so the engine never reruns or redispatches the deploy (I26): roll back, or a human runs the workflow with override_freeze` };
114
+ if (!run || !["failure", "timed_out", "cancelled"].includes(run.conclusion)) return { blocked: `${why}; nothing to rerun (a run that finished without changing live is not retried)` };
115
+ if (run.conclusion === "cancelled" && await superseded({ io, repo, workflow }, run)) return { blocked: `${why}; run ${run.databaseId} was cancelled by a newer run of the concurrency group: expected, not rerun` };
116
+ if (st.reruns >= rerunMax || st.attempts >= maxAttempts) return { blocked: `${why}; recovery spent (${st.reruns}/${rerunMax} reruns, ${st.attempts}/${maxAttempts} actions): hand off to the rollback ladder (#5563)` };
117
+ let log = ""; try { log = String(await io.gh(["run", "view", String(run.databaseId), "--repo", repo, "--log-failed"])); } catch { /* unreadable log: not transient */ }
118
+ const cls = classifyDeploy(log, rec.signatures);
119
+ if (cls !== "transient") return hold(`${why}; ${cls === "migration" ? "migration failure" : "deterministic build failure"}, never retried blindly: ${tail(log, 200)}`, cls);
120
+ st.reruns += 1; st.attempts += 1; ctx.save(); // counted before the act: a crash can only spend budget, never exceed it
121
+ const f = await fenced(ctx.fence, { action: "rerun", key: idemKey(ctx, `rerun:${run.databaseId}:${st.reruns}`) }, () => io.gh(["run", "rerun", String(run.databaseId), "--repo", repo, "--failed"]));
122
+ if (f.refused) return { blocked: `rerun ${f.refused}` };
123
+ await io.sleep(b.pollMs); // the rerun flips the run back to in_progress before the next observation
124
+ return { rerun: true };
125
+ }
126
+
127
+ /**
128
+ * reconcile(): re-observe GitHub before acting on a persisted phase (resume after a crash or a moved world).
129
+ * A LIVE_CHECKED phase whose live record no longer matches goes back to DEPLOYING (the run is observed, never redispatched);
130
+ * a phase with no recorded run adopts the run GitHub already has for the merge sha.
131
+ */
132
+ export async function reconcile(ctx, d, pipe, sha) {
133
+ const { io, repo } = ctx, st = ctx.state.deploy;
134
+ if (st.phase === "LIVE_CHECKED") {
135
+ if (!liveMatches(await readTarget(io, d.live_release_command), sha, st.expected)) { st.phase = "DEPLOYING"; ctx.save(); }
136
+ } else if (st.phase === "DEPLOYING" && !st.runId) {
137
+ const run = await latestRun({ io, repo, workflow: pipe.workflow, sha });
138
+ if (run) { st.runId = run.databaseId; ctx.save(); }
139
+ }
140
+ return st.phase;
141
+ }
142
+
143
+ const stageS = (d) => (typeof d.stage_timeout_s === "number" ? d.stage_timeout_s : BOUNDS.defaultStageS);
144
+
145
+ /** @returns {Promise<{skipped: true}|{live: true, merge, run, reruns}|{blocked: true, reason, hold?}|{stopped: true, why}>} */
146
+ export async function deployStep(ctx) {
147
+ const { io, repo, state } = ctx;
148
+ const d = ctx.config.deploy;
149
+ if (!d?.pipelines || !Object.keys(d.pipelines).length) return { skipped: true };
150
+ const b = { ...BOUNDS, ...(ctx.config.deployBounds ?? {}) };
151
+ const pipe = d.pipelines[ctx.config.deployPipeline ?? "full"] ?? Object.values(d.pipelines)[0];
152
+ if (!pipe?.workflow) return blocked("deploy.pipelines has no workflow for this release");
153
+ let sha = state.steps["post-merge"]?.result?.merge ?? null;
154
+ if (!sha) {
155
+ const pr = state.steps["release-pr"]?.result?.pr;
156
+ const v = json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "state,mergeCommit"]));
157
+ sha = v?.state === "MERGED" ? v.mergeCommit?.oid : null;
158
+ if (!sha) return { stopped: true, why: `release PR #${pr} is not merged; nothing to deploy yet` };
159
+ }
160
+ const st = (state.deploy ??= { phase: "MERGED", attempts: 0, reruns: 0 });
161
+
162
+ if (!st.target) { // MERGED -> DEPLOYING guard (I9, 6.3): the rollback target is frozen before anything is dispatched
163
+ const target = await readTarget(io, d.live_release_command);
164
+ if (!target) return blocked("rollback target unknown: deploy.live_release_command is unset or returned no live sha (I9); nothing was dispatched");
165
+ let expected = null;
166
+ if (d.expected_digests_command) {
167
+ const r = await io.rehearse(d.expected_digests_command, { timeout: 120_000 });
168
+ try { expected = r?.ok ? json(r.output) : null; } catch { expected = null; }
169
+ if (!expected) return blocked("deploy.expected_digests_command returned no digests; refusing to deploy without them");
170
+ }
171
+ st.target = target; st.expected = expected; st.merge = sha; st.freezeBefore = await freezeValue(io, repo, d.freeze_variable); st.phase = "DEPLOYING";
172
+ ctx.save();
173
+ }
174
+
175
+ await reconcile(ctx, d, pipe, sha);
176
+ if (st.phase !== "LIVE_CHECKED" && st.phase !== "LIVE") {
177
+ for (;;) {
178
+ st.phase = "DEPLOYING"; ctx.save();
179
+ const r = await runFor(ctx, { workflow: pipe.workflow, sha, inputs: pipe.inputs ?? {}, key: `deploy:${sha}`, startPolls: pipe.trigger === "dispatch" ? 1 : Math.max(1, Math.ceil((d.start_timeout_s ?? 60) * 1000 / b.pollMs)), b });
180
+ if (r.err) return blocked(r.err);
181
+ st.runId = r.run.databaseId; ctx.save();
182
+ const done = await finished(ctx, pipe.workflow, sha, Math.ceil(stageS(d) * 1000 / b.runPollMs), b);
183
+ if (!done) return blocked(`${pipe.workflow} run ${st.runId} did not finish within stage_timeout_s; check the live record before any rerun, then resume`);
184
+ st.phase = "LIVE_CHECK"; ctx.save();
185
+ const live = await readTarget(io, d.live_release_command);
186
+ const freezeNow = await freezeValue(io, repo, d.freeze_variable);
187
+ const frozenByRun = !!freezeNow && !st.freezeBefore;
188
+ let why = null;
189
+ if (done.conclusion === "failure" || done.conclusion === "timed_out") why = `${pipe.workflow} run ${done.databaseId} concluded ${done.conclusion}`;
190
+ else if (!liveMatches(live, sha, st.expected)) why = `LIVE_CHECK failed: run ${done.databaseId} concluded ${done.conclusion} but live is ${live?.sha?.slice(0, 8) ?? "unreadable"}, not ${sha.slice(0, 8)} (I28)${frozenByRun ? `; the run set ${d.freeze_variable}` : ""}`;
191
+ else if (frozenByRun) why = `LIVE_CHECK failed: the run set ${d.freeze_variable}`;
192
+ if (!why) { st.phase = "LIVE_CHECKED"; ctx.save(); break; }
193
+ const rec = await recover(ctx, d, done, why, !!freezeNow, b, pipe.workflow);
194
+ if (rec.blocked) return { ...blocked(rec.blocked), ...(rec.hold ? { hold: rec.hold } : {}) };
195
+ }
196
+ }
197
+
198
+ let verify = null;
199
+ if (st.phase !== "LIVE") {
200
+ st.phase = "VERIFYING"; ctx.save();
201
+ if (verifyConfigured(ctx.config.verify)) { // #5562: layers, FORGE:VERIFIED, guarded close; unconfigured stays a bare transition
202
+ verify = await verifyStep(ctx, sha);
203
+ if (verify.blocked) return { ...blocked(verify.reason), ...(verify.hold ? { hold: verify.hold } : {}), ...(verify.rollback ? { rollback: verify.rollback } : {}) };
204
+ }
205
+ st.phase = "LIVE"; ctx.save();
206
+ }
207
+ io.print?.(`release: live at ${sha.slice(0, 8)} (run ${st.runId}, ${st.reruns} rerun(s))`);
208
+ return { live: true, merge: sha, run: st.runId, reruns: st.reruns, ...(verify ? { verify } : {}) };
209
+ }
@@ -0,0 +1,217 @@
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 { deployStep, parseLiveRelease, liveMatches } from "./release-deploy.mjs";
6
+ import { validatePolicy } from "./release-config.mjs";
7
+
8
+ const SHA = "a".repeat(40), OLD = "b".repeat(40);
9
+ const POLICY = { live_release_command: "live", freeze_variable: "DEPLOY_FREEZE", start_timeout_s: 10, stage_timeout_s: 100, recovery: { rerun_max: 2, max_attempts: 3, signatures: ["429 Too Many"] }, pipelines: { full: { workflow: "deploy.yml", trigger: "push" } } };
10
+
11
+ /** World: `live` is a queue (last repeats) of live shas; `runs` a queue of run rows; `freeze` the variable value. */
12
+ function world(o = {}) {
13
+ const w = { live: [OLD, SHA], runs: [{ databaseId: 9, status: "completed", conclusion: "success" }], freeze: "", log: "", gh: [], ran: [], ...o };
14
+ const io = {
15
+ print: () => {}, sleep: async () => {}, git: () => "{}",
16
+ rehearse: async (cmd) => { w.ran.push(cmd); if (cmd === "live") { const v = w.live.length > 1 ? w.live.shift() : w.live[0]; return v == null ? { ok: false, output: "" } : { ok: true, output: v }; } if (w.failCheck) return { ok: false, output: "boom" }; return { ok: true, output: "{}" }; },
17
+ gh: async (a) => {
18
+ w.gh.push(a.join(" "));
19
+ if (a[0] === "variable") { if (!w.freeze) throw new Error("HTTP 404"); return w.freeze; }
20
+ if (a[0] === "run" && a[1] === "list") { const r = w.runs[Math.min(w.reran ?? 0, w.runs.length - 1)]; return JSON.stringify(r ? [r] : []); }
21
+ if (a[0] === "run" && a[1] === "view") return w.log;
22
+ if (a[0] === "run" && a[1] === "rerun") { w.reran = (w.reran ?? 0) + 1; return ""; }
23
+ if (a[0] === "workflow" || a[0] === "pr") return "";
24
+ throw new Error(`unexpected gh ${a.join(" ")}`);
25
+ },
26
+ };
27
+ return { w, io };
28
+ }
29
+ const mk = (io, over = {}, deploy = POLICY) => ({ io, repo: "o/r", def: "main", config: { deploy, deployBounds: { pollMs: 1, runPollMs: 1 } }, state: { steps: { "post-merge": { result: { merge: SHA } }, "release-pr": { result: { pr: 7 } } } }, save() {}, ...over });
30
+ const active = (o) => ({ content: Buffer.from(JSON.stringify(o)).toString("base64") });
31
+ const fence = (calls = []) => ({ lctx: { io: { api: async () => active({ epoch: 3, lease: { holder: "h", epoch: 3 } }) }, repo: "o/r" }, lease: { holder: "h", epoch: 3, release: "r" }, now: () => "t", record: async (r) => calls.push(r) });
32
+
33
+ describe("release deploy stages (#5560)", () => {
34
+ it("skips without a deploy policy and leaves no trace", async () => {
35
+ const { io } = world(); const c = mk(io, {}, null);
36
+ assert.deepEqual(await deployStep(c), { skipped: true }); assert.equal(c.state.deploy, undefined);
37
+ });
38
+ it("MERGED -> LIVE: records the rollback target, observes the run, passes LIVE_CHECK, and, without a verify policy, writes no FORGE:VERIFIED (#5562)", async () => {
39
+ const { w, io } = world(); const c = mk(io);
40
+ const out = await deployStep(c);
41
+ assert.equal(out.live, true); assert.equal(c.state.deploy.target.sha, OLD); assert.equal(c.state.deploy.phase, "LIVE");
42
+ assert.ok(!w.gh.some((g) => g.startsWith("pr comment") || g.includes("FORGE:VERIFIED")));
43
+ assert.ok(!w.gh.some((g) => g.startsWith("workflow run")), "an observed push run is never redispatched");
44
+ });
45
+ it("I9: an unknown rollback target blocks before any dispatch", async () => {
46
+ const { w, io } = world({ live: [null], runs: [] });
47
+ const out = await deployStep(mk(io));
48
+ assert.match(out.reason, /rollback target unknown/); assert.ok(!w.gh.some((g) => g.startsWith("workflow run")));
49
+ });
50
+ it("I28 + I26: a freeze-skipped success fails LIVE_CHECK and is never rerun or redispatched", async () => {
51
+ const { w, io } = world({ live: [OLD], freeze: "" });
52
+ w.gh.push; const orig = io.gh; io.gh = async (a) => { if (a[0] === "run" && a[1] === "list") w.freeze = "1"; return orig(a); }; // the run sets the freeze
53
+ const out = await deployStep(mk(io));
54
+ assert.equal(out.blocked, true); assert.match(out.reason, /LIVE_CHECK failed/); assert.match(out.reason, /override_freeze|I26/);
55
+ assert.equal(w.reran, undefined); assert.equal(w.gh.filter((g) => g.startsWith("workflow run")).length, 0);
56
+ });
57
+ it("a success run with a stale live record (no freeze) is a failed deploy, not retried", async () => {
58
+ const { w, io } = world({ live: [OLD] });
59
+ const out = await deployStep(mk(io));
60
+ assert.match(out.reason, /live is bbbbbbbb/); assert.equal(w.reran, undefined);
61
+ });
62
+ it("a transient build failure is rerun once and reaches LIVE with no human", async () => {
63
+ const { w, io } = world({ live: [OLD, SHA], log: "build: 429 Too Many Requests", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }, { databaseId: 9, status: "completed", conclusion: "success" }] });
64
+ const out = await deployStep(mk(io));
65
+ assert.equal(out.live, true); assert.equal(out.reruns, 1); assert.equal(w.reran, 1);
66
+ });
67
+ it("rerun_max bounds the reruns, then escalates", async () => {
68
+ const { w, io } = world({ live: [OLD], log: "429 Too Many Requests", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }] });
69
+ const out = await deployStep(mk(io));
70
+ assert.match(out.reason, /recovery spent/); assert.equal(w.reran, 2);
71
+ });
72
+ it("max_attempts bounds the actions", async () => {
73
+ const { w, io } = world({ live: [OLD], log: "429 Too Many Requests", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }] });
74
+ const out = await deployStep(mk(io, {}, { ...POLICY, recovery: { ...POLICY.recovery, rerun_max: 5, max_attempts: 1 } }));
75
+ assert.match(out.reason, /recovery spent/); assert.equal(w.reran, 1);
76
+ });
77
+ it("a failure without a transient signature is not rerun", async () => {
78
+ const { w, io } = world({ live: [OLD], log: "tsc error", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }] });
79
+ const out = await deployStep(mk(io));
80
+ assert.match(out.reason, /never retried blindly/); assert.equal(w.reran, undefined);
81
+ });
82
+ it("dispatches (fenced, with forge_epoch) only when no run appears, and never an override input", async () => {
83
+ const { w, io } = world({ runs: [] }); const calls = [];
84
+ w.runs = []; const orig = io.gh; io.gh = async (a) => { const r = await orig(a); if (a[0] === "workflow") w.runs = [{ databaseId: 11, status: "completed", conclusion: "success" }]; return r; };
85
+ const out = await deployStep(mk(io, { fence: fence(calls) }));
86
+ const d = w.gh.filter((g) => g.startsWith("workflow run")); assert.equal(out.live, true); assert.equal(d.length, 1);
87
+ assert.match(d[0], /forge_epoch=3/); assert.ok(!/override_|acknowledge_/.test(d[0]));
88
+ assert.ok(calls.some((r) => r.key.endsWith(`:deploy:3:deploy:${SHA}`)));
89
+ });
90
+ it("a stale epoch refuses the dispatch", async () => {
91
+ const { io } = world({ runs: [] });
92
+ const f = fence(); f.lctx = { io: { api: async () => active({ lease: { holder: "other", epoch: 4 }, epoch: 4 }) }, repo: "o/r" };
93
+ const out = await deployStep(mk(io, { fence: f }));
94
+ assert.match(out.reason, /fenced|refused/);
95
+ });
96
+ it("chaos: a throw at every boundary, then a resume, repeats no dispatch or rerun", async () => {
97
+ for (const dieOn of ["variable", "run list", "run view", "run rerun", "live"]) {
98
+ const { w, io } = world({ live: [OLD, SHA], log: "429 Too Many Requests", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }, { databaseId: 9, status: "completed", conclusion: "success" }] });
99
+ let armed = true; const g0 = io.gh, r0 = io.rehearse;
100
+ const maybe = (k) => { if (armed && k === dieOn) { armed = false; throw new Error("kill -9"); } };
101
+ io.gh = async (a) => { maybe(a.slice(0, 2).join(" ").replace(/^variable get$/, "variable")); return g0(a); };
102
+ io.rehearse = async (c, o) => { if (c === "live" && w.ran.length >= 3) maybe("live"); return r0(c, o); };
103
+ const c = mk(io);
104
+ try { await deployStep(c); } catch { /* killed */ }
105
+ const out = await deployStep(c);
106
+ assert.equal(out.live, true, dieOn);
107
+ assert.ok((w.reran ?? 0) <= 1, `${dieOn}: one rerun`);
108
+ assert.equal(w.gh.filter((g) => g.startsWith("workflow run")).length, 0, dieOn);
109
+ }
110
+ });
111
+ });
112
+
113
+ describe("deploy observation and recovery (#5560)", () => {
114
+ it("trigger dispatch (service/hotfix) dispatches at once with unit inputs and forge_epoch, fenced under (release, step, epoch)", async () => {
115
+ const { w, io } = world({ runs: [] }); const calls = []; const orig = io.gh;
116
+ io.gh = async (a) => { const r = await orig(a); if (a[0] === "workflow") w.runs = [{ databaseId: 11, status: "completed", conclusion: "success" }]; return r; };
117
+ const pol = { ...POLICY, pipelines: { service: { workflow: "deploy.yml", trigger: "dispatch", inputs: { unit: "api" } } } };
118
+ const out = await deployStep(mk(io, { fence: fence(calls), config: { deploy: pol, deployPipeline: "service", deployBounds: { pollMs: 1, runPollMs: 1 } } }));
119
+ const d = w.gh.filter((g) => g.startsWith("workflow run")); assert.equal(out.live, true); assert.equal(d.length, 1);
120
+ assert.match(d[0], /unit=api/); assert.match(d[0], /forge_epoch=3/);
121
+ assert.ok(calls.some((r) => r.key.endsWith(`:deploy:3:deploy:${SHA}`)));
122
+ });
123
+ it("R2: a dispatch intent without a visible run is never redispatched on resume", async () => {
124
+ const { w, io } = world({ runs: [] });
125
+ const pol = { ...POLICY, pipelines: { service: { workflow: "deploy.yml", trigger: "dispatch" } } };
126
+ const intents = [{ key: `r:deploy:2:deploy:${SHA}`, action: "dispatch", epoch: 2 }];
127
+ const out = await deployStep(mk(io, { fence: fence(), state: { intents, steps: { "post-merge": { result: { merge: SHA } } } }, config: { deploy: pol, deployPipeline: "service", deployBounds: { pollMs: 1, runPollMs: 1 } } }));
128
+ assert.ok(out.blocked); assert.equal(w.gh.filter((g) => g.startsWith("workflow run")).length, 0);
129
+ });
130
+ it("a skipped push run is expected: it is not a run, so the deploy is dispatched", async () => {
131
+ const { w, io } = world({ runs: [{ databaseId: 5, status: "completed", conclusion: "skipped" }] }); const orig = io.gh;
132
+ io.gh = async (a) => { const r = await orig(a); if (a[0] === "workflow") w.runs = [{ databaseId: 12, status: "completed", conclusion: "success" }]; return r; };
133
+ const out = await deployStep(mk(io, { fence: fence() }));
134
+ assert.equal(out.live, true); assert.equal(w.gh.filter((g) => g.startsWith("workflow run")).length, 1);
135
+ });
136
+ it("a run cancelled by a newer concurrency-group run is expected: no rerun", async () => {
137
+ const { w, io } = world({ live: [OLD], runs: [{ databaseId: 9, status: "completed", conclusion: "cancelled" }], log: "429 Too Many Requests" }); const orig = io.gh;
138
+ io.gh = async (a) => (a[0] === "run" && a[1] === "list" && !a.includes("--commit") ? JSON.stringify([{ databaseId: 10, status: "in_progress" }]) : orig(a));
139
+ const out = await deployStep(mk(io));
140
+ assert.match(out.reason, /cancelled by a newer run/); assert.equal(w.reran, undefined);
141
+ });
142
+ it("another cancelled run is checked against live first: a matching live passes, a mismatch may be rerun only when transient", async () => {
143
+ const ok = world({ live: [OLD, SHA], runs: [{ databaseId: 9, status: "completed", conclusion: "cancelled" }] });
144
+ assert.equal((await deployStep(mk(ok.io))).live, true); assert.equal(ok.w.reran, undefined);
145
+ const bad = world({ live: [OLD], runs: [{ databaseId: 9, status: "completed", conclusion: "cancelled" }], log: "the runner received a shutdown signal" });
146
+ const out = await deployStep(mk(bad.io));
147
+ assert.equal(bad.w.reran, 2); assert.match(out.reason, /recovery spent/);
148
+ });
149
+ it("shared INFRA_SIGNATURES count as transient without any configured signature", async () => {
150
+ const { w, io } = world({ live: [OLD, SHA], log: "fatal: ECONNRESET", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }, { databaseId: 9, status: "completed", conclusion: "success" }] });
151
+ const out = await deployStep(mk(io, {}, { ...POLICY, recovery: { rerun_max: 2, max_attempts: 3 } }));
152
+ assert.equal(out.live, true); assert.equal(w.reran, 1);
153
+ });
154
+ it("a deterministic build failure and a migration failure hold with an owner ask and needs-agent", async () => {
155
+ for (const [log, kind] of [["tsc error TS2304", "deterministic"], ["migration 0042 failed", "migration"]]) {
156
+ const { w, io } = world({ live: [OLD], log, runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }] });
157
+ const out = await deployStep(mk(io));
158
+ assert.equal(out.hold?.kind, kind); assert.equal(out.hold.label, "needs-agent"); assert.match(out.reason, /owner ask/); assert.equal(w.reran, undefined);
159
+ }
160
+ });
161
+ it("max_attempts hands off to the rollback ladder", async () => {
162
+ const { io } = world({ live: [OLD], log: "ECONNRESET", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }] });
163
+ const out = await deployStep(mk(io, {}, { ...POLICY, recovery: { rerun_max: 5, max_attempts: 1 } }));
164
+ assert.match(out.reason, /rollback ladder/);
165
+ });
166
+ it("unreadable freeze-independent guard: an unreadable live record blocks LIVE_CHECK (I5)", async () => {
167
+ const { io } = world({ live: [OLD, null] });
168
+ const out = await deployStep(mk(io));
169
+ assert.equal(out.blocked, true); assert.match(out.reason, /unreadable/);
170
+ });
171
+ });
172
+
173
+ describe("deploy reconcile (#5560)", () => {
174
+ it("a LIVE_CHECKED phase whose live record moved is re-observed without a dispatch, then re-checked", async () => {
175
+ const { w, io } = world({ live: [OLD] });
176
+ const c = mk(io); c.state.deploy = { phase: "LIVE_CHECKED", attempts: 0, reruns: 0, target: { sha: OLD, images: {} }, expected: null, merge: SHA, freezeBefore: "" };
177
+ const out = await deployStep(c);
178
+ assert.equal(out.blocked, true); assert.match(out.reason, /LIVE_CHECK failed/);
179
+ assert.equal(w.gh.filter((g) => g.startsWith("workflow run")).length, 0);
180
+ });
181
+ });
182
+
183
+ describe("deploy VERIFYING (#5562)", () => {
184
+ it("a configured verify policy gates LIVE: the VERIFIED marker is written and the issue closes only after the layers pass", async () => {
185
+ const { w, io } = world(); const issue = { state: "OPEN", body: "", comments: [] };
186
+ const og = io.gh; io.gh = async (a) => {
187
+ if (a[0] === "issue" && a[1] === "view") return JSON.stringify(issue);
188
+ if (a[0] === "issue" && a[1] === "comment") { issue.comments.push({ body: a[a.indexOf("--body") + 1] }); return ""; }
189
+ if (a[0] === "issue" && a[1] === "close") { issue.state = "CLOSED"; return ""; }
190
+ return og(a);
191
+ };
192
+ const c = mk(io); c.config.verify = { close_requires: "verified" }; c.state.release = { issues: [7] };
193
+ const out = await deployStep(c);
194
+ assert.equal(out.live, true); assert.equal(out.verify.verified, true); assert.equal(issue.state, "CLOSED");
195
+ assert.ok(issue.comments.some((m) => m.body.includes(`FORGE:VERIFIED ${SHA}`)));
196
+ });
197
+ it("a blocked verification keeps the release out of LIVE", async () => {
198
+ const { io } = world(); const c = mk(io); c.config.verify = { results: [{ workflow: "smoke.yml", kind: "smoke" }] };
199
+ const og = io.gh; io.gh = async (a) => (a.includes("smoke.yml") ? "[]" : og(a));
200
+ const out = await deployStep(c);
201
+ assert.equal(out.blocked, true); assert.match(out.reason, /no completed run/); assert.equal(c.state.deploy.phase, "VERIFYING");
202
+ });
203
+ });
204
+
205
+ describe("deploy helpers", () => {
206
+ it("parseLiveRelease reads JSON and a bare sha; liveMatches prefers expected digests", () => {
207
+ assert.deepEqual(parseLiveRelease(`{"sha":"abc1234","images":{"api":"d1"}}`), { sha: "abc1234", images: { api: "d1" } });
208
+ assert.equal(parseLiveRelease("garbage!"), null);
209
+ assert.equal(liveMatches({ sha: "x".repeat(8), images: { api: "d1" } }, SHA, { api: "d1" }), true);
210
+ assert.equal(liveMatches({ sha: SHA, images: { api: "d0" } }, SHA, { api: "d1" }), false);
211
+ });
212
+ it("the policy schema accepts the typed recovery block and rejects a string rerun_max", () => {
213
+ const base = { schema: 1, deploy: { ...POLICY } };
214
+ assert.deepEqual(validatePolicy(base).filter((f) => /deploy\.recovery/.test(f)), []);
215
+ assert.ok(validatePolicy({ ...base, deploy: { ...POLICY, recovery: { rerun_max: "2" } } }).some((f) => /rerun_max/.test(f)));
216
+ });
217
+ });