forgedock 1.52.0 → 1.54.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 (233) hide show
  1. package/.claude-plugin/marketplace.json +51 -0
  2. package/README.md +8 -2
  3. package/bin/auth/app-manifest.mjs +89 -0
  4. package/bin/auth/app-manifest.test.mjs +75 -0
  5. package/bin/auth/app-token.mjs +256 -0
  6. package/bin/auth/app-token.test.mjs +232 -0
  7. package/bin/brand.mjs +7 -0
  8. package/bin/config-history.mjs +151 -0
  9. package/bin/config-schema.mjs +115 -0
  10. package/bin/demo.mjs +65 -11
  11. package/bin/engine/outcome-codes.mjs +9 -3
  12. package/bin/engine/telemetry-seam.mjs +11 -3
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +110 -36
  15. package/bin/experiment.mjs +58 -6
  16. package/bin/first-run.mjs +122 -0
  17. package/bin/forge-utils.mjs +6 -2
  18. package/bin/forgedock.mjs +138 -142
  19. package/bin/help-text.mjs +144 -0
  20. package/bin/hooks/pre-tool-use.mjs +7 -0
  21. package/bin/journey.mjs +82 -83
  22. package/bin/lean/acceptance.mjs +313 -0
  23. package/bin/lean/acceptance.test.mjs +215 -0
  24. package/bin/lean/account-watch.mjs +28 -0
  25. package/bin/lean/account-watch.test.mjs +30 -0
  26. package/bin/lean/activation.mjs +38 -0
  27. package/bin/lean/activation.test.mjs +36 -1
  28. package/bin/lean/basered.mjs +115 -0
  29. package/bin/lean/basered.test.mjs +66 -0
  30. package/bin/lean/batch-health.mjs +114 -7
  31. package/bin/lean/batch-health.test.mjs +87 -1
  32. package/bin/lean/batch.mjs +41 -2
  33. package/bin/lean/batch.test.mjs +115 -11
  34. package/bin/lean/branchlock.mjs +54 -0
  35. package/bin/lean/branchlock.test.mjs +49 -0
  36. package/bin/lean/ceiling.mjs +72 -0
  37. package/bin/lean/ceiling.test.mjs +54 -0
  38. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  39. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  40. package/bin/lean/ci-budget.mjs +366 -0
  41. package/bin/lean/ci-budget.test.mjs +167 -0
  42. package/bin/lean/conformance.e2e.test.mjs +8 -1
  43. package/bin/lean/conformance.mjs +269 -38
  44. package/bin/lean/conformance.test.mjs +280 -7
  45. package/bin/lean/context.mjs +35 -6
  46. package/bin/lean/context.test.mjs +27 -1
  47. package/bin/lean/depcache.mjs +25 -1
  48. package/bin/lean/depcache.test.mjs +26 -0
  49. package/bin/lean/e2e.mjs +18 -2
  50. package/bin/lean/e2e.test.mjs +26 -1
  51. package/bin/lean/effects.mjs +47 -14
  52. package/bin/lean/execution.mjs +19 -3
  53. package/bin/lean/execution.test.mjs +63 -0
  54. package/bin/lean/facts.mjs +3 -3
  55. package/bin/lean/facts.test.mjs +5 -0
  56. package/bin/lean/findinglabel.mjs +16 -0
  57. package/bin/lean/findinglabel.test.mjs +39 -0
  58. package/bin/lean/fixround.mjs +14 -0
  59. package/bin/lean/fixround.test.mjs +25 -2
  60. package/bin/lean/gh-assoc.test.mjs +2 -1
  61. package/bin/lean/integration.mjs +100 -9
  62. package/bin/lean/integration.test.mjs +98 -0
  63. package/bin/lean/issuewatch-parity.mjs +64 -0
  64. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  65. package/bin/lean/issuewatch-release.mjs +6 -2
  66. package/bin/lean/issuewatch-release.test.mjs +17 -1
  67. package/bin/lean/issuewatch.mjs +45 -6
  68. package/bin/lean/issuewatch.test.mjs +3 -2
  69. package/bin/lean/lanelock.mjs +14 -0
  70. package/bin/lean/lean.mjs +473 -100
  71. package/bin/lean/lean.test.mjs +686 -33
  72. package/bin/lean/light.mjs +48 -7
  73. package/bin/lean/light.test.mjs +37 -3
  74. package/bin/lean/limits.test.mjs +142 -9
  75. package/bin/lean/mechfix.mjs +124 -0
  76. package/bin/lean/mechfix.test.mjs +75 -0
  77. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  78. package/bin/lean/orchestrate.mjs +116 -28
  79. package/bin/lean/phaseledger.mjs +47 -5
  80. package/bin/lean/phaseledger.test.mjs +30 -1
  81. package/bin/lean/postdeploy-check.test.mjs +39 -0
  82. package/bin/lean/precheck.mjs +23 -4
  83. package/bin/lean/precheck.test.mjs +14 -1
  84. package/bin/lean/prereq.mjs +28 -0
  85. package/bin/lean/prereq.test.mjs +20 -0
  86. package/bin/lean/probe.mjs +4 -2
  87. package/bin/lean/prodparity.mjs +52 -0
  88. package/bin/lean/prodparity.test.mjs +67 -0
  89. package/bin/lean/prompts.mjs +77 -19
  90. package/bin/lean/quota.mjs +39 -0
  91. package/bin/lean/recovery.test.mjs +11 -1
  92. package/bin/lean/relaxation.mjs +73 -0
  93. package/bin/lean/relaxation.test.mjs +54 -0
  94. package/bin/lean/release-io.test.mjs +42 -0
  95. package/bin/lean/release-postmerge.mjs +125 -0
  96. package/bin/lean/release-preflight.mjs +58 -0
  97. package/bin/lean/release-preflight.test.mjs +114 -0
  98. package/bin/lean/release-rehearsal.mjs +64 -0
  99. package/bin/lean/release-rehearsal.test.mjs +93 -0
  100. package/bin/lean/release-review.e2e.test.mjs +77 -0
  101. package/bin/lean/release-review.mjs +254 -0
  102. package/bin/lean/release-review.test.mjs +307 -0
  103. package/bin/lean/release-snapshot.mjs +188 -0
  104. package/bin/lean/release-snapshot.test.mjs +190 -0
  105. package/bin/lean/release.mjs +296 -0
  106. package/bin/lean/release.test.mjs +387 -0
  107. package/bin/lean/render.mjs +1 -1
  108. package/bin/lean/replan.mjs +184 -0
  109. package/bin/lean/replan.test.mjs +110 -0
  110. package/bin/lean/resume.mjs +9 -7
  111. package/bin/lean/resume.test.mjs +16 -0
  112. package/bin/lean/rotator.mjs +150 -31
  113. package/bin/lean/rotator.test.mjs +105 -2
  114. package/bin/lean/sandbox-remote.mjs +9 -2
  115. package/bin/lean/schedd.mjs +83 -5
  116. package/bin/lean/schedd.test.mjs +108 -7
  117. package/bin/lean/selfreview.mjs +94 -0
  118. package/bin/lean/selfreview.test.mjs +58 -1
  119. package/bin/lean/selftest-gate.mjs +22 -0
  120. package/bin/lean/selftest-gate.test.mjs +18 -1
  121. package/bin/lean/selftest-journey.mjs +234 -0
  122. package/bin/lean/selftest-journey.test.mjs +130 -0
  123. package/bin/lean/selftest-live.mjs +2 -1
  124. package/bin/lean/seqlease.mjs +35 -1
  125. package/bin/lean/seqlease.test.mjs +15 -0
  126. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  127. package/bin/lean/seqreserve.mjs +73 -0
  128. package/bin/lean/seqreserve.test.mjs +134 -0
  129. package/bin/lean/sequence.mjs +35 -6
  130. package/bin/lean/seqversioned.mjs +147 -0
  131. package/bin/lean/stagestamp.mjs +28 -0
  132. package/bin/lean/stagestamp.test.mjs +32 -0
  133. package/bin/lean/surfaces.mjs +75 -0
  134. package/bin/lean/surfaces.test.mjs +59 -0
  135. package/bin/lean/toolplace.mjs +28 -0
  136. package/bin/lean/toolplace.test.mjs +24 -0
  137. package/bin/lean/toolstats.mjs +3 -1
  138. package/bin/lean/toolstats.test.mjs +11 -0
  139. package/bin/lean/validatebest.mjs +28 -0
  140. package/bin/lean/validatebest.test.mjs +27 -0
  141. package/bin/lean/verifier.mjs +3 -2
  142. package/bin/lean/verify.mjs +2 -1
  143. package/bin/lean/verify.test.mjs +6 -0
  144. package/bin/pool/agent.mjs +27 -4
  145. package/bin/pool/docker.mjs +5 -0
  146. package/bin/pool/router.mjs +74 -28
  147. package/bin/prereqs.mjs +111 -0
  148. package/bin/replay-timelapse.mjs +149 -0
  149. package/bin/review-staging.mjs +123 -16
  150. package/bin/review-staging.test.mjs +18 -0
  151. package/bin/runner.mjs +43 -6
  152. package/bin/splash-install.mjs +157 -0
  153. package/bin/stats/aggregate.mjs +8 -1
  154. package/bin/stats/conformance-outcomes.mjs +289 -0
  155. package/bin/stats/conformance-outcomes.test.mjs +274 -0
  156. package/bin/stats/depth.mjs +275 -0
  157. package/bin/stats/depth.test.mjs +158 -0
  158. package/bin/stats/efficiency.mjs +26 -5
  159. package/bin/stats/efficiency.test.mjs +45 -1
  160. package/bin/stats/experiment.mjs +7 -5
  161. package/bin/stats/first-review.mjs +77 -0
  162. package/bin/stats/first-review.test.mjs +36 -0
  163. package/bin/stats/firstmerge.mjs +40 -0
  164. package/bin/stats/firstmerge.test.mjs +41 -0
  165. package/bin/stats/github-source.mjs +53 -15
  166. package/bin/stats/index.mjs +147 -9
  167. package/bin/stats/local-source.mjs +12 -0
  168. package/bin/stats/origin.mjs +80 -0
  169. package/bin/stats/origin.test.mjs +58 -0
  170. package/bin/stats/query.mjs +69 -0
  171. package/bin/stats/render.mjs +3 -1
  172. package/bin/stats/scoreboard.mjs +137 -0
  173. package/bin/stats/scoreboard.test.mjs +87 -0
  174. package/bin/stats/selffiled.mjs +52 -0
  175. package/bin/stats/selffiled.test.mjs +71 -0
  176. package/bin/stats/stats.test.mjs +80 -0
  177. package/bin/tui.mjs +3 -2
  178. package/commands/bootstrap.md +15 -14
  179. package/commands/deploy-pr.md +18 -3
  180. package/commands/forge-stats.md +1 -1
  181. package/commands/forgedock-ci-setup.md +28 -0
  182. package/commands/forgedock-init.md +4 -5
  183. package/commands/issue.md +2 -0
  184. package/commands/milestone.md +9 -1
  185. package/commands/orchestrate.md +1 -1
  186. package/commands/replay.md +2 -0
  187. package/commands/review-pr-agents/security.md +4 -0
  188. package/commands/review-pr-staging.md +6 -1
  189. package/commands/work-on/build.md +4 -6
  190. package/commands/work-on/close.md +8 -0
  191. package/docs/CONFIG.md +170 -18
  192. package/docs/ISSUE-WATCH.md +25 -0
  193. package/docs/OUTCOME-CODES.md +4 -0
  194. package/docs/REPLAY.md +9 -0
  195. package/docs/SELFTEST.md +11 -0
  196. package/docs/STATS.md +61 -0
  197. package/docs/TELEMETRY.md +1 -1
  198. package/docs/eval/README.md +6 -0
  199. package/docs/eval/adversarial-bench.md +68 -0
  200. package/docs/eval/corpus/adversarial-v1.json +285 -0
  201. package/docs/eval/feature-bench.md +42 -0
  202. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  203. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  204. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  205. package/docs/site/start-a-new-project.md +2 -1
  206. package/package.json +5 -2
  207. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  208. package/plugins/forgedock-splash/README.md +27 -0
  209. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  210. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  211. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  212. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  213. package/pool/README.md +1 -1
  214. package/pool/image/cs-cred +14 -1
  215. package/scripts/backfill-finding-labels.mjs +50 -0
  216. package/scripts/backfill-finding-labels.test.mjs +36 -0
  217. package/scripts/bench-adversarial.mjs +216 -0
  218. package/scripts/bench-feature.mjs +170 -0
  219. package/scripts/bench-lightlane.mjs +2 -2
  220. package/scripts/bootstrap-create.mjs +2 -2
  221. package/scripts/bootstrap-validate.mjs +35 -2
  222. package/scripts/check-spec-size.sh +4 -3
  223. package/scripts/check-spec-size.test.sh +3 -0
  224. package/scripts/doctor-pipeline-state.sh +21 -6
  225. package/scripts/file-deferred-followups.sh +59 -251
  226. package/scripts/file-deferred-followups.test.sh +85 -206
  227. package/scripts/followup-route.mjs +12 -0
  228. package/scripts/owner-route-parity.test.sh +17 -1
  229. package/scripts/plan-validate-live.mjs +40 -6
  230. package/scripts/review-pr-side-effects.test.sh +40 -0
  231. package/scripts/review-pr-staging-scope.test.sh +1 -1
  232. package/scripts/review-staging-post.sh +23 -0
  233. package/scripts/review-staging-post.test.sh +8 -0
