forgedock 1.51.0 → 1.53.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/engine/outcome-codes.mjs +3 -0
- package/bin/engine/telemetry-seam.mjs +4 -2
- package/bin/engine-cli.mjs +61 -17
- package/bin/experiment.mjs +58 -6
- package/bin/forge-utils.mjs +6 -2
- package/bin/forgedock.mjs +25 -1
- package/bin/lean/account-watch.mjs +28 -0
- package/bin/lean/account-watch.test.mjs +30 -0
- package/bin/lean/activation.mjs +20 -0
- package/bin/lean/activation.test.mjs +14 -1
- package/bin/lean/basered.mjs +115 -0
- package/bin/lean/basered.test.mjs +66 -0
- package/bin/lean/batch-health.mjs +40 -6
- package/bin/lean/batch-health.test.mjs +34 -1
- package/bin/lean/batch.mjs +41 -2
- package/bin/lean/batch.test.mjs +104 -2
- package/bin/lean/checkpoint-reconcile.mjs +43 -0
- package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
- package/bin/lean/conformance.e2e.test.mjs +1 -1
- package/bin/lean/conformance.mjs +205 -23
- package/bin/lean/conformance.test.mjs +164 -3
- package/bin/lean/context.mjs +27 -17
- package/bin/lean/context.test.mjs +15 -0
- package/bin/lean/effects.mjs +11 -7
- package/bin/lean/execution.mjs +19 -3
- package/bin/lean/execution.test.mjs +39 -0
- package/bin/lean/findinglabel.mjs +16 -0
- package/bin/lean/findinglabel.test.mjs +39 -0
- package/bin/lean/heavy.mjs +6 -3
- package/bin/lean/hostload.mjs +78 -0
- package/bin/lean/hostload.test.mjs +117 -0
- package/bin/lean/hotspots-remote.e2e.test.mjs +71 -0
- package/bin/lean/issuewatch-release.mjs +6 -2
- package/bin/lean/issuewatch-release.test.mjs +16 -0
- package/bin/lean/issuewatch.mjs +11 -1
- package/bin/lean/lanelock.mjs +14 -0
- package/bin/lean/lean.mjs +171 -36
- package/bin/lean/lean.test.mjs +302 -10
- package/bin/lean/light.mjs +48 -7
- package/bin/lean/light.test.mjs +37 -3
- package/bin/lean/limits.test.mjs +142 -9
- package/bin/lean/orchestrate-cancel.test.mjs +143 -0
- package/bin/lean/orchestrate.mjs +110 -26
- package/bin/lean/postdeploy-check.test.mjs +39 -0
- package/bin/lean/prompts.mjs +8 -7
- package/bin/lean/quota.mjs +39 -0
- package/bin/lean/recovery.test.mjs +10 -0
- package/bin/lean/relaxation.mjs +73 -0
- package/bin/lean/relaxation.test.mjs +54 -0
- package/bin/lean/release-postmerge.mjs +119 -0
- package/bin/lean/release-rehearsal.mjs +63 -0
- package/bin/lean/release-rehearsal.test.mjs +93 -0
- package/bin/lean/release-review.e2e.test.mjs +77 -0
- package/bin/lean/release-review.mjs +198 -0
- package/bin/lean/release-review.test.mjs +180 -0
- package/bin/lean/release.mjs +228 -0
- package/bin/lean/release.test.mjs +292 -0
- package/bin/lean/rotator.mjs +150 -31
- package/bin/lean/rotator.test.mjs +105 -2
- package/bin/lean/sandbox-remote.mjs +9 -2
- package/bin/lean/schedd.mjs +56 -6
- package/bin/lean/schedd.test.mjs +108 -6
- package/bin/lean/verifier.mjs +3 -2
- package/bin/lean/verify.mjs +2 -1
- package/bin/lean/verify.test.mjs +6 -0
- package/bin/pool/agent.mjs +18 -4
- package/bin/pool/router.mjs +68 -25
- package/bin/review-staging.mjs +23 -0
- package/bin/stats/conformance-outcomes.mjs +208 -0
- package/bin/stats/conformance-outcomes.test.mjs +188 -0
- package/bin/stats/depth.mjs +218 -0
- package/bin/stats/depth.test.mjs +133 -0
- package/bin/stats/experiment.mjs +7 -5
- package/bin/stats/github-source.mjs +2 -2
- package/bin/stats/index.mjs +64 -2
- package/bin/stats/local-source.mjs +11 -0
- package/bin/stats/query.mjs +69 -0
- package/bin/stats/selffiled.mjs +52 -0
- package/bin/stats/selffiled.test.mjs +71 -0
- package/commands/orchestrate.md +1 -1
- package/commands/review-pr-agents/security.md +4 -0
- package/commands/review-pr-staging.md +2 -0
- package/commands/work-on/build.md +4 -6
- package/docs/CONFIG.md +66 -8
- package/docs/ISSUE-WATCH.md +2 -0
- package/docs/OUTCOME-CODES.md +3 -0
- package/docs/STATS.md +44 -0
- package/docs/TELEMETRY.md +1 -1
- package/package.json +1 -1
- package/pool/README.md +1 -1
- package/pool/image/cs-cred +14 -1
- package/pool/install/install-agent.ps1 +6 -2
- package/scripts/backfill-finding-labels.mjs +50 -0
- package/scripts/backfill-finding-labels.test.mjs +36 -0
- package/scripts/doctor-pipeline-state.sh +21 -6
- package/scripts/file-deferred-followups.sh +60 -238
- package/scripts/file-deferred-followups.test.sh +99 -187
- package/scripts/followup-route.mjs +12 -0
- package/scripts/hotspots.sh +12 -8
- package/scripts/hotspots.test.sh +22 -0
- package/scripts/owner-route-parity.test.sh +17 -1
- package/scripts/prior-attempts.test.mjs +1 -1
- package/scripts/review-pr-side-effects.test.sh +40 -0
|
@@ -0,0 +1,54 @@
|
|
|
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 { analyzeRelaxations, relaxationFailures, relaxationBlock, isRelaxationTestPath } from "./relaxation.mjs";
|
|
6
|
+
import { reviewerPrompt } from "./prompts.mjs";
|
|
7
|
+
import { verifierPrompt } from "./verifier.mjs";
|
|
8
|
+
|
|
9
|
+
const hunk = (file, lines, start = 10) => `diff --git a/${file} b/${file}\n@@ -1,0 +${start},${lines.length} @@\n${lines.map((l) => `+${l}`).join("\n")}\n`;
|
|
10
|
+
const removal = (file, lines) => `diff --git a/${file} b/${file}\n@@ -3,${lines.length} +3,0 @@\n${lines.map((l) => `-${l}`).join("\n")}\n`;
|
|
11
|
+
// modelled on AlterLab #39954: a "thin stub" rescue whose script_redirect class accepts JS cookie challenges
|
|
12
|
+
const RESCUE = hunk("shared/detection/antibot.py", ["def thin_stub_rescue(html):", " if SCRIPT_REDIRECT.search(html): # document.cookie=...; location.href=...", " return True"]);
|
|
13
|
+
const NEG = hunk("tests/test_antibot.py", ["def test_cookie_challenge_not_benign():", " assert not thin_stub_rescue(COOKIE_CHALLENGE)"]);
|
|
14
|
+
const GLOBS = ["shared/detection/**"];
|
|
15
|
+
|
|
16
|
+
describe("#5237 relaxation detector", () => {
|
|
17
|
+
it("replay of #39954: the cookie-challenge acceptance is flagged and blocks without a negative test", () => {
|
|
18
|
+
const a = analyzeRelaxations({ diff: RESCUE, riskPaths: GLOBS });
|
|
19
|
+
assert.ok(a.relaxations.length >= 1);
|
|
20
|
+
assert.equal(a.relaxations[0].file, "shared/detection/antibot.py");
|
|
21
|
+
assert.ok(a.relaxations.some((r) => /return True/.test(r.excerpt)));
|
|
22
|
+
const f = relaxationFailures(a);
|
|
23
|
+
assert.equal(f.length, 1); assert.equal(f[0].code, "conformance.unimplemented"); assert.equal(f[0].kind, "relaxation_untested");
|
|
24
|
+
});
|
|
25
|
+
it("a positive-only test does not satisfy the requirement; a negative test does", () => {
|
|
26
|
+
const pos = hunk("tests/test_antibot.py", ["def test_thin_page_ok():", " assert thin_stub_rescue(THIN_PAGE) is True"]);
|
|
27
|
+
assert.equal(relaxationFailures(analyzeRelaxations({ diff: RESCUE + pos, riskPaths: GLOBS })).length, 1);
|
|
28
|
+
const a = analyzeRelaxations({ diff: RESCUE + NEG, riskPaths: GLOBS });
|
|
29
|
+
assert.ok(a.negatives >= 1); assert.deepEqual(relaxationFailures(a), []);
|
|
30
|
+
});
|
|
31
|
+
it("a removed deny is a relaxation", () => {
|
|
32
|
+
const a = analyzeRelaxations({ diff: removal("shared/detection/rules.py", [" if challenge(html):", " raise Blocked()"]), riskPaths: GLOBS });
|
|
33
|
+
assert.deepEqual(a.relaxations.map((r) => r.class), ["deny_removed"]);
|
|
34
|
+
});
|
|
35
|
+
it("ignores files outside the declared globs, test files, comments, and an empty glob list", () => {
|
|
36
|
+
assert.deepEqual(analyzeRelaxations({ diff: RESCUE, riskPaths: ["billing/**"] }).relaxations, []);
|
|
37
|
+
assert.deepEqual(analyzeRelaxations({ diff: RESCUE, riskPaths: [] }).relaxations, []);
|
|
38
|
+
assert.deepEqual(analyzeRelaxations({ diff: hunk("shared/detection/x.py", ["# return True when benign"]), riskPaths: GLOBS }).relaxations, []);
|
|
39
|
+
assert.deepEqual(analyzeRelaxations({ diff: hunk("shared/detection/test_x.py", [" return True"]), riskPaths: GLOBS }).relaxations, []);
|
|
40
|
+
assert.ok(isRelaxationTestPath("tests/a.py") && isRelaxationTestPath("src/a.test.ts") && !isRelaxationTestPath("src/a.ts"));
|
|
41
|
+
assert.deepEqual(analyzeRelaxations({ diff: "", riskPaths: GLOBS }), { relaxations: [], negatives: 0 });
|
|
42
|
+
});
|
|
43
|
+
it("prompts carry the relaxed hunks; unchanged without relaxations", () => {
|
|
44
|
+
const { relaxations } = analyzeRelaxations({ diff: RESCUE, riskPaths: GLOBS });
|
|
45
|
+
const blk = relaxationBlock(relaxations);
|
|
46
|
+
assert.match(blk, /<relaxation_checks>[\s\S]*antibot\.py:\d+[\s\S]*negative-corpus/);
|
|
47
|
+
const base = { issue: { number: 1, title: "t", body: "b" }, contract: {}, diff: "d", files: ["a"] };
|
|
48
|
+
assert.doesNotMatch(verifierPrompt(base), /relaxation_checks/);
|
|
49
|
+
assert.match(verifierPrompt({ ...base, relaxations }), /<relaxation_checks>/);
|
|
50
|
+
assert.doesNotMatch(reviewerPrompt({ ...base, result: {} }), /relaxation_checks/);
|
|
51
|
+
assert.match(reviewerPrompt({ ...base, result: {}, relaxations }), /<relaxation_checks>/);
|
|
52
|
+
assert.equal(relaxationBlock([]), "");
|
|
53
|
+
});
|
|
54
|
+
});
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Post-merge step of `forgedock release` (#5213, part 3 of #5208): confirm or dispatch the publish run for the merge commit,
|
|
5
|
+
* wait for the published artifact (`release.artifact_check`), then open and merge the version-sync PR (`release.version_sync`).
|
|
6
|
+
* Every wait is bounded (`ctx.config.postMerge` overrides the bounds) and ends in `{blocked}`, never a throw, so a resume
|
|
7
|
+
* retries the step; each sub-step is idempotent (an existing run, PR or merged PR is reused). Rationale:
|
|
8
|
+
* devdocs/decisions/5208-release-postmerge.md.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const BOUNDS = {
|
|
12
|
+
publishPolls: 6, publishPollMs: 10_000, // wait for a run to appear (bot merges never trigger one)
|
|
13
|
+
runPolls: 90, runPollMs: 20_000, // wait for the run to finish
|
|
14
|
+
artifactTries: 8, artifactBaseMs: 5_000, artifactMaxMs: 120_000, // npm propagation: exponential backoff
|
|
15
|
+
branchPolls: 6, branchPollMs: 10_000, // wait for the sync branch to be pushed
|
|
16
|
+
checkPolls: 30, checkPollMs: 20_000, // wait for the sync PR's checks
|
|
17
|
+
};
|
|
18
|
+
const json = (s) => JSON.parse(String(s || "null"));
|
|
19
|
+
const blocked = (reason) => ({ blocked: true, reason });
|
|
20
|
+
const GREEN = new Set(["SUCCESS", "NEUTRAL", "SKIPPED"]);
|
|
21
|
+
|
|
22
|
+
async function findRun({ io, repo, workflow, sha }) {
|
|
23
|
+
const runs = json(await io.gh(["run", "list", "--repo", repo, "--workflow", workflow, "--commit", sha, "--json", "databaseId,status,conclusion", "--limit", "5"])) ?? [];
|
|
24
|
+
return runs[0] ?? null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Poll `fn` until it returns a truthy value, at most `polls` times, sleeping `ms` between tries. */
|
|
28
|
+
async function poll(io, polls, ms, fn) {
|
|
29
|
+
for (let i = 0; i < polls; i++) {
|
|
30
|
+
const v = await fn();
|
|
31
|
+
if (v) return v;
|
|
32
|
+
if (i < polls - 1) await io.sleep(ms);
|
|
33
|
+
}
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function publishRun(ctx, sha, b) {
|
|
38
|
+
const { io, repo, config } = ctx;
|
|
39
|
+
const workflow = config.publishWorkflow || "publish.yml";
|
|
40
|
+
const look = () => findRun({ io, repo, workflow, sha });
|
|
41
|
+
let run = await poll(io, b.publishPolls, b.publishPollMs, look);
|
|
42
|
+
let dispatched = false;
|
|
43
|
+
if (!run) {
|
|
44
|
+
await io.gh(["workflow", "run", workflow, "--repo", repo, "--ref", ctx.def]);
|
|
45
|
+
dispatched = true;
|
|
46
|
+
run = await poll(io, b.publishPolls, b.publishPollMs, look);
|
|
47
|
+
if (!run) return { err: `no ${workflow} run for ${sha.slice(0, 8)} after a dispatch on ${ctx.def}; check the Actions tab, then resume` };
|
|
48
|
+
}
|
|
49
|
+
const done = await poll(io, b.runPolls, b.runPollMs, async () => { const r = await look(); return r?.status === "completed" ? r : null; });
|
|
50
|
+
if (!done) return { err: `${workflow} run ${run.databaseId} did not finish in time; resume to keep waiting` };
|
|
51
|
+
if (done.conclusion !== "success") return { err: `${workflow} run ${done.databaseId} concluded ${done.conclusion}` };
|
|
52
|
+
return { run: done.databaseId, dispatched };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function artifact(ctx, b) {
|
|
56
|
+
const { io, config } = ctx;
|
|
57
|
+
let wait = b.artifactBaseMs;
|
|
58
|
+
for (let i = 0; i < b.artifactTries; i++) {
|
|
59
|
+
if ((await io.run(config.artifactCheck)).ok) return { ok: true, tries: i + 1 };
|
|
60
|
+
if (i < b.artifactTries - 1) { await io.sleep(wait); wait = Math.min(wait * 2, b.artifactMaxMs); }
|
|
61
|
+
}
|
|
62
|
+
return { err: `release.artifact_check still failing after ${b.artifactTries} tries: ${config.artifactCheck}` };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function versionSync(ctx, sha, b) {
|
|
66
|
+
const { io, repo, staging } = ctx;
|
|
67
|
+
const pkg = JSON.parse(Buffer.from(String(await io.gh(["api", `repos/${repo}/contents/package.json?ref=${sha}`, "--jq", ".content"])).replace(/\s/g, ""), "base64").toString("utf8"));
|
|
68
|
+
const branch = `chore/sync-version-${pkg.version}`;
|
|
69
|
+
const find = async () => json(await io.gh(["pr", "list", "--repo", repo, "--base", staging, "--head", branch, "--state", "all", "--json", "number,state", "--limit", "1"]))?.[0] ?? null;
|
|
70
|
+
let pr = await find();
|
|
71
|
+
if (pr?.state === "MERGED") return { pr: pr.number, merged: true, reused: true };
|
|
72
|
+
if (!pr) {
|
|
73
|
+
const has = await poll(io, b.branchPolls, b.branchPollMs, async () => { try { await io.gh(["api", `repos/${repo}/branches/${branch}`, "--jq", ".name"]); return true; } catch { return false; } });
|
|
74
|
+
if (!has) return { err: `version-sync branch ${branch} did not appear; publish.yml may have skipped the sync, open it by hand` };
|
|
75
|
+
const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", staging, "--head", branch, "--title", `chore: sync version ${pkg.version} to ${staging}`, "--body", `Version-only sync of the ${pkg.version} release back to ${staging} (forgedock release).`])).trim();
|
|
76
|
+
const n = Number(/\/pull\/(\d+)/.exec(url)?.[1]);
|
|
77
|
+
if (!Number.isSafeInteger(n)) return { err: `gh pr create returned no PR url: ${url}` };
|
|
78
|
+
pr = { number: n };
|
|
79
|
+
}
|
|
80
|
+
let red = null;
|
|
81
|
+
const green = await poll(io, b.checkPolls, b.checkPollMs, async () => {
|
|
82
|
+
const v = json(await io.gh(["pr", "view", String(pr.number), "--repo", repo, "--json", "state,headRefOid,statusCheckRollup"]));
|
|
83
|
+
if (v?.state === "MERGED") return { head: null, already: true };
|
|
84
|
+
const res = (v?.statusCheckRollup ?? []).map((c) => String(c.conclusion || c.state || "").toUpperCase());
|
|
85
|
+
if (res.some((r) => r && !GREEN.has(r) && !["PENDING", "IN_PROGRESS", "QUEUED", "EXPECTED"].includes(r))) { red = res.find((r) => r && !GREEN.has(r) && !["PENDING", "IN_PROGRESS", "QUEUED", "EXPECTED"].includes(r)); return { red: true }; }
|
|
86
|
+
return res.length && res.every((r) => GREEN.has(r)) ? { head: v.headRefOid } : null;
|
|
87
|
+
});
|
|
88
|
+
if (green?.already) return { pr: pr.number, merged: true };
|
|
89
|
+
if (green?.red) return { err: `version-sync PR #${pr.number} has a failing check (${red}); fix and merge it by hand` };
|
|
90
|
+
// GITHUB_TOKEN PRs get no CI, so "no checks" is a stop, not a green light.
|
|
91
|
+
if (!green) return { err: `version-sync PR #${pr.number} has no passing checks yet (a PR opened by GITHUB_TOKEN gets no CI: close and reopen it); resume once green` };
|
|
92
|
+
await io.gh(["pr", "merge", String(pr.number), "--repo", repo, "--merge", "--match-head-commit", green.head]);
|
|
93
|
+
return { pr: pr.number, merged: true };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** @returns {Promise<{published, run, artifact, sync}|{blocked: true, reason: string}|{stopped: true, why: string}>} */
|
|
97
|
+
export async function postMergeStep(ctx) {
|
|
98
|
+
const { io, repo, state, config = {} } = ctx;
|
|
99
|
+
const b = { ...BOUNDS, ...(config.postMerge ?? {}) };
|
|
100
|
+
const pr = state.steps["release-pr"].result.pr;
|
|
101
|
+
const view = json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "state,mergeCommit"]));
|
|
102
|
+
const sha = view?.mergeCommit?.oid;
|
|
103
|
+
if (view?.state !== "MERGED" || !sha) return { stopped: true, why: `release PR #${pr} is not merged (${view?.state ?? "unknown"}); nothing to publish yet` };
|
|
104
|
+
|
|
105
|
+
const pub = await publishRun(ctx, sha, b);
|
|
106
|
+
if (pub.err) return blocked(pub.err);
|
|
107
|
+
let art = null;
|
|
108
|
+
if (config.artifactCheck) {
|
|
109
|
+
art = await artifact(ctx, b);
|
|
110
|
+
if (art.err) return blocked(art.err);
|
|
111
|
+
}
|
|
112
|
+
let sync = null;
|
|
113
|
+
if (config.versionSync) {
|
|
114
|
+
sync = await versionSync(ctx, sha, b);
|
|
115
|
+
if (sync.err) return blocked(sync.err);
|
|
116
|
+
}
|
|
117
|
+
io.print(`release: published (run ${pub.run}${pub.dispatched ? ", dispatched" : ""})${art ? ", artifact confirmed" : ""}${sync ? `, version-sync PR #${sync.pr} merged` : ""}`);
|
|
118
|
+
return { published: true, merge: sha, run: pub.run, dispatched: pub.dispatched, artifact: art?.ok ?? null, sync };
|
|
119
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Rehearsal step of `forgedock release` (#5253): runs the project's own deploy dry-run (forge.yaml `release.rehearsal`) on the
|
|
5
|
+
* host against the release-PR head, after review and before promotion. A failing blocking rehearsal files (or updates) one
|
|
6
|
+
* `release-blocker` issue per head and stops the job like a GATE_FAILURE; `--resume` re-runs it. The result is recorded in the
|
|
7
|
+
* release state and in a FORGE:REHEARSAL section of the release PR body. No model call. Effects go through `ctx.io`.
|
|
8
|
+
*/
|
|
9
|
+
export const REHEARSAL_TIMEOUT_MS = 20 * 60_000;
|
|
10
|
+
export const OUTPUT_TAIL_CHARS = 6000;
|
|
11
|
+
export const BLOCKER_LABEL = "release-blocker";
|
|
12
|
+
const PR_START = "<!-- FORGE:REHEARSAL -->", PR_END = "<!-- /FORGE:REHEARSAL -->";
|
|
13
|
+
const json = (s) => JSON.parse(String(s || "null"));
|
|
14
|
+
const off = (v) => ["false", "off", "no", "0"].includes(String(v ?? "").trim().toLowerCase());
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The rehearsal keys of forge.yaml's `release` map -> `{command, timeoutMs, blocking}`, or null when no command is set. The
|
|
18
|
+
* forge.yaml parser reads two levels, so the block is the flat keys `rehearsal_command`, `rehearsal_timeout` (seconds) and
|
|
19
|
+
* `rehearsal_blocking`.
|
|
20
|
+
*/
|
|
21
|
+
export function parseRehearsalConfig(r) {
|
|
22
|
+
const command = typeof r?.rehearsal_command === "string" ? r.rehearsal_command.trim() : "";
|
|
23
|
+
if (!command) return null;
|
|
24
|
+
const secs = Number(r.rehearsal_timeout);
|
|
25
|
+
return { command, timeoutMs: Number.isFinite(secs) && secs > 0 ? secs * 1000 : REHEARSAL_TIMEOUT_MS, blocking: !off(r.rehearsal_blocking) };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const tail = (s) => { const t = String(s ?? ""); return t.length > OUTPUT_TAIL_CHARS ? `…${t.slice(-OUTPUT_TAIL_CHARS)}` : t; };
|
|
29
|
+
const marker = (head) => `<!-- FORGE:RELEASE_BLOCKER head=${head} -->`;
|
|
30
|
+
|
|
31
|
+
const prSection = (res) => `${PR_START}\n**Rehearsal**: ${res.ok ? "PASS" : res.blocking ? "FAIL (promotion held)" : "FAIL (non-blocking)"} at \`${res.head}\` — \`${res.command}\`${res.issue ? ` (#${res.issue})` : ""}\n${PR_END}`;
|
|
32
|
+
|
|
33
|
+
async function recordInPr({ io, repo, pr }, res) {
|
|
34
|
+
const body = String(json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "body"]))?.body ?? "");
|
|
35
|
+
const a = body.indexOf(PR_START), b = body.indexOf(PR_END);
|
|
36
|
+
const base = a >= 0 && b > a ? (body.slice(0, a) + body.slice(b + PR_END.length)).trimEnd() : body.trimEnd();
|
|
37
|
+
await io.gh(["pr", "edit", String(pr), "--repo", repo, "--body", `${base}\n\n${prSection(res)}\n`]);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** One open release-blocker issue per head: comment on it when it exists, else create it. @returns the issue number. */
|
|
41
|
+
async function fileBlocker({ io, repo, pr }, res) {
|
|
42
|
+
const text = `Release rehearsal failed on PR #${pr} at head \`${res.head}\`.\n\nCommand: \`${res.command}\` (exit ${res.code ?? "?"}${res.timedOut ? ", timed out" : ""})\n\n\`\`\`\n${tail(res.output)}\n\`\`\`\n`;
|
|
43
|
+
const open = json(await io.gh(["issue", "list", "--repo", repo, "--label", BLOCKER_LABEL, "--state", "open", "--limit", "100", "--json", "number,body"])) ?? [];
|
|
44
|
+
const found = open.find((i) => String(i.body ?? "").includes(marker(res.head)));
|
|
45
|
+
if (found) { await io.gh(["issue", "comment", String(found.number), "--repo", repo, "--body", text]); return found.number; }
|
|
46
|
+
const url = String(await io.gh(["issue", "create", "--repo", repo, "--label", BLOCKER_LABEL, "--title", `release-blocker: rehearsal failed at ${res.head.slice(0, 12)}`, "--body", `${marker(res.head)}\n${text}`])).trim();
|
|
47
|
+
return Number(/\/issues\/(\d+)/.exec(url)?.[1]) || null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function rehearsalStep(ctx) {
|
|
51
|
+
const { io, repo, config } = ctx;
|
|
52
|
+
const cfg = config.rehearsal;
|
|
53
|
+
if (!cfg) return { skipped: true };
|
|
54
|
+
const { pr } = ctx.state.steps["release-pr"].result;
|
|
55
|
+
const head = json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "headRefOid"]))?.headRefOid;
|
|
56
|
+
const run = await io.rehearse(cfg.command, { timeout: cfg.timeoutMs });
|
|
57
|
+
const res = { ok: !!run.ok, head, command: cfg.command, blocking: cfg.blocking, code: run.code ?? null, timedOut: !!run.timedOut, output: run.ok ? "" : tail(run.output), at: new Date(io.now()).toISOString() };
|
|
58
|
+
if (!res.ok) res.issue = await fileBlocker({ io, repo, pr }, res);
|
|
59
|
+
await recordInPr({ io, repo, pr }, res);
|
|
60
|
+
const { output, ...kept } = res;
|
|
61
|
+
if (!res.ok && res.blocking) return { stopped: true, why: `release rehearsal failed at ${head} (release-blocker #${res.issue}); fix it, then resume`, ...kept };
|
|
62
|
+
return kept;
|
|
63
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
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 { tmpDir } from "../tests/_tmp.mjs";
|
|
6
|
+
import { runRelease, withStubs, newReleaseId, readReleaseConfig, openRelease } from "./release.mjs";
|
|
7
|
+
import { parseRehearsalConfig } from "./release-rehearsal.mjs";
|
|
8
|
+
|
|
9
|
+
const DISK = [{ mount: "/", type: "ext4" }];
|
|
10
|
+
const REPO = "o/r", HEAD = "b".repeat(40);
|
|
11
|
+
const ok = async () => ({ ok: true });
|
|
12
|
+
|
|
13
|
+
function fakeIo({ run = { ok: true }, issues = [], body = "Bundle" } = {}) {
|
|
14
|
+
const calls = [], rehearsed = [];
|
|
15
|
+
const st = { issues: [...issues], body };
|
|
16
|
+
const io = {
|
|
17
|
+
calls, rehearsed, st, now: () => 1_700_000_000_000, print: () => {},
|
|
18
|
+
runningLanes: async () => [], batches: async () => [], setParallel: async () => {},
|
|
19
|
+
rehearse: async (cmd, o) => { rehearsed.push([cmd, o]); return run; },
|
|
20
|
+
gh: async (a) => {
|
|
21
|
+
calls.push(a); const j = a.join(" ");
|
|
22
|
+
if (a[0] === "pr" && a[1] === "list" && a.includes("open")) return JSON.stringify(a.includes("--head") ? [{ number: 7, headRefOid: HEAD, url: "u" }] : []);
|
|
23
|
+
if (j.includes("headRefOid")) return JSON.stringify({ headRefOid: HEAD });
|
|
24
|
+
if (j.includes("--json comments")) return JSON.stringify({ comments: [{ body: "FORGE:GATE_PASS" }] });
|
|
25
|
+
if (a[0] === "api") return JSON.stringify([{ name: "forge/deploy-gate", conclusion: "success" }]);
|
|
26
|
+
if (j.includes("--json body")) return JSON.stringify({ body: st.body });
|
|
27
|
+
if (a[0] === "pr" && a[1] === "edit") { st.body = a[a.indexOf("--body") + 1]; return ""; }
|
|
28
|
+
if (a[0] === "pr" && a[1] === "merge") return "";
|
|
29
|
+
if (a[0] === "issue" && a[1] === "list") return JSON.stringify(st.issues);
|
|
30
|
+
if (a[0] === "issue" && a[1] === "create") { st.issues.push({ number: 42, body: a[a.indexOf("--body") + 1] }); return "https://github.com/o/r/issues/42"; }
|
|
31
|
+
if (a[0] === "issue" && a[1] === "comment") return "";
|
|
32
|
+
throw new Error(`unexpected gh ${j}`);
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
return io;
|
|
36
|
+
}
|
|
37
|
+
const go = async (io, config, root = tmpDir("rehearsal-"), id = newReleaseId()) => ({
|
|
38
|
+
out: await runRelease({ io, repo: REPO, root, mounts: DISK, id, opts: { merge: true }, config, branches: { staging: "staging", default: "main" }, steps: withStubs({ review: ok, fixes: ok, "post-merge": ok }) }),
|
|
39
|
+
root, id,
|
|
40
|
+
});
|
|
41
|
+
const cfg = (o = {}) => ({ rehearsal: parseRehearsalConfig({ rehearsal_command: "./dry-run.sh", ...o }) });
|
|
42
|
+
|
|
43
|
+
describe("release rehearsal (#5253)", () => {
|
|
44
|
+
it("unconfigured: no rehearse, no issue/PR-body calls, promotion merges", async () => {
|
|
45
|
+
const io = fakeIo();
|
|
46
|
+
const { out } = await go(io, {});
|
|
47
|
+
assert.equal(out.status, "done");
|
|
48
|
+
assert.equal(io.rehearsed.length, 0);
|
|
49
|
+
assert.ok(!io.calls.some((a) => a[0] === "issue" || (a[0] === "pr" && a[1] === "edit")));
|
|
50
|
+
assert.ok(io.calls.some((a) => a[0] === "pr" && a[1] === "merge"));
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it("failing rehearsal holds promotion and files one blocker with output and head; a rerun comments", async () => {
|
|
54
|
+
const io = fakeIo({ run: { ok: false, code: 2, output: "bundle missing incident files" } });
|
|
55
|
+
const { out, root, id } = await go(io, cfg());
|
|
56
|
+
assert.equal(out.status, "stopped"); assert.equal(out.step, "rehearsal");
|
|
57
|
+
assert.ok(!io.calls.some((a) => a[0] === "pr" && a[1] === "merge"));
|
|
58
|
+
const creates = io.calls.filter((a) => a[0] === "issue" && a[1] === "create");
|
|
59
|
+
assert.equal(creates.length, 1);
|
|
60
|
+
const body = creates[0][creates[0].indexOf("--body") + 1];
|
|
61
|
+
assert.ok(body.includes("bundle missing incident files") && body.includes(HEAD));
|
|
62
|
+
assert.ok(creates[0].includes("release-blocker"));
|
|
63
|
+
assert.match(io.st.body, /Rehearsal\*\*: FAIL/);
|
|
64
|
+
assert.equal(openRelease(root, id).load().steps.rehearsal.result.head, HEAD);
|
|
65
|
+
await go(io, cfg(), root, id);
|
|
66
|
+
assert.equal(io.calls.filter((a) => a[0] === "issue" && a[1] === "create").length, 1);
|
|
67
|
+
assert.equal(io.calls.filter((a) => a[0] === "issue" && a[1] === "comment").length, 1);
|
|
68
|
+
assert.equal((io.st.body.match(/<!-- FORGE:REHEARSAL -->/g) ?? []).length, 1);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("blocking:false records the failure and still promotes", async () => {
|
|
72
|
+
const io = fakeIo({ run: { ok: false, code: 1, output: "x" } });
|
|
73
|
+
const { out } = await go(io, cfg({ rehearsal_blocking: "false" }));
|
|
74
|
+
assert.equal(out.status, "done");
|
|
75
|
+
assert.match(io.st.body, /non-blocking/);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it("passing rehearsal is recorded in state and PR body, then promotes; timeout is passed in ms", async () => {
|
|
79
|
+
const io = fakeIo();
|
|
80
|
+
const { out, root, id } = await go(io, cfg({ rehearsal_timeout: "30" }));
|
|
81
|
+
assert.equal(out.status, "done");
|
|
82
|
+
assert.equal(io.rehearsed[0][1].timeout, 30_000);
|
|
83
|
+
const r = openRelease(root, id).load().steps.rehearsal;
|
|
84
|
+
assert.ok(r.done && r.result.ok && r.result.head === HEAD);
|
|
85
|
+
assert.match(io.st.body, /Rehearsal\*\*: PASS/);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("config parsing", () => {
|
|
89
|
+
assert.ok(!("rehearsal" in readReleaseConfig("")));
|
|
90
|
+
assert.equal(parseRehearsalConfig({ rehearsal_command: " " }), null);
|
|
91
|
+
assert.deepEqual(readReleaseConfig("release:\n rehearsal_command: ./d.sh\n rehearsal_timeout: 60\n rehearsal_blocking: false\n").rehearsal, { command: "./d.sh", timeoutMs: 60000, blocking: false });
|
|
92
|
+
});
|
|
93
|
+
});
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* End-to-end run of `forgedock release` through the real job (preflight, release-pr, review, fixes, promotion) against an
|
|
5
|
+
* in-memory GitHub (#5212, R1): the release PR exists, the panel runs, a HIGH finding is filed and blocks, a fix lane merges
|
|
6
|
+
* to staging, the delta review passes, and the job stops at GATE_PASS with the merge command, with no manual step. GitHub, the
|
|
7
|
+
* model and the lane process are in memory (as in conformance.e2e.test.mjs); the job, steps, state and resume are real.
|
|
8
|
+
*/
|
|
9
|
+
import { describe, it } from "node:test";
|
|
10
|
+
import assert from "node:assert/strict";
|
|
11
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
12
|
+
import { runRelease, newReleaseId, openRelease } from "./release.mjs";
|
|
13
|
+
|
|
14
|
+
const DISK = [{ mount: "/", type: "ext4" }];
|
|
15
|
+
const sha = (n) => String(n).padStart(40, "a");
|
|
16
|
+
|
|
17
|
+
/** In-memory GitHub + panel: one release PR whose head is a counter; comments are the register. */
|
|
18
|
+
function world() {
|
|
19
|
+
const w = { head: 1, comments: [], issues: [], lanes: [], printed: [], fixed: false, agents: [], launched: [] };
|
|
20
|
+
const io = {
|
|
21
|
+
now: () => 1_700_000_000_000, print: (l) => w.printed.push(l),
|
|
22
|
+
runningLanes: async () => [], batches: async () => [], setParallel: async () => {},
|
|
23
|
+
gh: async (a) => {
|
|
24
|
+
const j = a.join(" ");
|
|
25
|
+
if (a[0] === "pr" && a[1] === "list") return JSON.stringify(a.includes("--head") && a[a.indexOf("--state") + 1] === "open" ? [{ number: 7, headRefOid: sha(w.head), url: "u" }] : []);
|
|
26
|
+
if (j.includes("headRefOid")) return JSON.stringify({ headRefOid: sha(w.head) });
|
|
27
|
+
if (j.includes("--json comments")) return JSON.stringify({ comments: w.comments.map((body) => ({ body })) });
|
|
28
|
+
if (a[0] === "api") return JSON.stringify([{ name: "forge/deploy-gate", conclusion: "success" }]);
|
|
29
|
+
throw new Error(`unexpected gh ${j}`);
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
io.review = {
|
|
33
|
+
pre: async ({ delta }) => ({ code: 0, lines: [], data: { pr: 7, headSha: sha(w.head), bundle: [1, 2], scopeMode: "full", contextFile: "/sd/ctx.json", launchedFile: "/sd/l", briefs: [{ domain: "security", path: "/sd/b" }], delta: delta ? { from: delta, files: ["f"] } : null } }),
|
|
34
|
+
headOf: async () => sha(w.head),
|
|
35
|
+
readFile: () => "brief",
|
|
36
|
+
markLaunched: (_f, domains) => { w.launched = domains; },
|
|
37
|
+
saveTestGate: () => "/sd/gate.txt",
|
|
38
|
+
runAgent: async ({ role }) => { w.agents.push(role); return { text: "FORGE:TEST_GATE:RESULT=PASS" }; },
|
|
39
|
+
finalize: async () => ({ code: 0, lines: [], data: { head: sha(w.head), notes: ["- nit"], toFile: w.fixed ? [] : [{ title: "leak", severity: "HIGH" }] } }),
|
|
40
|
+
fileIssue: async ({ item }) => { w.issues.push(item.title); return 100 + w.issues.length; },
|
|
41
|
+
fileCiIssue: async () => 999,
|
|
42
|
+
addNotes: async () => {},
|
|
43
|
+
summary: async ({ filed }) => {
|
|
44
|
+
const pass = w.fixed;
|
|
45
|
+
w.comments.push(pass ? "<!-- FORGE:GATE_PASS -->" : "<!-- FORGE:GATE_FAILURE -->");
|
|
46
|
+
return { code: pass ? 0 : 1, lines: [], data: { verdict: pass ? "APPROVE FOR DEPLOY" : "BLOCK DEPLOY", marker: pass ? "FORGE:GATE_PASS" : "FORGE:GATE_FAILURE", ciFailing: 0, filed } };
|
|
47
|
+
},
|
|
48
|
+
runLane: async ({ issue, lane }) => { w.lanes.push([issue, lane]); w.fixed = true; w.head++; return { terminalReason: "merged" }; },
|
|
49
|
+
};
|
|
50
|
+
return { w, io };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
describe("forgedock release, review to gate (e2e on in-memory GitHub)", () => {
|
|
54
|
+
it("reviews, files the blocking finding, fixes it on staging, re-reviews the delta and stops at GATE_PASS with the merge command", async () => {
|
|
55
|
+
const { w, io } = world();
|
|
56
|
+
const out = await runRelease({ io, repo: "o/r", root: tmpDir("rel-e2e-"), mounts: DISK, id: newReleaseId(), opts: {}, config: {}, branches: { staging: "staging", default: "main" } });
|
|
57
|
+
assert.equal(out.status, "stopped");
|
|
58
|
+
assert.equal(out.step, "promotion");
|
|
59
|
+
assert.match(out.reason, /GATE_PASS/);
|
|
60
|
+
assert.deepEqual(w.issues, ["leak"], "the finding was filed");
|
|
61
|
+
assert.deepEqual(w.lanes, [[101, "staging"]], "one fix lane on the staging branch");
|
|
62
|
+
assert.deepEqual(w.comments, ["<!-- FORGE:GATE_FAILURE -->", "<!-- FORGE:GATE_PASS -->"], "failure at the first head, pass after the delta review");
|
|
63
|
+
assert.ok(w.agents.includes("release-review-security") && w.agents.includes("release-review-regression-risk") && w.agents.includes("release-test-gate"), "the full panel ran");
|
|
64
|
+
assert.ok(w.printed.some((l) => l.includes(`--match-head-commit ${sha(2)}`)), "merge command at the fixed head");
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it("a killed job resumes after the review step without re-running it", async () => {
|
|
68
|
+
const { w, io } = world();
|
|
69
|
+
const root = tmpDir("rel-e2e-"), id = newReleaseId();
|
|
70
|
+
const args = { io, repo: "o/r", root, mounts: DISK, id, opts: {}, config: {}, branches: { staging: "staging", default: "main" } };
|
|
71
|
+
await runRelease(args);
|
|
72
|
+
const agents = w.agents.length;
|
|
73
|
+
assert.equal(openRelease(root, id, DISK).load().steps.fixes.done, true);
|
|
74
|
+
await runRelease(args);
|
|
75
|
+
assert.equal(w.agents.length, agents, "review and fixes are done: nothing re-dispatched");
|
|
76
|
+
});
|
|
77
|
+
});
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Review and fix steps of `forgedock release` (#5208 part 2, #5212). `reviewStep` runs the staging panel the way an operator
|
|
5
|
+
* session would (commands/review-pr-staging.md) but as one job: pre-dispatch, one isolated runner session per brief plus the
|
|
6
|
+
* spec-owned panel, the /test-gate output, a head check (a moved head is a `--delta` pass, never a finalize), finalize with
|
|
7
|
+
* one re-ask of reviewers whose findings block is missing, filing, NOTEs in the PR body, then `--summary`. `fixStep` starts a
|
|
8
|
+
* fix lane per blocking finding on the staging branch and re-reviews the delta, bounded like lanes. Every effect goes through
|
|
9
|
+
* a seam (`ctx.io.review`, default `realSeam`) so the steps are unit-tested without gh, git or a model.
|
|
10
|
+
*/
|
|
11
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
12
|
+
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, appendFileSync, rmSync } from "node:fs";
|
|
13
|
+
import { tmpdir } from "node:os";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
16
|
+
import { reviewStagingJson, reviewStagingIo, CI_EXCLUDED_CHECKS } from "../review-staging.mjs";
|
|
17
|
+
|
|
18
|
+
/** Delta passes after a head move, and fix-lane rounds: past either the job blocks for the manual path. */
|
|
19
|
+
export const MAX_DELTA_PASSES = 2;
|
|
20
|
+
export const MAX_FIX_ROUNDS = 2;
|
|
21
|
+
const REVIEW_MS = 45 * 60_000, LANE_MS = 3 * 60 * 60_000;
|
|
22
|
+
const ROOT = fileURLToPath(new URL("../..", import.meta.url));
|
|
23
|
+
const SEVERE = new Set(["CRITICAL", "HIGH"]);
|
|
24
|
+
const MANUAL = "use the manual path: forgedock review-staging <PR> (commands/review-pr-staging.md)";
|
|
25
|
+
const blocked = (why) => ({ blocked: true, reason: `${why}; ${MANUAL}` });
|
|
26
|
+
|
|
27
|
+
/** Reviewers whose prompts are prose in the spec (not briefed by the pre-dispatch): marker domain -> spec phase. */
|
|
28
|
+
export const SPEC_PANEL = [
|
|
29
|
+
{ domain: "material-change", phase: "Phase 2 (material-change)" },
|
|
30
|
+
{ domain: "bug-hunter-general", phase: "Phase 3 (bug hunters)" },
|
|
31
|
+
{ domain: "code-quality", phase: "Phase 4 (code-quality)" },
|
|
32
|
+
{ domain: "regression-risk", phase: "Phase 6 (regression-risk)" },
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
const specPrompt = (p, m, def) => [
|
|
36
|
+
`You are the ${p.domain} reviewer of the staging -> ${def} release review of PR #${m.pr}, head ${m.headSha}.`,
|
|
37
|
+
`Read commands/review-pr-staging.md, ${p.phase}, and do exactly what that phase asks for this PR (bundle PRs: ${(m.bundle ?? []).join(" ") || "none"}; scope mode ${m.scopeMode}; the scope lists are in ${m.pr}_scope.json next to ${m.contextFile}).`,
|
|
38
|
+
`Post your own comment on the PR with \`gh pr comment\`: it starts with \`<!-- FORGE:REVIEW-AGENT:${p.domain} -->\`, then the line \`Reviewed-SHA: ${m.headSha}\`, and ends with the structured findings block (REVIEW-FINDINGS-START/END, FINDING markers; an empty block when nothing is found).`,
|
|
39
|
+
"Read-only git rule: never checkout, switch, reset, stash or merge in the shared checkout.",
|
|
40
|
+
].join("\n\n");
|
|
41
|
+
|
|
42
|
+
/** `Reviewers` named by a finalize stop: delivery (`missing findings comment(s) for: a b`) or extract (`no structured findings block from: a, b.`). */
|
|
43
|
+
export function missingReviewers(lines) {
|
|
44
|
+
const t = (lines ?? []).join("\n");
|
|
45
|
+
const m = /missing findings comment\(s\) for:\s*([^\n]+)/.exec(t) ?? /no structured findings block from:\s*([^\n]+?)\.?(?:\s+Re-dispatch|\n|$)/.exec(t);
|
|
46
|
+
return m ? m[1].split(/[\s,]+/).filter((d) => /^[a-z0-9-]+$/.test(d)) : [];
|
|
47
|
+
}
|
|
48
|
+
const headMoved = (lines) => /head moved since/.test((lines ?? []).join("\n"));
|
|
49
|
+
|
|
50
|
+
/** One review round at the current head: dispatch, test gate, head check, finalize. @returns {{moved: string}|{fail}|{ok}} */
|
|
51
|
+
async function reviewRound({ seam, pr, def, delta }) {
|
|
52
|
+
const pre = await seam.pre({ pr, delta });
|
|
53
|
+
const m = pre.data;
|
|
54
|
+
if (pre.code !== 0 || !m?.headSha) return { fail: `the pre-dispatch stopped (exit ${pre.code}): ${(pre.lines ?? []).slice(-2).join(" | ").slice(0, 300)}` };
|
|
55
|
+
m.pr ??= pr;
|
|
56
|
+
// A delta pass credits the spec panel from the earlier pass: only the briefs the delta touches are dispatched.
|
|
57
|
+
const agents = [
|
|
58
|
+
...m.briefs.map((b) => ({ domain: b.domain, prompt: () => seam.readFile(b.path) })),
|
|
59
|
+
...(m.delta ? [] : SPEC_PANEL.map((p) => ({ domain: p.domain, prompt: () => specPrompt(p, m, def) }))),
|
|
60
|
+
];
|
|
61
|
+
const prompts = new Map(agents.map((a) => [a.domain, a.prompt()]));
|
|
62
|
+
seam.markLaunched(m.launchedFile, agents.map((a) => a.domain), m.headSha);
|
|
63
|
+
const send = (domain, note = "") => seam.runAgent({ role: `release-review-${domain}`, issue: pr, prompt: note ? `${prompts.get(domain)}\n\n${note}` : prompts.get(domain) });
|
|
64
|
+
await Promise.all(agents.map((a) => send(a.domain).catch((e) => ({ error: e.message }))));
|
|
65
|
+
const gate = await seam.runAgent({ role: "release-test-gate", issue: pr, prompt: `/test-gate --prs "${(m.bundle ?? []).join(" ")}" --base ${def}\n\nPrint the complete gate output, ending with its FORGE:TEST_GATE:RESULT= marker.` });
|
|
66
|
+
const gateFile = seam.saveTestGate(pr, gate?.text ?? "");
|
|
67
|
+
|
|
68
|
+
// The head moved while the panel ran: finalize would refuse, and must never run at the moved head. Delta from what was reviewed.
|
|
69
|
+
if ((await seam.headOf(pr)) !== m.headSha) return { moved: m.headSha };
|
|
70
|
+
let fin = await seam.finalize({ pr, testGateOutput: gateFile });
|
|
71
|
+
if (fin.code !== 0 || !fin.data) {
|
|
72
|
+
if (headMoved(fin.lines)) return { moved: m.headSha };
|
|
73
|
+
const missing = missingReviewers(fin.lines).filter((d) => prompts.has(d));
|
|
74
|
+
if (!missing.length) return { fail: `finalize stopped (exit ${fin.code}): ${(fin.lines ?? []).slice(-2).join(" | ").slice(0, 300)}` };
|
|
75
|
+
// once: the same brief with the note the spec prescribes; a second miss is a degraded panel
|
|
76
|
+
await Promise.all(missing.map((d) => send(d, "structured findings block required: post your findings comment again, ending with the REVIEW-FINDINGS-START/END block.").catch(() => null)));
|
|
77
|
+
fin = await seam.finalize({ pr, testGateOutput: gateFile });
|
|
78
|
+
if (fin.code !== 0 || !fin.data) {
|
|
79
|
+
if (headMoved(fin.lines)) return { moved: m.headSha };
|
|
80
|
+
return { fail: `reviewer findings block still missing after one re-ask (${missing.join(", ")}): degraded panel` };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return { ok: fin.data };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The whole review of PR `pr`: rounds until one finalizes at its own head. @returns the step result or `{blocked}`. */
|
|
87
|
+
async function runReview({ seam, pr, def, delta = null }) {
|
|
88
|
+
let st = null;
|
|
89
|
+
for (let pass = 0; ; pass++) {
|
|
90
|
+
const r = await reviewRound({ seam, pr, def, delta });
|
|
91
|
+
if (r.fail) return blocked(r.fail);
|
|
92
|
+
if (r.ok) { st = r.ok; break; }
|
|
93
|
+
if (pass >= MAX_DELTA_PASSES) return blocked(`head of #${pr} kept moving during the review (${MAX_DELTA_PASSES} delta passes)`);
|
|
94
|
+
delta = r.moved;
|
|
95
|
+
}
|
|
96
|
+
const filed = [], blocking = [];
|
|
97
|
+
for (const item of st.toFile ?? []) {
|
|
98
|
+
const n = await seam.fileIssue({ item, pr, head: st.head });
|
|
99
|
+
if (!n) return blocked(`could not file the finding "${item.title ?? item.id}"`);
|
|
100
|
+
filed.push(n);
|
|
101
|
+
if (SEVERE.has(String(item.severity ?? "").toUpperCase())) blocking.push(n);
|
|
102
|
+
}
|
|
103
|
+
if ((st.notes ?? []).length) await seam.addNotes(pr, st.notes);
|
|
104
|
+
const sum = await seam.summary({ pr, filed });
|
|
105
|
+
if (!sum.data) return blocked(`the gate summary was not posted (exit ${sum.code}): ${(sum.lines ?? []).slice(-1).join("").slice(0, 200)}`);
|
|
106
|
+
return { pr, head: st.head, verdict: sum.data.verdict, marker: sum.data.marker, ciFailing: sum.data.ciFailing, filed, blocking, delta: st.delta?.from ?? null };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Review step. @returns {{pr, head, verdict, marker, filed, blocking}|{blocked: true, reason: string}} */
|
|
110
|
+
export async function reviewStep(ctx) {
|
|
111
|
+
const pr = ctx.state?.steps?.["release-pr"]?.result?.pr;
|
|
112
|
+
if (!pr) return blocked("no release PR recorded by the release-pr step");
|
|
113
|
+
return runReview({ seam: seamOf(ctx), pr, def: ctx.def });
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Fix step: nothing to do on GATE_PASS; else a lane per blocking issue on the staging branch, then a delta review, up to MAX_FIX_ROUNDS. */
|
|
117
|
+
export async function fixStep(ctx) {
|
|
118
|
+
let r = ctx.state?.steps?.review?.result;
|
|
119
|
+
if (!r?.pr) return blocked("no review result recorded by the review step");
|
|
120
|
+
const seam = seamOf(ctx);
|
|
121
|
+
for (let round = 0; r.marker !== "FORGE:GATE_PASS"; round++) {
|
|
122
|
+
if (round >= MAX_FIX_ROUNDS) return blocked(`still ${r.verdict} after ${MAX_FIX_ROUNDS} fix round(s)`);
|
|
123
|
+
// Blocking findings are already filed issues; red CI has none, so it gets one issue naming the failing checks.
|
|
124
|
+
const issues = [...(r.blocking ?? [])];
|
|
125
|
+
if (r.ciFailing > 0) {
|
|
126
|
+
const n = await seam.fileCiIssue({ pr: r.pr, head: r.head });
|
|
127
|
+
if (!n) return blocked(`could not file an issue for the red CI of #${r.pr}`);
|
|
128
|
+
issues.push(n);
|
|
129
|
+
}
|
|
130
|
+
if (!issues.length) return blocked(`${r.verdict} with neither a blocking finding nor red CI to fix`);
|
|
131
|
+
for (const issue of issues) {
|
|
132
|
+
const lane = await seam.runLane({ issue, lane: ctx.staging });
|
|
133
|
+
if (lane?.terminalReason !== "merged") return blocked(`fix lane for #${issue} ended ${lane?.terminalReason ?? "without a result"}`);
|
|
134
|
+
}
|
|
135
|
+
const next = await runReview({ seam, pr: r.pr, def: ctx.def, delta: r.head });
|
|
136
|
+
if (next.blocked) return next;
|
|
137
|
+
r = next;
|
|
138
|
+
ctx.state.steps.review = { ...ctx.state.steps.review, result: r };
|
|
139
|
+
ctx.save();
|
|
140
|
+
}
|
|
141
|
+
return { verdict: r.verdict, head: r.head };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const seamOf = (ctx) => ctx.io.review ?? (ctx.seam ??= realSeam(ctx));
|
|
145
|
+
|
|
146
|
+
/** Real effects of the review steps: the review-staging library, the engine runner, the filing scripts, gh and a lane process. */
|
|
147
|
+
export function realSeam({ repo, def, env = process.env, cwd = process.cwd() }) {
|
|
148
|
+
const rs = { ...reviewStagingIo(), cwd, env };
|
|
149
|
+
const sd = env.FORGE_SCRATCHPAD || join(cwd, ".forge-scratch");
|
|
150
|
+
let runner = null;
|
|
151
|
+
const gh = (args, input) => execFileSync("gh", args, { encoding: "utf8", input, maxBuffer: 64 << 20, env });
|
|
152
|
+
return {
|
|
153
|
+
pre: ({ pr, delta }) => reviewStagingJson([String(pr), ...(delta ? ["--delta", delta] : [])], rs),
|
|
154
|
+
finalize: ({ pr, testGateOutput }) => reviewStagingJson([String(pr), "--finalize", "--test-gate-output", testGateOutput], rs),
|
|
155
|
+
summary: ({ pr, filed }) => reviewStagingJson([String(pr), "--summary", ...(filed.length ? ["--filed", filed.join(",")] : [])], rs),
|
|
156
|
+
headOf: (pr) => gh(["pr", "view", String(pr), "-R", repo, "--json", "headRefOid", "--jq", ".headRefOid"]).trim(),
|
|
157
|
+
readFile: (p) => readFileSync(p, "utf8"),
|
|
158
|
+
markLaunched: (file, domains, head) => { appendFileSync(file, domains.map((d) => `${d}\n`).join("")); writeFileSync(`${file}.head`, `${head}\n`); },
|
|
159
|
+
saveTestGate: (pr, text) => { mkdirSync(sd, { recursive: true }); const f = join(sd, `${pr}_test_gate_output.txt`); writeFileSync(f, text); return f; },
|
|
160
|
+
runAgent: async ({ role, issue, prompt }) => {
|
|
161
|
+
runner ??= (await import("./effects.mjs")).makeLeanRunner();
|
|
162
|
+
// not readOnly: each reviewer posts its own PR comment
|
|
163
|
+
return runner({ role, issue, cwd, prompt, system: "You are an isolated reviewer of one release PR. Do only what the prompt asks.", maxMs: REVIEW_MS, idleMs: 10 * 60_000 });
|
|
164
|
+
},
|
|
165
|
+
async fileCiIssue({ pr, head }) {
|
|
166
|
+
const rows = JSON.parse(gh(["pr", "checks", String(pr), "-R", repo, "--json", "name,bucket"]));
|
|
167
|
+
const names = rows.filter((c) => c.bucket === "fail" && !CI_EXCLUDED_CHECKS.includes(c.name)).map((c) => c.name);
|
|
168
|
+
return this.fileIssue({ item: { title: `Release PR #${pr}: CI red at ${head.slice(0, 7)}`, severity: "HIGH", body: `Failing required checks on the release PR #${pr} at ${head}:\n${names.map((n) => `- ${n}`).join("\n")}\n\nFix them on the staging branch.` }, pr });
|
|
169
|
+
},
|
|
170
|
+
fileIssue: async ({ item, pr }) => {
|
|
171
|
+
const dir = mkdtempSync(join(tmpdir(), "release-finding-"));
|
|
172
|
+
try {
|
|
173
|
+
const body = item.body ?? [`Found by the staging review of PR #${pr}.`, ...Object.entries(item).filter(([k, v]) => k !== "title" && ["string", "number"].includes(typeof v)).map(([k, v]) => `- **${k}**: ${v}`)].join("\n");
|
|
174
|
+
const bodyFile = join(dir, "body.md");
|
|
175
|
+
writeFileSync(bodyFile, body);
|
|
176
|
+
let out = "";
|
|
177
|
+
try { out = execFileSync("bash", [join(ROOT, "scripts", "issue-create.sh"), "--title", item.title, "--body-file", bodyFile, "--label", "review-finding", "--label", "staging-review", "--repo", repo], { encoding: "utf8", cwd, env }); } catch (e) { out = String(e.stdout ?? ""); }
|
|
178
|
+
try {
|
|
179
|
+
return Number(/ISSUE_NUM=(\d+)/.exec(execFileSync("bash", [join(ROOT, "scripts", "review-finalize.sh"), "file-verify", "--pr", String(pr), "--repo", repo, "--context", join(sd, `review-ctx-${pr}.json`)], { encoding: "utf8", input: out, cwd, env }))?.[1]) || null;
|
|
180
|
+
} catch { return null; }
|
|
181
|
+
} finally { rmSync(dir, { recursive: true, force: true }); }
|
|
182
|
+
},
|
|
183
|
+
addNotes: async (pr, notes) => {
|
|
184
|
+
const body = JSON.parse(gh(["pr", "view", String(pr), "-R", repo, "--json", "body"])).body ?? "";
|
|
185
|
+
const list = notes.map((n) => (n.startsWith("-") ? n : `- ${n}`)).join("\n");
|
|
186
|
+
const next = body.includes("## Non-blocking notes") ? `${body.trimEnd()}\n${list}\n` : `${body.trimEnd()}\n\n## Non-blocking notes\n${list}\n`;
|
|
187
|
+
gh(["pr", "edit", String(pr), "-R", repo, "--body-file", "-"], next);
|
|
188
|
+
},
|
|
189
|
+
runLane: ({ issue, lane }) => new Promise((resolve) => {
|
|
190
|
+
const dir = mkdtempSync(join(tmpdir(), "release-lane-"));
|
|
191
|
+
const rf = join(dir, "result.json");
|
|
192
|
+
const child = spawn(process.execPath, [join(ROOT, "bin", "forgedock.mjs"), "run-issue", String(issue), "--lane", lane, "--result-file", rf], { cwd, env, stdio: "ignore" });
|
|
193
|
+
const timer = setTimeout(() => child.kill("SIGTERM"), LANE_MS);
|
|
194
|
+
const done = () => { clearTimeout(timer); let r = null; try { r = JSON.parse(readFileSync(rf, "utf8")); } catch { /* no result */ } rmSync(dir, { recursive: true, force: true }); resolve(r); };
|
|
195
|
+
child.on("error", done); child.on("exit", done);
|
|
196
|
+
}),
|
|
197
|
+
};
|
|
198
|
+
}
|