forgedock 1.57.0 → 1.59.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/engine/outcome-codes.mjs +1 -1
- package/bin/engine-cli.mjs +2 -2
- package/bin/help-text.mjs +1 -1
- package/bin/lean/conformance.mjs +37 -5
- package/bin/lean/conformance.test.mjs +93 -0
- package/bin/lean/decisions.mjs +12 -0
- package/bin/lean/decisions.test.mjs +9 -0
- package/bin/lean/issuewatch-parity.mjs +4 -1
- package/bin/lean/issuewatch-parity.test.mjs +6 -0
- package/bin/lean/lean.mjs +44 -8
- package/bin/lean/lean.test.mjs +37 -4
- package/bin/lean/prompts.mjs +1 -1
- package/bin/lean/recovery.test.mjs +3 -3
- package/bin/lean/release-config.mjs +19 -8
- package/bin/lean/release-config.test.mjs +31 -0
- package/bin/lean/release-control.mjs +26 -3
- package/bin/lean/release-control.test.mjs +24 -0
- package/bin/lean/release-deploy.mjs +209 -0
- package/bin/lean/release-deploy.test.mjs +217 -0
- package/bin/lean/release-fixloop.mjs +108 -0
- package/bin/lean/release-fixloop.test.mjs +80 -0
- package/bin/lean/release-gates.mjs +230 -0
- package/bin/lean/release-gates.test.mjs +146 -0
- package/bin/lean/release-ledger.mjs +16 -0
- package/bin/lean/release-ledger.test.mjs +3 -3
- package/bin/lean/release-minutes.mjs +12 -2
- package/bin/lean/release-minutes.test.mjs +8 -0
- package/bin/lean/release-preflight.mjs +22 -0
- package/bin/lean/release-preflight.test.mjs +18 -2
- package/bin/lean/release-review.e2e.test.mjs +3 -2
- package/bin/lean/release-review.mjs +114 -31
- package/bin/lean/release-review.test.mjs +107 -20
- package/bin/lean/release-snapshot.mjs +32 -1
- package/bin/lean/release-snapshot.test.mjs +18 -1
- package/bin/lean/release-status.mjs +300 -0
- package/bin/lean/release-status.test.mjs +220 -0
- package/bin/lean/release-verify.mjs +221 -0
- package/bin/lean/release-verify.test.mjs +176 -0
- package/bin/lean/release.mjs +77 -7
- package/bin/lean/release.test.mjs +5 -1
- package/docs/CONFIG.md +20 -1
- package/package.json +1 -1
- package/scripts/ci-local/scoping.mjs +19 -0
- package/scripts/ci-local.test.sh +13 -0
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
* (`(args, {env, input}) => stdout`, throws on failure) and `io.gh`, so the module is testable with a real temp repo.
|
|
10
10
|
*/
|
|
11
11
|
const REMOTE = "origin";
|
|
12
|
+
/** Head movement after the cut (#5567): the fix push, a recorded `main-sync` cherry-pick of a staging commit, or a mechanical `revert`. */
|
|
13
|
+
export const PICK_KINDS = ["fix", "main-sync", "revert"];
|
|
12
14
|
import { BLOCKER_LABEL } from "./release-rehearsal.mjs";
|
|
13
15
|
export const DEFAULT_PATTERN = "release/{date}-{n}";
|
|
14
16
|
const MARKER = "FORGE:RELEASE";
|
|
@@ -116,7 +118,7 @@ export async function pickFixes(ctx, { issues = [] } = {}) {
|
|
|
116
118
|
const [an, ae, ad] = git(["log", "-1", "--format=%an%n%ae%n%aI", orig]).trim().split("\n");
|
|
117
119
|
const msg = `${git(["log", "-1", "--format=%B", orig]).trimEnd()}\n\n(cherry picked from commit ${orig})\n`;
|
|
118
120
|
const sha = git(["commit-tree", tree, "-p", head, "-F", "-"], { input: msg, env: { GIT_AUTHOR_NAME: an, GIT_AUTHOR_EMAIL: ae, GIT_AUTHOR_DATE: ad, ...committer(git) } }).trim();
|
|
119
|
-
rec.picks.push({ sha, orig, pr: p.number });
|
|
121
|
+
rec.picks.push({ sha, orig, pr: p.number, kind: "fix" });
|
|
120
122
|
picked.push(p.number);
|
|
121
123
|
head = sha;
|
|
122
124
|
}
|
|
@@ -127,6 +129,27 @@ export async function pickFixes(ctx, { issues = [] } = {}) {
|
|
|
127
129
|
return { picked };
|
|
128
130
|
}
|
|
129
131
|
|
|
132
|
+
/**
|
|
133
|
+
* #5567: the mechanical revert of the newest pick (the round-1 fix commit): a commit whose tree is the tree before that pick, recorded
|
|
134
|
+
* as a `revert` pick naming the reverted commit. No new code; `checkChain` verifies the tree. @returns {{reverted: string}|{err: string}}
|
|
135
|
+
*/
|
|
136
|
+
export async function revertLast(ctx) {
|
|
137
|
+
const { git, state } = ctx;
|
|
138
|
+
const rec = state.release;
|
|
139
|
+
if (!rec?.picks?.length) return { err: "no recorded pick to revert" };
|
|
140
|
+
const last = rec.picks.at(-1);
|
|
141
|
+
if (last.kind === "revert") return { err: "the newest pick is already a revert" };
|
|
142
|
+
const parent = git(["rev-parse", `${last.sha}^`]).trim();
|
|
143
|
+
const tree = git(["rev-parse", `${parent}^{tree}`]).trim();
|
|
144
|
+
const msg = `Revert "${git(["log", "-1", "--format=%s", last.sha]).trim()}"\n\n(reverts commit ${last.sha})\n`;
|
|
145
|
+
const sha = git(["commit-tree", tree, "-p", last.sha, "-F", "-"], { input: msg, env: committer(git) }).trim();
|
|
146
|
+
rec.picks.push({ sha, orig: last.sha, kind: "revert" });
|
|
147
|
+
ctx.save();
|
|
148
|
+
git(["push", "--quiet", REMOTE, `${sha}:refs/heads/${rec.branch}`]);
|
|
149
|
+
await writeRecord(ctx);
|
|
150
|
+
return { reverted: last.sha };
|
|
151
|
+
}
|
|
152
|
+
|
|
130
153
|
/** `fix_mode: recut`: move the (unmerged) release branch to the current staging tip and start the record's picks over. */
|
|
131
154
|
export async function recut(ctx) {
|
|
132
155
|
const { git, staging, state } = ctx;
|
|
@@ -163,6 +186,14 @@ export function checkChain({ git, record, sha, staging, exact = false }) {
|
|
|
163
186
|
const pick = record.picks[i];
|
|
164
187
|
if (c !== pick.sha) return no(`commit ${c.slice(0, 12)} is not the recorded pick ${pick.sha.slice(0, 12)}`);
|
|
165
188
|
if (parents.length !== 1 || parents[0] !== prev) return no(`commit ${c.slice(0, 12)} is not a linear child of ${prev.slice(0, 12)}`);
|
|
189
|
+
if (pick.kind && !PICK_KINDS.includes(pick.kind)) return no(`commit ${c.slice(0, 12)} has the unrecorded pick kind ${JSON.stringify(pick.kind)}`);
|
|
190
|
+
if (pick.kind === "revert") { // #5567: a mechanical revert of the previous pick: same tree as before it, and it names it
|
|
191
|
+
if (pick.orig !== prev) return no(`revert ${c.slice(0, 12)} does not revert the previous pick`);
|
|
192
|
+
if (!git(["log", "-1", "--format=%B", c]).includes(`(reverts commit ${pick.orig})`)) return no(`revert ${c.slice(0, 12)} does not name ${pick.orig.slice(0, 12)}`);
|
|
193
|
+
if (git(["rev-parse", `${c}^{tree}`]).trim() !== git(["rev-parse", `${pick.orig}~1^{tree}`]).trim()) return no(`revert ${c.slice(0, 12)} is not the mechanical revert of ${pick.orig.slice(0, 12)}`);
|
|
194
|
+
prev = c;
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
166
197
|
if (!isAncestor(git, pick.orig, stagingTip)) return no(`${pick.orig} is not a ${staging} commit`);
|
|
167
198
|
if (!git(["log", "-1", "--format=%B", c]).includes(`(cherry picked from commit ${pick.orig})`)) return no(`commit ${c.slice(0, 12)} does not name ${pick.orig} as its cherry-pick source`);
|
|
168
199
|
if (git(["rev-parse", `${c}^{tree}`]).trim() !== pickTree(git, prev, pick.orig)) return no(`commit ${c.slice(0, 12)} differs from the cherry-pick of ${pick.orig.slice(0, 12)}`);
|
|
@@ -6,7 +6,7 @@ import { execFileSync } from "node:child_process";
|
|
|
6
6
|
import { writeFileSync } from "node:fs";
|
|
7
7
|
import { join } from "node:path";
|
|
8
8
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
9
|
-
import { cutSnapshot, pickFixes, recut, checkChain, verifyRelease, cleanupSnapshot, parseRecord, withRecord, branchName, patternPrefix } from "./release-snapshot.mjs";
|
|
9
|
+
import { cutSnapshot, pickFixes, revertLast, recut, checkChain, verifyRelease, cleanupSnapshot, parseRecord, withRecord, branchName, patternPrefix } from "./release-snapshot.mjs";
|
|
10
10
|
|
|
11
11
|
const ENV = { GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t", GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" };
|
|
12
12
|
const mk = (cwd) => (args, { env, input } = {}) => execFileSync("git", args, { cwd, encoding: "utf8", input, env: { ...process.env, ...ENV, ...env }, stdio: ["pipe", "pipe", "pipe"] });
|
|
@@ -109,6 +109,23 @@ describe("cherry-picks and the verifier (#5276)", () => {
|
|
|
109
109
|
assert.deepEqual(checkChain({ git: s.git, record: s.ctx.state.release, sha: pick.sha, staging: "staging", exact: true }), { ok: true, picks: 1 });
|
|
110
110
|
});
|
|
111
111
|
|
|
112
|
+
it("#5567: a recorded mechanical revert verifies; an unrecorded pick kind fails; staging advancing leaves the head alone", async () => {
|
|
113
|
+
const { s, c } = await blockerWorld();
|
|
114
|
+
await pickFixes(s.ctx);
|
|
115
|
+
const rec = s.ctx.state.release;
|
|
116
|
+
const head0 = s.git(["ls-remote", "origin", `refs/heads/${c.branch}`]).split("\t")[0];
|
|
117
|
+
s.commit("later.txt", "l\n", "feat: later");
|
|
118
|
+
assert.equal(s.git(["ls-remote", "origin", `refs/heads/${c.branch}`]).split("\t")[0], head0, "a staging merge does not move the release head");
|
|
119
|
+
const rv = await revertLast(s.ctx);
|
|
120
|
+
assert.equal(rv.reverted, rec.picks[0].sha);
|
|
121
|
+
assert.equal(rec.picks.at(-1).kind, "revert");
|
|
122
|
+
assert.equal(checkChain({ git: s.git, record: rec, sha: rec.picks.at(-1).sha, staging: "staging", exact: true }).ok, true);
|
|
123
|
+
const bad = { ...rec, picks: [{ ...rec.picks[0], kind: "sneaky" }] };
|
|
124
|
+
assert.match(checkChain({ git: s.git, record: bad, sha: rec.picks[0].sha, staging: "staging", exact: true }).why, /unrecorded pick kind/);
|
|
125
|
+
const unrec = { ...rec, picks: [rec.picks[0]] };
|
|
126
|
+
assert.equal(checkChain({ git: s.git, record: unrec, sha: rec.picks.at(-1).sha, staging: "staging", exact: true }).ok, false, "an unrecorded pick fails");
|
|
127
|
+
});
|
|
128
|
+
|
|
112
129
|
it("picks a fix that closes a named issue even without the label", async () => {
|
|
113
130
|
const { s } = await blockerWorld();
|
|
114
131
|
s.w.prs = s.w.prs.map((p) => ({ ...p, labels: [], closingIssuesReferences: [{ number: 31 }] }));
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* `forgedock release status [<id>] [--watch] [--json]` and `release explain <id | #issue | PR>` (#5554, epic #5549 Phase 0):
|
|
5
|
+
* read-only views of a release over the ledger (when `release.managed`) or the local cache, plus GitHub. No GitHub write is made.
|
|
6
|
+
* Output carries no host name or wall clock (only recorded timestamps), so a second host prints the same bytes. JSON schemas
|
|
7
|
+
* `forgedock.release.status/v1` and `forgedock.release.explain/v1`; both carry `next_actions[]`, the exact commands an agent may run.
|
|
8
|
+
* `explain #N` traces the rules that exist today (classification record, skip labels, risk/forces, priority, theme_map, `Depends on`
|
|
9
|
+
* closure, recorded release set, lane); the wave planner (#5559) registers into PLANNER_RULES, until then `planner: not installed`. Effects (`io`, `gateState`, local cache) are injected, so it is unit-testable.
|
|
10
|
+
*/
|
|
11
|
+
import { readLedger, readActiveView as readActive } from "./release-ledger.mjs";
|
|
12
|
+
import { parseForgeYaml } from "../forge-utils.mjs";
|
|
13
|
+
import { VERBS, LANES } from "./release-control.mjs";
|
|
14
|
+
import { priorityOf, classifyTheme, closure } from "./issuewatch-release.mjs";
|
|
15
|
+
|
|
16
|
+
export const STATUS_SCHEMA = "forgedock.release.status/v1";
|
|
17
|
+
export const EXPLAIN_SCHEMA = "forgedock.release.explain/v1";
|
|
18
|
+
export const TERMINAL = ["done", "refused", "blocked", "cancelled"];
|
|
19
|
+
export const SKIP_LABELS = ["epic", "needs-human", "post-deploy", "workflow:merged", "awaiting-promotion", "host-task"];
|
|
20
|
+
const STEPS = ["preflight", "host-preflight", "release-pr", "review", "fixes", "mark-ready", "rehearsal", "promotion", "post-merge"];
|
|
21
|
+
/** The verbs `release <verb>` runs (#5556, `release-control.mjs`): the one source for what `next_actions[]` may name. */
|
|
22
|
+
export const CONTROL_VERBS = VERBS;
|
|
23
|
+
const OK = ["success", "neutral", "skipped"];
|
|
24
|
+
const ACTION_FLAGS = ["--repo", "--merge", "--watch", "--resume", "--json", "--interval", "--reason", "--force", "--mode", "--issue", "--until"];
|
|
25
|
+
const unk = (v) => (v === undefined || v === null || v === "" ? "unknown" : v);
|
|
26
|
+
const json = (s) => JSON.parse(String(s || "null"));
|
|
27
|
+
|
|
28
|
+
/** Planner rules (#5559 fills this): each `({issue, state}) => ({rule, config_key, result, detail, would_change})`. */
|
|
29
|
+
export const PLANNER_RULES = [];
|
|
30
|
+
export const registerPlannerRule = (fn) => { PLANNER_RULES.push(fn); };
|
|
31
|
+
|
|
32
|
+
/** The release id of `_active`'s lease (managed), else the newest local one. */
|
|
33
|
+
async function pickId({ io, repo, config, local }) {
|
|
34
|
+
if (config?.managed && io.api) {
|
|
35
|
+
const active = await readActive({ io, repo, credential: "driver" });
|
|
36
|
+
return active.lease?.release ?? active.release ?? null;
|
|
37
|
+
}
|
|
38
|
+
return local.ids().sort().at(-1) ?? null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function ciSummary(io, repo, head) {
|
|
42
|
+
try {
|
|
43
|
+
const runs = json(await io.gh(["api", `repos/${repo}/commits/${head}/check-runs`, "--jq", "[.check_runs[] | {name, conclusion}]"])) ?? [];
|
|
44
|
+
return { total: runs.length, failed: runs.filter((c) => c.conclusion && !OK.includes(c.conclusion)).length, pending: runs.filter((c) => !c.conclusion).length };
|
|
45
|
+
} catch { return null; }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The release `id` (default: the active one) as `{schema, ...}`; `null` when there is none. A field the ledger does not hold is `"unknown"`. */
|
|
49
|
+
export async function collectStatus({ io, repo, id, config = {}, local, gateState }) {
|
|
50
|
+
id ??= await pickId({ io, repo, config, local });
|
|
51
|
+
if (!id) return null;
|
|
52
|
+
const ctx = { io, repo, credential: "driver" }, managed = !!(config.managed && io.api);
|
|
53
|
+
const led = managed ? await readLedger(ctx, id) : null;
|
|
54
|
+
if (led?.rejected) return { schema: STATUS_SCHEMA, id, repo, source: "ledger", status: "rejected", reason: led.rejected, steps: [], next_actions: [`forgedock release explain ${id} --repo ${repo}`] };
|
|
55
|
+
const state = led?.state ?? local.load(id);
|
|
56
|
+
if (!state) return null;
|
|
57
|
+
const active = managed ? await readActive(ctx) : null;
|
|
58
|
+
const steps = STEPS.map((step) => ({ step, done: !!state.steps?.[step]?.done, at: state.steps?.[step]?.at ?? null }));
|
|
59
|
+
const stopped = Object.entries(state.steps ?? {}).find(([, v]) => v && v.done === false)?.[0];
|
|
60
|
+
const next = stopped ?? STEPS.find((st) => !state.steps?.[st]) ?? null;
|
|
61
|
+
const prRes = state.steps?.["release-pr"]?.result, pr = prRes?.pr ? { number: prRes.pr, head: prRes.head ?? null, gate: null, ci: null } : null;
|
|
62
|
+
if (pr?.head && gateState) { try { pr.gate = await gateState({ io, repo, pr: pr.number, head: pr.head }); } catch { pr.gate = null; } }
|
|
63
|
+
if (pr?.head) pr.ci = await ciSummary(io, repo, pr.head);
|
|
64
|
+
const status = state.status ?? "running";
|
|
65
|
+
const lease = active?.lease;
|
|
66
|
+
const hb = lease?.heartbeat_at ? Math.max(0, Math.round((io.now() - Date.parse(lease.heartbeat_at)) / 1000)) : null;
|
|
67
|
+
const w = state.wave;
|
|
68
|
+
const marker = pr?.gate?.marker, verdict = marker ? (marker === "pass" ? "GATE_PASS" : "GATE_FAILURE") : state.steps?.review?.result?.verdict;
|
|
69
|
+
const out = {
|
|
70
|
+
schema: STATUS_SCHEMA, id, repo, source: led ? "ledger" : "local", status, next_step: TERMINAL.includes(status) ? null : next,
|
|
71
|
+
wave: w ? `${w.n}/${w.of ?? w.m}` : "unknown", lane: unk(state.lane ?? w?.lane),
|
|
72
|
+
steps, pr,
|
|
73
|
+
lease: lease ? { holder: unk(lease.holder), epoch: unk(lease.epoch), heartbeat_age_s: hb ?? "unknown" } : "unknown",
|
|
74
|
+
hold: active ? !!(active.holds?.[id] ?? active.holds?.["*"] ?? active.cancelled?.[id]) : "unknown",
|
|
75
|
+
intake: active?.intake ? (active.intake.paused ? "paused" : "open") : "unknown",
|
|
76
|
+
cut_sha: unk(state.release?.snapshot),
|
|
77
|
+
review: verdict ? { verdict, head: pr?.head ?? "unknown" } : "unknown",
|
|
78
|
+
merge_sha: unk(state.steps?.promotion?.result?.sha ?? state.merge_sha),
|
|
79
|
+
deploy: state.deploy ? { run: unk(state.deploy.run), stage: unk(state.deploy.stage), attempt: unk(state.deploy.attempt) } : "unknown",
|
|
80
|
+
rollback_target: unk(state.rollback?.target), auto_rollback: state.rollback?.armed === undefined ? "unknown" : state.rollback.armed ? "armed" : "off",
|
|
81
|
+
release: state.release ? { snapshot: state.release.snapshot ?? null, branch: state.release.branch ?? null, issues: issueNumbers(state), picks: (state.release.picks ?? []).length } : null,
|
|
82
|
+
};
|
|
83
|
+
out.next_actions = nextActions(out);
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const issueNumbers = (state) => (state.release?.issues ?? []).map((i) => (typeof i === "object" ? i.number : i)).filter((n) => n != null).sort((a, b) => a - b);
|
|
88
|
+
|
|
89
|
+
function nextActions(s) {
|
|
90
|
+
const r = `--repo ${s.repo}`, out = [];
|
|
91
|
+
if (!TERMINAL.includes(s.status)) {
|
|
92
|
+
out.push(`forgedock release --resume ${s.id} ${r}`);
|
|
93
|
+
if (s.pr?.gate?.marker === "pass") out.push(`forgedock release --resume ${s.id} ${r} --merge`);
|
|
94
|
+
out.push(s.hold === true ? `forgedock release resume ${s.id} ${r} --reason <reason>` : `forgedock release hold ${s.id} ${r} --reason <reason>`);
|
|
95
|
+
out.push(`forgedock release cancel ${s.id} ${r} --reason <reason>`);
|
|
96
|
+
for (const n of s.release?.issues ?? []) out.push(`forgedock release lane #${n} ${r} --force <${LANES.join("|")}> --reason <reason>`);
|
|
97
|
+
}
|
|
98
|
+
if (s.pr) out.push(`forgedock release explain ${s.pr.number} ${r}`);
|
|
99
|
+
out.push(`forgedock release explain ${s.id} ${r}`, `forgedock release status ${s.id} ${r} --json`);
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Parse a `next_actions[]` command under the release CLI grammar; mutating verbs need `--reason`. Throws on anything else. */
|
|
104
|
+
export function parseNextAction(cmd) {
|
|
105
|
+
const t = String(cmd).split(/\s+/);
|
|
106
|
+
if (t[0] !== "forgedock" || t[1] !== "release") throw new Error(`not a release command: ${cmd}`);
|
|
107
|
+
const verb = [...CONTROL_VERBS, "status", "explain", "verify"].includes(t[2]) ? t[2] : null;
|
|
108
|
+
if (t[2] && !t[2].startsWith("--") && !verb) throw new Error(`unknown verb ${t[2]}: ${cmd}`);
|
|
109
|
+
const flags = t.filter((x) => x.startsWith("--"));
|
|
110
|
+
const bad = flags.find((f) => !ACTION_FLAGS.includes(f));
|
|
111
|
+
if (bad) throw new Error(`unknown option ${bad}: ${cmd}`);
|
|
112
|
+
if (CONTROL_VERBS.includes(verb) && !flags.includes("--reason")) throw new Error(`${verb} needs --reason: ${cmd}`);
|
|
113
|
+
if (!verb && !flags.includes("--resume")) throw new Error(`no verb or --resume: ${cmd}`);
|
|
114
|
+
if (verb === "lane" && !flags.includes("--force")) throw new Error(`lane needs --force: ${cmd}`);
|
|
115
|
+
return { verb, flags };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const show = (v) => (typeof v === "object" && v !== null ? Object.entries(v).map(([k, x]) => `${k}=${x}`).join(" ") : String(v));
|
|
119
|
+
|
|
120
|
+
export function renderReleaseStatus(s) {
|
|
121
|
+
if (!s) return "no active release";
|
|
122
|
+
const head = `${s.id} ${s.repo} status=${s.status}${s.next_step ? ` next=${s.next_step}` : ""} source=${s.source} hold=${s.hold === true ? "yes" : s.hold === false ? "no" : s.hold} intake=${s.intake}`;
|
|
123
|
+
const lines = [head];
|
|
124
|
+
if (s.reason) lines.push(` rejected: ${s.reason}`);
|
|
125
|
+
if (s.steps.length) {
|
|
126
|
+
lines.push(` wave: ${s.wave} lane: ${s.lane}`, ` lease: ${show(s.lease)}`, ` cut: ${s.cut_sha}`);
|
|
127
|
+
for (const st of s.steps) lines.push(` ${st.done ? "[x]" : "[ ]"} ${st.step}${st.at ? ` ${st.at}` : ""}`);
|
|
128
|
+
lines.push(s.pr ? ` PR #${s.pr.number} head ${s.pr.head ?? "unknown"} gate marker=${s.pr.gate?.marker ?? "none"} deploy-gate=${s.pr.gate?.deployGate ?? "none"} ci: ${s.pr.ci ? show(s.pr.ci) : "unknown"}` : " PR: unknown");
|
|
129
|
+
lines.push(` review: ${show(s.review)}`, ` merge: ${s.merge_sha}`, ` deploy: ${show(s.deploy)}`, ` rollback: target=${s.rollback_target} auto=${s.auto_rollback}`);
|
|
130
|
+
if (s.release) lines.push(` release set: ${s.release.issues.map((n) => `#${n}`).join(" ") || "(none recorded)"} picks=${s.release.picks}`);
|
|
131
|
+
}
|
|
132
|
+
lines.push(" next:", ...s.next_actions.map((a) => ` ${a}`));
|
|
133
|
+
return lines.join("\n");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Poll `collect` until the release is terminal (or `maxPolls`); a poll is printed only when its output changed. */
|
|
137
|
+
export async function watchStatus({ collect, print, sleep, asJson = false, intervalMs = 10_000, maxPolls = Infinity }) {
|
|
138
|
+
let last = null, prev;
|
|
139
|
+
for (let n = 0; n < maxPolls; n++) {
|
|
140
|
+
last = await collect();
|
|
141
|
+
const text = asJson ? JSON.stringify(last) : renderReleaseStatus(last);
|
|
142
|
+
if (text !== prev) print(text);
|
|
143
|
+
prev = text;
|
|
144
|
+
if (!last || TERMINAL.includes(last.status)) break;
|
|
145
|
+
await sleep(intervalMs);
|
|
146
|
+
}
|
|
147
|
+
return last;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
let stepNo = 0;
|
|
151
|
+
const item = (rule, config_key, result, detail, would_change = []) => ({ step: ++stepNo, rule, config_key, result, detail, would_change });
|
|
152
|
+
const resetSteps = () => { stepNo = 0; };
|
|
153
|
+
const res = (ok) => (ok === null ? "n/a" : ok ? "pass" : "fail");
|
|
154
|
+
|
|
155
|
+
/** The `FORGE:CLASSIFY` record of an issue (latest comment carrying it): `{files, confidence, source, set_by}` or `null`. */
|
|
156
|
+
function classificationOf(comments) {
|
|
157
|
+
const c = (comments ?? []).map((x) => String(x?.body ?? "")).filter((b) => b.includes("FORGE:CLASSIFY")).at(-1);
|
|
158
|
+
if (!c) return null;
|
|
159
|
+
const body = c.replace(/<!--[^>]*-->/g, "");
|
|
160
|
+
let rec = null;
|
|
161
|
+
try { rec = JSON.parse(body.slice(body.indexOf("{"), body.lastIndexOf("}") + 1)); } catch { /* key: value lines */ }
|
|
162
|
+
if (!rec) { rec = {}; for (const m of body.matchAll(/^\s*([a-z_]+):\s*(.+)$/gm)) rec[m[1]] = m[2].trim(); if (typeof rec.files === "string") rec.files = rec.files.split(/\s*,\s*/); }
|
|
163
|
+
return { files: rec.files ?? "unknown", confidence: rec.confidence ?? "unknown", source: rec.source ?? "unknown", set_by: rec.set_by ?? rec.who ?? "unknown" };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const hasLabel = (names, r) => names.includes(r.label);
|
|
167
|
+
|
|
168
|
+
/** `explain #N`: the ordered rule trace for one issue. `watch`: issue_watch config; `policy`: {skip_labels, min_confidence, risk_rules[], forces[]}; `controls`: controls.jsonl entries (`{verb, after, actor}`); `lanes`: `_active.lanes` (`{<issue>: {force, actor}}`). */
|
|
169
|
+
export async function explainIssue({ io, repo, number, state, watch = {}, policy = {}, controls = [], lanes = {}, planner = PLANNER_RULES }) {
|
|
170
|
+
resetSteps();
|
|
171
|
+
const issue = json(await io.gh(["issue", "view", String(number), "--repo", repo, "--json", "number,title,body,labels,comments,createdAt"]));
|
|
172
|
+
const open = json(await io.gh(["issue", "list", "--repo", repo, "--state", "open", "--limit", "500", "--json", "number,title,body,labels,createdAt"])) ?? [];
|
|
173
|
+
const names = (issue.labels ?? []).map((l) => (typeof l === "string" ? l : l?.name)).filter(Boolean);
|
|
174
|
+
const trace = [];
|
|
175
|
+
const cls = classificationOf(issue.comments);
|
|
176
|
+
trace.push(item("classification", "FORGE:CLASSIFY", cls ? "pass" : "n/a", cls ? `files ${show(cls.files)}; confidence ${cls.confidence}; source ${cls.source}; set by ${cls.set_by}` : "classification: absent"));
|
|
177
|
+
const skipList = policy.skip_labels ?? SKIP_LABELS, skip = names.filter((l) => skipList.includes(l));
|
|
178
|
+
trace.push(item("skip_labels", "plan.skip_labels", res(skip.length === 0), skip.length ? `labelled ${skip.join(", ")}` : "no skip label", skip.length ? [`remove label ${skip.join(", ")}`] : []));
|
|
179
|
+
const min = policy.min_confidence, conf = Number(cls?.confidence);
|
|
180
|
+
trace.push(item("min_confidence", "classify.min_confidence", min === undefined || !cls || Number.isNaN(conf) ? "n/a" : res(conf >= min), min === undefined ? "no minimum configured" : cls ? `confidence ${cls.confidence} vs minimum ${min}` : "no classification to compare", conf < min ? ["raise confidence or lower classify.min_confidence"] : []));
|
|
181
|
+
for (const [key, rules] of [["risk.rules", policy.risk_rules ?? []], ["forces", policy.forces ?? []]]) {
|
|
182
|
+
if (!rules.length) trace.push(item(key, key, "n/a", "no rules configured"));
|
|
183
|
+
rules.forEach((r, i) => { const hit = hasLabel(names, r); trace.push(item(key, `${key}[${i}]`, res(!hit), hit ? `label ${r.label} fires${r.lane ? ` -> lane ${r.lane}` : ""}` : `label ${r.label} absent`, hit ? [`remove label ${r.label} or edit ${key}[${i}]`] : [])); });
|
|
184
|
+
}
|
|
185
|
+
const prio = priorityOf(issue);
|
|
186
|
+
trace.push(item("priority", "issue_watch.watches.<name>.immediate", prio !== null ? "pass" : "n/a", prio ? `priority ${prio}` : "no P0-P3 label (weighs as P3)"));
|
|
187
|
+
const theme = classifyTheme(issue, watch.theme_map ?? {});
|
|
188
|
+
trace.push(item("theme", "issue_watch.watches.<name>.theme_map", res(!!theme), theme ? `theme ${theme.theme} via ${theme.via}` : "no theme rule matches", theme ? [] : ["add a theme_map rule (label:, scope: or path:) in forge.yaml"]));
|
|
189
|
+
const byNum = new Map(open.map((i) => [i.number, i])); byNum.set(issue.number, issue);
|
|
190
|
+
const prereq = closure(issue, byNum).filter((i) => i.number !== issue.number).map((i) => i.number);
|
|
191
|
+
trace.push(item("depends_on", "release.managed", res(prereq.length === 0), prereq.length ? `open prerequisites ${prereq.map((n) => `#${n}`).join(", ")} must ship first` : "no open prerequisite", prereq.length ? [`close or ship ${prereq.map((n) => `#${n}`).join(", ")}`] : []));
|
|
192
|
+
const member = (state ? issueNumbers(state) : []).includes(issue.number);
|
|
193
|
+
trace.push(item("release_set", "release.mode", res(member), state ? (member ? `in the recorded release set of ${state.id}` : `not in the recorded release set of ${state.id}`) : "no release recorded", member || skip.length ? [] : ["include it in the next release cut"]));
|
|
194
|
+
if (planner.length) for (const fn of planner) { const p = fn({ issue, state }); trace.push(item(p.rule, p.config_key, p.result, p.detail ?? "", p.would_change ?? [])); }
|
|
195
|
+
else trace.push(item("planner", "release.planner", "n/a", "planner: not installed"));
|
|
196
|
+
const lastLane = controls.filter((c) => c.verb === "lane" && c.after?.[number] !== undefined).at(-1);
|
|
197
|
+
const rec = lanes[number] ?? (lastLane ? { force: lastLane.after[number], actor: lastLane.actor } : null);
|
|
198
|
+
const ctl = rec ? { lane: rec.force, actor: rec.actor } : null;
|
|
199
|
+
const planned = member ? "release" : skip.length ? "excluded" : "pool";
|
|
200
|
+
const lane = ctl?.lane ?? planned;
|
|
201
|
+
trace.push(item("lane", "controls.jsonl lane | plan lane", "n/a", ctl ? `lane ${lane} (control decision${ctl.actor ? ` by ${ctl.actor}` : ""})` : `lane ${lane} (plan)`, [`label or config key above, or: forgedock release lane #${number} --force <${LANES.join("|")}> --reason <reason>`]));
|
|
202
|
+
return { schema: EXPLAIN_SCHEMA, kind: "issue", repo, issue: number, lane, classification: cls ?? "absent", trace, would_change: trace.flatMap((t) => t.would_change), next_actions: [`forgedock release status --repo ${repo} --json`] };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** `explain <PR>`: every required check and its outcome at the head, the deploy gate, and any exemption (demotion) from `controls`. */
|
|
206
|
+
export async function explainPr({ io, repo, pr, gateState, policy = {}, exemptions = {} }) {
|
|
207
|
+
resetSteps();
|
|
208
|
+
const head = json(await io.gh(["pr", "view", String(pr), "--repo", repo, "--json", "headRefOid"]))?.headRefOid;
|
|
209
|
+
const g = await gateState({ io, repo, pr, head });
|
|
210
|
+
const checks = json(await io.gh(["api", `repos/${repo}/commits/${head}/check-runs`, "--jq", "[.check_runs[] | {name, conclusion}]"])) ?? [];
|
|
211
|
+
const byName = new Map(checks.map((c) => [c.name, c]));
|
|
212
|
+
const names = (policy.required_checks ?? checks.map((c) => c.name)).slice().sort();
|
|
213
|
+
const exempt = (n) => exemptions?.[n] ?? null; // `_active.exemptions[check]` = {mode, issue, reason, actor, at, until}, as `release exempt` writes it (#5556)
|
|
214
|
+
const live = (e) => e && e.until && Date.parse(e.until) > io.now();
|
|
215
|
+
const trace = [
|
|
216
|
+
item("gate_marker", "release.gate", res(g.marker === "pass"), `FORGE:GATE_PASS marker: ${g.marker ?? "none"}`),
|
|
217
|
+
item("deploy_gate", "forge/deploy-gate", res(g.deployGate === "success"), `forge/deploy-gate: ${g.deployGate ?? "none"}`),
|
|
218
|
+
];
|
|
219
|
+
const demoted = [];
|
|
220
|
+
for (const n of names) {
|
|
221
|
+
const c = byName.get(n), concl = c?.conclusion ?? null, ex = exempt(n);
|
|
222
|
+
const ok = concl ? OK.includes(concl) : null;
|
|
223
|
+
if (live(ex) && ok !== true) {
|
|
224
|
+
demoted.push({ check: n, mode: unk(ex.mode), actor: unk(ex.actor), expires: unk(ex.until), reason: unk(ex.reason), issue: unk(ex.issue) });
|
|
225
|
+
trace.push(item(`check:${n}`, "branches.required_checks", "n/a", `${concl ?? "missing"}; demoted (${unk(ex.mode)}) by ${unk(ex.actor)} until ${unk(ex.until)}: ${unk(ex.reason)} (issue ${unk(ex.issue)})`));
|
|
226
|
+
} else trace.push(item(`check:${n}`, "branches.required_checks", ok === null ? "fail" : res(ok), c ? `${concl ?? "pending"}` : "missing", ok === true ? [] : [`make ${n} pass, or demote it: forgedock release exempt ${n} --mode skip --issue <issue> --until 24h --reason <reason>`]));
|
|
227
|
+
}
|
|
228
|
+
return { schema: EXPLAIN_SCHEMA, kind: "pr", repo, pr, head, decision: trace.every((t) => t.result !== "fail") ? "pass" : "hold", demoted, trace, would_change: trace.flatMap((t) => t.would_change), next_actions: [`forgedock release explain ${pr} --repo ${repo} --json`] };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export function renderExplain(e) {
|
|
232
|
+
const lines = [e.kind === "issue" ? `#${e.issue} lane=${e.lane}` : e.kind === "pr" ? `PR #${e.pr} head ${e.head} decision=${e.decision}` : `${e.id} status=${e.status}`];
|
|
233
|
+
e.trace.forEach((t) => lines.push(` ${t.step}. ${t.result === "pass" ? "pass" : t.result === "fail" ? "FAIL" : "n/a "} ${t.rule} [${t.config_key}] ${t.detail}`));
|
|
234
|
+
if (e.would_change?.length) lines.push(" would change:", ...e.would_change.map((w) => ` - ${w}`));
|
|
235
|
+
lines.push(" next:", ...e.next_actions.map((a) => ` ${a}`));
|
|
236
|
+
return lines.join("\n");
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const ruleList = (v) => (Array.isArray(v) ? v : v ? [v] : []).map((r) => (typeof r === "string" ? { label: r.replace(/^\s*label:\s*/, "").trim() } : r)).filter((r) => r?.label);
|
|
240
|
+
const strList = (v) => (Array.isArray(v) ? v : v ? [v] : []).map(String);
|
|
241
|
+
|
|
242
|
+
/** `{policy, watch}` read from forge.yaml (`plan.skip_labels`, `classify.min_confidence`, `risk.rules`, `forces`, `branches.required_checks`, `issue_watch` theme_map); a key that is absent stays undefined. */
|
|
243
|
+
export function policyFromYaml(raw) {
|
|
244
|
+
let y = {}; try { y = parseForgeYaml(String(raw ?? "")) ?? {}; } catch { y = {}; }
|
|
245
|
+
const mc = y.classify?.min_confidence === undefined ? undefined : Number(y.classify.min_confidence);
|
|
246
|
+
const watches = Object.values(y.issue_watch?.watches ?? {}).filter((w) => w && typeof w === "object");
|
|
247
|
+
return {
|
|
248
|
+
policy: {
|
|
249
|
+
skip_labels: y.plan?.skip_labels === undefined ? undefined : strList(y.plan.skip_labels),
|
|
250
|
+
min_confidence: Number.isNaN(mc) ? undefined : mc,
|
|
251
|
+
risk_rules: ruleList(y.risk?.rules), forces: ruleList(y.forces?.rules ?? y.forces),
|
|
252
|
+
required_checks: y.branches?.required_checks === undefined ? undefined : strList(y.branches.required_checks),
|
|
253
|
+
},
|
|
254
|
+
watch: watches.find((w) => w.theme_map) ?? {},
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const flag = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
|
|
259
|
+
|
|
260
|
+
/** `release status|explain ...`; @returns the exit code (0 found, 1 nothing found). `deps`: {io, config, local, gateState, watch, maxPolls}. */
|
|
261
|
+
export async function statusFromCli(argv, deps) {
|
|
262
|
+
const { io } = deps, verb = argv[0], rest = argv.slice(1);
|
|
263
|
+
const known = ["--repo", "--json", "--watch", "--interval"];
|
|
264
|
+
const bad = rest.find((a) => a.startsWith("--") && !known.includes(a));
|
|
265
|
+
if (bad) throw new Error(`unknown option ${bad}; usage: forgedock release ${verb} ${verb === "status" ? "[<id>] [--watch] [--interval s] [--json]" : "<id | #issue | PR>"} [--repo owner/repo] [--json]`);
|
|
266
|
+
const asJson = rest.includes("--json"), arg = rest.find((a, i) => !a.startsWith("--") && !["--repo", "--interval"].includes(rest[i - 1]));
|
|
267
|
+
const repo = flag(rest, "--repo") ?? json(await io.gh(["repo", "view", "--json", "nameWithOwner"])).nameWithOwner;
|
|
268
|
+
const base = { io, repo, config: deps.config, local: deps.local, gateState: deps.gateState };
|
|
269
|
+
const none = (s) => s ?? { schema: STATUS_SCHEMA, id: null, repo, status: "no active release", next_actions: [] };
|
|
270
|
+
const show1 = (s) => (asJson ? JSON.stringify(none(s)) : arg && !s ? `no release ${arg}` : renderReleaseStatus(s));
|
|
271
|
+
if (verb === "status") {
|
|
272
|
+
const collect = () => collectStatus({ ...base, id: arg });
|
|
273
|
+
if (rest.includes("--watch")) {
|
|
274
|
+
const secs = flag(rest, "--interval") === null ? 10 : Number(flag(rest, "--interval"));
|
|
275
|
+
if (!(secs > 0)) throw new Error("--interval needs a positive number of seconds");
|
|
276
|
+
const s = await watchStatus({ collect, print: io.print, sleep: io.sleep, asJson, intervalMs: secs * 1000, maxPolls: deps.maxPolls });
|
|
277
|
+
return s ? 0 : 1;
|
|
278
|
+
}
|
|
279
|
+
const s = await collect();
|
|
280
|
+
io.print(show1(s));
|
|
281
|
+
return s ? 0 : 1;
|
|
282
|
+
}
|
|
283
|
+
if (!arg) throw new Error("release explain needs <id | #issue | PR>");
|
|
284
|
+
const act = deps.config?.managed && io.api ? await readActive({ io, repo, credential: "driver" }) : {};
|
|
285
|
+
const controls = act.controls ?? [], lanes = act.lanes ?? {}, exemptions = act.exemptions ?? {};
|
|
286
|
+
let out;
|
|
287
|
+
if (arg.startsWith("#")) {
|
|
288
|
+
const s = await collectStatus({ ...base }).catch(() => null);
|
|
289
|
+
out = await explainIssue({ io, repo, number: Number(arg.slice(1)), state: s ? { id: s.id, release: s.release } : null, watch: deps.watch, policy: deps.policy, controls, lanes });
|
|
290
|
+
} else if (/^\d+$/.test(arg) || /\/pull\/\d+/.test(arg)) {
|
|
291
|
+
out = await explainPr({ io, repo, pr: Number(/\d+$/.exec(arg)[0]), gateState: deps.gateState, policy: deps.policy, exemptions });
|
|
292
|
+
} else {
|
|
293
|
+
const s = await collectStatus({ ...base, id: arg });
|
|
294
|
+
if (!s) { io.print(`no release ${arg}`); return 1; }
|
|
295
|
+
resetSteps();
|
|
296
|
+
out = { schema: EXPLAIN_SCHEMA, kind: "release", id: s.id, repo, status: s.status, trace: s.steps.map((st) => item(st.step, "release.steps", st.done ? "pass" : "n/a", st.done ? `done ${st.at ?? ""}`.trim() : "not done")), would_change: s.next_step ? [`run step ${s.next_step}`] : [], next_actions: s.next_actions };
|
|
297
|
+
}
|
|
298
|
+
io.print(asJson ? JSON.stringify(out) : renderExplain(out));
|
|
299
|
+
return 0;
|
|
300
|
+
}
|