@@ -0,0 +1,149 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * `forgedock replay --timelapse <batch|epic>` (#5293): a time-lapse of a recorded run, rendered from the local lifecycle
5
+ * event log (docs/EVENTS.md) and the batch plan. Deterministic, no model call, read-only: the only GitHub access is an
6
+ * `issue view` / GET `api` read to list an epic's children, enforced by `readOnlyGh`. Output is text frames plus a vhs
7
+ * tape; GIF/MP4 are encoded only when `vhs` is already on PATH (nothing is installed).
8
+ */
9
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { join, resolve } from "node:path";
11
+ import { spawnSync, execFileSync } from "node:child_process";
12
+ import { batchRoot, listBatches } from "./lean/batch.mjs";
13
+ import { sinkPath } from "./engine/events.mjs";
14
+ import { parseForgeYaml } from "./forge-utils.mjs";
15
+
16
+ export const MIN_SECONDS = 30;
17
+ export const MAX_SECONDS = 90;
18
+ export const DEFAULT_SECONDS = 60;
19
+ export const FPS = 2;
20
+ const USAGE = "usage: forgedock replay --timelapse <batch-id|epic-number> [--repo owner/repo] [--out dir] [--format gif|mp4] [--duration 30-90] [--events file]";
21
+
22
+ /** Wrap a gh runner so any call that is not an issue read or a GET api call throws (the no-live-writes guarantee). */
23
+ export function readOnlyGh(gh) {
24
+ return (args) => {
25
+ const a = args.map(String);
26
+ const method = a.findIndex((x) => x === "-X" || x === "--method");
27
+ const read = (a[0] === "issue" && a[1] === "view") || (a[0] === "api" && !a.includes("-f") && !a.includes("-F") && !a.includes("--input") && (method < 0 || /^GET$/i.test(a[method + 1] ?? "")));
28
+ if (!read) throw new Error(`replay is read-only: refused gh ${a.slice(0, 2).join(" ")}`);
29
+ return gh(args);
30
+ };
31
+ }
32
+
33
+ const issueNum = (x) => (typeof x === "number" ? x : typeof x === "string" && /^#?\d+$/.test(x.trim()) ? parseInt(x.trim().replace("#", ""), 10) : x && typeof x === "object" ? issueNum(x.issue ?? x.number) : NaN);
34
+
35
+ /** Resolve a batch id (local plan) or an epic number (children referenced in its body) to {issues, repo, created}. */
36
+ export async function resolveTarget(target, { root = batchRoot(), gh = null, repo = null } = {}) {
37
+ const t = String(target ?? "").trim();
38
+ if (listBatches(root).includes(t)) {
39
+ const plan = JSON.parse(readFileSync(join(root, t, "plan.json"), "utf8"));
40
+ const issues = (Array.isArray(plan.issues) ? plan.issues : []).map(issueNum).filter(Number.isInteger);
41
+ return { kind: "batch", id: t, issues, repo: plan.repo ?? repo, created: typeof plan.created === "string" ? plan.created : null };
42
+ }
43
+ if (!/^#?\d+$/.test(t)) throw new Error(`no local batch "${t}" and it is not an epic number\n${USAGE}`);
44
+ const epic = parseInt(t.replace("#", ""), 10);
45
+ if (!gh) throw new Error("epic resolution needs gh");
46
+ const raw = gh(["issue", "view", String(epic), ...(repo ? ["-R", repo] : []), "--json", "body"]);
47
+ const body = String(JSON.parse(typeof raw === "string" ? raw : String(raw ?? "{}")).body ?? "");
48
+ const issues = [...new Set([...body.matchAll(/#(\d+)/g)].map((m) => parseInt(m[1], 10)))].filter((n) => n !== epic);
49
+ return { kind: "epic", id: `epic-${epic}`, issues, repo, created: null };
50
+ }
51
+
52
+ /** Events of `issues` from a lifecycle-events JSONL file, normalised to timeline items sorted by time. */
53
+ export function buildTimeline(lines, issues, { created = null } = {}) {
54
+ const want = new Set(issues);
55
+ const items = [];
56
+ const seen = new Set();
57
+ const createdMs = Date.parse(created ?? "");
58
+ const kinds = { "lane.picked_up": "lane_start", "pr.opened": "pr_open", "pr.merged": "pr_merged", "release.promoted": "gate", "probe.passed": "gate" };
59
+ for (const line of lines) {
60
+ let e; try { e = JSON.parse(line); } catch { continue; }
61
+ const t = Date.parse(e?.ts ?? "");
62
+ if (!e || e.schema !== "forgedock.event" || !Number.isFinite(t) || !want.has(e.issue)) continue;
63
+ if (!seen.has(e.issue)) { seen.add(e.issue); items.push({ t: Number.isFinite(createdMs) && createdMs < t ? createdMs : t, kind: "issue", issue: e.issue }); }
64
+ if (kinds[e.type]) items.push({ t, kind: kinds[e.type], issue: e.issue, pr: e.pr ?? null, cost: e.type === "pr.merged" && Number.isFinite(e.cost_usd) ? e.cost_usd : 0 });
65
+ }
66
+ return items.sort((a, b) => a.t - b.t);
67
+ }
68
+
69
+ const clock = (ms) => { const s = Math.floor(ms / 1000); return [Math.floor(s / 3600), Math.floor(s / 60) % 60, s % 60].map((n) => String(n).padStart(2, "0")).join(":"); };
70
+ const STATE = { issue: "open", lane_start: "building", pr_open: "PR open", pr_merged: "merged" };
71
+
72
+ /** `seconds` of frames (FPS each) evenly spaced across the timeline, whatever its real length; seconds clamped 30-90. */
73
+ export function buildFrames(items, { seconds = DEFAULT_SECONDS, title = "run" } = {}) {
74
+ const dur = Math.min(MAX_SECONDS, Math.max(MIN_SECONDS, Number.isFinite(+seconds) ? +seconds : DEFAULT_SECONDS));
75
+ const n = Math.round(dur * FPS);
76
+ const t0 = items[0]?.t ?? 0, span = Math.max(0, (items[items.length - 1]?.t ?? 0) - t0);
77
+ const frames = [];
78
+ let k = 0, cost = 0, gate = false;
79
+ const state = new Map();
80
+ for (let i = 0; i < n; i++) {
81
+ const T = t0 + (n > 1 ? (span * i) / (n - 1) : 0);
82
+ for (; k < items.length && items[k].t <= T; k++) {
83
+ const it = items[k];
84
+ if (it.kind === "gate") gate = true; else state.set(it.issue, { ...state.get(it.issue), state: STATE[it.kind], pr: it.pr ?? state.get(it.issue)?.pr ?? null });
85
+ cost += it.cost ?? 0;
86
+ }
87
+ const merged = [...state.values()].filter((s) => s.state === "merged").length;
88
+ const rows = [...state].map(([issue, s]) => ` #${String(issue).padEnd(6)} ${String(s.state).padEnd(9)} ${s.pr ? `PR #${s.pr}` : ""}`.trimEnd());
89
+ frames.push([`ForgeDock time-lapse: ${title}`, `clock ${clock(T - t0)} cost $${cost.toFixed(2)} merged ${merged}/${state.size} release gate ${gate ? "PASSED" : "pending"}`, "", ...rows, ""].join("\n"));
90
+ }
91
+ return frames;
92
+ }
93
+
94
+ /** vhs tape that plays the frame files at FPS and records `format` (gif|mp4). */
95
+ export function tapeFor(dir, format) {
96
+ return ["# generated by `forgedock replay --timelapse`; render with: vhs timelapse.tape", `Output timelapse.${format}`, "Set FontSize 14", "Set Width 1200", "Set Height 650", "Set Theme \"Dracula\"", "Hide",
97
+ `Type "for f in frames/*.txt; do clear; cat $f; sleep ${1 / FPS}; done; exit"`, "Enter", "Show", `Sleep ${Math.ceil(1 / FPS)}s`, ""].join("\n");
98
+ }
99
+
100
+ /** Write frames, the tape and meta under `out`; encode when vhs exists. Returns {out, frames, encoded, command}. */
101
+ export function writeOutput(out, frames, { format = "gif", meta = {}, spawn = spawnSync } = {}) {
102
+ const dir = resolve(out), fdir = join(dir, "frames");
103
+ mkdirSync(fdir, { recursive: true });
104
+ frames.forEach((f, i) => writeFileSync(join(fdir, `frame-${String(i + 1).padStart(4, "0")}.txt`), f));
105
+ writeFileSync(join(dir, "timelapse.tape"), tapeFor(dir, format));
106
+ writeFileSync(join(dir, "timelapse.json"), JSON.stringify({ ...meta, frames: frames.length, fps: FPS, seconds: frames.length / FPS, format }, null, 2) + "\n");
107
+ const command = `cd ${dir} && vhs timelapse.tape`;
108
+ const have = spawn("vhs", ["--version"], { stdio: "ignore" });
109
+ if (have?.error || have?.status !== 0) return { out: dir, frames: frames.length, encoded: false, command };
110
+ const run = spawn("vhs", ["timelapse.tape"], { cwd: dir, stdio: "ignore" });
111
+ return { out: dir, frames: frames.length, encoded: run?.status === 0, command };
112
+ }
113
+
114
+ function parseArgs(argv) {
115
+ const o = { target: null, repo: null, out: null, format: "gif", seconds: DEFAULT_SECONDS, events: null };
116
+ for (let i = 0; i < argv.length; i++) {
117
+ const a = argv[i], v = () => argv[++i];
118
+ if (a === "--timelapse") o.target = v(); else if (a === "--repo") o.repo = v(); else if (a === "--out") o.out = v(); else if (a === "--events") o.events = v();
119
+ else if (a === "--format") o.format = v(); else if (a === "--duration") o.seconds = Number(v());
120
+ else throw new Error(`unknown argument ${a}\n${USAGE}`);
121
+ }
122
+ if (!o.target) throw new Error(USAGE);
123
+ if (o.format !== "gif" && o.format !== "mp4") throw new Error(`--format must be gif or mp4\n${USAGE}`);
124
+ return o;
125
+ }
126
+
127
+ function repoFromConfig(cwd) {
128
+ try {
129
+ const y = parseForgeYaml(readFileSync(join(cwd, process.env.FORGE_CONFIG || "forge.yaml"), "utf8"));
130
+ return y.project?.owner && y.project?.repo ? `${y.project.owner}/${y.project.repo}` : null;
131
+ } catch { return null; }
132
+ }
133
+
134
+ /** CLI entry. Returns the exit code; `deps` = {gh, root, env, cwd, spawn, log} for tests. */
135
+ export async function replayFromCli(argv, deps = {}) {
136
+ const o = parseArgs(argv), env = deps.env ?? process.env, log = deps.log ?? ((s) => process.stdout.write(`${s}\n`));
137
+ const gh = readOnlyGh(deps.gh ?? ((args) => execFileSync("gh", args, { encoding: "utf8" })));
138
+ const repo = o.repo ?? repoFromConfig(deps.cwd ?? process.cwd());
139
+ const target = await resolveTarget(o.target, { root: deps.root ?? batchRoot(env), gh, repo });
140
+ const file = o.events ?? sinkPath(target.repo ?? repo, env.FORGE_EVENTS_DIR);
141
+ if (!existsSync(file)) throw new Error(`no lifecycle event log at ${file} (docs/EVENTS.md); pass --events <file>`);
142
+ const items = buildTimeline(readFileSync(file, "utf8").split("\n").filter(Boolean), target.issues, { created: target.created });
143
+ if (!items.length) throw new Error(`no recorded events for ${target.id} in ${file}`);
144
+ const frames = buildFrames(items, { seconds: o.seconds, title: target.id });
145
+ const res = writeOutput(o.out ?? `timelapse-${target.id}`, frames, { format: o.format, spawn: deps.spawn, meta: { target: target.id, issues: target.issues.length } });
146
+ log(`${res.frames} frames written to ${res.out}/frames`);
147
+ log(res.encoded ? `rendered ${res.out}/timelapse.${o.format}` : `vhs not available or failed; render with: ${res.command}`);
148
+ return 0;
149
+ }
@@ -27,11 +27,15 @@ import { join } from "node:path";
27
27
  import { fileURLToPath } from "node:url";
28
28
  import { parseForgeYaml } from "./forge-utils.mjs";
29
29
  import { selftestGate, readMarkerComments } from "./lean/selftest-gate.mjs";
30
+ import { gateByRef } from "./lean/acceptance.mjs";
31
+ import { DEFAULT_FEATURE_PATTERN } from "./lean/lane.mjs";
32
+ import { requiredChecksRead } from "./lean/effects.mjs";
30
33
 
31
34
  const INSTALL_ROOT = fileURLToPath(new URL("..", import.meta.url));
32
35
  const USAGE = "usage: forgedock review-staging [<PR number|PR URL>] [--thorough | --delta <from-sha>] [--json]\n" +
33
36
  " forgedock review-staging [<PR>] --finalize --test-gate-output <file> [--notes-dropped <n>] [--json]\n" +
34
- " forgedock review-staging [<PR>] --summary [--filed <issue>]... [--json]";
37
+ " forgedock review-staging [<PR>] --summary [--filed <issue>]... [--json]\n" +
38
+ " forgedock review-staging [<PR>] --post-reviewer <domain> --body-file <file>";
35
39
  const SHA_RE = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
36
40
  /** selftest.sandbox_repo turns the release gate on only when it names a repo (`null`, `~`, `false` or prose leave it off). */
37
41
  const SANDBOX_RE = /^[\w.-]+\/[\w.-]+$/;
@@ -48,7 +52,7 @@ class Stop extends Error {
48
52
 
49
53
  /** argv -> {pr, thorough, json, mode, testGateOutput, notesDropped, filed, delta}. Throws Stop(2) on anything else. */
50
54
  export function parseArgs(argv) {
51
- const o = { pr: null, thorough: false, json: false, mode: "pre", testGateOutput: null, notesDropped: 0, filed: [], delta: null };
55
+ const o = { pr: null, thorough: false, json: false, mode: "pre", testGateOutput: null, notesDropped: 0, filed: [], delta: null, domain: null, bodyFile: null };
52
56
  const setMode = (m, a) => { if (o.mode !== "pre") throw new Stop(2, [`review-staging: ${a} cannot be combined with --${o.mode}`, USAGE]); o.mode = m; };
53
57
  const value = (i, a) => { const v = argv[i + 1]; if (v == null || v.startsWith("--")) throw new Stop(2, [`review-staging: ${a} requires a value`, USAGE]); return v; };
54
58
  for (let i = 0; i < argv.length; i++) {
@@ -57,6 +61,8 @@ export function parseArgs(argv) {
57
61
  else if (a === "--json") o.json = true;
58
62
  else if (a === "--finalize") setMode("finalize", a);
59
63
  else if (a === "--summary") setMode("summary", a);
64
+ else if (a === "--post-reviewer") { setMode("post-reviewer", a); o.domain = value(i++, a); }
65
+ else if (a === "--body-file") o.bodyFile = value(i++, a);
60
66
  else if (a === "--test-gate-output") o.testGateOutput = value(i++, a);
61
67
  else if (a === "--delta") {
62
68
  const v = value(i++, a);
@@ -79,6 +85,8 @@ export function parseArgs(argv) {
79
85
  o.pr = Number(m[1]);
80
86
  } else throw new Stop(2, [`review-staging: unknown argument: ${a}`, USAGE]);
81
87
  }
88
+ if (o.mode === "post-reviewer" && (!/^[a-z0-9-]+$/.test(o.domain) || !o.bodyFile || o.json || o.delta)) throw new Stop(2, ["review-staging: --post-reviewer takes a lowercase marker domain and --body-file <file>", USAGE]);
89
+ if (o.mode !== "post-reviewer" && o.bodyFile) throw new Stop(2, ["review-staging: --body-file belongs to --post-reviewer", USAGE]);
82
90
  if (o.mode !== "finalize" && (o.testGateOutput != null || o.notesDropped)) throw new Stop(2, ["review-staging: --test-gate-output/--notes-dropped belong to --finalize", USAGE]);
83
91
  if (o.mode !== "summary" && o.filed.length) throw new Stop(2, ["review-staging: --filed belongs to --summary", USAGE]);
84
92
  if (o.mode !== "pre" && o.thorough) throw new Stop(2, ["review-staging: --thorough belongs to the pre-dispatch", USAGE]);
@@ -107,10 +115,10 @@ export function buildManifest(m) {
107
115
  ...(m.delta ? [`DELTA: ${m.delta.from}..${m.headSha} files=${m.delta.files.length}`] : []),
108
116
  `CONTEXT_FILE=${m.contextFile}`,
109
117
  ...m.briefs.map((b) => `DISPATCH ${b.domain} ${b.path}`),
110
- `NEXT: dispatch one isolated reviewer per DISPATCH line (prompt = the brief file's content) in a single message; before each launch append its domain to ${m.launchedFile}.`,
118
+ `NEXT: dispatch one isolated reviewer per DISPATCH line (prompt = the brief file's content) in a single message; these domains are already recorded in ${m.launchedFile}. Reviewers post with: forgedock review-staging ${m.pr} --post-reviewer <domain> --body-file <file> (it writes the marker and the full Reviewed-SHA).`,
111
119
  m.delta
112
120
  ? `NEXT: delta pass: the spec-owned panel (${SPEC_PANEL}) is credited from the earlier pass at ${m.delta.from.slice(0, 7)}; dispatch only the DISPATCH lines.`
113
- : `NEXT: dispatch the spec-owned panel per commands/review-pr-staging.md (${SPEC_PANEL}), appending each domain to the same file.`,
121
+ : `NEXT: dispatch the spec-owned panel per commands/review-pr-staging.md (${SPEC_PANEL}), appending each domain to ${m.launchedFile} before launch (the manifest ${m.manifestFile ?? ""} already lists the briefed ones).`,
114
122
  `NEXT: after every reviewer posted, run /test-gate, save its output to a file, then run: forgedock review-staging ${m.pr} --finalize --test-gate-output <file>`,
115
123
  ];
116
124
  return lines.join("\n");
@@ -140,7 +148,7 @@ function readConfig(io) {
140
148
  try { cfg = parseForgeYaml(io.readFile(path)) ?? {}; } catch { /* absent config: owner/repo check below fails */ }
141
149
  const owner = cfg.project?.owner, repo = cfg.project?.repo;
142
150
  if (!owner || !repo) throw new Stop(1, [`review-staging: project.owner/project.repo not set in ${path}`]);
143
- return { ghRepo: `${owner}/${repo}`, defaultBranch: cfg.branches?.default || "main", stagingBranch: cfg.branches?.staging || "staging", configPath: path, sandboxRepo: SANDBOX_RE.test(String(cfg.selftest?.sandbox_repo ?? "").trim()) ? String(cfg.selftest.sandbox_repo).trim() : "", sandboxRaw: String(cfg.selftest?.sandbox_repo ?? "").trim() };
151
+ return { ghRepo: `${owner}/${repo}`, defaultBranch: cfg.branches?.default || "main", stagingBranch: cfg.branches?.staging || "staging", featurePattern: typeof cfg.branches?.feature_pattern === "string" && cfg.branches.feature_pattern.includes("{slug}") ? cfg.branches.feature_pattern : null, configPath: path, extraRequiredChecks: Array.isArray(cfg.gate?.required_checks) ? cfg.gate.required_checks.map((x) => String(x).trim()).filter(Boolean) : [], sandboxRepo: SANDBOX_RE.test(String(cfg.selftest?.sandbox_repo ?? "").trim()) ? String(cfg.selftest.sandbox_repo).trim() : "", sandboxRaw: String(cfg.selftest?.sandbox_repo ?? "").trim() };
144
152
  }
145
153
 
146
154
  /** Same derivation as commands/review-pr-staging.md Phase -1 (and scripts/lib/fence-bootstrap.sh). */
@@ -228,6 +236,7 @@ async function main(argv, io) {
228
236
  const a = parseArgs(argv);
229
237
  if (a.mode === "finalize") return finalize(a, io);
230
238
  if (a.mode === "summary") return summary(a, io);
239
+ if (a.mode === "post-reviewer") return postReviewer(a, io);
231
240
  const c = readConfig(io);
232
241
  const sd = io.env.FORGE_SCRATCHPAD || join(io.cwd, ".forge-scratch");
233
242
  io.mkdir(sd);
@@ -299,7 +308,7 @@ async function main(argv, io) {
299
308
  // Roster + briefs
300
309
  const agents = ctx.roster?.agents?.length ? ctx.roster.agents : ["security"];
301
310
  const launchedFile = join(sd, `${pr}_launched_review_agents`);
302
- io.writeFile(launchedFile, "");
311
+ const manifestFile = join(sd, `${pr}_review_manifest.json`);
303
312
  // The head this list describes: review-prepare trusts the list as --delta proof only for this head.
304
313
  io.writeFile(`${launchedFile}.head`, `${head}\n`);
305
314
  const briefDir = join(sd, `review-staging-${pr}`);
@@ -322,7 +331,7 @@ async function main(argv, io) {
322
331
  };
323
332
  const extra = [
324
333
  `## Staging review (staging->main PR #${pr}, head ${head})`,
325
- `Your marker domain is \`${domain}\`: start your comment with \`<!-- FORGE:REVIEW-AGENT:${domain} -->\`, then the line \`Reviewed-SHA: ${head}\`, and end it with the structured findings block.`,
334
+ `Your marker domain is \`${domain}\`: start your comment with \`<!-- FORGE:REVIEW-AGENT:${domain} -->\`, then the line \`Reviewed-SHA: ${head}\`, and end it with the structured findings block. Post it with \`forgedock review-staging ${pr} --post-reviewer ${domain} --body-file <file>\`: the tool writes that marker and the full SHA itself, from the launch manifest.`,
326
335
  scopeSection(scope, delta, head),
327
336
  ...(ctx.broken_assumptions?.length ? ["## Pre-found integration issues to verify", ...ctx.broken_assumptions.map((x) => `- ${x}`)] : []),
328
337
  ...(priorOpen.length ? ["## Prior open findings (carried forward: do not re-file)", ...priorOpen.map((x) => `- ${x}`)] : []),
@@ -334,9 +343,13 @@ async function main(argv, io) {
334
343
  briefs.push({ domain, path });
335
344
  }
336
345
 
346
+ // One source of names: the launch manifest. The launched file is generated from it; --post-reviewer reads it for the marker and SHA.
347
+ io.writeFile(manifestFile, `${JSON.stringify({ pr, head, agents: briefs.map((b) => ({ domain: b.domain, brief: b.path })) })}\n`);
348
+ io.writeFile(launchedFile, briefs.map((b) => `${b.domain}\n`).join(""));
349
+
337
350
  let bundle = [];
338
351
  try { bundle = io.readFile(prsFile).split(/\s+/).filter((n) => /^\d+$/.test(n)); } catch { /* reported empty */ }
339
- const m = { pr, headSha: head, gate, bundle, scopeMode: scope.scope_mode, tier: ctx.roster?.tier ?? "full", reason: ctx.roster?.reason ?? "", contextFile: ctxFile, launchedFile, briefs, reentry: priorRoutes > 0, delta };
352
+ const m = { pr, headSha: head, gate, bundle, scopeMode: scope.scope_mode, tier: ctx.roster?.tier ?? "full", reason: ctx.roster?.reason ?? "", contextFile: ctxFile, launchedFile, manifestFile, briefs, reentry: priorRoutes > 0, delta };
340
353
  io.out(a.json ? JSON.stringify(m) : buildManifest(m));
341
354
  return 0;
342
355
  }
@@ -373,6 +386,23 @@ function testGateResult(io, sd, pr) {
373
386
  return VERDICT_RE.test(v) ? { verdict: v, reason, invalid: false } : { verdict: "BLOCK", reason: "persisted test-gate verdict missing/invalid", invalid: true };
374
387
  }
375
388
 
389
+ /** --post-reviewer: post one reviewer's comment with the marker and full Reviewed-SHA written from the launch manifest, never from the agent's text. */
390
+ async function postReviewer(a, io) {
391
+ const { c, sd, pr } = await postContext(a, io);
392
+ const man = readJson(io, join(sd, `${pr}_review_manifest.json`));
393
+ if (!man || !SHA_RE.test(man.head ?? "")) throw new Stop(1, [`review-staging: no launch manifest for PR #${pr} (run the pre-dispatch first)`]);
394
+ const launched = (readText(io, join(sd, `${pr}_launched_review_agents`)) ?? "").split("\n").filter((l) => /^[a-z0-9-]+$/.test(l));
395
+ const known = [...new Set([...(man.agents ?? []).map((x) => x.domain), ...launched])];
396
+ if (!known.includes(a.domain)) throw new Stop(1, [`review-staging: ${a.domain} is not a launched reviewer of PR #${pr} (launched: ${known.join(" ")}); the marker name must come from the launch manifest`]);
397
+ let body;
398
+ try { body = io.readFile(a.bodyFile); } catch { throw new Stop(1, [`review-staging: cannot read --body-file ${a.bodyFile}`]); }
399
+ // Whatever header the reviewer typed is replaced: only the manifest's SHA and name reach the comment.
400
+ body = body.replace(/^(?:\s*<!-- FORGE:REVIEW-AGENT:[^>]*-->[ \t]*\r?\n|\s*Reviewed-SHA:[^\n]*\n)+/, "").replace(/^\s+/, "");
401
+ await retryGh(io, ["pr", "comment", String(pr), "-R", c.ghRepo, "--body", `<!-- FORGE:REVIEW-AGENT:${a.domain} -->\nReviewed-SHA: ${man.head}\n\n${body}`]);
402
+ io.out(`POSTED ${a.domain} Reviewed-SHA ${man.head} on PR #${pr}`);
403
+ return 0;
404
+ }
405
+
376
406
  /** --finalize: delivery, test gate, extract, classify (dry run + real), file-prepare; prints the items to file. */
377
407
  async function finalize(a, io) {
378
408
  const { c, sd, env, pr, head } = await postContext(a, io);
@@ -387,7 +417,12 @@ async function finalize(a, io) {
387
417
  relay(io, d);
388
418
  // Exit 2 = the comments could not be listed on any attempt (forge#5166): rerun, never re-dispatch reviewers that may have posted.
389
419
  if (d.code === 2) throw new Stop(1, ["REVIEW_RESULT: status: BLOCKED, blocker: reviewer delivery could not be verified (GitHub comment listing failed); rerun --finalize, do not re-dispatch reviewers", BLOCK_DEPLOY]);
390
- if (d.code !== 0) throw new Stop(1, [`REVIEW_RESULT: status: BLOCKED, blocker: reviewer delivery incomplete (exit ${d.code}); re-dispatch each missing reviewer once with the note "structured findings block required", else the panel is degraded`, BLOCK_DEPLOY]);
420
+ if (d.code !== 0) {
421
+ // review-staging-post.sh names each failing reviewer and why on a REDISPATCH line: repair only those, never the whole panel.
422
+ const redo = String(d.stdout ?? "").split("\n").filter((l) => l.startsWith("REDISPATCH ")).map((l) => l.slice(11).split(" ")[0]);
423
+ const only = redo.length ? `re-run only ${redo.join(", ")} (REDISPATCH lines above; post with --post-reviewer so the SHA is right), then rerun --finalize` : `re-dispatch each missing reviewer once with the note "structured findings block required", else the panel is degraded`;
424
+ throw new Stop(1, [`REVIEW_RESULT: status: BLOCKED, blocker: reviewer delivery incomplete (exit ${d.code}); ${only}`, BLOCK_DEPLOY]);
425
+ }
391
426
 
392
427
  // 6.5 verdict handling (override, posture, test-gate markers)
393
428
  const prsFile = join(sd, `${pr}_bundle-prs.txt`);
@@ -489,13 +524,37 @@ export const CI_EXCLUDED_CHECKS = ["forgedock/verify", "forge/deploy-gate", "Che
489
524
 
490
525
  const parseChecks = (out) => { try { const j = JSON.parse(out); return Array.isArray(j) ? j : null; } catch { return null; } };
491
526
 
527
+ const isRed = (k) => k?.bucket === "fail" || k?.bucket === "cancel";
528
+
529
+ /**
530
+ * The required-check set classifyChecks gets. An unreadable protection read (e.g. a non-admin token) must not let
531
+ * gate.required_checks alone demote the protection-required red checks to warnings: it yields [] (every red check blocks).
532
+ */
533
+ export function requiredSet({ checks = [], unreadable = false } = {}, extra = []) {
534
+ return unreadable ? [] : [...new Set([...checks, ...extra])];
535
+ }
536
+
537
+ /**
538
+ * Red checks outside CI_EXCLUDED_CHECKS, split by whether they block. With a non-empty `required` set (branch protection,
539
+ * rulesets and forge.yaml gate.required_checks) only required red checks block and the rest are warnings. An empty set
540
+ * (no protection, or a failed read: indistinguishable) keeps every red check blocking (fail closed).
541
+ */
542
+ export function classifyChecks(checks, required = []) {
543
+ const red = checks.filter((k) => !CI_EXCLUDED_CHECKS.includes(k?.name) && isRed(k));
544
+ const req = new Set(required);
545
+ if (!req.size) return { blocking: red.length, warnings: [] };
546
+ const hit = red.filter((k) => req.has(k.name));
547
+ return { blocking: hit.length, warnings: [...new Set(red.filter((k) => !req.has(k.name)).map((k) => String(k.name)))] };
548
+ }
549
+
492
550
  /** Failing (fail/cancel) checks outside CI_EXCLUDED_CHECKS. */
493
551
  export function countFailingChecks(checks) {
494
- return checks.filter((k) => !CI_EXCLUDED_CHECKS.includes(k?.name) && (k?.bucket === "fail" || k?.bucket === "cancel")).length;
552
+ return classifyChecks(checks).blocking;
495
553
  }
496
554
 
497
555
  /** Phase 8 verdict from the deterministic inputs (CI, test gate, CONFIRMED CRITICAL/HIGH). */
498
- export function stagingVerdict({ ciFailing, testGateInvalid, confirmedCritical, confirmedHigh }) {
556
+ export function stagingVerdict({ ciFailing, testGateInvalid, acceptanceBlocked = null, confirmedCritical, confirmedHigh }) {
557
+ if (acceptanceBlocked) return { verdict: "BLOCK DEPLOY", why: `feature acceptance blocked: ${acceptanceBlocked}` };
499
558
  if (ciFailing > 0) return { verdict: "BLOCK DEPLOY", why: `CI failing (${ciFailing} required check(s) red; forgedock/verify, forge/deploy-gate and the gate-marker check excluded)` };
500
559
  if (testGateInvalid) return { verdict: "BLOCK DEPLOY", why: "test-gate result missing/invalid (fail closed)" };
501
560
  if (confirmedCritical > 0) return { verdict: "BLOCK DEPLOY", why: `${confirmedCritical} CONFIRMED CRITICAL finding(s)` };
@@ -503,6 +562,24 @@ export function stagingVerdict({ ciFailing, testGateInvalid, confirmedCritical,
503
562
  return { verdict: "APPROVE FOR DEPLOY", why: "no CI failure, no blocking test gate, no CONFIRMED CRITICAL/HIGH finding" };
504
563
  }
505
564
 
565
+ /**
566
+ * #5336: the feature-acceptance gate of a milestone release PR (head ref `milestone/<slug>` by the feature pattern). A milestone
567
+ * with an epic is blocked by a red or never-run journey, and a SKIP test gate is a blocking finding there, not a pass.
568
+ * Returns the blocking reason or null. A PR that is not from a milestone branch is not gated; an unreadable head branch or gate read fails closed.
569
+ */
570
+ async function acceptanceBlock(io, c, pr, tg) {
571
+ let branch = "";
572
+ try { branch = (await io.gh(["pr", "view", String(pr), "-R", c.ghRepo, "--json", "headRefName", "--jq", ".headRefName"])).trim(); } catch (e) { return `PR head branch unreadable (${String(e?.message ?? e).slice(0, 120)}; fail closed)`; }
573
+ if (!branch) return "PR head branch unreadable (empty; fail closed)";
574
+ const [pre, post = ""] = String(c.featurePattern ?? DEFAULT_FEATURE_PATTERN).split("{slug}");
575
+ if (!pre || !branch.startsWith(pre) || !branch.endsWith(post) || branch.length <= pre.length + post.length) return null;
576
+ let g;
577
+ try { g = await gateByRef({ io, repo: c.ghRepo, branch, stage: "ship", pattern: c.featurePattern ?? DEFAULT_FEATURE_PATTERN }); } catch (e) { return `journey gate unreadable (${String(e?.message ?? e).slice(0, 120)}; fail closed)`; }
578
+ if (!g.gated) return null;
579
+ if (!g.ok) return g.reasons.join("; ");
580
+ return tg.verdict === "SKIP" ? "Test Gate SKIP (verification.integration_tests not configured) on a milestone with an epic" : null;
581
+ }
582
+
506
583
  /** --summary: Phase 8 verdict + summary comment ending in exactly one gate marker kind. Never merges. */
507
584
  async function summary(a, io) {
508
585
  const { c, sd, env, pr, head } = await postContext(a, io);
@@ -516,9 +593,15 @@ async function summary(a, io) {
516
593
  let ciFailing = 1;
517
594
  const ci = await io.run("gh", ["pr", "checks", String(pr), "-R", c.ghRepo, "--json", "name,bucket"], { env, cwd: io.cwd });
518
595
  const checks = ci.code === 0 ? parseChecks(ci.stdout) : null;
519
- if (checks) ciFailing = countFailingChecks(checks);
596
+ let warnings = [];
597
+ if (checks) {
598
+ const read = await requiredChecksRead({ gh: io.gh, repo: c.ghRepo, lane: c.defaultBranch });
599
+ const required = requiredSet(read, c.extraRequiredChecks);
600
+ ({ blocking: ciFailing, warnings } = classifyChecks(checks, required));
601
+ }
520
602
 
521
- const v = stagingVerdict({ ciFailing, testGateInvalid: tg.invalid, confirmedCritical: st.confirmedCritical, confirmedHigh: st.confirmedHigh });
603
+ const acceptanceBlocked = await acceptanceBlock(io, c, pr, tg);
604
+ const v = stagingVerdict({ ciFailing, testGateInvalid: tg.invalid, acceptanceBlocked, confirmedCritical: st.confirmedCritical, confirmedHigh: st.confirmedHigh });
522
605
  const pass = v.verdict === "APPROVE FOR DEPLOY";
523
606
  const marker = pass ? "FORGE:GATE_PASS" : "FORGE:GATE_FAILURE";
524
607
  const bundle = (st.bundle ?? []).join(" ");
@@ -542,9 +625,10 @@ async function summary(a, io) {
542
625
  "### Risk Matrix",
543
626
  "| Domain | Result | Notes |",
544
627
  "|--------|--------|-------|",
545
- `| CI | ${ciFailing > 0 ? "FAIL" : "PASS"} | ${ciFailing} failing required check(s), forgedock/verify, forge/deploy-gate and the gate-marker check excluded |`,
628
+ `| CI | ${ciFailing > 0 ? "FAIL" : "PASS"} | ${ciFailing} failing required check(s), forgedock/verify, forge/deploy-gate and the gate-marker check excluded${warnings.length ? `; ${warnings.length} non-required check(s) red, non-blocking warning: ${warnings.join(", ")}` : ""} |`,
546
629
  `| Findings | ${st.confirmedCritical} CRITICAL / ${st.confirmedHigh} HIGH (CONFIRMED) | per-domain verdicts are in the FORGE:REVIEW-AGENT comments |`,
547
630
  `| **Test Gate** | \`${tg.verdict}\` | \`${tg.reason || "Phase 6.5 not run"}\` |`,
631
+ ...(acceptanceBlocked ? [`| **Feature acceptance** | \`BLOCK\` | ${acceptanceBlocked.replace(/\|/g, "/")} |`] : []),
548
632
  "",
549
633
  (TEST_GATE_NOTE[tg.verdict] ?? TEST_GATE_NOTE.BLOCK)(tg.reason),
550
634
  "",
@@ -570,8 +654,8 @@ async function summary(a, io) {
570
654
  } catch (e) {
571
655
  throw new Stop(1, [`REVIEW_RESULT: status: BLOCKED, blocker: could not post the Phase 8 summary and gate marker (${e.message})`, BLOCK_DEPLOY]);
572
656
  }
573
- if (a.json) io.out(JSON.stringify({ pr, headSha: head, verdict: v.verdict, why: v.why, marker, ciFailing, testGate: tg.verdict, filed: a.filed }));
574
- else io.out([`VERDICT: ${v.verdict} (${v.why})`, `GATE: ${marker} posted on PR #${pr}`, ...(pass ? [] : [BLOCK_DEPLOY])].join("\n"));
657
+ if (a.json) io.out(JSON.stringify({ pr, headSha: head, verdict: v.verdict, why: v.why, marker, ciFailing, warnings, testGate: tg.verdict, filed: a.filed }));
658
+ else io.out([`VERDICT: ${v.verdict} (${v.why})`, ...(warnings.length ? [`WARNING: ${warnings.length} non-required check(s) red, non-blocking: ${warnings.join(", ")}`] : []), `GATE: ${marker} posted on PR #${pr}`, ...(pass ? [] : [BLOCK_DEPLOY])].join("\n"));
575
659
  return pass ? 0 : 1;
576
660
  }
577
661
 
@@ -585,3 +669,26 @@ export async function reviewStagingFromCli(argv, io = defaultIo()) {
585
669
  return 1;
586
670
  }
587
671
  }
672
+
673
+ /** The real io of the CLI, for a library caller that overrides only `out`/`err`/`cwd`/`env` (#5212). */
674
+ export const reviewStagingIo = defaultIo;
675
+
676
+ /**
677
+ * Library entry (#5212): any mode of the CLI, run with `--json`, without printing. Returns `{code, data, lines}`: `data` is the
678
+ * parsed `--json` object (manifest, finalize state or summary; null when the run stopped before printing one) and `lines` the
679
+ * diagnostics a CLI run would have written to stderr, with a stop's reason last. The CLI path is untouched.
680
+ */
681
+ export async function reviewStagingJson(argv, io = defaultIo()) {
682
+ const out = [], lines = [];
683
+ const cap = { ...io, out: (s) => out.push(s), err: (s) => lines.push(s) };
684
+ let code;
685
+ try {
686
+ code = await main([...argv.filter((x) => x !== "--json"), "--json"], cap);
687
+ } catch (e) {
688
+ if (e instanceof Stop) return { code: e.code, data: null, lines: [...lines, ...e.lines] };
689
+ throw e;
690
+ }
691
+ let data = null;
692
+ try { data = JSON.parse(out[out.length - 1]); } catch { /* no object printed */ }
693
+ return { code, data, lines };
694
+ }
@@ -0,0 +1,18 @@
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 { stagingVerdict } from "./review-staging.mjs";
6
+
7
+ const ok = { ciFailing: 0, testGateInvalid: false, confirmedCritical: 0, confirmedHigh: 0 };
8
+
9
+ describe("stagingVerdict feature acceptance (#5336)", () => {
10
+ it("approves without an acceptance block (no epic: unchanged)", () => {
11
+ assert.equal(stagingVerdict(ok).verdict, "APPROVE FOR DEPLOY");
12
+ });
13
+ it("a red/never-run journey or a SKIP test gate on an epic milestone is BLOCK DEPLOY", () => {
14
+ const v = stagingVerdict({ ...ok, acceptanceBlocked: "Test Gate SKIP (verification.integration_tests not configured) on a milestone with an epic" });
15
+ assert.equal(v.verdict, "BLOCK DEPLOY");
16
+ assert.match(v.why, /feature acceptance blocked: Test Gate SKIP/);
17
+ });
18
+ });
package/bin/runner.mjs CHANGED
@@ -2053,6 +2053,10 @@ export function readScopeLimitEvents(pid, { procRoot = "/proc", cgroupRoot = "/s
2053
2053
  const count = (file, key) => { try { return Number((readFileSync(join(cgroupRoot, path, file), "utf8").match(new RegExp(`^${key} (\\d+)`, "m")) ?? [])[1]) || 0; } catch { return 0; } };
2054
2054
  return { tasks: count("pids.events", "max"), memory: count("memory.events", "oom_kill") };
2055
2055
  }
2056
+ /** #5346: tools whose unresolved tool_use means an unapplied change; the context-ceiling kill waits for their result. */
2057
+ const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
2058
+ /** #5346: the ceiling is a hard stop at this multiple even when an edit is still pending (loop guard). */
2059
+ const CONTEXT_HARD_CAP = 1.25;
2056
2060
  /**
2057
2061
  * Async twin of runCliBackend (core work-on live comments): the CLI runs under child_process.spawn so the caller's event
2058
2062
  * loop keeps turning while the session runs. It returns the SAME envelope (and throws the same errors) because the
@@ -2066,6 +2070,7 @@ export function readScopeLimitEvents(pid, { procRoot = "/proc", cgroupRoot = "/s
2066
2070
  * does not count as idle. `onSpawn(child)` receives the ChildProcess.
2067
2071
  * #4390: `contextMax` (stream only; 0 = off) kills the session once one assistant turn's context (input + cache read +
2068
2072
  * cache creation) reaches it, throwing CLI_CONTEXT with the stream-aggregated usage (null when none was seen) and turns.
2073
+ * #5346: the context kill defers while an Edit/Write/MultiEdit/NotebookEdit tool_use has no tool_result yet (hard stop at 1.25x contextMax).
2069
2074
  * #4392: `turnMax` (stream only; 0 = off) kills the session once it has produced that many assistant turns (deduped by
2070
2075
  * message id), throwing CLI_TURNS with `turns`, `turnMax`, `lastTool` and the stream-aggregated usage.
2071
2076
  * #4405: `busy(children)` (info or null) is asked once idle (at most every min(5 s, idleMs)); while it answers busy (a live
@@ -2074,9 +2079,11 @@ export function readScopeLimitEvents(pid, { procRoot = "/proc", cgroupRoot = "/s
2074
2079
  * #4395: a stream result carries `baselineTokens`, the first assistant turn's context; absent when no message was seen.
2075
2080
  * #4410: a stream result (and a CLI_TURNS / CLI_CONTEXT error) carries `toolUses`, [{msg, name, path, cmd}] per tool_use
2076
2081
  * (deduped by tool_use id, capped at TOOL_USES_MAX), for bin/lean/toolstats.mjs; absent on the non-stream path.
2082
+ * #5334: every stream kill (CLI_IDLE, CLI_TIMEOUT, a host kill's CLI_BACKEND_FAILED) carries the usage, `turns` and `toolUses`
2083
+ * seen so far, and `session` (an object the caller owns) gets `snapshot()` -> {usage, turns, toolUses} for the in-flight call.
2077
2084
  */
2078
2085
  export async function runCliBackendAsync(opts) {
2079
- const { spawnFn: _ignored, onSpawn = null, idleMs = 0, maxMs = 0, stream = false, wrap = null, control = null, contextMax = 0, turnMax = 0, busy = null, busyMs = 0, onIdleExtend = null, limitProbe = readScopeLimitEvents, ...rest } = opts;
2086
+ const { spawnFn: _ignored, onSpawn = null, session = null, idleMs = 0, maxMs = 0, stream = false, wrap = null, control = null, contextMax = 0, turnMax = 0, busy = null, busyMs = 0, onIdleExtend = null, limitProbe = readScopeLimitEvents, ...rest } = opts;
2080
2087
  let captured = null;
2081
2088
  try {
2082
2089
  runCliBackend({ ...rest, spawnFn: (bin, args, o) => {
@@ -2106,10 +2113,14 @@ export async function runCliBackendAsync(opts) {
2106
2113
  let collected, idleInfo = null, ctxInfo = null, turnInfo = null;
2107
2114
  const msgUsage = new Map(); // #4390: assistant message id -> its usage (a message spans several stream lines)
2108
2115
  const toolUses = new Map(); // #4410: tool_use id -> {msg, name, path, cmd}
2116
+ const sum = (k) => [...msgUsage.values()].reduce((a, u) => a + toFiniteUsageNumber(u[k]), 0);
2117
+ const streamUsage = () => (msgUsage.size ? { input_tokens: sum("input_tokens"), output_tokens: sum("output_tokens"), cache_creation_input_tokens: sum("cache_creation_input_tokens"), cache_read_input_tokens: sum("cache_read_input_tokens") } : null);
2118
+ if (session) session.snapshot = () => ({ usage: streamUsage(), turns: msgUsage.size, toolUses: [...toolUses.values()] }); // #5334
2109
2119
  try {
2110
2120
  collected = await new Promise((resolveP) => {
2111
2121
  let stdout = "", stderr = "", settled = false, timedOut = false, paused = false;
2112
2122
  let lineBuf = "", resultLine = null, lastTool = null;
2123
+ const pendingEdits = new Set(); let ctxArmed = null; // #5346
2113
2124
  const max = o.maxBuffer ?? DEFAULT_SPAWN_MAX_BUFFER_BYTES;
2114
2125
  const startedAt = Date.now();
2115
2126
  let lastActivity = startedAt, pausedAt = 0, pausedTotal = 0, timer = null, busyAsk = null, extendedSince = null, extendInfo = null;
@@ -2165,10 +2176,15 @@ export async function runCliBackendAsync(opts) {
2165
2176
  if (!line.startsWith("{") || line.length > 4_000_000) return;
2166
2177
  let j; try { j = JSON.parse(line); } catch { return; }
2167
2178
  if (j?.type === "result") resultLine = line;
2168
- else if (j?.type === "assistant" && Array.isArray(j.message?.content)) {
2179
+ else if (j?.type === "user" && Array.isArray(j.message?.content)) {
2180
+ // #5346: a tool_result closes its edit; a ceiling crossed mid-edit stops the session at this safe point
2181
+ for (const c of j.message.content) if (c?.type === "tool_result" && c.tool_use_id) pendingEdits.delete(c.tool_use_id);
2182
+ if (ctxArmed && !pendingEdits.size && !ctxInfo && !turnInfo && !idleInfo && !timedOut) { ctxInfo = { context: ctxArmed.context, lastTool: ctxArmed.lastTool }; kill(); }
2183
+ } else if (j?.type === "assistant" && Array.isArray(j.message?.content)) {
2169
2184
  for (const c of j.message.content) {
2170
2185
  if (c?.type !== "tool_use") continue;
2171
2186
  lastTool = { name: c.name, input: JSON.stringify(c.input ?? {}).slice(0, 200), at: Date.now() };
2187
+ if (EDIT_TOOLS.has(c.name) && c.id) pendingEdits.add(c.id); // #5346: an unapplied edit is not a checkpointable point
2172
2188
  const key = c.id ?? `${j.message.id}#${toolUses.size}`, inp = c.input ?? {};
2173
2189
  if (!toolUses.has(key) && toolUses.size < TOOL_USES_MAX) toolUses.set(key, { msg: j.message.id ?? null, name: c.name ?? null,
2174
2190
  path: typeof (inp.file_path ?? inp.path) === "string" ? (inp.file_path ?? inp.path) : null, cmd: typeof inp.command === "string" ? inp.command.slice(0, 1000) : null });
@@ -2177,7 +2193,11 @@ export async function runCliBackendAsync(opts) {
2177
2193
  if (u && typeof u === "object") {
2178
2194
  msgUsage.set(j.message.id ?? `#${msgUsage.size}`, u);
2179
2195
  const ctx = toFiniteUsageNumber(u.input_tokens) + toFiniteUsageNumber(u.cache_read_input_tokens) + toFiniteUsageNumber(u.cache_creation_input_tokens);
2180
- if (contextMax > 0 && ctx >= contextMax && !ctxInfo && !turnInfo && !idleInfo && !timedOut) { ctxInfo = { context: ctx, lastTool }; kill(); }
2196
+ if (contextMax > 0 && ctx >= contextMax && !ctxInfo && !turnInfo && !idleInfo && !timedOut) {
2197
+ // #5346: never restart mid-edit: wait for the pending edit's tool_result, unless the hard cap (1.25x) is reached
2198
+ if (pendingEdits.size && ctx < contextMax * CONTEXT_HARD_CAP) ctxArmed ??= { context: ctx, lastTool };
2199
+ else { ctxInfo = { context: ctx, lastTool }; kill(); }
2200
+ }
2181
2201
  else if (turnMax > 0 && msgUsage.size >= turnMax && !ctxInfo && !turnInfo && !idleInfo && !timedOut) { turnInfo = { lastTool }; kill(); }
2182
2202
  }
2183
2203
  }
@@ -2200,8 +2220,6 @@ export async function runCliBackendAsync(opts) {
2200
2220
  });
2201
2221
  });
2202
2222
  } finally { if (sysDir) rmSync(sysDir, { recursive: true, force: true }); }
2203
- const sum = (k) => [...msgUsage.values()].reduce((a, u) => a + toFiniteUsageNumber(u[k]), 0);
2204
- const streamUsage = () => (msgUsage.size ? { input_tokens: sum("input_tokens"), output_tokens: sum("output_tokens"), cache_creation_input_tokens: sum("cache_creation_input_tokens"), cache_read_input_tokens: sum("cache_read_input_tokens") } : null);
2205
2223
  if (limitInfo) {
2206
2224
  const err = new Error(`claude CLI lane hit its scope ${limitInfo.limit} limit (${limitInfo.unit}) and was stopped`);
2207
2225
  err.code = "CLI_LANE_LIMIT"; err.limit = limitInfo.limit; err.unit = limitInfo.unit; err.events = limitInfo.events; err.toolUses = [...toolUses.values()];
@@ -2223,9 +2241,15 @@ export async function runCliBackendAsync(opts) {
2223
2241
  const err = new Error(`claude CLI had no stream activity for ${mins} min and was killed (idle${idleInfo.extended ? ", after the busy extension" : ""}). Last tool: ${idleInfo.lastTool ? `${idleInfo.lastTool.name} ${idleInfo.lastTool.input}` : "none"}. Live children: ${idleInfo.children.map((c) => `${c.pid}:${c.cmd}`).join("; ") || "none"}`);
2224
2242
  err.code = "CLI_IDLE"; err.lastTool = idleInfo.lastTool; err.children = idleInfo.children; err.idleMs = idleInfo.idleMs;
2225
2243
  err.extended = idleInfo.extended; err.heavyQueue = idleInfo.heavyQueue;
2244
+ err.usage = streamUsage(); err.turns = msgUsage.size; err.toolUses = [...toolUses.values()]; // #5334
2245
+ throw err;
2246
+ }
2247
+ let r;
2248
+ try { r = runCliBackend({ ...rest, spawnFn: () => collected }); } catch (err) {
2249
+ // #5334: a killed stream (CLI_TIMEOUT, host kill) never reached its result line: keep what the stream showed
2250
+ if (stream && msgUsage.size && err && typeof err === "object") { err.usage ??= streamUsage(); err.turns ??= msgUsage.size; err.toolUses ??= [...toolUses.values()]; }
2226
2251
  throw err;
2227
2252
  }
2228
- const r = runCliBackend({ ...rest, spawnFn: () => collected });
2229
2253
  // #4395: the session baseline is the first assistant turn's context (system prompt, tools, instructions, first prompt).
2230
2254
  const first = msgUsage.values().next().value;
2231
2255
  if (stream && toolUses.size && r && typeof r === "object") r.toolUses = [...toolUses.values()];
@@ -3289,3 +3313,16 @@ export async function runCommand(opts = {}) {
3289
3313
  backend: "api",
3290
3314
  };
3291
3315
  }
3316
+
3317
+ /**
3318
+ * #5334: USD per million tokens by model family [input, output, cache read, cache write], for sessions killed before the
3319
+ * CLI's `result` line (the only place it reports a cost). An estimate: callers flag it `cost_estimated`.
3320
+ */
3321
+ const TOKEN_PRICES = { opus: [15, 75, 1.5, 18.75], sonnet: [3, 15, 0.3, 3.75], haiku: [1, 5, 0.1, 1.25] };
3322
+ export function estimateCostUsd(usage, model = null) {
3323
+ if (!usage || typeof usage !== "object") return null;
3324
+ const fam = /opus|haiku|sonnet/i.exec(String(model ?? ""))?.[0]?.toLowerCase() ?? "sonnet"; // unnamed/"default" model: the middle tier
3325
+ const [i, o, cr, cw] = TOKEN_PRICES[fam];
3326
+ const t = (k) => toFiniteUsageNumber(usage[k]);
3327
+ return Math.round(((t("input_tokens") * i + t("output_tokens") * o + t("cache_read_input_tokens") * cr + t("cache_creation_input_tokens") * cw) / 1e6) * 1e6) / 1e6;
3328
+ }