forgedock 1.53.0 → 1.54.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +51 -0
- package/README.md +8 -2
- package/bin/auth/app-manifest.mjs +89 -0
- package/bin/auth/app-manifest.test.mjs +75 -0
- package/bin/auth/app-token.mjs +258 -0
- package/bin/auth/app-token.test.mjs +240 -0
- package/bin/brand.mjs +7 -0
- package/bin/config-history.mjs +151 -0
- package/bin/config-schema.mjs +115 -0
- package/bin/demo.mjs +65 -11
- package/bin/engine/outcome-codes.mjs +6 -3
- package/bin/engine/telemetry-seam.mjs +8 -2
- package/bin/engine/telemetry-seam.test.mjs +17 -0
- package/bin/engine-cli.mjs +57 -20
- package/bin/first-run.mjs +122 -0
- package/bin/forgedock.mjs +128 -146
- package/bin/help-text.mjs +144 -0
- package/bin/hooks/pre-tool-use.mjs +7 -0
- package/bin/journey.mjs +82 -83
- package/bin/lean/acceptance.mjs +313 -0
- package/bin/lean/acceptance.test.mjs +215 -0
- package/bin/lean/activation.mjs +18 -0
- package/bin/lean/activation.test.mjs +23 -1
- package/bin/lean/batch-health.mjs +74 -1
- package/bin/lean/batch-health.test.mjs +54 -1
- package/bin/lean/batch.test.mjs +11 -9
- package/bin/lean/branchlock.mjs +54 -0
- package/bin/lean/branchlock.test.mjs +49 -0
- package/bin/lean/ceiling.mjs +72 -0
- package/bin/lean/ceiling.test.mjs +54 -0
- package/bin/lean/ci-budget.mjs +366 -0
- package/bin/lean/ci-budget.test.mjs +167 -0
- package/bin/lean/conformance.e2e.test.mjs +7 -0
- package/bin/lean/conformance.mjs +77 -19
- package/bin/lean/conformance.test.mjs +129 -3
- package/bin/lean/context.mjs +35 -6
- package/bin/lean/context.test.mjs +27 -1
- package/bin/lean/depcache.mjs +25 -1
- package/bin/lean/depcache.test.mjs +26 -0
- package/bin/lean/e2e.mjs +18 -2
- package/bin/lean/e2e.test.mjs +26 -1
- package/bin/lean/effects.mjs +40 -11
- package/bin/lean/execution.test.mjs +24 -0
- package/bin/lean/facts.mjs +3 -3
- package/bin/lean/facts.test.mjs +5 -0
- package/bin/lean/fixround.mjs +14 -0
- package/bin/lean/fixround.test.mjs +25 -2
- package/bin/lean/gh-assoc.test.mjs +2 -1
- package/bin/lean/integration.mjs +100 -9
- package/bin/lean/integration.test.mjs +98 -0
- package/bin/lean/issuewatch-parity.mjs +64 -0
- package/bin/lean/issuewatch-parity.test.mjs +127 -0
- package/bin/lean/issuewatch-release.test.mjs +1 -1
- package/bin/lean/issuewatch.mjs +34 -5
- package/bin/lean/issuewatch.test.mjs +3 -2
- package/bin/lean/lean.mjs +316 -74
- package/bin/lean/lean.test.mjs +397 -24
- package/bin/lean/mechfix.mjs +136 -0
- package/bin/lean/mechfix.test.mjs +95 -0
- package/bin/lean/orchestrate.mjs +20 -2
- package/bin/lean/phaseledger.mjs +47 -5
- package/bin/lean/phaseledger.test.mjs +30 -1
- package/bin/lean/precheck.mjs +23 -4
- package/bin/lean/precheck.test.mjs +14 -1
- package/bin/lean/prereq.mjs +28 -0
- package/bin/lean/prereq.test.mjs +20 -0
- package/bin/lean/probe.mjs +4 -2
- package/bin/lean/prodparity.mjs +52 -0
- package/bin/lean/prodparity.test.mjs +67 -0
- package/bin/lean/prompts.mjs +69 -12
- package/bin/lean/recovery.test.mjs +1 -1
- package/bin/lean/release-io.test.mjs +42 -0
- package/bin/lean/release-postmerge.mjs +6 -0
- package/bin/lean/release-preflight.mjs +58 -0
- package/bin/lean/release-preflight.test.mjs +114 -0
- package/bin/lean/release-rehearsal.mjs +8 -7
- package/bin/lean/release-review.mjs +67 -11
- package/bin/lean/release-review.test.mjs +128 -1
- package/bin/lean/release-snapshot.mjs +188 -0
- package/bin/lean/release-snapshot.test.mjs +190 -0
- package/bin/lean/release.mjs +87 -13
- package/bin/lean/release.test.mjs +104 -0
- package/bin/lean/render.mjs +1 -1
- package/bin/lean/replan.mjs +184 -0
- package/bin/lean/replan.test.mjs +110 -0
- package/bin/lean/resume.mjs +9 -7
- package/bin/lean/resume.test.mjs +16 -0
- package/bin/lean/schedd.mjs +34 -1
- package/bin/lean/schedd.test.mjs +21 -1
- package/bin/lean/selfreview.mjs +94 -0
- package/bin/lean/selfreview.test.mjs +58 -1
- package/bin/lean/selftest-gate.mjs +22 -0
- package/bin/lean/selftest-gate.test.mjs +18 -1
- package/bin/lean/selftest-journey.mjs +234 -0
- package/bin/lean/selftest-journey.test.mjs +130 -0
- package/bin/lean/selftest-live.mjs +2 -1
- package/bin/lean/seqlease.mjs +35 -1
- package/bin/lean/seqlease.test.mjs +15 -0
- package/bin/lean/seqreserve.e2e.test.mjs +135 -0
- package/bin/lean/seqreserve.mjs +73 -0
- package/bin/lean/seqreserve.test.mjs +134 -0
- package/bin/lean/sequence.mjs +35 -6
- package/bin/lean/seqversioned.mjs +147 -0
- package/bin/lean/stagestamp.mjs +28 -0
- package/bin/lean/stagestamp.test.mjs +32 -0
- package/bin/lean/surfaces.mjs +75 -0
- package/bin/lean/surfaces.test.mjs +59 -0
- package/bin/lean/toolplace.mjs +28 -0
- package/bin/lean/toolplace.test.mjs +24 -0
- package/bin/lean/toolstats.mjs +3 -1
- package/bin/lean/toolstats.test.mjs +11 -0
- package/bin/lean/validatebest.mjs +28 -0
- package/bin/lean/validatebest.test.mjs +27 -0
- package/bin/pool/agent.mjs +9 -0
- package/bin/pool/docker.mjs +5 -0
- package/bin/pool/router.mjs +8 -4
- package/bin/prereqs.mjs +111 -0
- package/bin/replay-timelapse.mjs +149 -0
- package/bin/review-staging.mjs +100 -16
- package/bin/review-staging.test.mjs +18 -0
- package/bin/runner.mjs +49 -7
- package/bin/splash-install.mjs +157 -0
- package/bin/stats/aggregate.mjs +8 -1
- package/bin/stats/conformance-outcomes.mjs +100 -19
- package/bin/stats/conformance-outcomes.test.mjs +87 -1
- package/bin/stats/depth.mjs +88 -31
- package/bin/stats/depth.test.mjs +63 -38
- package/bin/stats/efficiency.mjs +26 -5
- package/bin/stats/efficiency.test.mjs +45 -1
- package/bin/stats/first-review.mjs +77 -0
- package/bin/stats/first-review.test.mjs +36 -0
- package/bin/stats/firstmerge.mjs +40 -0
- package/bin/stats/firstmerge.test.mjs +41 -0
- package/bin/stats/github-source.mjs +51 -13
- package/bin/stats/index.mjs +91 -15
- package/bin/stats/local-source.mjs +1 -0
- package/bin/stats/origin.mjs +80 -0
- package/bin/stats/origin.test.mjs +58 -0
- package/bin/stats/render.mjs +3 -1
- package/bin/stats/scoreboard.mjs +137 -0
- package/bin/stats/scoreboard.test.mjs +87 -0
- package/bin/stats/stats.test.mjs +80 -0
- package/bin/tui.mjs +3 -2
- package/commands/bootstrap.md +15 -14
- package/commands/deploy-pr.md +18 -3
- package/commands/forge-stats.md +1 -1
- package/commands/forgedock-ci-setup.md +28 -0
- package/commands/forgedock-init.md +4 -5
- package/commands/issue.md +2 -0
- package/commands/milestone.md +9 -1
- package/commands/replay.md +2 -0
- package/commands/review-pr-staging.md +4 -1
- package/commands/work-on/close.md +8 -0
- package/docs/CI.md +1 -1
- package/docs/CONFIG.md +105 -10
- package/docs/ISSUE-WATCH.md +23 -0
- package/docs/OUTCOME-CODES.md +1 -0
- package/docs/REPLAY.md +9 -0
- package/docs/SELFTEST.md +11 -0
- package/docs/STATS.md +19 -2
- package/docs/eval/README.md +6 -0
- package/docs/eval/adversarial-bench.md +68 -0
- package/docs/eval/corpus/adversarial-v1.json +285 -0
- package/docs/eval/feature-bench.md +42 -0
- package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
- package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
- package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
- package/docs/site/start-a-new-project.md +2 -1
- package/package.json +5 -2
- package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
- package/plugins/forgedock-splash/README.md +27 -0
- package/plugins/forgedock-splash/hooks/hooks.json +1 -0
- package/plugins/forgedock-splash/hooks/register.tsx +74 -0
- package/plugins/forgedock-splash/hooks/scene.ts +222 -0
- package/plugins/forgedock-splash/types/index.d.ts +10 -0
- package/scripts/bench-adversarial.mjs +216 -0
- package/scripts/bench-feature.mjs +170 -0
- package/scripts/bench-lightlane.mjs +2 -2
- package/scripts/bootstrap-create.mjs +2 -2
- package/scripts/bootstrap-validate.mjs +35 -2
- package/scripts/check-spec-size.sh +4 -3
- package/scripts/check-spec-size.test.sh +3 -0
- package/scripts/plan-validate-live.mjs +40 -6
- package/scripts/review-pr-staging-scope.test.sh +1 -1
- package/scripts/review-staging-post.sh +23 -0
- 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
|
+
}
|
package/bin/review-staging.mjs
CHANGED
|
@@ -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;
|
|
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
|
|
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
|
-
|
|
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)
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
|
@@ -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
|
@@ -1564,8 +1564,13 @@ export const CLI_ARGV_PROMPT_MAX_BYTES = 64 * 1024;
|
|
|
1564
1564
|
*/
|
|
1565
1565
|
export const CLI_ARGV_PROMPT_MAX_BYTES_WIN32 = 16 * 1024;
|
|
1566
1566
|
|
|
1567
|
-
/**
|
|
1567
|
+
/**
|
|
1568
|
+
* forge#4763: true when the prompt must go over stdin: prompt bytes plus the other argv bytes exceed the platform bound.
|
|
1569
|
+
* Also when the prompt starts with `-` (e.g. a brief opening with `---` front matter): as an argv word the CLI would
|
|
1570
|
+
* parse it as an option and exit 1 ("unknown option '---'").
|
|
1571
|
+
*/
|
|
1568
1572
|
export function promptGoesViaStdin(prompt, otherArgs = [], platform = process.platform) {
|
|
1573
|
+
if (/^\s*-/.test(String(prompt ?? ""))) return true;
|
|
1569
1574
|
const max = platform === "win32" ? CLI_ARGV_PROMPT_MAX_BYTES_WIN32 : CLI_ARGV_PROMPT_MAX_BYTES;
|
|
1570
1575
|
const rest = platform === "win32" ? otherArgs.reduce((n, a) => n + Buffer.byteLength(String(a), "utf-8") + 1, 0) : 0;
|
|
1571
1576
|
return Buffer.byteLength(String(prompt ?? ""), "utf-8") + rest > max;
|
|
@@ -2053,6 +2058,10 @@ export function readScopeLimitEvents(pid, { procRoot = "/proc", cgroupRoot = "/s
|
|
|
2053
2058
|
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
2059
|
return { tasks: count("pids.events", "max"), memory: count("memory.events", "oom_kill") };
|
|
2055
2060
|
}
|
|
2061
|
+
/** #5346: tools whose unresolved tool_use means an unapplied change; the context-ceiling kill waits for their result. */
|
|
2062
|
+
const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
|
|
2063
|
+
/** #5346: the ceiling is a hard stop at this multiple even when an edit is still pending (loop guard). */
|
|
2064
|
+
const CONTEXT_HARD_CAP = 1.25;
|
|
2056
2065
|
/**
|
|
2057
2066
|
* Async twin of runCliBackend (core work-on live comments): the CLI runs under child_process.spawn so the caller's event
|
|
2058
2067
|
* loop keeps turning while the session runs. It returns the SAME envelope (and throws the same errors) because the
|
|
@@ -2066,6 +2075,7 @@ export function readScopeLimitEvents(pid, { procRoot = "/proc", cgroupRoot = "/s
|
|
|
2066
2075
|
* does not count as idle. `onSpawn(child)` receives the ChildProcess.
|
|
2067
2076
|
* #4390: `contextMax` (stream only; 0 = off) kills the session once one assistant turn's context (input + cache read +
|
|
2068
2077
|
* cache creation) reaches it, throwing CLI_CONTEXT with the stream-aggregated usage (null when none was seen) and turns.
|
|
2078
|
+
* #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
2079
|
* #4392: `turnMax` (stream only; 0 = off) kills the session once it has produced that many assistant turns (deduped by
|
|
2070
2080
|
* message id), throwing CLI_TURNS with `turns`, `turnMax`, `lastTool` and the stream-aggregated usage.
|
|
2071
2081
|
* #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 +2084,11 @@ export function readScopeLimitEvents(pid, { procRoot = "/proc", cgroupRoot = "/s
|
|
|
2074
2084
|
* #4395: a stream result carries `baselineTokens`, the first assistant turn's context; absent when no message was seen.
|
|
2075
2085
|
* #4410: a stream result (and a CLI_TURNS / CLI_CONTEXT error) carries `toolUses`, [{msg, name, path, cmd}] per tool_use
|
|
2076
2086
|
* (deduped by tool_use id, capped at TOOL_USES_MAX), for bin/lean/toolstats.mjs; absent on the non-stream path.
|
|
2087
|
+
* #5334: every stream kill (CLI_IDLE, CLI_TIMEOUT, a host kill's CLI_BACKEND_FAILED) carries the usage, `turns` and `toolUses`
|
|
2088
|
+
* seen so far, and `session` (an object the caller owns) gets `snapshot()` -> {usage, turns, toolUses} for the in-flight call.
|
|
2077
2089
|
*/
|
|
2078
2090
|
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;
|
|
2091
|
+
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
2092
|
let captured = null;
|
|
2081
2093
|
try {
|
|
2082
2094
|
runCliBackend({ ...rest, spawnFn: (bin, args, o) => {
|
|
@@ -2106,10 +2118,14 @@ export async function runCliBackendAsync(opts) {
|
|
|
2106
2118
|
let collected, idleInfo = null, ctxInfo = null, turnInfo = null;
|
|
2107
2119
|
const msgUsage = new Map(); // #4390: assistant message id -> its usage (a message spans several stream lines)
|
|
2108
2120
|
const toolUses = new Map(); // #4410: tool_use id -> {msg, name, path, cmd}
|
|
2121
|
+
const sum = (k) => [...msgUsage.values()].reduce((a, u) => a + toFiniteUsageNumber(u[k]), 0);
|
|
2122
|
+
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);
|
|
2123
|
+
if (session) session.snapshot = () => ({ usage: streamUsage(), turns: msgUsage.size, toolUses: [...toolUses.values()] }); // #5334
|
|
2109
2124
|
try {
|
|
2110
2125
|
collected = await new Promise((resolveP) => {
|
|
2111
2126
|
let stdout = "", stderr = "", settled = false, timedOut = false, paused = false;
|
|
2112
2127
|
let lineBuf = "", resultLine = null, lastTool = null;
|
|
2128
|
+
const pendingEdits = new Set(); let ctxArmed = null; // #5346
|
|
2113
2129
|
const max = o.maxBuffer ?? DEFAULT_SPAWN_MAX_BUFFER_BYTES;
|
|
2114
2130
|
const startedAt = Date.now();
|
|
2115
2131
|
let lastActivity = startedAt, pausedAt = 0, pausedTotal = 0, timer = null, busyAsk = null, extendedSince = null, extendInfo = null;
|
|
@@ -2165,10 +2181,15 @@ export async function runCliBackendAsync(opts) {
|
|
|
2165
2181
|
if (!line.startsWith("{") || line.length > 4_000_000) return;
|
|
2166
2182
|
let j; try { j = JSON.parse(line); } catch { return; }
|
|
2167
2183
|
if (j?.type === "result") resultLine = line;
|
|
2168
|
-
else if (j?.type === "
|
|
2184
|
+
else if (j?.type === "user" && Array.isArray(j.message?.content)) {
|
|
2185
|
+
// #5346: a tool_result closes its edit; a ceiling crossed mid-edit stops the session at this safe point
|
|
2186
|
+
for (const c of j.message.content) if (c?.type === "tool_result" && c.tool_use_id) pendingEdits.delete(c.tool_use_id);
|
|
2187
|
+
if (ctxArmed && !pendingEdits.size && !ctxInfo && !turnInfo && !idleInfo && !timedOut) { ctxInfo = { context: ctxArmed.context, lastTool: ctxArmed.lastTool }; kill(); }
|
|
2188
|
+
} else if (j?.type === "assistant" && Array.isArray(j.message?.content)) {
|
|
2169
2189
|
for (const c of j.message.content) {
|
|
2170
2190
|
if (c?.type !== "tool_use") continue;
|
|
2171
2191
|
lastTool = { name: c.name, input: JSON.stringify(c.input ?? {}).slice(0, 200), at: Date.now() };
|
|
2192
|
+
if (EDIT_TOOLS.has(c.name) && c.id) pendingEdits.add(c.id); // #5346: an unapplied edit is not a checkpointable point
|
|
2172
2193
|
const key = c.id ?? `${j.message.id}#${toolUses.size}`, inp = c.input ?? {};
|
|
2173
2194
|
if (!toolUses.has(key) && toolUses.size < TOOL_USES_MAX) toolUses.set(key, { msg: j.message.id ?? null, name: c.name ?? null,
|
|
2174
2195
|
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 +2198,11 @@ export async function runCliBackendAsync(opts) {
|
|
|
2177
2198
|
if (u && typeof u === "object") {
|
|
2178
2199
|
msgUsage.set(j.message.id ?? `#${msgUsage.size}`, u);
|
|
2179
2200
|
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) {
|
|
2201
|
+
if (contextMax > 0 && ctx >= contextMax && !ctxInfo && !turnInfo && !idleInfo && !timedOut) {
|
|
2202
|
+
// #5346: never restart mid-edit: wait for the pending edit's tool_result, unless the hard cap (1.25x) is reached
|
|
2203
|
+
if (pendingEdits.size && ctx < contextMax * CONTEXT_HARD_CAP) ctxArmed ??= { context: ctx, lastTool };
|
|
2204
|
+
else { ctxInfo = { context: ctx, lastTool }; kill(); }
|
|
2205
|
+
}
|
|
2181
2206
|
else if (turnMax > 0 && msgUsage.size >= turnMax && !ctxInfo && !turnInfo && !idleInfo && !timedOut) { turnInfo = { lastTool }; kill(); }
|
|
2182
2207
|
}
|
|
2183
2208
|
}
|
|
@@ -2200,8 +2225,6 @@ export async function runCliBackendAsync(opts) {
|
|
|
2200
2225
|
});
|
|
2201
2226
|
});
|
|
2202
2227
|
} 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
2228
|
if (limitInfo) {
|
|
2206
2229
|
const err = new Error(`claude CLI lane hit its scope ${limitInfo.limit} limit (${limitInfo.unit}) and was stopped`);
|
|
2207
2230
|
err.code = "CLI_LANE_LIMIT"; err.limit = limitInfo.limit; err.unit = limitInfo.unit; err.events = limitInfo.events; err.toolUses = [...toolUses.values()];
|
|
@@ -2223,9 +2246,15 @@ export async function runCliBackendAsync(opts) {
|
|
|
2223
2246
|
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
2247
|
err.code = "CLI_IDLE"; err.lastTool = idleInfo.lastTool; err.children = idleInfo.children; err.idleMs = idleInfo.idleMs;
|
|
2225
2248
|
err.extended = idleInfo.extended; err.heavyQueue = idleInfo.heavyQueue;
|
|
2249
|
+
err.usage = streamUsage(); err.turns = msgUsage.size; err.toolUses = [...toolUses.values()]; // #5334
|
|
2250
|
+
throw err;
|
|
2251
|
+
}
|
|
2252
|
+
let r;
|
|
2253
|
+
try { r = runCliBackend({ ...rest, spawnFn: () => collected }); } catch (err) {
|
|
2254
|
+
// #5334: a killed stream (CLI_TIMEOUT, host kill) never reached its result line: keep what the stream showed
|
|
2255
|
+
if (stream && msgUsage.size && err && typeof err === "object") { err.usage ??= streamUsage(); err.turns ??= msgUsage.size; err.toolUses ??= [...toolUses.values()]; }
|
|
2226
2256
|
throw err;
|
|
2227
2257
|
}
|
|
2228
|
-
const r = runCliBackend({ ...rest, spawnFn: () => collected });
|
|
2229
2258
|
// #4395: the session baseline is the first assistant turn's context (system prompt, tools, instructions, first prompt).
|
|
2230
2259
|
const first = msgUsage.values().next().value;
|
|
2231
2260
|
if (stream && toolUses.size && r && typeof r === "object") r.toolUses = [...toolUses.values()];
|
|
@@ -3289,3 +3318,16 @@ export async function runCommand(opts = {}) {
|
|
|
3289
3318
|
backend: "api",
|
|
3290
3319
|
};
|
|
3291
3320
|
}
|
|
3321
|
+
|
|
3322
|
+
/**
|
|
3323
|
+
* #5334: USD per million tokens by model family [input, output, cache read, cache write], for sessions killed before the
|
|
3324
|
+
* CLI's `result` line (the only place it reports a cost). An estimate: callers flag it `cost_estimated`.
|
|
3325
|
+
*/
|
|
3326
|
+
const TOKEN_PRICES = { opus: [15, 75, 1.5, 18.75], sonnet: [3, 15, 0.3, 3.75], haiku: [1, 5, 0.1, 1.25] };
|
|
3327
|
+
export function estimateCostUsd(usage, model = null) {
|
|
3328
|
+
if (!usage || typeof usage !== "object") return null;
|
|
3329
|
+
const fam = /opus|haiku|sonnet/i.exec(String(model ?? ""))?.[0]?.toLowerCase() ?? "sonnet"; // unnamed/"default" model: the middle tier
|
|
3330
|
+
const [i, o, cr, cw] = TOKEN_PRICES[fam];
|
|
3331
|
+
const t = (k) => toFiniteUsageNumber(usage[k]);
|
|
3332
|
+
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;
|
|
3333
|
+
}
|