forgedock 1.56.0 → 1.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +2 -1
  3. package/bin/engine/phases.mjs +4 -3
  4. package/bin/engine-cli.mjs +48 -12
  5. package/bin/forgedock.mjs +52 -3
  6. package/bin/gc.mjs +43 -6
  7. package/bin/help-text.mjs +4 -2
  8. package/bin/lean/batch-health.mjs +5 -1
  9. package/bin/lean/batch-health.test.mjs +7 -1
  10. package/bin/lean/batch.mjs +7 -2
  11. package/bin/lean/batch.test.mjs +45 -0
  12. package/bin/lean/conformance.e2e.test.mjs +3 -2
  13. package/bin/lean/conformance.mjs +118 -20
  14. package/bin/lean/conformance.test.mjs +172 -3
  15. package/bin/lean/decisions.mjs +98 -1
  16. package/bin/lean/decisions.test.mjs +30 -1
  17. package/bin/lean/depcache.mjs +124 -13
  18. package/bin/lean/depcache.test.mjs +121 -3
  19. package/bin/lean/design-gate.mjs +144 -0
  20. package/bin/lean/design-gate.test.mjs +169 -0
  21. package/bin/lean/effects-cap.test.mjs +17 -0
  22. package/bin/lean/effects.mjs +58 -13
  23. package/bin/lean/heavy.mjs +25 -8
  24. package/bin/lean/hostload.test.mjs +28 -0
  25. package/bin/lean/intake.mjs +97 -0
  26. package/bin/lean/intake.test.mjs +105 -0
  27. package/bin/lean/interfaces.mjs +181 -0
  28. package/bin/lean/interfaces.test.mjs +192 -0
  29. package/bin/lean/issuewatch-install.mjs +52 -12
  30. package/bin/lean/issuewatch-install.test.mjs +50 -0
  31. package/bin/lean/issuewatch-parity.mjs +16 -3
  32. package/bin/lean/issuewatch-parity.test.mjs +32 -0
  33. package/bin/lean/issuewatch-reconcile.mjs +29 -1
  34. package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
  35. package/bin/lean/issuewatch.mjs +34 -3
  36. package/bin/lean/issuewatch.test.mjs +49 -1
  37. package/bin/lean/lanecheck.test.mjs +15 -4
  38. package/bin/lean/lean.mjs +110 -24
  39. package/bin/lean/lean.test.mjs +183 -4
  40. package/bin/lean/orchestrate-blocked.test.mjs +18 -2
  41. package/bin/lean/orchestrate-owned.test.mjs +14 -5
  42. package/bin/lean/orchestrate.mjs +26 -4
  43. package/bin/lean/orphan-pr.mjs +3 -2
  44. package/bin/lean/orphan-pr.test.mjs +8 -1
  45. package/bin/lean/pagegate.mjs +35 -12
  46. package/bin/lean/pagegate.test.mjs +39 -1
  47. package/bin/lean/preflight.mjs +35 -1
  48. package/bin/lean/preflight.test.mjs +27 -1
  49. package/bin/lean/prompts.mjs +2 -1
  50. package/bin/lean/reap.test.mjs +39 -0
  51. package/bin/lean/recovery.test.mjs +28 -3
  52. package/bin/lean/release-config.mjs +169 -0
  53. package/bin/lean/release-config.test.mjs +132 -0
  54. package/bin/lean/release-control.mjs +171 -0
  55. package/bin/lean/release-control.test.mjs +167 -0
  56. package/bin/lean/release-deploy.mjs +209 -0
  57. package/bin/lean/release-deploy.test.mjs +217 -0
  58. package/bin/lean/release-fence.mjs +50 -0
  59. package/bin/lean/release-fence.test.mjs +105 -0
  60. package/bin/lean/release-flakes.mjs +139 -0
  61. package/bin/lean/release-flakes.test.mjs +116 -0
  62. package/bin/lean/release-gates.mjs +230 -0
  63. package/bin/lean/release-gates.test.mjs +146 -0
  64. package/bin/lean/release-ledger.mjs +176 -0
  65. package/bin/lean/release-ledger.test.mjs +226 -0
  66. package/bin/lean/release-minutes.mjs +102 -0
  67. package/bin/lean/release-minutes.test.mjs +107 -0
  68. package/bin/lean/release-nightly.mjs +75 -0
  69. package/bin/lean/release-nightly.test.mjs +48 -0
  70. package/bin/lean/release-postmerge.mjs +8 -2
  71. package/bin/lean/release-review.e2e.test.mjs +1 -0
  72. package/bin/lean/release-review.mjs +54 -7
  73. package/bin/lean/release-review.test.mjs +76 -7
  74. package/bin/lean/release-status.mjs +300 -0
  75. package/bin/lean/release-status.test.mjs +220 -0
  76. package/bin/lean/release-unitmap.mjs +35 -0
  77. package/bin/lean/release-unitmap.test.mjs +41 -0
  78. package/bin/lean/release-verify.mjs +221 -0
  79. package/bin/lean/release-verify.test.mjs +176 -0
  80. package/bin/lean/release.mjs +244 -22
  81. package/bin/lean/release.test.mjs +44 -0
  82. package/bin/lean/render.mjs +3 -1
  83. package/bin/lean/run-issue-placement.test.mjs +82 -0
  84. package/bin/lean/sandbox-remote.mjs +16 -0
  85. package/bin/lean/schedd.mjs +1 -1
  86. package/bin/lean/seam.mjs +115 -0
  87. package/bin/lean/seam.test.mjs +118 -0
  88. package/bin/lean/selftest-journey.mjs +40 -2
  89. package/bin/lean/selftest-journey.test.mjs +43 -3
  90. package/bin/lean/statuscomment.mjs +168 -0
  91. package/bin/lean/statuscomment.test.mjs +133 -0
  92. package/bin/lean/ui-quality.mjs +57 -0
  93. package/bin/lean/ui-quality.test.mjs +55 -0
  94. package/bin/lean/visual-gate.test.mjs +63 -0
  95. package/bin/pool/agent.mjs +16 -2
  96. package/bin/pool/router.mjs +5 -1
  97. package/bin/review-staging.mjs +5 -3
  98. package/bin/stats/card.mjs +117 -0
  99. package/bin/stats/card.test.mjs +109 -0
  100. package/bin/stats/conformance-outcomes.test.mjs +2 -1
  101. package/bin/stats/depth.mjs +1 -1
  102. package/bin/stats/gh-retry.test.mjs +152 -0
  103. package/bin/stats/github-source.mjs +147 -14
  104. package/bin/stats/index.mjs +35 -2
  105. package/bin/stats/stats.test.mjs +31 -3
  106. package/bin/vendor/js-yaml/LICENSE +21 -0
  107. package/bin/vendor/js-yaml/PIN.md +7 -0
  108. package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
  109. package/commands/design-render-critique-loop.md +2 -0
  110. package/commands/design.md +2 -0
  111. package/commands/issue.md +1 -1
  112. package/commands/milestone.md +1 -1
  113. package/commands/review-pr-agents/frontend.md +1 -0
  114. package/commands/review-pr-staging.md +5 -0
  115. package/docs/CONFIG.md +95 -2
  116. package/docs/ISSUE-WATCH.md +7 -0
  117. package/docs/OUTCOME-CODES.md +1 -0
  118. package/docs/STATS.md +10 -0
  119. package/docs/design/visual-gate.md +25 -0
  120. package/docs/eval/adversarial-bench.md +2 -2
  121. package/docs/eval/corpus/adversarial-v1.json +3 -3
  122. package/docs/site/start-a-new-project.md +7 -0
  123. package/docs/spec/forge-protocol-v1.md +31 -0
  124. package/package.json +1 -1
  125. package/pool/README.md +2 -0
  126. package/scripts/acceptance-red-green.sh +15 -1
  127. package/scripts/acceptance-red-green.test.sh +12 -0
  128. package/scripts/bench-adversarial.mjs +4 -0
  129. package/scripts/bench-lightlane.mjs +4 -1
  130. package/scripts/bootstrap-create.mjs +8 -2
  131. package/scripts/ci-local/scoping.mjs +19 -0
  132. package/scripts/ci-local.test.sh +16 -3
  133. package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
  134. package/scripts/plan-validate-live.mjs +9 -6
  135. package/scripts/review-prepare.sh +7 -1
  136. package/scripts/review-roster.sh +5 -2
  137. package/scripts/review-roster.test.sh +9 -0
  138. package/scripts/visual-gate.mjs +64 -0
  139. package/templates/bootstrap/technical-spike.md +17 -0
  140. package/templates/contracts/seam-check.mjs +236 -0
