forgedock 1.57.0 → 1.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +30 -3
- package/bin/lean/conformance.test.mjs +74 -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 +41 -6
- package/bin/lean/lean.test.mjs +34 -1
- package/bin/lean/recovery.test.mjs +3 -3
- package/bin/lean/release-config.mjs +18 -7
- package/bin/lean/release-config.test.mjs +23 -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-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-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 +70 -6
- 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
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import { writeFileSync } from "node:fs";
|
|
5
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import assert from "node:assert/strict";
|
|
8
|
+
import { releaseFromCli, gateState } from "./release.mjs";
|
|
9
|
+
import { controlFromCli, VERBS } from "./release-control.mjs";
|
|
10
|
+
import { CONTROL_VERBS, collectStatus, renderReleaseStatus, watchStatus, explainIssue, explainPr, renderExplain, parseNextAction, policyFromYaml, registerPlannerRule, PLANNER_RULES } from "./release-status.mjs";
|
|
11
|
+
|
|
12
|
+
const REPO = "o/r", ID = "r20261112-141530-4242", HEAD = "a".repeat(40);
|
|
13
|
+
const STATE = { v: 1, id: ID, repo: REPO, steps: { preflight: { done: true, at: "T1" }, "release-pr": { done: true, at: "T2", result: { pr: 7, head: HEAD } }, promotion: { done: false, at: "T3" } }, release: { snapshot: "s1", issues: [12, 5], picks: [] } };
|
|
14
|
+
const GOLDEN_ISSUE = "{\"schema\":\"forgedock.release.explain/v1\",\"kind\":\"issue\",\"repo\":\"o/r\",\"issue\":40,\"lane\":\"pool\",\"classification\":\"absent\",\"trace\":[{\"step\":1,\"rule\":\"classification\",\"config_key\":\"FORGE:CLASSIFY\",\"result\":\"n/a\",\"detail\":\"classification: absent\",\"would_change\":[]},{\"step\":2,\"rule\":\"skip_labels\",\"config_key\":\"plan.skip_labels\",\"result\":\"pass\",\"detail\":\"no skip label\",\"would_change\":[]},{\"step\":3,\"rule\":\"min_confidence\",\"config_key\":\"classify.min_confidence\",\"result\":\"n/a\",\"detail\":\"no minimum configured\",\"would_change\":[]},{\"step\":4,\"rule\":\"risk.rules\",\"config_key\":\"risk.rules\",\"result\":\"n/a\",\"detail\":\"no rules configured\",\"would_change\":[]},{\"step\":5,\"rule\":\"forces\",\"config_key\":\"forces\",\"result\":\"n/a\",\"detail\":\"no rules configured\",\"would_change\":[]},{\"step\":6,\"rule\":\"priority\",\"config_key\":\"issue_watch.watches.<name>.immediate\",\"result\":\"pass\",\"detail\":\"priority P1\",\"would_change\":[]},{\"step\":7,\"rule\":\"theme\",\"config_key\":\"issue_watch.watches.<name>.theme_map\",\"result\":\"fail\",\"detail\":\"no theme rule matches\",\"would_change\":[\"add a theme_map rule (label:, scope: or path:) in forge.yaml\"]},{\"step\":8,\"rule\":\"depends_on\",\"config_key\":\"release.managed\",\"result\":\"pass\",\"detail\":\"no open prerequisite\",\"would_change\":[]},{\"step\":9,\"rule\":\"release_set\",\"config_key\":\"release.mode\",\"result\":\"fail\",\"detail\":\"no release recorded\",\"would_change\":[\"include it in the next release cut\"]},{\"step\":10,\"rule\":\"planner\",\"config_key\":\"release.planner\",\"result\":\"n/a\",\"detail\":\"planner: not installed\",\"would_change\":[]},{\"step\":11,\"rule\":\"lane\",\"config_key\":\"controls.jsonl lane | plan lane\",\"result\":\"n/a\",\"detail\":\"lane pool (plan)\",\"would_change\":[\"label or config key above, or: forgedock release lane #40 --force <train|release|p0|exclude> --reason <reason>\"]}],\"would_change\":[\"add a theme_map rule (label:, scope: or path:) in forge.yaml\",\"include it in the next release cut\",\"label or config key above, or: forgedock release lane #40 --force <train|release|p0|exclude> --reason <reason>\"],\"next_actions\":[\"forgedock release status --repo o/r --json\"]}";
|
|
15
|
+
const GOLDEN_PR = "{\"schema\":\"forgedock.release.explain/v1\",\"kind\":\"pr\",\"repo\":\"o/r\",\"pr\":7,\"head\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"decision\":\"pass\",\"demoted\":[],\"trace\":[{\"step\":1,\"rule\":\"gate_marker\",\"config_key\":\"release.gate\",\"result\":\"pass\",\"detail\":\"FORGE:GATE_PASS marker: pass\",\"would_change\":[]},{\"step\":2,\"rule\":\"deploy_gate\",\"config_key\":\"forge/deploy-gate\",\"result\":\"pass\",\"detail\":\"forge/deploy-gate: success\",\"would_change\":[]},{\"step\":3,\"rule\":\"check:unit\",\"config_key\":\"branches.required_checks\",\"result\":\"pass\",\"detail\":\"success\",\"would_change\":[]}],\"would_change\":[],\"next_actions\":[\"forgedock release explain 7 --repo o/r --json\"]}";
|
|
16
|
+
const GOLDEN_PR_TEXT = "PR #7 head aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa decision=pass\n 1. pass gate_marker [release.gate] FORGE:GATE_PASS marker: pass\n 2. pass deploy_gate [forge/deploy-gate] forge/deploy-gate: success\n 3. pass check:unit [branches.required_checks] success\n next:\n forgedock release explain 7 --repo o/r --json";
|
|
17
|
+
const b64 = (o) => ({ content: Buffer.from(typeof o === "string" ? o : JSON.stringify(o)).toString("base64") });
|
|
18
|
+
|
|
19
|
+
/** io fake: GitHub is a read-only world; any non-GET api call is recorded in `writes`. */
|
|
20
|
+
function fakeIo(world = {}) {
|
|
21
|
+
const writes = [], printed = [], gh = [];
|
|
22
|
+
const w = { controls: null, state: STATE, active: { lease: { holder: "h", epoch: 2, release: ID }, holds: [] }, issues: {}, marker: "pass", deployGate: "success", checks: [], ...world };
|
|
23
|
+
const io = {
|
|
24
|
+
writes, printed, now: () => 1, print: (l) => printed.push(l), sleep: async () => {},
|
|
25
|
+
api: async (method, path) => {
|
|
26
|
+
if (method !== "GET") { writes.push([method, path]); throw new Error("write"); }
|
|
27
|
+
if (path.includes("git/matching-refs")) return [{ ref: `refs/heads/forge-ledger/${ID}` }, { ref: "refs/heads/forge-ledger/_active" }];
|
|
28
|
+
if (path.includes("git/ref/heads/forge-ledger/")) return { object: { sha: "h" } };
|
|
29
|
+
if (path.includes("contents/state.json")) return b64(w.state);
|
|
30
|
+
if (path.includes("contents/active.json")) return b64(w.active);
|
|
31
|
+
if (path.includes("contents/controls.jsonl") && w.controls) return b64(w.controls.map((c) => JSON.stringify(c)).join("\n"));
|
|
32
|
+
throw Object.assign(new Error("HTTP 404"), { status: 404 });
|
|
33
|
+
},
|
|
34
|
+
gh: async (a) => {
|
|
35
|
+
gh.push(a); const j = a.join(" ");
|
|
36
|
+
if (j.includes("repo view")) return JSON.stringify({ nameWithOwner: REPO });
|
|
37
|
+
if (j.includes("--json comments")) return JSON.stringify({ comments: w.marker ? [{ body: `FORGE:GATE_${w.marker.toUpperCase()}` }] : [] });
|
|
38
|
+
if (j.includes("--json headRefOid")) return JSON.stringify({ headRefOid: HEAD });
|
|
39
|
+
if (a[0] === "api" && /\/status$/.test(a[1])) return JSON.stringify([]);
|
|
40
|
+
if (a[0] === "api") return JSON.stringify([{ name: "forge/deploy-gate", conclusion: w.deployGate }, ...w.checks]);
|
|
41
|
+
if (a[0] === "issue" && a[1] === "view") return JSON.stringify(w.issues[a[2]]);
|
|
42
|
+
if (a[0] === "issue" && a[1] === "list") return JSON.stringify(Object.values(w.issues));
|
|
43
|
+
throw new Error(`unexpected gh ${j}`);
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
return io;
|
|
47
|
+
}
|
|
48
|
+
const managedDir = tmpDir("rs5554-"); writeFileSync(join(managedDir, "forge.yaml"), "release:\n managed: true\n");
|
|
49
|
+
const local = { load: () => null, ids: () => [] };
|
|
50
|
+
const base = (io, over = {}) => ({ io, repo: REPO, config: { managed: true }, local, gateState, ...over });
|
|
51
|
+
|
|
52
|
+
describe("release status / explain (#5554)", () => {
|
|
53
|
+
it("R1: status reads the ledger plus GitHub, JSON has schema and next_actions, no write is made", async () => {
|
|
54
|
+
const io = fakeIo(), s = await collectStatus(base(io));
|
|
55
|
+
assert.equal(s.schema, "forgedock.release.status/v1");
|
|
56
|
+
assert.equal(s.id, ID); assert.equal(s.source, "ledger"); assert.equal(s.next_step, "promotion");
|
|
57
|
+
assert.deepEqual(s.pr.gate, { marker: "pass", deployGate: "success" });
|
|
58
|
+
assert.deepEqual(s.release.issues, [5, 12]);
|
|
59
|
+
assert.ok(s.next_actions.includes(`forgedock release --resume ${ID} --repo ${REPO} --merge`));
|
|
60
|
+
assert.deepEqual(io.writes, []);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("R4: golden text output", async () => {
|
|
64
|
+
const out = renderReleaseStatus(await collectStatus(base(fakeIo(), { id: ID })));
|
|
65
|
+
assert.equal(out, [
|
|
66
|
+
`${ID} o/r status=running next=promotion source=ledger hold=no intake=unknown`,
|
|
67
|
+
" wave: unknown lane: unknown", " lease: holder=h epoch=2 heartbeat_age_s=unknown", " cut: s1",
|
|
68
|
+
" [x] preflight T1", " [ ] host-preflight", " [x] release-pr T2", " [ ] review", " [ ] fixes", " [ ] mark-ready", " [ ] rehearsal", " [ ] promotion T3", " [ ] post-merge",
|
|
69
|
+
` PR #7 head ${HEAD} gate marker=pass deploy-gate=success ci: total=1 failed=0 pending=0`,
|
|
70
|
+
` review: verdict=GATE_PASS head=${HEAD}`, " merge: unknown", " deploy: unknown", " rollback: target=unknown auto=unknown",
|
|
71
|
+
" release set: #5 #12 picks=0",
|
|
72
|
+
" next:",
|
|
73
|
+
` forgedock release --resume ${ID} --repo o/r`,
|
|
74
|
+
` forgedock release --resume ${ID} --repo o/r --merge`,
|
|
75
|
+
` forgedock release hold ${ID} --repo o/r --reason <reason>`,
|
|
76
|
+
` forgedock release cancel ${ID} --repo o/r --reason <reason>`,
|
|
77
|
+
" forgedock release lane #5 --repo o/r --force <train|release|p0|exclude> --reason <reason>",
|
|
78
|
+
" forgedock release lane #12 --repo o/r --force <train|release|p0|exclude> --reason <reason>",
|
|
79
|
+
` forgedock release explain 7 --repo o/r`,
|
|
80
|
+
` forgedock release explain ${ID} --repo o/r`,
|
|
81
|
+
` forgedock release status ${ID} --repo o/r --json`,
|
|
82
|
+
].join("\n"));
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it("R4: a second host (other cwd, env, clock) prints the same bytes", async () => {
|
|
86
|
+
const run = async (cwd, now) => { const io = fakeIo(); io.now = () => now; const code = await releaseFromCli(["status", "--json", "--repo", REPO], { io, cwd: managedDir, env: { HOME: cwd, FORGEDOCK_RELEASE_DIR: `${cwd}/rel`, HOSTNAME: cwd } }); return [code, io.printed.join("\n")]; };
|
|
87
|
+
const [a, b] = [await run("/tmp/hostA", 1), await run("/tmp/hostB", 99)];
|
|
88
|
+
assert.deepEqual(a, b); assert.equal(a[0], 0); assert.equal(JSON.parse(a[1]).source, "ledger");
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it("R1: local cache is used when release.managed is off, with no ledger call", async () => {
|
|
92
|
+
const io = fakeIo(), calls = []; const api = io.api; io.api = async (...a) => { calls.push(a); return api(...a); };
|
|
93
|
+
const s = await collectStatus({ ...base(io, { config: {}, id: ID }), local: { load: () => STATE, ids: () => [ID] } });
|
|
94
|
+
assert.equal(s.source, "local"); assert.deepEqual(calls, []);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
const RULES = ["classification", "skip_labels", "min_confidence", "risk.rules", "forces", "priority", "theme", "depends_on", "release_set", "planner", "lane"];
|
|
98
|
+
|
|
99
|
+
it("R5: explain #N gives an ordered {step,rule,config_key,result,would_change} trace, planner not installed, lane", async () => {
|
|
100
|
+
const issues = { 40: { number: 40, title: "fix(api): x", body: "Depends on #41", labels: [{ name: "P1" }, { name: "needs-human" }] }, 41: { number: 41, title: "y", body: "", labels: [] } };
|
|
101
|
+
const e = await explainIssue({ io: fakeIo({ issues }), repo: REPO, number: 40, state: { id: ID, release: { issues: [12] } }, watch: { theme_map: { api: ["scope:api"] } } });
|
|
102
|
+
assert.deepEqual(e.trace.map((t) => t.rule), RULES);
|
|
103
|
+
assert.deepEqual(e.trace.map((t) => t.step), RULES.map((_, i) => i + 1));
|
|
104
|
+
assert.deepEqual(e.trace.map((t) => t.result), ["n/a", "fail", "n/a", "n/a", "n/a", "pass", "pass", "fail", "fail", "n/a", "n/a"]);
|
|
105
|
+
assert.ok(e.trace.every((t) => t.config_key && Array.isArray(t.would_change)));
|
|
106
|
+
assert.equal(e.classification, "absent"); assert.match(e.trace[0].detail, /classification: absent/);
|
|
107
|
+
assert.equal(e.trace[1].config_key, "plan.skip_labels");
|
|
108
|
+
assert.equal(e.trace[9].detail, "planner: not installed");
|
|
109
|
+
assert.equal(e.lane, "excluded");
|
|
110
|
+
assert.match(e.trace[7].detail, /#41/);
|
|
111
|
+
assert.ok(e.would_change.some((w) => w.includes("needs-human")));
|
|
112
|
+
assert.ok(e.trace[10].would_change[0].includes("release lane #40 --force"));
|
|
113
|
+
assert.match(renderExplain(e), /^#40 lane=excluded\n 1\. n\/a classification \[FORGE:CLASSIFY\] classification: absent/);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it("R5: explain #N reads the FORGE:CLASSIFY record, risk/forces rules, min_confidence, a registered planner rule and a controls lane", async () => {
|
|
117
|
+
const body = "<!-- FORGE:CLASSIFY -->\n" + JSON.stringify({ files: ["a.js"], confidence: 0.4, source: "model", set_by: "bot" });
|
|
118
|
+
const issues = { 12: { number: 12, title: "fix(api): z", body: "", labels: [{ name: "P2" }, { name: "risky" }], comments: [{ body }] } };
|
|
119
|
+
const policy = { min_confidence: 0.8, risk_rules: [{ label: "risky", lane: "solo" }], forces: [{ label: "force-x" }] };
|
|
120
|
+
PLANNER_RULES.length = 0; registerPlannerRule(() => ({ rule: "units_max", config_key: "plan.units_max", result: "pass", detail: "ok" }));
|
|
121
|
+
try {
|
|
122
|
+
const e = await explainIssue({ io: fakeIo({ issues }), repo: REPO, number: 12, state: { id: ID, release: { issues: [12] } }, watch: { theme_map: { api: ["scope:api"] } }, policy, lanes: { 12: { force: "p0", reason: "r", actor: "op", at: "T" } } });
|
|
123
|
+
assert.deepEqual(e.classification, { files: ["a.js"], confidence: 0.4, source: "model", set_by: "bot" });
|
|
124
|
+
assert.deepEqual(e.trace.map((t) => [t.rule, t.config_key, t.result]).slice(0, 5), [["classification", "FORGE:CLASSIFY", "pass"], ["skip_labels", "plan.skip_labels", "pass"], ["min_confidence", "classify.min_confidence", "fail"], ["risk.rules", "risk.rules[0]", "fail"], ["forces", "forces[0]", "pass"]]);
|
|
125
|
+
assert.equal(e.trace.at(-2).rule, "units_max"); assert.ok(!e.trace.some((t) => t.rule === "planner"));
|
|
126
|
+
assert.equal(e.lane, "p0"); assert.match(e.trace.at(-1).detail, /control decision by op/);
|
|
127
|
+
const viaLog = await explainIssue({ io: fakeIo({ issues }), repo: REPO, number: 12, state: null, controls: [{ verb: "lane", after: { 12: "exclude" }, actor: "ops" }, { verb: "lane", after: { 12: "train" }, actor: "ops2" }] });
|
|
128
|
+
assert.equal(viaLog.lane, "train"); assert.match(viaLog.trace.at(-1).detail, /by ops2/);
|
|
129
|
+
} finally { PLANNER_RULES.length = 0; }
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it("R8: explain #N and explain <PR> JSON are byte-for-byte goldens", async () => {
|
|
133
|
+
const issues = { 40: { number: 40, title: "fix(api): x", body: "", labels: [{ name: "P1" }] } };
|
|
134
|
+
const e = await explainIssue({ io: fakeIo({ issues }), repo: REPO, number: 40, state: null });
|
|
135
|
+
assert.equal(JSON.stringify(e), GOLDEN_ISSUE);
|
|
136
|
+
const p = await explainPr({ io: fakeIo({ checks: [{ name: "unit", conclusion: "success" }] }), repo: REPO, pr: 7, gateState, policy: { required_checks: ["unit"] } });
|
|
137
|
+
assert.equal(JSON.stringify(p), GOLDEN_PR);
|
|
138
|
+
assert.equal(renderExplain(p), GOLDEN_PR_TEXT);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it("R5/R6: policyFromYaml reads skip_labels, min_confidence, risk/forces labels and required_checks from forge.yaml", () => {
|
|
142
|
+
const { policy } = policyFromYaml("plan:\n skip_labels: [epic, foo]\nclassify:\n min_confidence: 0.7\nrisk:\n rules:\n - label: risky\nbranches:\n required_checks: [ci, lint]\n");
|
|
143
|
+
assert.deepEqual(policy.skip_labels, ["epic", "foo"]); assert.equal(policy.min_confidence, 0.7);
|
|
144
|
+
assert.deepEqual(policy.risk_rules, [{ label: "risky" }]); assert.deepEqual(policy.required_checks, ["ci", "lint"]);
|
|
145
|
+
assert.deepEqual(policyFromYaml("").policy.skip_labels, undefined);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("R6: explain <PR> lists each required check, the demotion (actor, expiry, reason, issue) and the gate decision", async () => {
|
|
149
|
+
const io = fakeIo({ marker: "failure", deployGate: "failure", checks: [{ name: "lint", conclusion: "failure" }, { name: "unit", conclusion: "failure" }, { name: "e2e", conclusion: "success" }] });
|
|
150
|
+
const exemptions = { unit: { mode: "skip", issue: "99", reason: "flaky", actor: "op", at: "2026-11-30T00:00:00Z", until: "2026-12-01T00:00:00Z" } }; // the `_active.exemptions` record `release exempt` writes
|
|
151
|
+
io.now = () => Date.parse("2026-11-30T12:00:00Z");
|
|
152
|
+
const e = await explainPr({ io, repo: REPO, pr: 7, gateState, exemptions });
|
|
153
|
+
assert.equal(e.decision, "hold");
|
|
154
|
+
assert.deepEqual(e.trace.map((t) => [t.rule, t.result]), [["gate_marker", "fail"], ["deploy_gate", "fail"], ["check:e2e", "pass"], ["check:forge/deploy-gate", "fail"], ["check:lint", "fail"], ["check:unit", "n/a"]]);
|
|
155
|
+
assert.deepEqual(e.demoted, [{ check: "unit", mode: "skip", actor: "op", expires: "2026-12-01T00:00:00Z", reason: "flaky", issue: "99" }]);
|
|
156
|
+
assert.match(e.trace.at(-1).detail, /demoted \(skip\) by op until 2026-12-01T00:00:00Z: flaky \(issue 99\)/);
|
|
157
|
+
io.now = () => Date.parse("2026-12-02T00:00:00Z"); // expired: the check counts again
|
|
158
|
+
const late = await explainPr({ io, repo: REPO, pr: 7, gateState, exemptions });
|
|
159
|
+
assert.deepEqual(late.demoted, []); assert.equal(late.trace.at(-1).result, "fail");
|
|
160
|
+
const ok = await explainPr({ io: fakeIo(), repo: REPO, pr: 7, gateState });
|
|
161
|
+
assert.equal(ok.decision, "pass");
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it("R5/R6: explain via the CLI dispatches #N, bare number and PR URL, and every command is read-only", async () => {
|
|
165
|
+
const issues = { 12: { number: 12, title: "t", body: "", labels: [] } };
|
|
166
|
+
for (const [arg, kind] of [["#12", "issue"], ["7", "pr"], ["https://github.com/o/r/pull/7", "pr"], [ID, "release"]]) {
|
|
167
|
+
const io = fakeIo({ issues, controls: [{ type: "lane", issue: 12, lane: "pool" }] });
|
|
168
|
+
assert.equal(await releaseFromCli(["explain", arg, "--json", "--repo", REPO], { io, cwd: managedDir, env: { FORGEDOCK_RELEASE_DIR: join(managedDir, "rel") }, deps: {} }).catch((e) => e.message), 0, arg);
|
|
169
|
+
assert.equal(JSON.parse(io.printed.join("")).kind, kind); assert.deepEqual(io.writes, []);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it("R2/R3: missing fields print unknown; recorded fields are shown; every next_actions command parses", async () => {
|
|
174
|
+
const st = { ...STATE, wave: { n: 1, of: 3 }, lane: "fast", merge_sha: "m1", deploy: { run: 5, stage: "canary", attempt: 2 }, rollback: { target: "v1", armed: true }, steps: { ...STATE.steps, review: { done: true, result: { verdict: "pass" } }, promotion: { done: true } } };
|
|
175
|
+
const active = { lease: { holder: "h", epoch: 2, release: ID, heartbeat_at: "1970-01-01T00:00:00.100Z" }, holds: { [ID]: { reason: "r", actor: "o", at: "T" } }, intake: { paused: true } };
|
|
176
|
+
const io = fakeIo({ state: st, active }); io.now = () => 5100;
|
|
177
|
+
const s = await collectStatus(base(io));
|
|
178
|
+
assert.equal(s.wave, "1/3"); assert.equal(s.lane, "fast"); assert.equal(s.lease.heartbeat_age_s, 5); assert.equal(s.hold, true); assert.equal(s.intake, "paused");
|
|
179
|
+
assert.equal(s.merge_sha, "m1"); assert.deepEqual(s.deploy, { run: 5, stage: "canary", attempt: 2 }); assert.equal(s.rollback_target, "v1"); assert.equal(s.auto_rollback, "armed");
|
|
180
|
+
assert.deepEqual(s.review, { verdict: "GATE_PASS", head: HEAD });
|
|
181
|
+
const bare = await collectStatus(base(fakeIo()));
|
|
182
|
+
for (const k of ["wave", "lane", "cut_sha", "merge_sha", "deploy", "rollback_target", "auto_rollback", "intake"]) assert.ok(bare[k] === "unknown" || k === "cut_sha", k);
|
|
183
|
+
for (const x of [s, bare]) for (const a of x.next_actions) parseNextAction(a);
|
|
184
|
+
assert.ok(s.next_actions.some((a) => /release resume .* --reason <reason>/.test(a)));
|
|
185
|
+
assert.ok(!s.next_actions.some((a) => /release rollback/.test(a)), "rollback has no CLI verb");
|
|
186
|
+
assert.ok(s.next_actions.some((a) => /release lane #12 .* --force <train\|release\|p0\|exclude> --reason <reason>/.test(a)));
|
|
187
|
+
assert.deepEqual(CONTROL_VERBS, VERBS);
|
|
188
|
+
// each command runs through the real CLI grammar: no usage refusal (read-only ones fully; control ones against a fake that rejects writes)
|
|
189
|
+
for (const a of s.next_actions) {
|
|
190
|
+
const [, , verb, ...rest] = a.replace("<reason>", "why").replace(/<train\|[^>]*>/, "release").split(/\s+/);
|
|
191
|
+
const io2 = fakeIo({ state: st, active }); let out = "";
|
|
192
|
+
if (VERBS.includes(verb)) { try { await controlFromCli(verb, rest, { io: io2, policy: null }); } catch { /* the write is refused by the fake */ } out = io2.printed.join("\n"); }
|
|
193
|
+
else if (verb === "status" || verb === "explain") { assert.equal(await releaseFromCli([verb, ...rest], { io: io2, cwd: managedDir, env: { FORGEDOCK_RELEASE_DIR: join(managedDir, "rel") }, deps: {} }), 0, a); }
|
|
194
|
+
else assert.ok(a.includes("--resume"), a);
|
|
195
|
+
assert.doesNotMatch(out, /required|unknown control verb|must be one of|at least one/, a);
|
|
196
|
+
}
|
|
197
|
+
assert.throws(() => parseNextAction("forgedock release hold x"), /needs --reason/);
|
|
198
|
+
assert.throws(() => parseNextAction("forgedock release status x --bogus"), /unknown option/);
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it("R1: no active release prints `no active release`", async () => {
|
|
202
|
+
const io = fakeIo({ active: {} });
|
|
203
|
+
assert.equal(await releaseFromCli(["status", "--repo", REPO], { io, cwd: managedDir, env: { FORGEDOCK_RELEASE_DIR: join(managedDir, "rel") }, deps: {} }), 1);
|
|
204
|
+
assert.deepEqual(io.printed, ["no active release"]);
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
it("R4/R11: status --watch prints only on change, stops at a terminal state, honours --interval", async () => {
|
|
208
|
+
const seq = ["running", "running", "done"], slept = [], printed = [];
|
|
209
|
+
const last = await watchStatus({ collect: async () => ({ status: seq.shift(), id: ID, repo: REPO, steps: [], next_actions: [] }), print: (l) => printed.push(l), sleep: async (ms) => slept.push(ms), asJson: true, intervalMs: 2500 });
|
|
210
|
+
assert.equal(last.status, "done"); assert.equal(printed.length, 2); assert.deepEqual(slept, [2500, 2500]);
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
it("R4: bare `release --watch` and `status --watch --interval` run the loop; a terminal release ends it; bad interval and unknown options are rejected", async () => {
|
|
214
|
+
const term = { ...STATE, status: "done" };
|
|
215
|
+
const run = (argv) => { const io = fakeIo({ state: term }); return releaseFromCli(argv, { io, cwd: managedDir, env: { FORGEDOCK_RELEASE_DIR: join(managedDir, "rel") }, deps: {} }).then((code) => [code, io]); };
|
|
216
|
+
for (const argv of [["--watch", "--repo", REPO], ["status", "--watch", "--interval", "3", "--repo", REPO]]) { const [code, io] = await run(argv); assert.equal(code, 0); assert.equal(io.printed.length, 1); assert.match(io.printed[0], /status=done/); }
|
|
217
|
+
await assert.rejects(run(["status", "--watch", "--interval", "0", "--repo", REPO]), /positive number/);
|
|
218
|
+
await assert.rejects(releaseFromCli(["status", "--bogus"], { io: fakeIo() }), /unknown option --bogus/);
|
|
219
|
+
});
|
|
220
|
+
});
|