@@ -0,0 +1,220 @@
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 { writeFileSync } from "node:fs";
5
+ import { tmpDir } from "../tests/_tmp.mjs";
6
+ import { join } from "node:path";
7
+ import assert from "node:assert/strict";
8
+ import { releaseFromCli, gateState } from "./release.mjs";
9
+ import { controlFromCli, VERBS } from "./release-control.mjs";
10
+ import { CONTROL_VERBS, collectStatus, renderReleaseStatus, watchStatus, explainIssue, explainPr, renderExplain, parseNextAction, policyFromYaml, registerPlannerRule, PLANNER_RULES } from "./release-status.mjs";
11
+
12
+ const REPO = "o/r", ID = "r20261112-141530-4242", HEAD = "a".repeat(40);
13
+ const STATE = { v: 1, id: ID, repo: REPO, steps: { preflight: { done: true, at: "T1" }, "release-pr": { done: true, at: "T2", result: { pr: 7, head: HEAD } }, promotion: { done: false, at: "T3" } }, release: { snapshot: "s1", issues: [12, 5], picks: [] } };
14
+ const GOLDEN_ISSUE = "{\"schema\":\"forgedock.release.explain/v1\",\"kind\":\"issue\",\"repo\":\"o/r\",\"issue\":40,\"lane\":\"pool\",\"classification\":\"absent\",\"trace\":[{\"step\":1,\"rule\":\"classification\",\"config_key\":\"FORGE:CLASSIFY\",\"result\":\"n/a\",\"detail\":\"classification: absent\",\"would_change\":[]},{\"step\":2,\"rule\":\"skip_labels\",\"config_key\":\"plan.skip_labels\",\"result\":\"pass\",\"detail\":\"no skip label\",\"would_change\":[]},{\"step\":3,\"rule\":\"min_confidence\",\"config_key\":\"classify.min_confidence\",\"result\":\"n/a\",\"detail\":\"no minimum configured\",\"would_change\":[]},{\"step\":4,\"rule\":\"risk.rules\",\"config_key\":\"risk.rules\",\"result\":\"n/a\",\"detail\":\"no rules configured\",\"would_change\":[]},{\"step\":5,\"rule\":\"forces\",\"config_key\":\"forces\",\"result\":\"n/a\",\"detail\":\"no rules configured\",\"would_change\":[]},{\"step\":6,\"rule\":\"priority\",\"config_key\":\"issue_watch.watches.<name>.immediate\",\"result\":\"pass\",\"detail\":\"priority P1\",\"would_change\":[]},{\"step\":7,\"rule\":\"theme\",\"config_key\":\"issue_watch.watches.<name>.theme_map\",\"result\":\"fail\",\"detail\":\"no theme rule matches\",\"would_change\":[\"add a theme_map rule (label:, scope: or path:) in forge.yaml\"]},{\"step\":8,\"rule\":\"depends_on\",\"config_key\":\"release.managed\",\"result\":\"pass\",\"detail\":\"no open prerequisite\",\"would_change\":[]},{\"step\":9,\"rule\":\"release_set\",\"config_key\":\"release.mode\",\"result\":\"fail\",\"detail\":\"no release recorded\",\"would_change\":[\"include it in the next release cut\"]},{\"step\":10,\"rule\":\"planner\",\"config_key\":\"release.planner\",\"result\":\"n/a\",\"detail\":\"planner: not installed\",\"would_change\":[]},{\"step\":11,\"rule\":\"lane\",\"config_key\":\"controls.jsonl lane | plan lane\",\"result\":\"n/a\",\"detail\":\"lane pool (plan)\",\"would_change\":[\"label or config key above, or: forgedock release lane #40 --force <train|release|p0|exclude> --reason <reason>\"]}],\"would_change\":[\"add a theme_map rule (label:, scope: or path:) in forge.yaml\",\"include it in the next release cut\",\"label or config key above, or: forgedock release lane #40 --force <train|release|p0|exclude> --reason <reason>\"],\"next_actions\":[\"forgedock release status --repo o/r --json\"]}";
15
+ const GOLDEN_PR = "{\"schema\":\"forgedock.release.explain/v1\",\"kind\":\"pr\",\"repo\":\"o/r\",\"pr\":7,\"head\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"decision\":\"pass\",\"demoted\":[],\"trace\":[{\"step\":1,\"rule\":\"gate_marker\",\"config_key\":\"release.gate\",\"result\":\"pass\",\"detail\":\"FORGE:GATE_PASS marker: pass\",\"would_change\":[]},{\"step\":2,\"rule\":\"deploy_gate\",\"config_key\":\"forge/deploy-gate\",\"result\":\"pass\",\"detail\":\"forge/deploy-gate: success\",\"would_change\":[]},{\"step\":3,\"rule\":\"check:unit\",\"config_key\":\"branches.required_checks\",\"result\":\"pass\",\"detail\":\"success\",\"would_change\":[]}],\"would_change\":[],\"next_actions\":[\"forgedock release explain 7 --repo o/r --json\"]}";
16
+ const GOLDEN_PR_TEXT = "PR #7 head aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa decision=pass\n 1. pass gate_marker [release.gate] FORGE:GATE_PASS marker: pass\n 2. pass deploy_gate [forge/deploy-gate] forge/deploy-gate: success\n 3. pass check:unit [branches.required_checks] success\n next:\n forgedock release explain 7 --repo o/r --json";
17
+ const b64 = (o) => ({ content: Buffer.from(typeof o === "string" ? o : JSON.stringify(o)).toString("base64") });
18
+
19
+ /** io fake: GitHub is a read-only world; any non-GET api call is recorded in `writes`. */
20
+ function fakeIo(world = {}) {
21
+ const writes = [], printed = [], gh = [];
22
+ const w = { controls: null, state: STATE, active: { lease: { holder: "h", epoch: 2, release: ID }, holds: [] }, issues: {}, marker: "pass", deployGate: "success", checks: [], ...world };
23
+ const io = {
24
+ writes, printed, now: () => 1, print: (l) => printed.push(l), sleep: async () => {},
25
+ api: async (method, path) => {
26
+ if (method !== "GET") { writes.push([method, path]); throw new Error("write"); }
27
+ if (path.includes("git/matching-refs")) return [{ ref: `refs/heads/forge-ledger/${ID}` }, { ref: "refs/heads/forge-ledger/_active" }];
28
+ if (path.includes("git/ref/heads/forge-ledger/")) return { object: { sha: "h" } };
29
+ if (path.includes("contents/state.json")) return b64(w.state);
30
+ if (path.includes("contents/active.json")) return b64(w.active);
31
+ if (path.includes("contents/controls.jsonl") && w.controls) return b64(w.controls.map((c) => JSON.stringify(c)).join("\n"));
32
+ throw Object.assign(new Error("HTTP 404"), { status: 404 });
33
+ },
34
+ gh: async (a) => {
35
+ gh.push(a); const j = a.join(" ");
36
+ if (j.includes("repo view")) return JSON.stringify({ nameWithOwner: REPO });
37
+ if (j.includes("--json comments")) return JSON.stringify({ comments: w.marker ? [{ body: `FORGE:GATE_${w.marker.toUpperCase()}` }] : [] });
38
+ if (j.includes("--json headRefOid")) return JSON.stringify({ headRefOid: HEAD });
39
+ if (a[0] === "api" && /\/status$/.test(a[1])) return JSON.stringify([]);
40
+ if (a[0] === "api") return JSON.stringify([{ name: "forge/deploy-gate", conclusion: w.deployGate }, ...w.checks]);
41
+ if (a[0] === "issue" && a[1] === "view") return JSON.stringify(w.issues[a[2]]);
42
+ if (a[0] === "issue" && a[1] === "list") return JSON.stringify(Object.values(w.issues));
43
+ throw new Error(`unexpected gh ${j}`);
44
+ },
45
+ };
46
+ return io;
47
+ }
48
+ const managedDir = tmpDir("rs5554-"); writeFileSync(join(managedDir, "forge.yaml"), "release:\n managed: true\n");
49
+ const local = { load: () => null, ids: () => [] };
50
+ const base = (io, over = {}) => ({ io, repo: REPO, config: { managed: true }, local, gateState, ...over });
51
+
52
+ describe("release status / explain (#5554)", () => {
53
+ it("R1: status reads the ledger plus GitHub, JSON has schema and next_actions, no write is made", async () => {
54
+ const io = fakeIo(), s = await collectStatus(base(io));
55
+ assert.equal(s.schema, "forgedock.release.status/v1");
56
+ assert.equal(s.id, ID); assert.equal(s.source, "ledger"); assert.equal(s.next_step, "promotion");
57
+ assert.deepEqual(s.pr.gate, { marker: "pass", deployGate: "success" });
58
+ assert.deepEqual(s.release.issues, [5, 12]);
59
+ assert.ok(s.next_actions.includes(`forgedock release --resume ${ID} --repo ${REPO} --merge`));
60
+ assert.deepEqual(io.writes, []);
61
+ });
62
+
63
+ it("R4: golden text output", async () => {
64
+ const out = renderReleaseStatus(await collectStatus(base(fakeIo(), { id: ID })));
65
+ assert.equal(out, [
66
+ `${ID} o/r status=running next=promotion source=ledger hold=no intake=unknown`,
67
+ " wave: unknown lane: unknown", " lease: holder=h epoch=2 heartbeat_age_s=unknown", " cut: s1",
68
+ " [x] preflight T1", " [ ] host-preflight", " [x] release-pr T2", " [ ] review", " [ ] fixes", " [ ] mark-ready", " [ ] rehearsal", " [ ] promotion T3", " [ ] post-merge",
69
+ ` PR #7 head ${HEAD} gate marker=pass deploy-gate=success ci: total=1 failed=0 pending=0`,
70
+ ` review: verdict=GATE_PASS head=${HEAD}`, " merge: unknown", " deploy: unknown", " rollback: target=unknown auto=unknown",
71
+ " release set: #5 #12 picks=0",
72
+ " next:",
73
+ ` forgedock release --resume ${ID} --repo o/r`,
74
+ ` forgedock release --resume ${ID} --repo o/r --merge`,
75
+ ` forgedock release hold ${ID} --repo o/r --reason <reason>`,
76
+ ` forgedock release cancel ${ID} --repo o/r --reason <reason>`,
77
+ " forgedock release lane #5 --repo o/r --force <train|release|p0|exclude> --reason <reason>",
78
+ " forgedock release lane #12 --repo o/r --force <train|release|p0|exclude> --reason <reason>",
79
+ ` forgedock release explain 7 --repo o/r`,
80
+ ` forgedock release explain ${ID} --repo o/r`,
81
+ ` forgedock release status ${ID} --repo o/r --json`,
82
+ ].join("\n"));
83
+ });
84
+
85
+ it("R4: a second host (other cwd, env, clock) prints the same bytes", async () => {
86
+ const run = async (cwd, now) => { const io = fakeIo(); io.now = () => now; const code = await releaseFromCli(["status", "--json", "--repo", REPO], { io, cwd: managedDir, env: { HOME: cwd, FORGEDOCK_RELEASE_DIR: `${cwd}/rel`, HOSTNAME: cwd } }); return [code, io.printed.join("\n")]; };
87
+ const [a, b] = [await run("/tmp/hostA", 1), await run("/tmp/hostB", 99)];
88
+ assert.deepEqual(a, b); assert.equal(a[0], 0); assert.equal(JSON.parse(a[1]).source, "ledger");
89
+ });
90
+
91
+ it("R1: local cache is used when release.managed is off, with no ledger call", async () => {
92
+ const io = fakeIo(), calls = []; const api = io.api; io.api = async (...a) => { calls.push(a); return api(...a); };
93
+ const s = await collectStatus({ ...base(io, { config: {}, id: ID }), local: { load: () => STATE, ids: () => [ID] } });
94
+ assert.equal(s.source, "local"); assert.deepEqual(calls, []);
95
+ });
96
+
97
+ const RULES = ["classification", "skip_labels", "min_confidence", "risk.rules", "forces", "priority", "theme", "depends_on", "release_set", "planner", "lane"];
98
+
99
+ it("R5: explain #N gives an ordered {step,rule,config_key,result,would_change} trace, planner not installed, lane", async () => {
100
+ const issues = { 40: { number: 40, title: "fix(api): x", body: "Depends on #41", labels: [{ name: "P1" }, { name: "needs-human" }] }, 41: { number: 41, title: "y", body: "", labels: [] } };
101
+ const e = await explainIssue({ io: fakeIo({ issues }), repo: REPO, number: 40, state: { id: ID, release: { issues: [12] } }, watch: { theme_map: { api: ["scope:api"] } } });
102
+ assert.deepEqual(e.trace.map((t) => t.rule), RULES);
103
+ assert.deepEqual(e.trace.map((t) => t.step), RULES.map((_, i) => i + 1));
104
+ assert.deepEqual(e.trace.map((t) => t.result), ["n/a", "fail", "n/a", "n/a", "n/a", "pass", "pass", "fail", "fail", "n/a", "n/a"]);
105
+ assert.ok(e.trace.every((t) => t.config_key && Array.isArray(t.would_change)));
106
+ assert.equal(e.classification, "absent"); assert.match(e.trace[0].detail, /classification: absent/);
107
+ assert.equal(e.trace[1].config_key, "plan.skip_labels");
108
+ assert.equal(e.trace[9].detail, "planner: not installed");
109
+ assert.equal(e.lane, "excluded");
110
+ assert.match(e.trace[7].detail, /#41/);
111
+ assert.ok(e.would_change.some((w) => w.includes("needs-human")));
112
+ assert.ok(e.trace[10].would_change[0].includes("release lane #40 --force"));
113
+ assert.match(renderExplain(e), /^#40 lane=excluded\n 1\. n\/a classification \[FORGE:CLASSIFY\] classification: absent/);
114
+ });
115
+
116
+ it("R5: explain #N reads the FORGE:CLASSIFY record, risk/forces rules, min_confidence, a registered planner rule and a controls lane", async () => {
117
+ const body = "<!-- FORGE:CLASSIFY -->\n" + JSON.stringify({ files: ["a.js"], confidence: 0.4, source: "model", set_by: "bot" });
118
+ const issues = { 12: { number: 12, title: "fix(api): z", body: "", labels: [{ name: "P2" }, { name: "risky" }], comments: [{ body }] } };
119
+ const policy = { min_confidence: 0.8, risk_rules: [{ label: "risky", lane: "solo" }], forces: [{ label: "force-x" }] };
120
+ PLANNER_RULES.length = 0; registerPlannerRule(() => ({ rule: "units_max", config_key: "plan.units_max", result: "pass", detail: "ok" }));
121
+ try {
122
+ const e = await explainIssue({ io: fakeIo({ issues }), repo: REPO, number: 12, state: { id: ID, release: { issues: [12] } }, watch: { theme_map: { api: ["scope:api"] } }, policy, lanes: { 12: { force: "p0", reason: "r", actor: "op", at: "T" } } });
123
+ assert.deepEqual(e.classification, { files: ["a.js"], confidence: 0.4, source: "model", set_by: "bot" });
124
+ assert.deepEqual(e.trace.map((t) => [t.rule, t.config_key, t.result]).slice(0, 5), [["classification", "FORGE:CLASSIFY", "pass"], ["skip_labels", "plan.skip_labels", "pass"], ["min_confidence", "classify.min_confidence", "fail"], ["risk.rules", "risk.rules[0]", "fail"], ["forces", "forces[0]", "pass"]]);
125
+ assert.equal(e.trace.at(-2).rule, "units_max"); assert.ok(!e.trace.some((t) => t.rule === "planner"));
126
+ assert.equal(e.lane, "p0"); assert.match(e.trace.at(-1).detail, /control decision by op/);
127
+ const viaLog = await explainIssue({ io: fakeIo({ issues }), repo: REPO, number: 12, state: null, controls: [{ verb: "lane", after: { 12: "exclude" }, actor: "ops" }, { verb: "lane", after: { 12: "train" }, actor: "ops2" }] });
128
+ assert.equal(viaLog.lane, "train"); assert.match(viaLog.trace.at(-1).detail, /by ops2/);
129
+ } finally { PLANNER_RULES.length = 0; }
130
+ });
131
+
132
+ it("R8: explain #N and explain <PR> JSON are byte-for-byte goldens", async () => {
133
+ const issues = { 40: { number: 40, title: "fix(api): x", body: "", labels: [{ name: "P1" }] } };
134
+ const e = await explainIssue({ io: fakeIo({ issues }), repo: REPO, number: 40, state: null });
135
+ assert.equal(JSON.stringify(e), GOLDEN_ISSUE);
136
+ const p = await explainPr({ io: fakeIo({ checks: [{ name: "unit", conclusion: "success" }] }), repo: REPO, pr: 7, gateState, policy: { required_checks: ["unit"] } });
137
+ assert.equal(JSON.stringify(p), GOLDEN_PR);
138
+ assert.equal(renderExplain(p), GOLDEN_PR_TEXT);
139
+ });
140
+
141
+ it("R5/R6: policyFromYaml reads skip_labels, min_confidence, risk/forces labels and required_checks from forge.yaml", () => {
142
+ const { policy } = policyFromYaml("plan:\n skip_labels: [epic, foo]\nclassify:\n min_confidence: 0.7\nrisk:\n rules:\n - label: risky\nbranches:\n required_checks: [ci, lint]\n");
143
+ assert.deepEqual(policy.skip_labels, ["epic", "foo"]); assert.equal(policy.min_confidence, 0.7);
144
+ assert.deepEqual(policy.risk_rules, [{ label: "risky" }]); assert.deepEqual(policy.required_checks, ["ci", "lint"]);
145
+ assert.deepEqual(policyFromYaml("").policy.skip_labels, undefined);
146
+ });
147
+
148
+ it("R6: explain <PR> lists each required check, the demotion (actor, expiry, reason, issue) and the gate decision", async () => {
149
+ const io = fakeIo({ marker: "failure", deployGate: "failure", checks: [{ name: "lint", conclusion: "failure" }, { name: "unit", conclusion: "failure" }, { name: "e2e", conclusion: "success" }] });
150
+ const exemptions = { unit: { mode: "skip", issue: "99", reason: "flaky", actor: "op", at: "2026-11-30T00:00:00Z", until: "2026-12-01T00:00:00Z" } }; // the `_active.exemptions` record `release exempt` writes
151
+ io.now = () => Date.parse("2026-11-30T12:00:00Z");
152
+ const e = await explainPr({ io, repo: REPO, pr: 7, gateState, exemptions });
153
+ assert.equal(e.decision, "hold");
154
+ assert.deepEqual(e.trace.map((t) => [t.rule, t.result]), [["gate_marker", "fail"], ["deploy_gate", "fail"], ["check:e2e", "pass"], ["check:forge/deploy-gate", "fail"], ["check:lint", "fail"], ["check:unit", "n/a"]]);
155
+ assert.deepEqual(e.demoted, [{ check: "unit", mode: "skip", actor: "op", expires: "2026-12-01T00:00:00Z", reason: "flaky", issue: "99" }]);
156
+ assert.match(e.trace.at(-1).detail, /demoted \(skip\) by op until 2026-12-01T00:00:00Z: flaky \(issue 99\)/);
157
+ io.now = () => Date.parse("2026-12-02T00:00:00Z"); // expired: the check counts again
158
+ const late = await explainPr({ io, repo: REPO, pr: 7, gateState, exemptions });
159
+ assert.deepEqual(late.demoted, []); assert.equal(late.trace.at(-1).result, "fail");
160
+ const ok = await explainPr({ io: fakeIo(), repo: REPO, pr: 7, gateState });
161
+ assert.equal(ok.decision, "pass");
162
+ });
163
+
164
+ it("R5/R6: explain via the CLI dispatches #N, bare number and PR URL, and every command is read-only", async () => {
165
+ const issues = { 12: { number: 12, title: "t", body: "", labels: [] } };
166
+ for (const [arg, kind] of [["#12", "issue"], ["7", "pr"], ["https://github.com/o/r/pull/7", "pr"], [ID, "release"]]) {
167
+ const io = fakeIo({ issues, controls: [{ type: "lane", issue: 12, lane: "pool" }] });
168
+ assert.equal(await releaseFromCli(["explain", arg, "--json", "--repo", REPO], { io, cwd: managedDir, env: { FORGEDOCK_RELEASE_DIR: join(managedDir, "rel") }, deps: {} }).catch((e) => e.message), 0, arg);
169
+ assert.equal(JSON.parse(io.printed.join("")).kind, kind); assert.deepEqual(io.writes, []);
170
+ }
171
+ });
172
+
173
+ it("R2/R3: missing fields print unknown; recorded fields are shown; every next_actions command parses", async () => {
174
+ const st = { ...STATE, wave: { n: 1, of: 3 }, lane: "fast", merge_sha: "m1", deploy: { run: 5, stage: "canary", attempt: 2 }, rollback: { target: "v1", armed: true }, steps: { ...STATE.steps, review: { done: true, result: { verdict: "pass" } }, promotion: { done: true } } };
175
+ const active = { lease: { holder: "h", epoch: 2, release: ID, heartbeat_at: "1970-01-01T00:00:00.100Z" }, holds: { [ID]: { reason: "r", actor: "o", at: "T" } }, intake: { paused: true } };
176
+ const io = fakeIo({ state: st, active }); io.now = () => 5100;
177
+ const s = await collectStatus(base(io));
178
+ assert.equal(s.wave, "1/3"); assert.equal(s.lane, "fast"); assert.equal(s.lease.heartbeat_age_s, 5); assert.equal(s.hold, true); assert.equal(s.intake, "paused");
179
+ assert.equal(s.merge_sha, "m1"); assert.deepEqual(s.deploy, { run: 5, stage: "canary", attempt: 2 }); assert.equal(s.rollback_target, "v1"); assert.equal(s.auto_rollback, "armed");
180
+ assert.deepEqual(s.review, { verdict: "GATE_PASS", head: HEAD });
181
+ const bare = await collectStatus(base(fakeIo()));
182
+ for (const k of ["wave", "lane", "cut_sha", "merge_sha", "deploy", "rollback_target", "auto_rollback", "intake"]) assert.ok(bare[k] === "unknown" || k === "cut_sha", k);
183
+ for (const x of [s, bare]) for (const a of x.next_actions) parseNextAction(a);
184
+ assert.ok(s.next_actions.some((a) => /release resume .* --reason <reason>/.test(a)));
185
+ assert.ok(!s.next_actions.some((a) => /release rollback/.test(a)), "rollback has no CLI verb");
186
+ assert.ok(s.next_actions.some((a) => /release lane #12 .* --force <train\|release\|p0\|exclude> --reason <reason>/.test(a)));
187
+ assert.deepEqual(CONTROL_VERBS, VERBS);
188
+ // each command runs through the real CLI grammar: no usage refusal (read-only ones fully; control ones against a fake that rejects writes)
189
+ for (const a of s.next_actions) {
190
+ const [, , verb, ...rest] = a.replace("<reason>", "why").replace(/<train\|[^>]*>/, "release").split(/\s+/);
191
+ const io2 = fakeIo({ state: st, active }); let out = "";
192
+ if (VERBS.includes(verb)) { try { await controlFromCli(verb, rest, { io: io2, policy: null }); } catch { /* the write is refused by the fake */ } out = io2.printed.join("\n"); }
193
+ else if (verb === "status" || verb === "explain") { assert.equal(await releaseFromCli([verb, ...rest], { io: io2, cwd: managedDir, env: { FORGEDOCK_RELEASE_DIR: join(managedDir, "rel") }, deps: {} }), 0, a); }
194
+ else assert.ok(a.includes("--resume"), a);
195
+ assert.doesNotMatch(out, /required|unknown control verb|must be one of|at least one/, a);
196
+ }
197
+ assert.throws(() => parseNextAction("forgedock release hold x"), /needs --reason/);
198
+ assert.throws(() => parseNextAction("forgedock release status x --bogus"), /unknown option/);
199
+ });
200
+
201
+ it("R1: no active release prints `no active release`", async () => {
202
+ const io = fakeIo({ active: {} });
203
+ assert.equal(await releaseFromCli(["status", "--repo", REPO], { io, cwd: managedDir, env: { FORGEDOCK_RELEASE_DIR: join(managedDir, "rel") }, deps: {} }), 1);
204
+ assert.deepEqual(io.printed, ["no active release"]);
205
+ });
206
+
207
+ it("R4/R11: status --watch prints only on change, stops at a terminal state, honours --interval", async () => {
208
+ const seq = ["running", "running", "done"], slept = [], printed = [];
209
+ const last = await watchStatus({ collect: async () => ({ status: seq.shift(), id: ID, repo: REPO, steps: [], next_actions: [] }), print: (l) => printed.push(l), sleep: async (ms) => slept.push(ms), asJson: true, intervalMs: 2500 });
210
+ assert.equal(last.status, "done"); assert.equal(printed.length, 2); assert.deepEqual(slept, [2500, 2500]);
211
+ });
212
+
213
+ it("R4: bare `release --watch` and `status --watch --interval` run the loop; a terminal release ends it; bad interval and unknown options are rejected", async () => {
214
+ const term = { ...STATE, status: "done" };
215
+ const run = (argv) => { const io = fakeIo({ state: term }); return releaseFromCli(argv, { io, cwd: managedDir, env: { FORGEDOCK_RELEASE_DIR: join(managedDir, "rel") }, deps: {} }).then((code) => [code, io]); };
216
+ for (const argv of [["--watch", "--repo", REPO], ["status", "--watch", "--interval", "3", "--repo", REPO]]) { const [code, io] = await run(argv); assert.equal(code, 0); assert.equal(io.printed.length, 1); assert.match(io.printed[0], /status=done/); }
217
+ await assert.rejects(run(["status", "--watch", "--interval", "0", "--repo", REPO]), /positive number/);
218
+ await assert.rejects(releaseFromCli(["status", "--bogus"], { io: fakeIo() }), /unknown option --bogus/);
219
+ });
220
+ });
@@ -0,0 +1,35 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /** Unit/coupling/contract/force resolver for `.forge/release.yaml` (#5551): every path resolves to a unit or "none". */
4
+
5
+ /** Glob to RegExp: `**` any depth (a trailing `/**` also matches the directory's files), `*` within a segment, `?` one char. */
6
+ export function unitGlobToRegExp(glob) {
7
+ let re = "";
8
+ for (let i = 0; i < glob.length; i++) {
9
+ const c = glob[i];
10
+ if (c === "*" && glob[i + 1] === "*") {
11
+ i++;
12
+ if (glob[i + 1] === "/") { i++; re += "(?:.*/)?"; } else re += ".*";
13
+ } else if (c === "*") re += "[^/]*";
14
+ else if (c === "?") re += "[^/]";
15
+ else re += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
16
+ }
17
+ return new RegExp(`^${re}$`);
18
+ }
19
+
20
+ export const matchesAny = (globs, path) => (globs ?? []).some((g) => unitGlobToRegExp(String(g)).test(path));
21
+
22
+ /**
23
+ * @returns {{path, unit: string|"none", units: string[], affects: string[], contracts: object[], forces: object[]}}
24
+ * `unit` is the first unit (declaration order) owning the path; `units` every owner; `affects` the units the matching couplings fan out to.
25
+ */
26
+ export function resolvePath(policy, rawPath) {
27
+ const path = String(rawPath).replace(/^\.\//, "");
28
+ const units = Object.entries(policy?.units ?? {}).filter(([, u]) => matchesAny(u?.paths, path)).map(([id]) => id);
29
+ const affects = [...new Set((policy?.couplings ?? []).filter((c) => matchesAny(c.paths, path)).flatMap((c) => c.affects ?? []))];
30
+ return {
31
+ path, unit: units[0] ?? "none", units, affects,
32
+ contracts: (policy?.contracts ?? []).filter((c) => matchesAny(c.paths, path)),
33
+ forces: (policy?.forces ?? []).filter((f) => matchesAny(f.paths, path)),
34
+ };
35
+ }
@@ -0,0 +1,41 @@
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 { unitGlobToRegExp, resolvePath } from "./release-unitmap.mjs";
6
+
7
+ const policy = {
8
+ units: { api: { paths: ["services/api/**"] }, worker: { paths: ["services/worker/**"] }, web: { paths: ["web/*.js"] } },
9
+ couplings: [{ paths: ["shared/**"], affects: ["api", "worker"] }, { paths: ["emails/**"], affects: ["api", "web"] }],
10
+ contracts: [{ producer: "api", consumers: ["web"], paths: ["services/api/app/routers/**"] }],
11
+ forces: [{ paths: ["infra/migrations/**"], pipeline: "full", reason: "migrations" }, { paths: ["docker-compose*.yml"], pipeline: "full", reason: "deploy-mechanics" }],
12
+ };
13
+
14
+ describe("unitGlobToRegExp", () => {
15
+ it("** crosses directories, * does not, ? is one char", () => {
16
+ assert.ok(unitGlobToRegExp("a/**").test("a/b/c.txt"));
17
+ assert.ok(unitGlobToRegExp("**/x.json").test("x.json") && unitGlobToRegExp("**/x.json").test("a/b/x.json"));
18
+ assert.ok(unitGlobToRegExp("a/*.js").test("a/b.js") && !unitGlobToRegExp("a/*.js").test("a/b/c.js"));
19
+ assert.ok(unitGlobToRegExp("a?.js").test("ab.js") && !unitGlobToRegExp("a?.js").test("a/.js"));
20
+ assert.ok(!unitGlobToRegExp("a.js").test("axjs"));
21
+ });
22
+ });
23
+
24
+ describe("resolvePath", () => {
25
+ it("resolves a path to its unit or none", () => {
26
+ for (const [p, u] of [["services/api/app/main.py", "api"], ["services/worker/x.py", "worker"], ["web/a.js", "web"], ["README.md", "none"], ["web/sub/a.js", "none"]]) assert.equal(resolvePath(policy, p).unit, u, p);
27
+ });
28
+ it("fans a coupling out, flags a contract and a force", () => {
29
+ assert.deepEqual(resolvePath(policy, "shared/x.py").affects, ["api", "worker"]);
30
+ assert.equal(resolvePath(policy, "shared/x.py").unit, "none");
31
+ assert.equal(resolvePath(policy, "services/api/app/routers/a.py").contracts[0].producer, "api");
32
+ assert.equal(resolvePath(policy, "infra/migrations/001.sql").forces[0].reason, "migrations");
33
+ assert.equal(resolvePath(policy, "./docker-compose.prod.yml").forces[0].reason, "deploy-mechanics");
34
+ });
35
+ it("first declared unit wins and every owner is listed", () => {
36
+ const p = { units: { a: { paths: ["x/**"] }, b: { paths: ["x/y/**"] } } };
37
+ const r = resolvePath(p, "x/y/z");
38
+ assert.equal(r.unit, "a"); assert.deepEqual(r.units, ["a", "b"]);
39
+ });
40
+ it("an empty policy resolves everything to none", () => assert.equal(resolvePath({}, "a").unit, "none"));
41
+ });
@@ -0,0 +1,221 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Verification of a deployed release (#5562, epic #5549 Phase 3, invariants I19/I22): the VERIFYING stage between LIVE_CHECK and LIVE.
5
+ * Layers in order: (1) repo workflow results (smoke, edge gate, convergence), (2) the configured verification workflow, dispatched
6
+ * through `fenced()`, (3) the SLI soak against an injected read-only metric source, (4) each issue's `[check:id]`, (5) flag-gated
7
+ * features verified in the off state. Only then is `FORGE:VERIFIED <deploy sha>` written on each issue and the issue closed (I19).
8
+ * An input this module cannot read blocks (I5). Verification only reads production: every probe is an injected `io.metrics` or a
9
+ * default-branch check command, and the module has no write path of its own (I22, enforced by a static scan in the test).
10
+ * Rationale: devdocs/decisions/5562-release-verify.md.
11
+ */
12
+ import { fenced } from "./release-fence.mjs";
13
+ import { runFor, finished, BOUNDS } from "./release-deploy.mjs";
14
+ import { INFRA_SIGNATURES } from "./release-flakes.mjs";
15
+
16
+ /** Soak minutes by risk class (design 6.4); `lanes.<lane>.soak_min` (a number or a map by class) overrides. */
17
+ export const SOAK_MIN = { low: 10, medium: 20, full: 30, p0: 15 };
18
+ const KEYS = ["workflow", "results", "slis", "post_deploy_checks_file", "flags", "close_requires"];
19
+ const TRANSPORT = /identity|unauthori[sz]ed|\b40[13]\b|ECONN|ETIMEDOUT|timed? ?out|certificate|\bdns\b|transport|\b50[234]\b/i;
20
+ const json = (s) => JSON.parse(String(s || "null"));
21
+ const blocked = (reason, extra = {}) => ({ blocked: true, reason, ...extra });
22
+ 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" } });
23
+ const sameSha = (a, b) => !!a && !!b && (a.startsWith(b) || b.startsWith(a));
24
+ const short = (sha) => String(sha).slice(0, 8);
25
+
26
+ export const verifiedMarker = (sha) => `<!-- FORGE:VERIFIED ${sha} -->`;
27
+ /** True when a comment names the deploy sha in a `FORGE:VERIFIED <sha>` marker (the prod-watch `fp=` form never matches). */
28
+ export function hasVerified(comments, sha) {
29
+ return (comments ?? []).some((c) => [...String(c?.body ?? c ?? "").matchAll(/<!--\s*FORGE:VERIFIED\s+([0-9a-f]{7,64})\s*-->/gi)].some((m) => sameSha(m[1], sha)));
30
+ }
31
+
32
+ export const verifyConfigured = (v) => !!v && KEYS.some((k) => v[k] != null && !(Array.isArray(v[k]) && !v[k].length));
33
+
34
+ /** Risk class of a release: p0 lane, a full-pipeline release, else medium. */
35
+ export const riskClass = (lane, pipeline) => (lane === "p0" ? "p0" : pipeline === "full" ? "full" : "medium");
36
+
37
+ export function soakMinutes(risk, override) {
38
+ const o = override && typeof override === "object" ? override[risk] : override;
39
+ return typeof o === "number" && o > 0 ? o : SOAK_MIN[risk] ?? SOAK_MIN.medium;
40
+ }
41
+
42
+ /** SLI breaches of `{baseline, current}` readings beyond tolerance (default 20%); `worse: "lower"` for rates where a drop is bad. */
43
+ export function sliBreaches(slis, readings) {
44
+ return slis.filter((s) => {
45
+ const { baseline, current } = readings[s.name];
46
+ const tol = typeof s.tolerance === "number" ? s.tolerance : 0.2, abs = s.abs ?? 0;
47
+ return s.worse === "lower" ? current < baseline * (1 - tol) - abs : current > baseline * (1 + tol) + abs;
48
+ }).map((s) => ({ sli: s.name, ...readings[s.name] }));
49
+ }
50
+
51
+ /** An emitted rollback trigger is recorded once and handed to the ladder's sink (#5563) when one is attached. */
52
+ function rollbackResult(ctx, st, reason) {
53
+ if (!st.rollback) { st.rollback = { reason }; ctx.save(); ctx.rollbackTrigger?.({ reason, sha: ctx.state.deploy?.merge }); }
54
+ return blocked(`${reason}; rollback trigger emitted to the ladder (#5563)`, { rollback: st.rollback });
55
+ }
56
+
57
+ async function layerResults(ctx, v, sha, st, b) {
58
+ const { io, repo } = ctx;
59
+ for (const w of v.results ?? []) {
60
+ let run;
61
+ try { run = (json(await io.gh(["run", "list", "--repo", repo, "--workflow", w.workflow, "--commit", sha, "--json", "databaseId,status,conclusion", "--limit", "5"])) ?? []).find((r) => r.conclusion !== "skipped"); }
62
+ catch (e) { return blocked(`cannot read ${w.workflow} results (I5): ${String(e?.message ?? e).split("\n")[0]}`); }
63
+ if (!run || run.status !== "completed") return blocked(`${w.workflow} (${w.kind}) has no completed run for ${short(sha)}; resume once it finishes`);
64
+ if (run.conclusion === "success") continue;
65
+ if (w.kind === "convergence") { (st.convergence ??= []).push(`${w.workflow} run ${run.databaseId} ${run.conclusion}`); continue; }
66
+ let log = null; try { log = String(await io.gh(["run", "view", String(run.databaseId), "--repo", repo, "--log-failed"])); } catch { /* unreadable log */ }
67
+ if (log == null || TRANSPORT.test(log) || INFRA_SIGNATURES.some(([, re]) => re.test(log))) { // identity/transport: not evidence about the release
68
+ if (log != null && st.reverifies < 1) { st.reverifies += 1; ctx.save(); await io.sleep(b.pollMs); return layerResults(ctx, v, sha, st, b); }
69
+ return hold(`${w.workflow} (${w.kind}) run ${run.databaseId} failed on identity/transport after ${st.reverifies} re-verify; no blind rollback`, "verify-transport");
70
+ }
71
+ return rollbackResult(ctx, st, `${w.workflow} (${w.kind}) run ${run.databaseId} concluded ${run.conclusion}`);
72
+ }
73
+ return null;
74
+ }
75
+
76
+ async function layerWorkflow(ctx, v, sha, st, b) {
77
+ const r = await runFor(ctx, { workflow: v.workflow, sha, inputs: {}, key: `verify:${sha}`, startPolls: 1, b });
78
+ if (r.err) return blocked(r.err);
79
+ const stageS = ctx.config.deploy?.stage_timeout_s ?? BOUNDS.defaultStageS;
80
+ const done = await finished(ctx, v.workflow, sha, Math.ceil(stageS * 1000 / b.runPollMs), b);
81
+ if (!done) return blocked(`${v.workflow} run ${r.run.databaseId} did not finish within stage_timeout_s; resume (never redispatched)`);
82
+ return done.conclusion === "success" ? null : rollbackResult(ctx, st, `${v.workflow} run ${done.databaseId} concluded ${done.conclusion}`);
83
+ }
84
+
85
+ async function layerSoak(ctx, v, sha, st) {
86
+ const { io } = ctx, slis = v.slis ?? [];
87
+ if (!io.metrics) { st.sli = "skipped (no host)"; return null; }
88
+ if (!slis.length) { st.sli = "skipped (no slis configured)"; return null; }
89
+ const min = soakMinutes(ctx.config.verifyRisk ?? "medium", ctx.config.verifySoak);
90
+ st.soakStart ??= io.now(); ctx.save();
91
+ const wait = st.soakStart + min * 60_000 - io.now();
92
+ if (wait > 0) await io.sleep(wait);
93
+ const readings = {};
94
+ for (const s of slis) {
95
+ let r; try { r = await io.metrics({ sli: s, minutes: min, sha }); } catch (e) { return blocked(`cannot read SLI ${s.name} (I5): ${String(e?.message ?? e).split("\n")[0]}`); }
96
+ if (![r?.baseline, r?.current].every(Number.isFinite)) return blocked(`SLI ${s.name} returned no baseline/current (I5)`);
97
+ readings[s.name] = { baseline: r.baseline, current: r.current };
98
+ }
99
+ const bad = sliBreaches(slis, readings);
100
+ if (bad.length) return rollbackResult(ctx, st, `SLI breach over ${min} min: ${bad.map((x) => `${x.sli} ${x.current} vs baseline ${x.baseline}`).join(", ")}`);
101
+ st.sli = `pass (${min} min soak, ${slis.length} sli)`;
102
+ return null;
103
+ }
104
+
105
+ async function readIssue(ctx, n) {
106
+ return json(await ctx.io.gh(["issue", "view", String(n), "--repo", ctx.repo, "--json", "state,body,comments"])) ?? {};
107
+ }
108
+
109
+ /** Windowed checks are follow-ups on the rollup issue and never block the close. */
110
+ async function followUp(ctx, st, id, issue, entry, sha) {
111
+ const key = `${issue}:${id}`;
112
+ if (st.followups.includes(key)) return;
113
+ try {
114
+ const [roll] = json(await ctx.io.gh(["issue", "list", "--repo", ctx.repo, "--state", "open", "--search", "FORGE:POSTDEPLOY_ROLLUP in:body", "--json", "number", "--limit", "1"])) ?? [];
115
+ if (roll) await ctx.io.gh(["issue", "comment", String(roll.number), "--repo", ctx.repo, "--body", `- [ ] [check:${id}] windowed (${entry.for}) for #${issue} at deploy ${short(sha)}`]);
116
+ } catch { /* a follow-up that cannot be filed does not block the close */ }
117
+ st.followups.push(key); ctx.save();
118
+ }
119
+
120
+ async function layerChecks(ctx, v, sha, st, issues) {
121
+ if (!v.post_deploy_checks_file || !issues.length) return null;
122
+ const want = [];
123
+ for (const n of issues) {
124
+ let info; try { info = await readIssue(ctx, n); } catch (e) { return blocked(`cannot read issue #${n} (I5): ${String(e?.message ?? e).split("\n")[0]}`); }
125
+ for (const m of String(info.body ?? "").matchAll(/\[check:([\w.-]+)\]/g)) want.push([n, m[1]]);
126
+ }
127
+ if (!want.length) return null;
128
+ let table; // the registry comes from the default branch, never the working tree (I13)
129
+ try { table = json(ctx.io.git(["show", `origin/${ctx.def}:${v.post_deploy_checks_file}`])); } catch (e) { return blocked(`cannot read ${v.post_deploy_checks_file} from origin/${ctx.def} (I13, I5): ${String(e?.message ?? e).split("\n")[0]}`); }
130
+ for (const [n, id] of want) {
131
+ const entry = table?.[id];
132
+ if (!entry?.run) return blocked(`#${n} names [check:${id}] but ${v.post_deploy_checks_file} has no such check`);
133
+ if (entry.for) { await followUp(ctx, st, id, n, entry, sha); continue; }
134
+ if (st.checks[id] === "pass") continue; // each check runs once
135
+ const r = await ctx.io.rehearse(entry.run, { timeout: (entry.timeout ?? 120) * 1000 });
136
+ if (!r?.ok) return hold(`post-deploy check ${id} (#${n}) failed: ${String(r?.output ?? "").trim().slice(-200)}`, "check");
137
+ st.checks[id] = "pass"; ctx.save();
138
+ }
139
+ return null;
140
+ }
141
+
142
+ async function layerFlags(ctx, v, st) {
143
+ for (const f of v.flags ?? []) {
144
+ if (st.flags[f.flag] === "off") continue;
145
+ const r = await ctx.io.rehearse(f.off_command, { timeout: 120_000 }); // observes the off state; activation is never performed
146
+ if (!r?.ok) return hold(`flag ${f.flag} could not be verified in the off state: ${String(r?.output ?? "").trim().slice(-200)}`, "flag");
147
+ st.flags[f.flag] = "off"; ctx.save();
148
+ }
149
+ return null;
150
+ }
151
+
152
+ /** CLOSING guard (I19): with `mode: verified` an issue closes only when a `FORGE:VERIFIED` names the deploy sha; `deployed` is the opt-out. */
153
+ export async function closeIssues(ctx, { issues, sha, mode = "verified" }) {
154
+ const { io, repo } = ctx, closed = [], refused = [];
155
+ for (const n of issues) {
156
+ let info; try { info = await readIssue(ctx, n); } catch (e) { refused.push({ issue: n, why: `unreadable: ${String(e?.message ?? e).split("\n")[0]}` }); continue; }
157
+ if (String(info.state).toUpperCase() === "CLOSED") continue;
158
+ if (mode !== "deployed" && !hasVerified(info.comments, sha)) { refused.push({ issue: n, why: `no FORGE:VERIFIED ${short(sha)}` }); continue; }
159
+ const key = `${ctx.fence?.lease?.release ?? ctx.state.id ?? "-"}:verify:${ctx.fence?.lease?.epoch ?? 0}:close:${n}`;
160
+ const f = await fenced(ctx.fence, { action: "close", key }, () => io.gh(["issue", "close", String(n), "--repo", repo, "--comment", `Released and verified at ${short(sha)}.`]));
161
+ if (f.refused) refused.push({ issue: n, why: f.refused }); else closed.push(n);
162
+ }
163
+ return { closed, refused };
164
+ }
165
+
166
+ /** Issue numbers of the release (the release record, else the release-PR step). */
167
+ export function releaseIssues(state) {
168
+ const raw = state.release?.issues ?? state.steps?.["release-pr"]?.result?.issues ?? [];
169
+ return raw.map((i) => Number(i?.number ?? i)).filter(Number.isInteger);
170
+ }
171
+
172
+ /**
173
+ * Run the layers (resumable: `state.verify` records each passed layer, so a resume re-runs none and redispatches nothing).
174
+ * @returns {Promise<{verified: true, outcome, sli, closed}|{blocked: true, reason, hold?, rollback?}>}
175
+ */
176
+ export async function verifyStep(ctx, sha) {
177
+ const v = ctx.config.verify, { io } = ctx;
178
+ const st = (ctx.state.verify ??= { layers: {}, reverifies: 0, checks: {}, flags: {}, followups: [] });
179
+ const b = { ...BOUNDS, ...(ctx.config.deployBounds ?? {}) };
180
+ const issues = releaseIssues(ctx.state);
181
+ const layers = [
182
+ ["results", () => layerResults(ctx, v, sha, st, b), !!v.results?.length],
183
+ ["workflow", () => layerWorkflow(ctx, v, sha, st, b), !!v.workflow],
184
+ ["sli", () => layerSoak(ctx, v, sha, st), true],
185
+ ["checks", () => layerChecks(ctx, v, sha, st, issues), true],
186
+ ["flags", () => layerFlags(ctx, v, st), !!v.flags?.length],
187
+ ];
188
+ for (const [name, run, on] of layers) {
189
+ if (!on || st.layers[name]) continue;
190
+ const r = await run();
191
+ if (r) return r;
192
+ st.layers[name] = "pass"; ctx.save();
193
+ }
194
+ io.print?.(`release verify ${short(sha)}: sli: ${st.sli ?? "n/a"}`);
195
+ if (st.convergence?.length) {
196
+ st.outcome = "released-with-convergence-failures";
197
+ if (!st.repair) {
198
+ st.repair = true; ctx.save();
199
+ await io.gh(["issue", "create", "--repo", ctx.repo, "--title", `released-with-convergence-failures: ${short(sha)}`, "--body", `Deploy and smoke are green; convergence failed (no rollback):\n${st.convergence.map((c) => `- ${c}`).join("\n")}`]);
200
+ }
201
+ }
202
+ for (const n of issues) { // every layer passed: the evidence comment, then the guarded close
203
+ const info = await readIssue(ctx, n).catch(() => null);
204
+ if (info && !hasVerified(info.comments, sha)) await io.gh(["issue", "comment", String(n), "--repo", ctx.repo, "--body", `${verifiedMarker(sha)}\nrelease verified at ${short(sha)} (${Object.keys(st.layers).join(", ")}).`]);
205
+ }
206
+ const c = await closeIssues(ctx, { issues, sha, mode: v.close_requires ?? "verified" });
207
+ if (c.refused.length) return blocked(`CLOSING refused (I19): ${c.refused.map((r) => `#${r.issue} ${r.why}`).join("; ")}`);
208
+ return { verified: true, outcome: st.outcome ?? "verified", sli: st.sli ?? null, closed: c.closed };
209
+ }
210
+
211
+ /** `forgedock release verify <id>`: re-run the verification of a deployed release from its local record. */
212
+ export async function verifyReleaseById({ io, state, save, def, policy, lane }) {
213
+ const sha = state?.deploy?.merge;
214
+ if (!sha || !["LIVE_CHECKED", "VERIFYING", "LIVE"].includes(state.deploy.phase)) return blocked("release has not passed LIVE_CHECK; nothing to verify yet");
215
+ const pipeline = policy?.lanes?.[lane]?.pipeline ?? "full";
216
+ const config = { deploy: policy?.deploy, verify: policy?.verify, verifyRisk: riskClass(lane, pipeline), verifySoak: policy?.lanes?.[lane]?.soak_min };
217
+ if (!verifyConfigured(config.verify)) return blocked("verify policy is not configured (.forge/release.yaml verify)");
218
+ const r = await verifyStep({ io, repo: state.repo, def, config, state, save }, sha);
219
+ io.print(r.verified ? `release verify ${state.id}: ${r.outcome}; sli: ${r.sli ?? "n/a"}; closed ${r.closed.length} issue(s)` : `release verify ${state.id}: blocked: ${r.reason}`);
220
+ return r;
221
+ }