forgedock 1.55.0 → 1.56.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/config-schema.mjs +12 -0
- package/bin/engine-cli.mjs +12 -0
- package/bin/forge-utils.mjs +37 -5
- package/bin/gc.mjs +11 -3
- package/bin/lean/lean.mjs +10 -6
- package/bin/lean/orphan-pr.mjs +124 -0
- package/bin/lean/orphan-pr.test.mjs +138 -0
- package/bin/lean/release-postmerge.mjs +38 -20
- package/bin/lean/release-review.mjs +12 -1
- package/bin/lean/release-review.test.mjs +14 -0
- package/bin/lean/release.test.mjs +40 -16
- package/bin/review-staging.mjs +53 -10
- package/commands/incident-response.md +4 -0
- package/commands/pipeline-status.md +13 -0
- package/package.json +1 -1
package/bin/config-schema.mjs
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
// The sections below mirror docs/CONFIG.md (bin/tests/config-schema.test.mjs fails when a documented section is missing here).
|
|
7
7
|
// Nested keys are only checked where a section is listed in CLOSED; elsewhere only the top level and typed keys are.
|
|
8
8
|
|
|
9
|
+
import { parseForgeYaml } from "./forge-utils.mjs";
|
|
10
|
+
|
|
9
11
|
export const TOP_LEVEL = [
|
|
10
12
|
"project", "paths", "branches", "agents", "repos", "project_board", "orchestration", "orchestrate", "notify", "decisions",
|
|
11
13
|
"hygiene", "pipeline", "execution", "engine", "prod_watch", "selftest", "release", "issue_watch", "followups", "rollouts",
|
|
@@ -30,6 +32,7 @@ export const TYPES = {
|
|
|
30
32
|
"verification.ci_local.max_parallel": "number",
|
|
31
33
|
"engine.path": { enum: ["core", "full", "lean", "auto"] },
|
|
32
34
|
"billing.enabled": "bool",
|
|
35
|
+
"gate.required_checks": "list",
|
|
33
36
|
};
|
|
34
37
|
|
|
35
38
|
/** Keys the legacy `full` path never reads (the core path reads them: bin/engine-cli.mjs readEnvConfig, readConformanceMode). */
|
|
@@ -91,6 +94,8 @@ function typeError(spec, { kind, value }) {
|
|
|
91
94
|
*/
|
|
92
95
|
export function validateForgeYaml(text, { path } = {}) {
|
|
93
96
|
const keys = scanKeys(text);
|
|
97
|
+
let parsed = {};
|
|
98
|
+
try { parsed = parseForgeYaml(String(text)); } catch { /* unparseable: scan findings still apply */ }
|
|
94
99
|
const active = keys.get("engine.path")?.value.replace(/^["']|["']$/g, "") ?? "";
|
|
95
100
|
const engine = path ?? (active || "core");
|
|
96
101
|
const side = engine === "full" ? "full" : "core";
|
|
@@ -103,6 +108,13 @@ export function validateForgeYaml(text, { path } = {}) {
|
|
|
103
108
|
const ignored = IGNORED_ON[side].find((p) => key === p || key.startsWith(p + "."));
|
|
104
109
|
if (ignored && key === ignored) add("error", "ignored-on-path", key, `"${key}" is set but the ${side} engine path (engine.path: ${engine}) never reads it`);
|
|
105
110
|
if (DEPRECATED[key]) add("warn", "deprecated-alias", key, `"${key}" is a deprecated alias; use "${DEPRECATED[key]}"`);
|
|
111
|
+
// #5504: a list the YAML text writes (block or flow) or the schema types as a list must reach readers as an array.
|
|
112
|
+
// Only `key` and `section.key` are checked: deeper blocks have their own readers (e.g. issue_watch.watches.*).
|
|
113
|
+
const [sec, leaf, deeper] = key.split(".");
|
|
114
|
+
const got = leaf === undefined ? parsed[sec] : deeper === undefined ? parsed[sec]?.[leaf] : undefined;
|
|
115
|
+
if (deeper === undefined && (node.kind === "list" || TYPES[key] === "list") && node.kind !== "map" && got !== undefined && !Array.isArray(got)) {
|
|
116
|
+
add("warn", "list-not-array", key, `"${key}" is a list but parses to ${typeof got === "string" ? JSON.stringify(got) : typeof got}, not an array (readers of it will ignore it)`);
|
|
117
|
+
}
|
|
106
118
|
if (TYPES[key]) {
|
|
107
119
|
const want = typeError(TYPES[key], node);
|
|
108
120
|
if (want) add("error", "wrong-type", key, `"${key}" must be ${want} (got ${node.kind === "scalar" ? JSON.stringify(node.value) : node.kind})`);
|
package/bin/engine-cli.mjs
CHANGED
|
@@ -2371,6 +2371,7 @@ async function scheddDue() {
|
|
|
2371
2371
|
const leanIo = (await import("./lean/effects.mjs")).makeLeanIo({ repo });
|
|
2372
2372
|
await sweepDue({ repo, cwd: process.cwd(), io: leanIo, onResult: probeEventSink(repo) });
|
|
2373
2373
|
await sweepParkedFollowups({ repo, io: leanIo }); // #4689: re-queue parked post-deploy follow-ups on the same pass
|
|
2374
|
+
await sweepOrphanPrFollowups({ repo, io: leanIo }); // #5505: close open PRs whose issue is closed
|
|
2374
2375
|
try { const prem = await import("./lean/needs-human-premise.mjs"); await prem.sweepPremises({ repo, io: { gh: (a) => leanIo.gh(a), pkgVersion: prem.registryPkgVersion } }); } catch { /* best effort (#4725) */ } // clear needs-human whose recorded premise now holds
|
|
2375
2376
|
try { // #4894: opt-in nightly live selftest (forge.yaml selftest.nightly_interval_hours); best effort
|
|
2376
2377
|
const { nightlyDue, launchNightly } = await import("./lean/selftest-nightly.mjs");
|
|
@@ -2380,6 +2381,15 @@ async function scheddDue() {
|
|
|
2380
2381
|
} catch { /* never stops the other sweeps */ }
|
|
2381
2382
|
}
|
|
2382
2383
|
|
|
2384
|
+
/** #5505: close or follow up the open lane PRs whose issue is closed (orphan-pr sweep); never throws. */
|
|
2385
|
+
async function sweepOrphanPrFollowups({ repo, io, dryRun = false }) {
|
|
2386
|
+
try {
|
|
2387
|
+
const { sweepOrphanPrs } = await import("./lean/orphan-pr.mjs");
|
|
2388
|
+
const base = readBranches().staging ?? "staging";
|
|
2389
|
+
return await sweepOrphanPrs({ repo, cwd: process.cwd(), io, base, dryRun });
|
|
2390
|
+
} catch { return []; }
|
|
2391
|
+
}
|
|
2392
|
+
|
|
2383
2393
|
/** #4689: re-evaluate the parked post-deploy follow-ups of the repo (promotion, due date, check now defined); never throws. */
|
|
2384
2394
|
async function sweepParkedFollowups({ repo, io, dryRun = false }) {
|
|
2385
2395
|
try {
|
|
@@ -2903,6 +2913,8 @@ export async function probeFromCli(argv, deps = {}) {
|
|
|
2903
2913
|
for (const r of parkedRows) console.log(`#${r.issue} → ${r.outcome}${r.detail ? ` (${r.detail})` : ""}`);
|
|
2904
2914
|
const { formatParkedSweepSummary } = await import("./lean/parked-sweep.mjs");
|
|
2905
2915
|
console.log(formatParkedSweepSummary(parkedRows) || "parked: nothing released");
|
|
2916
|
+
const orphanRows = await sweepOrphanPrFollowups({ repo, io: leanIo, dryRun: argv.includes("--dry-run") }); // #5505
|
|
2917
|
+
console.log((await import("./lean/orphan-pr.mjs")).formatOrphanSummary(orphanRows) || "orphan PRs: none");
|
|
2906
2918
|
return { rows, parkedRows };
|
|
2907
2919
|
}
|
|
2908
2920
|
const { sweepProbes, formatProbeSummary } = await import("./lean/probe.mjs");
|
package/bin/forge-utils.mjs
CHANGED
|
@@ -29,6 +29,20 @@
|
|
|
29
29
|
// YAML parser
|
|
30
30
|
// ---------------------------------------------------------------------------
|
|
31
31
|
|
|
32
|
+
/** A block-list item without its trailing comment and surrounding quotes. */
|
|
33
|
+
function unquoteListItem(raw) {
|
|
34
|
+
const q = raw.match(/^"([^"]*)"|^'([^']*)'/);
|
|
35
|
+
return q ? (q[1] ?? q[2]) : raw.replace(/\s+#.*$/, "").trim();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** `[a, "b, c"]` -> ["a", "b, c"]; null when `value` is not a flow list (kept as the raw string). */
|
|
39
|
+
function flowList(value) {
|
|
40
|
+
const m = value.match(/^\[(.*)\]$/);
|
|
41
|
+
if (!m) return null;
|
|
42
|
+
const items = [...m[1].matchAll(/\s*(?:"([^"]*)"|'([^']*)'|([^,]*?))\s*(?:,|$)/g)].map((x) => x[1] ?? x[2] ?? x[3]);
|
|
43
|
+
return items.filter((x, k) => !(x === "" && k === items.length - 1 || x === undefined)).map((x) => x.trim());
|
|
44
|
+
}
|
|
45
|
+
|
|
32
46
|
/**
|
|
33
47
|
* Minimal YAML parser for forge.yaml files.
|
|
34
48
|
*
|
|
@@ -38,23 +52,41 @@
|
|
|
38
52
|
* - Nested scalars under a section: ` key: value`
|
|
39
53
|
* - Comments (`# ...`) and blank lines are skipped
|
|
40
54
|
* - Both LF and CRLF line endings (split on /\r?\n/)
|
|
55
|
+
* - Lists of scalars as string arrays (forge#5504): flow `key: [a, "b"]` at top level or under a section, and
|
|
56
|
+
* block ` key:` followed by deeper-indented `- item` lines under a section
|
|
41
57
|
*
|
|
42
|
-
* Does NOT handle:
|
|
58
|
+
* Does NOT handle: nested lists of maps, multi-line values, anchors, aliases, or other
|
|
43
59
|
* YAML features. Intended only for the flat key-value structure of forge.yaml.
|
|
44
60
|
*
|
|
45
61
|
* @param {string} raw - Raw string content of a forge.yaml file.
|
|
46
62
|
* @param {{dottedSections?: string[]}} [opts] - forge#5206: sections whose nested keys may also contain `.` and `-`
|
|
47
63
|
* after the first character (e.g. `experiment:` arm overrides `on.lean.explore: on`); other sections are unchanged.
|
|
48
|
-
* @returns {Record<string, string | Record<string, string>>}
|
|
64
|
+
* @returns {Record<string, string | string[] | Record<string, string | string[]>>}
|
|
49
65
|
*/
|
|
50
66
|
export function parseForgeYaml(raw, { dottedSections = [] } = {}) {
|
|
51
67
|
const result = {};
|
|
52
68
|
let currentSection = null;
|
|
69
|
+
const lines = raw.split(/\r?\n/);
|
|
53
70
|
|
|
54
|
-
for (
|
|
71
|
+
for (let i = 0; i < lines.length; i++) {
|
|
72
|
+
const line = lines[i];
|
|
55
73
|
// Skip comments and blank lines
|
|
56
74
|
if (/^\s*#/.test(line) || /^\s*$/.test(line)) continue;
|
|
57
75
|
|
|
76
|
+
// Nested block list under a section: ` key:` then deeper `- item` lines (forge#5504)
|
|
77
|
+
const listKey = currentSection && line.match(/^(\s+)([a-zA-Z_][a-zA-Z0-9_]*):\s*(?:#.*)?$/);
|
|
78
|
+
if (listKey && typeof result[currentSection] === "object") {
|
|
79
|
+
const items = [];
|
|
80
|
+
let j = i + 1;
|
|
81
|
+
for (; j < lines.length; j++) {
|
|
82
|
+
if (/^\s*(#.*)?$/.test(lines[j])) continue;
|
|
83
|
+
const it = lines[j].match(/^(\s*)-\s+(.*?)\s*$/);
|
|
84
|
+
if (!it || it[1].length < listKey[1].length) break;
|
|
85
|
+
items.push(unquoteListItem(it[2]));
|
|
86
|
+
}
|
|
87
|
+
if (items.length) { result[currentSection][listKey[2]] = items; i = j - 1; continue; }
|
|
88
|
+
}
|
|
89
|
+
|
|
58
90
|
// Top-level section header: `section:` (no value on same line)
|
|
59
91
|
const sectionMatch = line.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(?:#.*)?$/);
|
|
60
92
|
if (sectionMatch) {
|
|
@@ -72,7 +104,7 @@ export function parseForgeYaml(raw, { dottedSections = [] } = {}) {
|
|
|
72
104
|
const value = topScalarMatch[2] ?? topScalarMatch[4]?.trim();
|
|
73
105
|
if (key && value !== undefined) {
|
|
74
106
|
currentSection = null;
|
|
75
|
-
result[key] = value;
|
|
107
|
+
result[key] = topScalarMatch[2] === undefined ? flowList(value) ?? value : value;
|
|
76
108
|
}
|
|
77
109
|
continue;
|
|
78
110
|
}
|
|
@@ -92,7 +124,7 @@ export function parseForgeYaml(raw, { dottedSections = [] } = {}) {
|
|
|
92
124
|
value !== undefined &&
|
|
93
125
|
typeof result[currentSection] === "object"
|
|
94
126
|
) {
|
|
95
|
-
result[currentSection][key] = value;
|
|
127
|
+
result[currentSection][key] = nestedMatch[2] === undefined ? flowList(value) ?? value : value;
|
|
96
128
|
}
|
|
97
129
|
}
|
|
98
130
|
}
|
package/bin/gc.mjs
CHANGED
|
@@ -154,7 +154,7 @@ const errText = (e) => String(e?.stderr || e?.message || e).trim().split("\n")[0
|
|
|
154
154
|
*/
|
|
155
155
|
export async function planGc({ probes, scopes = new Set(GC_SCOPES), olderThanMs = LEDGER_TTL_MS, ttlMs = null, deleteMergedBranches = true, now = Date.now() } = {}) {
|
|
156
156
|
const P = probes, fs = P.fs ?? nodeFs;
|
|
157
|
-
const items = [], notes = [], seen = new Set(), liveIds = new Set(), ledgers = [];
|
|
157
|
+
const items = [], notes = [], seen = new Set(), liveIds = new Set(), ledgers = [], liveLaneIssues = new Set();
|
|
158
158
|
const want = (type) => scopes.has(SCOPE_OF[type]);
|
|
159
159
|
const ttl = (type) => (Number.isFinite(ttlMs?.[type]) ? ttlMs[type] : olderThanMs); // forge.yaml hygiene TTLs, else --older-than
|
|
160
160
|
const add = (it) => { const k = `${it.type}:${it.id}`; if (seen.has(k)) return; seen.add(k); items.push(it); };
|
|
@@ -232,6 +232,7 @@ export async function planGc({ probes, scopes = new Set(GC_SCOPES), olderThanMs
|
|
|
232
232
|
const sameHost = j.host === P.host;
|
|
233
233
|
// A live owner on this host is a running lane, even past `expires` (long CI waits refresh it only on register).
|
|
234
234
|
const stale = sameHost ? !(Number.isSafeInteger(j.pid) && P.alive(j.pid)) : Number(j.expires) < now;
|
|
235
|
+
if (!stale && j.issue != null) liveLaneIssues.add(String(j.issue));
|
|
235
236
|
ledgers.push({ path, batch: j.batch, lane: j.lane, repo: j.repo ?? null, stale });
|
|
236
237
|
for (const r of j.resources) {
|
|
237
238
|
const type = TYPE_OF_KIND[r.kind];
|
|
@@ -280,9 +281,15 @@ export async function planGc({ probes, scopes = new Set(GC_SCOPES), olderThanMs
|
|
|
280
281
|
|
|
281
282
|
// ---- 2. docker: labelled forgedock.owner=1 is owned; everything else is "not owned" ----
|
|
282
283
|
if (want("container") || want("volume")) {
|
|
284
|
+
let psOut = null, psErr = null;
|
|
285
|
+
try { psOut = jsonLines(await P.docker(["ps", "-a", "--size", "--no-trunc", "--format", "{{json .}}"])); } catch (e) { psErr = e; }
|
|
286
|
+
// #5496: a lane compose project is live when its issue has a live ledger or any of its containers is running.
|
|
287
|
+
const runningLane = new Set((psOut ?? []).filter((c) => /^running$/i.test(String(c.State ?? "")) || /^up\b/i.test(String(c.Status ?? ""))).map((c) => String(parseLabels(c.Labels)["com.docker.compose.project"] ?? "")));
|
|
283
288
|
const ownedBy = (labels, createdMs, type) => {
|
|
284
|
-
const
|
|
289
|
+
const project = String(labels["com.docker.compose.project"] ?? "");
|
|
290
|
+
const lane = LANE_COMPOSE_RE.test(project); // #5421: lane compose project by name
|
|
285
291
|
if (labels["forgedock.owner"] !== "1" && !lane) return { owned: false, action: "report", reason: "not owned" };
|
|
292
|
+
if (labels["forgedock.owner"] !== "1" && (liveLaneIssues.has(project.match(/^forgedock-lane-(\d+)/)[1]) || runningLane.has(project))) return { owned: true, action: "report", reason: "live lane compose project" };
|
|
286
293
|
let exp = Number(labels["forgedock.expires"]);
|
|
287
294
|
if (Number.isFinite(exp) && exp > 0 && exp < 1e12) exp *= 1000;
|
|
288
295
|
if (Number.isFinite(exp) && exp > 0 && exp < now) return { owned: true, action: "reclaim", reason: "forgedock label, expired" };
|
|
@@ -291,7 +298,8 @@ export async function planGc({ probes, scopes = new Set(GC_SCOPES), olderThanMs
|
|
|
291
298
|
};
|
|
292
299
|
if (want("container")) {
|
|
293
300
|
try {
|
|
294
|
-
|
|
301
|
+
if (psErr) throw psErr;
|
|
302
|
+
for (const c of psOut) {
|
|
295
303
|
const name = String(c.Names ?? c.ID ?? "").split(",")[0];
|
|
296
304
|
if (!name || seen.has(`container:${name}`)) continue;
|
|
297
305
|
if (liveIds.has(`container:${name}`)) continue;
|
package/bin/lean/lean.mjs
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* ForgeDock registers everything on GitHub (labels, one register comment, PR, merge). No investigation, synthesis,
|
|
6
6
|
* severity taxonomy, risk tiers or local CI gates. All effects are injected through `io` so it is unit-testable.
|
|
7
7
|
*/
|
|
8
|
+
import { issuePrMarker, supersedeOlderPrs, openPrBlockingClose } from "./orphan-pr.mjs";
|
|
8
9
|
import { resolveFindingLabel } from "./findinglabel.mjs";
|
|
9
10
|
import { spawnSync } from "node:child_process";
|
|
10
11
|
import { existsSync, readFileSync } from "node:fs";
|
|
@@ -300,6 +301,8 @@ export async function runCore(o) {
|
|
|
300
301
|
let lane = null, base = null, defaults = [], milestone = null; // set by lane resolution, before the lease
|
|
301
302
|
// #4267: a batch recovery lane for a mechanical needs-human ({code, attempt, final}); #4302: only a final attempt relabels.
|
|
302
303
|
const recover = o.recover && typeof o.recover.code === "string" ? { code: o.recover.code, attempt: Number.isInteger(o.recover.attempt) ? o.recover.attempt : 1, final: o.recover.final !== false } : null;
|
|
304
|
+
const withLink = (body) => `${issuePrMarker(issue)}\n${body}`; // #5505: the issue → PR link GitHub does not record for a staging PR
|
|
305
|
+
const closeBlockers = (reason, exceptPr = null) => openPrBlockingClose({ repo, io: { gh: ghw }, issue, reason, exceptPr }).catch(() => []); // #5505: fail open
|
|
303
306
|
let branch = `feat/issue-${issue}-lean`; // #5469: an adopted PR's own head branch replaces it
|
|
304
307
|
const wt = join(o.worktreeRoot ?? join(cwd, ".claude", "worktrees"), `lean-${issue}`);
|
|
305
308
|
const t0 = now();
|
|
@@ -2139,7 +2142,7 @@ export async function runCore(o) {
|
|
|
2139
2142
|
T.plan = "skipped"; T.implement = "skipped"; T.review = "skipped"; T.pr = "none"; T.merge = "n/a";
|
|
2140
2143
|
T.decisions.push(`Builder verdict: ${result.status}`);
|
|
2141
2144
|
// #5152: already-fixed is delivered behaviour (`completed`); only invalid is dropped scope (`not planned`)
|
|
2142
|
-
await Promise.all([ghw(["issue", "close", String(issue), "-R", repo, "--reason", result.status === "already-fixed" ? "completed" : "not planned"]), label("invalid")]); // #5437: independent calls
|
|
2145
|
+
await Promise.all([result.status === "already-fixed" && (await closeBlockers("completed")).length ? null : ghw(["issue", "close", String(issue), "-R", repo, "--reason", result.status === "already-fixed" ? "completed" : "not planned"]), label("invalid")]); // #5437: independent calls
|
|
2143
2146
|
if (result.status === "invalid") { const f = await resolveFindingLabel({ io, issue, labels: iss.labels, reason: "invalid" }); if (f.error) T.anomalies.push(`finding label not resolved: ${f.error}`); } // #5254
|
|
2144
2147
|
return await finish("invalid", result.summary ?? result.status, result.status === "already-fixed" ? { close: "already-fixed" } : {});
|
|
2145
2148
|
}
|
|
@@ -3215,7 +3218,7 @@ export async function runCore(o) {
|
|
|
3215
3218
|
const sha = String(await git(["rev-parse", base]).catch(() => "")).trim().slice(0, 12) || base;
|
|
3216
3219
|
const note = `Already fixed on the base: the repro test passes on \`${base}\` (${sha}) without this change, and the diff changes no source file. Closing as delivered.\n\n${list}`;
|
|
3217
3220
|
T.decisions.push(`Already fixed on base ${sha} (repro BASE=RAN HEAD=RAN)`);
|
|
3218
|
-
await ghw(["issue", "close", String(issue), "-R", repo, "--reason", "completed", "--comment", note]);
|
|
3221
|
+
if (!(await closeBlockers("completed")).length) await ghw(["issue", "close", String(issue), "-R", repo, "--reason", "completed", "--comment", note]);
|
|
3219
3222
|
return await finish("invalid", `already fixed on base ${sha}`, { close: "already-fixed" });
|
|
3220
3223
|
}
|
|
3221
3224
|
if (outcome.state === "review.unparseable") return await needsHuman(`The conformance reviewer returned no parseable JSON twice; nothing merged.`, OUTCOME_CODES.REVIEW_NO_VERDICT);
|
|
@@ -3296,14 +3299,15 @@ export async function runCore(o) {
|
|
|
3296
3299
|
await gitPush(["push", "-u", "origin", branch]);
|
|
3297
3300
|
laneGuard(lane, "open a PR");
|
|
3298
3301
|
const prOut = resumed?.pr ? `/pull/${resumed.pr}` : String(await ghw(["pr", "create", "-R", repo, "--base", lane, "--head", branch,
|
|
3299
|
-
"--title", `${iss.title} (#${issue})`, "--body", isSplit ? (o.refactorModule ?? (await import("./refactor.mjs"))).renderSplitPrBody({ issue, ...split })
|
|
3300
|
-
: renderPrBody({ issue, investigation: await readStage(STAGES[0]), contract: effective, implementation: await readStage(STAGES[1]), result, gitFiles: files, tracked: closing.tracked })])).trim();
|
|
3302
|
+
"--title", `${iss.title} (#${issue})`, "--body", withLink(isSplit ? (o.refactorModule ?? (await import("./refactor.mjs"))).renderSplitPrBody({ issue, ...split })
|
|
3303
|
+
: renderPrBody({ issue, investigation: await readStage(STAGES[0]), contract: effective, implementation: await readStage(STAGES[1]), result, gitFiles: files, tracked: closing.tracked }))])).trim();
|
|
3301
3304
|
const pr = Number(/\/pull\/(\d+)/.exec(prOut)?.[1] ?? /(\d+)\s*$/.exec(prOut)?.[1]);
|
|
3302
3305
|
if (!Number.isInteger(pr)) return await needsHuman(`Could not parse the PR number from: ${prOut.slice(0, 200)}`);
|
|
3303
3306
|
ev({ event: "PR_OPENED", pr });
|
|
3304
3307
|
await emit({ event: "PR_OPENED", pr });
|
|
3308
|
+
if (!resumed?.pr && !adoptPr) { try { const old = await supersedeOlderPrs({ repo, io: { gh: ghw }, issue, newPr: pr }); if (old.length) T.decisions.push(`Superseded older open PR(s) ${old.map((n) => `#${n}`).join(", ")} (one live PR per issue)`); } catch { /* best effort: the orphan sweep closes it later */ } } // #5505
|
|
3305
3309
|
if (resumed?.pr && closing.tracked.length) { // an existing PR still has to link the tracking issues visibly
|
|
3306
|
-
try { await ghw(["pr", "edit", String(pr), "-R", repo, "--body", renderPrBody({ issue, investigation: await readStage(STAGES[0]), contract: effective, implementation: await readStage(STAGES[1]), result, gitFiles: files, tracked: closing.tracked })]); }
|
|
3310
|
+
try { await ghw(["pr", "edit", String(pr), "-R", repo, "--body", withLink(renderPrBody({ issue, investigation: await readStage(STAGES[0]), contract: effective, implementation: await readStage(STAGES[1]), result, gitFiles: files, tracked: closing.tracked }))]); }
|
|
3307
3311
|
catch (e) { e.deferCode = OUTCOME_CODES.FOLLOWUP_UNAVAILABLE; e.deferDetail = `could not link the tracking issues on PR #${pr}; nothing merged, rerun to retry`; throw e; }
|
|
3308
3312
|
}
|
|
3309
3313
|
if (degraded) {
|
|
@@ -3747,7 +3751,7 @@ export async function runCore(o) {
|
|
|
3747
3751
|
try { await post("FORGE:TRACKED", `## Left open: live acceptance deferred on a default-on change\nMerged by PR #${pr}, but the rollout is live and these requirements still need live verification:\n${closing.blocks.map((b) => `- ${b.id} (flag ${b.flag})`).join("\n")}\n\nKeep the flag default-off until they are verified, or verify them and close.${closing.tracked.length ? ` Tracked in ${closing.tracked.join(", ")}.` : ""}`); } catch { /* the trajectory decision records it too */ }
|
|
3748
3752
|
}
|
|
3749
3753
|
// #5152: a merged change is `completed` even when partial: the remainder is tracked (FORGE:TRACKED), not dropped
|
|
3750
|
-
if (!keepOpen) await ghw(["issue", "close", String(issue), "-R", repo, "--reason", "completed"]).catch(() => {});
|
|
3754
|
+
if (!keepOpen && !(await closeBlockers("completed", pr)).length) await ghw(["issue", "close", String(issue), "-R", repo, "--reason", "completed"]).catch(() => {}); // #5505: not while another own PR is open
|
|
3751
3755
|
if (closing.transferred) { // #5339: record what is transferred, not met
|
|
3752
3756
|
try { await post("FORGE:TRACKED", `## Left open: transferred, not met\nMerged by PR #${pr}, but these end-to-end/manual requirements were not run in the lane:\n${(closing.transfer ?? closing.open).map((r) => `- ${r.id}: ${r.transferred ? `transferred to epic #${r.transferred} (post-deploy journey)` : "no epic to take it"}`).join("\n")}${closing.tracked.length ? `\n\nTracked in ${closing.tracked.join(", ")}.` : ""}`); } catch { /* the PR body carries them too */ }
|
|
3753
3757
|
} else if (closing.liveBlocked) { /* #5285: posted above */ } else if (closing.checklist) { // #5240: partial: left open; the unticked criteria, tracked follow-ups and any inert rollout are the record
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Orphan-PR sweep (#5505). A lane PR targets the lane base (`staging`), so GitHub never links it to its issue
|
|
5
|
+
* (`closingIssuesReferences` is empty) and nothing closed it when the issue was resolved another way. The issue → PR link is
|
|
6
|
+
* derived here from the lane branch `feat/issue-<n>-lean` or a `FORGE:ISSUE_PR` marker in the PR body, never from GitHub's link.
|
|
7
|
+
* Deterministic, no model call. Each open PR whose issue is closed is classified, in order:
|
|
8
|
+
* backport-pending (kept) > not_planned > duplicate > superseded > undelivered.
|
|
9
|
+
*/
|
|
10
|
+
export const BACKPORT_LABEL = "backport-pending";
|
|
11
|
+
export const ALERT_AGE_MS = 24 * 3600 * 1000;
|
|
12
|
+
const MARK = (n) => `<!-- FORGE:ISSUE_PR issue=${n} -->`;
|
|
13
|
+
|
|
14
|
+
/** Issue number a PR was built for, or null (not a ForgeDock PR). */
|
|
15
|
+
export function parseIssueLink(pr) {
|
|
16
|
+
const m = /^feat\/issue-(\d+)-lean$/.exec(String(pr?.headRefName ?? "")) ?? /FORGE:ISSUE_PR issue=(\d+)/.exec(String(pr?.body ?? ""));
|
|
17
|
+
return m ? Number(m[1]) : null;
|
|
18
|
+
}
|
|
19
|
+
export const issuePrMarker = MARK;
|
|
20
|
+
|
|
21
|
+
/** Pure: `{ kind, detail }` for one open PR whose issue is closed. `ctx`: { issue:{stateReason,labels}, preferred, merged, onBase, base }. */
|
|
22
|
+
export function classifyOrphanPr(pr, ctx) {
|
|
23
|
+
const labels = (ctx.issue?.labels ?? []).map((l) => (typeof l === "string" ? l : l?.name));
|
|
24
|
+
if (labels.includes(BACKPORT_LABEL)) return { kind: "backport-pending", detail: "the backport is still pending" };
|
|
25
|
+
if (/^(not_planned|duplicate)$/i.test(String(ctx.issue?.stateReason ?? ""))) return { kind: "not_planned", detail: "the issue was closed as not planned" };
|
|
26
|
+
if (ctx.merged) return { kind: "duplicate", detail: `PR #${ctx.merged} for the same issue is merged` };
|
|
27
|
+
if (ctx.preferred && ctx.preferred !== pr.number) return { kind: "duplicate", detail: `PR #${ctx.preferred} is the preferred PR for the same issue` };
|
|
28
|
+
if (ctx.onBase) return { kind: "superseded", detail: `an equivalent change is already on \`${ctx.base}\` (${ctx.onBase})` };
|
|
29
|
+
return { kind: "undelivered", detail: `the change is not on \`${ctx.base}\`` };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** `{ count, oldestAgeMs, alert }` over rows with an `ageMs`; alert when any orphan is older than 24h. Kept PRs (backport-pending) do not count. */
|
|
33
|
+
export function orphanTelemetry(rows) {
|
|
34
|
+
const r = (rows ?? []).filter((x) => x.kind && x.kind !== "backport-pending");
|
|
35
|
+
const oldestAgeMs = r.reduce((m, x) => Math.max(m, x.ageMs ?? 0), 0);
|
|
36
|
+
return { count: r.length, oldestAgeMs, alert: r.length > 0 && oldestAgeMs > ALERT_AGE_MS };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const json = async (io, args) => { try { const v = JSON.parse(String(await io.gh(args)) || "null"); return v; } catch { return null; } };
|
|
40
|
+
|
|
41
|
+
/** Open PRs (other than `exceptPr`) built for `issue`; empty when the close is `not planned`/`duplicate` or gh fails (fail open). */
|
|
42
|
+
export async function openPrBlockingClose({ repo, io, issue, reason = "completed", exceptPr = null }) {
|
|
43
|
+
if (/not.?planned|duplicate/i.test(reason)) return [];
|
|
44
|
+
const prs = await json(io, ["pr", "list", "-R", repo, "--state", "open", "--limit", "200", "--json", "number,headRefName,body"]);
|
|
45
|
+
return (prs ?? []).filter((p) => p.number !== exceptPr && parseIssueLink(p) === issue).map((p) => p.number);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** One live PR per issue: close every other open PR of `issue` as superseded by `newPr`. Returns the closed numbers. */
|
|
49
|
+
export async function supersedeOlderPrs({ repo, io, issue, newPr, dryRun = false }) {
|
|
50
|
+
const prs = await json(io, ["pr", "list", "-R", repo, "--state", "open", "--limit", "200", "--json", "number,headRefName,body"]);
|
|
51
|
+
const old = (prs ?? []).filter((p) => p.number !== newPr && parseIssueLink(p) === issue).map((p) => p.number);
|
|
52
|
+
if (!dryRun) for (const n of old) await io.gh(["pr", "close", String(n), "-R", repo, "--comment", `Superseded by #${newPr}: one live PR per issue (#${issue}).`]);
|
|
53
|
+
return old;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Sweep every open PR to `base` whose issue is closed; one row per PR. Never throws; an unreadable PR is an `error` row. */
|
|
57
|
+
export async function sweepOrphanPrs({ repo, cwd = process.cwd(), io, base = "staging", dryRun = false, onResult = null } = {}) {
|
|
58
|
+
const now = io.now?.() ?? Date.now();
|
|
59
|
+
const rows = [];
|
|
60
|
+
const open = await json(io, ["pr", "list", "-R", repo, "--state", "open", "--base", base, "--limit", "200", "--json", "number,headRefName,body,createdAt"]);
|
|
61
|
+
const merged = await json(io, ["pr", "list", "-R", repo, "--state", "merged", "--base", base, "--limit", "200", "--json", "number,headRefName,body"]);
|
|
62
|
+
const byIssue = new Map();
|
|
63
|
+
for (const p of open ?? []) { const n = parseIssueLink(p); if (n) byIssue.set(n, [...(byIssue.get(n) ?? []), p]); }
|
|
64
|
+
const mergedFor = new Map();
|
|
65
|
+
for (const p of merged ?? []) { const n = parseIssueLink(p); if (n && !mergedFor.has(n)) mergedFor.set(n, p.number); }
|
|
66
|
+
for (const [issue, prs] of [...byIssue].sort((a, b) => a[0] - b[0])) {
|
|
67
|
+
const iss = await json(io, ["issue", "view", String(issue), "-R", repo, "--json", "state,stateReason,labels"]);
|
|
68
|
+
if (!iss || String(iss.state).toUpperCase() !== "CLOSED") continue;
|
|
69
|
+
const preferred = Math.max(...prs.map((p) => p.number));
|
|
70
|
+
for (const pr of prs.sort((a, b) => a.number - b.number)) {
|
|
71
|
+
let row = { pr: pr.number, issue, kind: null, ageMs: Math.max(0, now - Date.parse(pr.createdAt ?? now)) };
|
|
72
|
+
try {
|
|
73
|
+
let onBase = null;
|
|
74
|
+
try {
|
|
75
|
+
await io.git(["fetch", "-q", "origin", base, pr.headRefName], { cwd });
|
|
76
|
+
const cherry = String(await io.git(["cherry", `origin/${base}`, `origin/${pr.headRefName}`], { cwd })).split("\n").filter(Boolean);
|
|
77
|
+
if (!cherry.some((l) => l.startsWith("+"))) onBase = String(await io.git(["rev-parse", "--short=12", `origin/${base}`], { cwd })).trim();
|
|
78
|
+
} catch { onBase = null; } // unknown: never close as superseded on a git failure
|
|
79
|
+
const c = classifyOrphanPr(pr, { issue: iss, preferred, merged: mergedFor.get(issue), onBase, base });
|
|
80
|
+
row = { ...row, ...c };
|
|
81
|
+
if (c.kind !== "backport-pending" && !dryRun) {
|
|
82
|
+
let note = `Closing: issue #${issue} is closed and this PR is orphaned (${c.kind}): ${c.detail}.`;
|
|
83
|
+
if (c.kind === "undelivered") {
|
|
84
|
+
const marker = `FORGE:ORPHAN_PR pr=${pr.number}`;
|
|
85
|
+
const found = await json(io, ["issue", "list", "-R", repo, "--state", "all", "--search", `"${marker}" in:body`, "--json", "number"]);
|
|
86
|
+
let ref = found?.[0]?.number ? `#${found[0].number}` : null;
|
|
87
|
+
if (!ref) { const out = String(await io.gh(["issue", "create", "-R", repo, "--title", `Follow-up: undelivered work from PR #${pr.number} (issue #${issue})`, "--body", `PR #${pr.number} (branch \`${pr.headRefName}\`) was never merged and issue #${issue} is closed. Its change is not on \`${base}\`.\n\n<!-- ${marker} -->`])).trim(); ref = /(\d+)$/.test(out) ? `#${/(\d+)$/.exec(out)[1]}` : out; }
|
|
88
|
+
row.followup = ref;
|
|
89
|
+
note += ` Follow-up filed: ${ref} (branch \`${pr.headRefName}\` is kept).`;
|
|
90
|
+
}
|
|
91
|
+
await io.gh(["pr", "close", String(pr.number), "-R", repo, "--comment", note]);
|
|
92
|
+
row.closed = true;
|
|
93
|
+
}
|
|
94
|
+
} catch (e) { row = { ...row, kind: "error", detail: String(e?.message ?? e).slice(0, 160) }; }
|
|
95
|
+
rows.push(row);
|
|
96
|
+
try { if (!dryRun) await onResult?.(row); } catch { /* an event sink never fails the sweep */ }
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (!dryRun) await clearBackportPending({ repo, io, rows });
|
|
100
|
+
return rows;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** A closed issue labelled `backport-pending` whose backport PR (a `hotfix/*` or `backport/*` head naming it) is merged and none open: unlabel and close it. */
|
|
104
|
+
async function clearBackportPending({ repo, io, rows }) {
|
|
105
|
+
const issues = await json(io, ["issue", "list", "-R", repo, "--state", "all", "--label", BACKPORT_LABEL, "--limit", "100", "--json", "number,state"]);
|
|
106
|
+
for (const i of issues ?? []) {
|
|
107
|
+
try {
|
|
108
|
+
const prs = (await json(io, ["pr", "list", "-R", repo, "--state", "all", "--search", `#${i.number} in:title,body`, "--limit", "20", "--json", "number,state,headRefName"])) ?? [];
|
|
109
|
+
const bp = prs.filter((p) => /^(hotfix|backport)\//.test(p.headRefName));
|
|
110
|
+
if (!bp.length || bp.some((p) => p.state === "OPEN") || !bp.some((p) => p.state === "MERGED")) continue;
|
|
111
|
+
await io.gh(["issue", "edit", String(i.number), "-R", repo, "--remove-label", BACKPORT_LABEL]);
|
|
112
|
+
if (String(i.state).toUpperCase() === "OPEN") await io.gh(["issue", "close", String(i.number), "-R", repo, "--reason", "completed", "--comment", `The backport merged (PR #${bp.find((p) => p.state === "MERGED").number}); closing.`]);
|
|
113
|
+
rows.push({ issue: i.number, kind: "backport-merged", detail: "label cleared" });
|
|
114
|
+
} catch { /* retried on the next sweep */ }
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** One line, e.g. `orphan PRs: closed 2 (superseded #4); ALERT oldest 30h`; "" when nothing orphaned. */
|
|
119
|
+
export function formatOrphanSummary(rows) {
|
|
120
|
+
const t = orphanTelemetry(rows);
|
|
121
|
+
const closed = (rows ?? []).filter((r) => r.closed);
|
|
122
|
+
if (!t.count && !closed.length) return "";
|
|
123
|
+
return `orphan PRs: ${t.count} found, ${closed.length} closed${closed.length ? ` (${closed.map((r) => `${r.kind} #${r.pr}`).join(", ")})` : ""}${t.alert ? `; ALERT oldest ${Math.round(t.oldestAgeMs / 3600000)}h` : ""}`;
|
|
124
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
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 { parseIssueLink, classifyOrphanPr, orphanTelemetry, openPrBlockingClose, supersedeOlderPrs, sweepOrphanPrs, formatOrphanSummary, issuePrMarker } from "./orphan-pr.mjs";
|
|
6
|
+
|
|
7
|
+
const NOW = Date.parse("2026-11-11T12:00:00Z");
|
|
8
|
+
const pr = (number, issue, extra = {}) => ({ number, headRefName: `feat/issue-${issue}-lean`, body: "", createdAt: "2026-11-09T12:00:00Z", ...extra });
|
|
9
|
+
|
|
10
|
+
/** Fake repo. `issues`: n -> {state, stateReason, labels}; `cherry`: head -> git cherry output. */
|
|
11
|
+
function world({ open = [], merged = [], issues = {}, cherry = {}, labelled = [], all = [] }) {
|
|
12
|
+
const w = { closed: [], created: [], edits: [], gitFail: false };
|
|
13
|
+
w.io = {
|
|
14
|
+
now: () => NOW,
|
|
15
|
+
gh: async (a) => {
|
|
16
|
+
const k = a.slice(0, 2).join(" ");
|
|
17
|
+
if (k === "pr list") { const st = a[a.indexOf("--state") + 1]; return JSON.stringify(a.includes("--search") ? all : st === "merged" ? merged : open); }
|
|
18
|
+
if (k === "issue view") return JSON.stringify({ labels: [], ...issues[Number(a[2])], labels: (issues[Number(a[2])]?.labels ?? []).map((name) => ({ name })) });
|
|
19
|
+
if (k === "issue list") return JSON.stringify(a.includes("--search") ? [] : labelled);
|
|
20
|
+
if (k === "issue create") { w.created.push(a); return "https://github.com/o/r/issues/900\n"; }
|
|
21
|
+
if (k === "pr close") { w.closed.push({ pr: Number(a[2]), comment: a[a.indexOf("--comment") + 1] }); return ""; }
|
|
22
|
+
if (k === "issue edit" || k === "issue close") { w.edits.push(a); return ""; }
|
|
23
|
+
throw new Error(`unexpected gh ${a.join(" ")}`);
|
|
24
|
+
},
|
|
25
|
+
git: async (a) => {
|
|
26
|
+
if (w.gitFail) throw new Error("git down");
|
|
27
|
+
if (a[0] === "fetch") return "";
|
|
28
|
+
if (a[0] === "cherry") return cherry[a[2].replace("origin/", "")] ?? "+ abc\n";
|
|
29
|
+
if (a[0] === "rev-parse") return "c0ffee123456\n";
|
|
30
|
+
throw new Error(`unexpected git ${a.join(" ")}`);
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
return w;
|
|
34
|
+
}
|
|
35
|
+
const run = (w, extra = {}) => sweepOrphanPrs({ repo: "o/r", io: w.io, ...extra });
|
|
36
|
+
|
|
37
|
+
describe("orphan-PR sweep (#5505)", () => {
|
|
38
|
+
it("derives the link from the branch or the marker, never closingIssuesReferences", () => {
|
|
39
|
+
assert.equal(parseIssueLink(pr(1, 7)), 7);
|
|
40
|
+
assert.equal(parseIssueLink({ headRefName: "x", body: `hi ${issuePrMarker(9)}` }), 9);
|
|
41
|
+
assert.equal(parseIssueLink({ headRefName: "hand/fix-7", body: "Closes #7", closingIssuesReferences: [{ number: 7 }] }), null);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it("pattern 1: issue closed by another PR; the equivalent change is on base -> superseded, citing the commit", async () => {
|
|
45
|
+
const w = world({ open: [pr(40338, 40048)], issues: { 40048: { state: "CLOSED", stateReason: "COMPLETED" } }, cherry: { "feat/issue-40048-lean": "- abc\n" } });
|
|
46
|
+
const rows = await run(w);
|
|
47
|
+
assert.equal(rows[0].kind, "superseded");
|
|
48
|
+
assert.match(w.closed[0].comment, /c0ffee123456/);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("pattern 2: two PRs for one closed issue -> the older is a duplicate; the newest is judged on its own diff", async () => {
|
|
52
|
+
const w = world({ open: [pr(40138, 40137), pr(40340, 40137)], issues: { 40137: { state: "CLOSED", stateReason: "COMPLETED" } } });
|
|
53
|
+
const rows = await run(w);
|
|
54
|
+
assert.equal(rows.find((r) => r.pr === 40138).kind, "duplicate");
|
|
55
|
+
assert.equal(rows.find((r) => r.pr === 40340).kind, "undelivered");
|
|
56
|
+
assert.equal(w.closed.length, 2);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("pattern 3: a hotfix backport issue labelled backport-pending keeps its PR open", async () => {
|
|
60
|
+
const w = world({ open: [pr(39718, 39450)], issues: { 39450: { state: "CLOSED", stateReason: "COMPLETED", labels: [BACK] } } });
|
|
61
|
+
const rows = await run(w);
|
|
62
|
+
assert.equal(rows[0].kind, "backport-pending");
|
|
63
|
+
assert.equal(w.closed.length, 0);
|
|
64
|
+
assert.equal(orphanTelemetry(rows).count, 0);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it("pattern 3b: the backport merged -> label cleared and the issue closed", async () => {
|
|
68
|
+
const w = world({ labelled: [{ number: 39450, state: "OPEN" }], all: [{ number: 5, state: "MERGED", headRefName: "hotfix/google-mobile-pool-39450" }] });
|
|
69
|
+
await run(w);
|
|
70
|
+
assert.ok(w.edits.some((a) => a.includes("--remove-label")) && w.edits.some((a) => a[1] === "close"));
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("pattern 4: lane PR left behind after decompose, never delivered -> follow-up filed first, then PR closed", async () => {
|
|
74
|
+
const w = world({ open: [pr(38601, 38564)], issues: { 38564: { state: "CLOSED", stateReason: "COMPLETED" } } });
|
|
75
|
+
const rows = await run(w);
|
|
76
|
+
assert.equal(rows[0].kind, "undelivered");
|
|
77
|
+
assert.equal(w.created.length, 1);
|
|
78
|
+
assert.match(w.created[0].join(" "), /feat\/issue-38564-lean/);
|
|
79
|
+
assert.match(w.closed[0].comment, /#900/);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it("pattern 4b: a failed follow-up filing never closes the PR (no lost work)", async () => {
|
|
83
|
+
const w = world({ open: [pr(38601, 38564)], issues: { 38564: { state: "CLOSED", stateReason: "COMPLETED" } } });
|
|
84
|
+
const gh = w.io.gh; w.io.gh = async (a) => { if (a[0] === "issue" && a[1] === "create") throw new Error("boom"); return gh(a); };
|
|
85
|
+
const rows = await run(w);
|
|
86
|
+
assert.equal(rows[0].kind, "error");
|
|
87
|
+
assert.equal(w.closed.length, 0);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("pattern 5: issue closed as not planned -> PR closed", async () => {
|
|
91
|
+
const w = world({ open: [pr(36719, 36662)], issues: { 36662: { state: "CLOSED", stateReason: "NOT_PLANNED" } } });
|
|
92
|
+
assert.equal((await run(w))[0].kind, "not_planned");
|
|
93
|
+
assert.equal(w.closed.length, 1);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it("a merged sibling PR makes the open one a duplicate", () => {
|
|
97
|
+
assert.equal(classifyOrphanPr({ number: 3 }, { issue: {}, merged: 9, base: "staging" }).kind, "duplicate");
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("an open issue, a non-lane PR and a git failure are never closed", async () => {
|
|
101
|
+
const w = world({ open: [pr(1, 5), { number: 2, headRefName: "hand/x", body: "" }, pr(3, 6)], issues: { 5: { state: "OPEN" }, 6: { state: "CLOSED", stateReason: "COMPLETED" } }, cherry: { "feat/issue-6-lean": "" } });
|
|
102
|
+
w.gitFail = true;
|
|
103
|
+
const rows = await run(w);
|
|
104
|
+
assert.equal(rows.length, 1);
|
|
105
|
+
assert.equal(rows[0].kind, "undelivered"); // git unknown is not superseded
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it("--dry-run writes nothing", async () => {
|
|
109
|
+
const w = world({ open: [pr(36719, 36662)], issues: { 36662: { state: "CLOSED", stateReason: "NOT_PLANNED" } } });
|
|
110
|
+
const rows = await run(w, { dryRun: true });
|
|
111
|
+
assert.equal(rows[0].kind, "not_planned");
|
|
112
|
+
assert.equal(w.closed.length + w.created.length + w.edits.length, 0);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("telemetry counts orphans and alerts only past 24h", () => {
|
|
116
|
+
assert.deepEqual(orphanTelemetry([{ kind: "superseded", ageMs: 3600000 }]), { count: 1, oldestAgeMs: 3600000, alert: false });
|
|
117
|
+
assert.equal(orphanTelemetry([{ kind: "undelivered", ageMs: 90000000 }]).alert, true);
|
|
118
|
+
assert.match(formatOrphanSummary([{ kind: "undelivered", pr: 4, ageMs: 90000000, closed: true }]), /ALERT oldest 25h/);
|
|
119
|
+
assert.equal(formatOrphanSummary([]), "");
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
describe("one live PR per issue and the close gate (#5505)", () => {
|
|
124
|
+
it("supersedes the older open PR of the same issue, not other issues' PRs", async () => {
|
|
125
|
+
const w = world({ open: [pr(10, 7), pr(11, 7), pr(12, 8)] });
|
|
126
|
+
assert.deepEqual(await supersedeOlderPrs({ repo: "o/r", io: w.io, issue: 7, newPr: 11 }), [10]);
|
|
127
|
+
assert.deepEqual(w.closed.map((c) => c.pr), [10]);
|
|
128
|
+
assert.match(w.closed[0].comment, /Superseded by #11/);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it("blocks a completed close while another own PR is open; not planned and duplicate close freely", async () => {
|
|
132
|
+
const w = world({ open: [pr(10, 7), pr(11, 7)] });
|
|
133
|
+
assert.deepEqual(await openPrBlockingClose({ repo: "o/r", io: w.io, issue: 7, reason: "completed", exceptPr: 11 }), [10]);
|
|
134
|
+
assert.deepEqual(await openPrBlockingClose({ repo: "o/r", io: w.io, issue: 7, reason: "not planned" }), []);
|
|
135
|
+
assert.deepEqual(await openPrBlockingClose({ repo: "o/r", io: w.io, issue: 7, reason: "duplicate" }), []);
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
const BACK = "backport-pending";
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
/**
|
|
4
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`).
|
|
5
|
+
* wait for the published artifact (`release.artifact_check`), then open and auto-merge the version-sync PR (`release.version_sync`).
|
|
6
6
|
* Every wait is bounded (`ctx.config.postMerge` overrides the bounds) and ends in `{blocked}`, never a throw, so a resume
|
|
7
7
|
* retries the step; each sub-step is idempotent (an existing run, PR or merged PR is reused). Rationale:
|
|
8
8
|
* devdocs/decisions/5208-release-postmerge.md.
|
|
@@ -15,7 +15,7 @@ const BOUNDS = {
|
|
|
15
15
|
runPolls: 90, runPollMs: 20_000, // wait for the run to finish
|
|
16
16
|
artifactTries: 8, artifactBaseMs: 5_000, artifactMaxMs: 120_000, // npm propagation: exponential backoff
|
|
17
17
|
branchPolls: 6, branchPollMs: 10_000, // wait for the sync branch to be pushed
|
|
18
|
-
|
|
18
|
+
autoPolls: 30, autoPollMs: 20_000, // wait for the sync PR's auto-merge
|
|
19
19
|
};
|
|
20
20
|
const json = (s) => JSON.parse(String(s || "null"));
|
|
21
21
|
const blocked = (reason) => ({ blocked: true, reason });
|
|
@@ -64,35 +64,52 @@ async function artifact(ctx, b) {
|
|
|
64
64
|
return { err: `release.artifact_check still failing after ${b.artifactTries} tries: ${config.artifactCheck}` };
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
const b64 = (s) => Buffer.from(String(s).replace(/\s/g, ""), "base64").toString("utf8");
|
|
68
|
+
const semverLt = (a, b) => { const x = String(a).split(/[.-]/).map(Number), y = String(b).split(/[.-]/).map(Number); for (let i = 0; i < 3; i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) < (y[i] || 0); return false; };
|
|
69
|
+
const VERSION_FILES = ["package.json", ".claude-plugin/plugin.json"];
|
|
70
|
+
|
|
71
|
+
/** The sync branch is missing (publish.yml failed before pushing): cut it from the staging head with a version-only commit, through the gh API. */
|
|
72
|
+
async function createSyncBranch({ io, repo, staging }, branch, version) {
|
|
73
|
+
const base = String(await io.gh(["api", `repos/${repo}/git/ref/heads/${staging}`, "--jq", ".object.sha"])).trim();
|
|
74
|
+
await io.gh(["api", "-X", "POST", `repos/${repo}/git/refs`, "-f", `ref=refs/heads/${branch}`, "-f", `sha=${base}`]);
|
|
75
|
+
for (const f of VERSION_FILES) {
|
|
76
|
+
let cur;
|
|
77
|
+
try { cur = json(await io.gh(["api", `repos/${repo}/contents/${f}?ref=${staging}`])); } catch { if (f === "package.json") throw new Error(`${f} unreadable on ${staging}`); continue; }
|
|
78
|
+
const doc = JSON.parse(b64(cur.content));
|
|
79
|
+
doc.version = version;
|
|
80
|
+
await io.gh(["api", "-X", "PUT", `repos/${repo}/contents/${f}`, "-f", `message=chore: sync version ${version} to ${staging}`, "-f", `content=${Buffer.from(JSON.stringify(doc, null, 2) + "\n").toString("base64")}`, "-f", `sha=${cur.sha}`, "-f", `branch=${branch}`]);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The release PR's version goes back to staging (#5513): publish.yml cannot open the PR (enterprise policy), so the host does, then enables auto-merge. */
|
|
67
85
|
async function versionSync(ctx, sha, b) {
|
|
68
86
|
const { io, repo, staging } = ctx;
|
|
69
|
-
const
|
|
70
|
-
const
|
|
87
|
+
const read = async (ref) => JSON.parse(b64(await io.gh(["api", `repos/${repo}/contents/package.json?ref=${ref}`, "--jq", ".content"]))).version;
|
|
88
|
+
const version = await read(sha);
|
|
89
|
+
const cur = await read(staging);
|
|
90
|
+
if (!semverLt(cur, version)) return { skipped: true, version, staging: cur };
|
|
91
|
+
const branch = `chore/sync-version-${version}`;
|
|
71
92
|
const find = async () => json(await io.gh(["pr", "list", "--repo", repo, "--base", staging, "--head", branch, "--state", "all", "--json", "number,state", "--limit", "1"]))?.[0] ?? null;
|
|
72
93
|
let pr = await find();
|
|
73
94
|
if (pr?.state === "MERGED") return { pr: pr.number, merged: true, reused: true };
|
|
74
95
|
if (!pr) {
|
|
75
96
|
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; } });
|
|
76
|
-
if (!has)
|
|
77
|
-
|
|
97
|
+
if (!has) {
|
|
98
|
+
try { await createSyncBranch(ctx, branch, version); } catch (e) { return { err: `version-sync branch ${branch} is missing and could not be created (${String(e.message).split("\n")[0]}); open it by hand` }; }
|
|
99
|
+
}
|
|
100
|
+
const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", staging, "--head", branch, "--title", `chore: sync version ${version} to ${staging}`, "--body", `Version-only sync of the ${version} release back to ${staging} (forgedock release).\n\ndocs-not-needed: version-only sync, no behaviour change`])).trim();
|
|
78
101
|
const n = Number(/\/pull\/(\d+)/.exec(url)?.[1]);
|
|
79
102
|
if (!Number.isSafeInteger(n)) return { err: `gh pr create returned no PR url: ${url}` };
|
|
80
103
|
pr = { number: n };
|
|
81
104
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
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 }; }
|
|
88
|
-
return res.length && res.every((r) => GREEN.has(r)) ? { head: v.headRefOid } : null;
|
|
105
|
+
const warn = (why) => ({ pr: pr.number, merged: false, warning: `version-sync PR #${pr.number} ${why}; merge it by hand so ${staging} reaches ${version}` });
|
|
106
|
+
try { await io.gh(["pr", "merge", String(pr.number), "--repo", repo, "--merge", "--auto"]); } catch (e) { return warn(`could not enable auto-merge (${String(e.message).split("\n")[0]})`); }
|
|
107
|
+
const end = await poll(io, b.autoPolls, b.autoPollMs, async () => {
|
|
108
|
+
const st = json(await io.gh(["pr", "view", String(pr.number), "--repo", repo, "--json", "state"]))?.state;
|
|
109
|
+
return st === "MERGED" || st === "CLOSED" ? st : null;
|
|
89
110
|
});
|
|
90
|
-
if (
|
|
91
|
-
|
|
92
|
-
// GITHUB_TOKEN PRs get no CI, so "no checks" is a stop, not a green light.
|
|
93
|
-
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` };
|
|
94
|
-
await io.gh(["pr", "merge", String(pr.number), "--repo", repo, "--merge", "--match-head-commit", green.head]);
|
|
95
|
-
return { pr: pr.number, merged: true };
|
|
111
|
+
if (end === "MERGED") return { pr: pr.number, merged: true };
|
|
112
|
+
return warn(end === "CLOSED" ? "was closed without merging" : "did not merge in time (auto-merge is enabled)");
|
|
96
113
|
}
|
|
97
114
|
|
|
98
115
|
/** @returns {Promise<{published, run, artifact, sync}|{blocked: true, reason: string}|{stopped: true, why: string}>} */
|
|
@@ -115,11 +132,12 @@ export async function postMergeStep(ctx) {
|
|
|
115
132
|
if (config.versionSync) {
|
|
116
133
|
sync = await versionSync(ctx, sha, b);
|
|
117
134
|
if (sync.err) return blocked(sync.err);
|
|
135
|
+
if (sync.warning) io.print(`release: WARNING ${sync.warning}`);
|
|
118
136
|
}
|
|
119
137
|
if (state.release?.branch) {
|
|
120
138
|
const gone = cleanupSnapshot({ git: io.git, branch: state.release.branch });
|
|
121
139
|
if (!gone.deleted) io.print(`release: could not delete ${state.release.branch} (${gone.why}); delete it by hand`);
|
|
122
140
|
}
|
|
123
|
-
io.print(`release: published (run ${pub.run}${pub.dispatched ? ", dispatched" : ""})${art ? ", artifact confirmed" : ""}${sync ? `, version-sync PR #${sync.pr} merged` : ""}`);
|
|
141
|
+
io.print(`release: published (run ${pub.run}${pub.dispatched ? ", dispatched" : ""})${art ? ", artifact confirmed" : ""}${sync?.pr ? `, version-sync PR #${sync.pr} ${sync.merged ? "merged" : "pending"}` : sync?.skipped ? ", staging already synced" : ""}`);
|
|
124
142
|
return { published: true, merge: sha, run: pub.run, dispatched: pub.dispatched, artifact: art?.ok ?? null, sync };
|
|
125
143
|
}
|
|
@@ -126,7 +126,7 @@ async function runReview({ seam, pr, def, delta = null }) {
|
|
|
126
126
|
if ((st.notes ?? []).length) await seam.addNotes(pr, st.notes);
|
|
127
127
|
const sum = await seam.summary({ pr, filed });
|
|
128
128
|
if (!sum.data) return blocked(`the gate summary was not posted (exit ${sum.code}): ${(sum.lines ?? []).slice(-1).join("").slice(0, 200)}`);
|
|
129
|
-
return { pr, head: st.head, verdict: sum.data.verdict, marker: sum.data.marker, ciFailing: sum.data.ciFailing, filed, blocking, delta: st.delta?.from ?? null };
|
|
129
|
+
return { pr, head: st.head, verdict: sum.data.verdict, marker: sum.data.marker, ciFailing: sum.data.ciFailing, ciCancelOnly: Boolean(sum.data.ciCancelOnly), filed, blocking, delta: st.delta?.from ?? null };
|
|
130
130
|
}
|
|
131
131
|
|
|
132
132
|
/** Review step. @returns {{pr, head, verdict, marker, filed, blocking}|{blocked: true, reason: string}} */
|
|
@@ -143,6 +143,17 @@ export async function fixStep(ctx) {
|
|
|
143
143
|
const seam = seamOf(ctx);
|
|
144
144
|
for (let round = 0; r.marker !== "FORGE:GATE_PASS"; round++) {
|
|
145
145
|
if (round >= MAX_FIX_ROUNDS) return blocked(`still ${r.verdict} after ${MAX_FIX_ROUNDS} fix round(s)`);
|
|
146
|
+
// Only cancelled duplicate runs are red (#5502): nothing to fix. The summary reruns them once; re-summarise without spending the round.
|
|
147
|
+
if (!r.blocking?.length && r.ciFailing > 0 && r.ciCancelOnly) {
|
|
148
|
+
const sum = await seam.summary({ pr: r.pr, filed: r.filed ?? [] });
|
|
149
|
+
if (!sum.data) return blocked(`the gate summary was not posted (exit ${sum.code}) after rerunning the cancelled checks of #${r.pr}`);
|
|
150
|
+
r = { ...r, verdict: sum.data.verdict, marker: sum.data.marker, ciFailing: sum.data.ciFailing, ciCancelOnly: Boolean(sum.data.ciCancelOnly) };
|
|
151
|
+
ctx.state.steps.review = { ...ctx.state.steps.review, result: r };
|
|
152
|
+
ctx.save();
|
|
153
|
+
if (r.marker === "FORGE:GATE_PASS") break;
|
|
154
|
+
if (r.ciCancelOnly) return blocked(`required checks of #${r.pr} still cancelled after a rerun, with no failure to fix`);
|
|
155
|
+
round--; continue;
|
|
156
|
+
}
|
|
146
157
|
// Blocking findings are already filed issues; red CI has none, so it gets one issue naming the failing checks.
|
|
147
158
|
const issues = [...(r.blocking ?? [])];
|
|
148
159
|
if (r.ciFailing > 0) {
|
|
@@ -192,6 +192,20 @@ describe("fixStep", () => {
|
|
|
192
192
|
assert.deepEqual(s.log.filter((e) => e[0] === "lane").map((e) => e[1]), [101, 100]);
|
|
193
193
|
});
|
|
194
194
|
|
|
195
|
+
it("only cancelled CI: no CI issue, no lane, no round spent; re-summarises and goes on", async () => {
|
|
196
|
+
const pass = { code: 0, data: { verdict: "APPROVE FOR DEPLOY", marker: "FORGE:GATE_PASS", ciFailing: 0 }, lines: [] };
|
|
197
|
+
const s = fakeSeam({ summary: pass });
|
|
198
|
+
const r = await fixStep(ctx(s, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 2, ciCancelOnly: true } } }));
|
|
199
|
+
assert.deepEqual(s.log, [["summary", []]]);
|
|
200
|
+
assert.equal(r.blocked, undefined);
|
|
201
|
+
assert.equal(r.verdict, "APPROVE FOR DEPLOY");
|
|
202
|
+
const still = { code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 1, ciCancelOnly: true }, lines: [] };
|
|
203
|
+
const s2 = fakeSeam({ summary: still });
|
|
204
|
+
const r2 = await fixStep(ctx(s2, { review: { result: { ...failed, blocking: [], filed: [], ciFailing: 1, ciCancelOnly: true } } }));
|
|
205
|
+
assert.match(r2.reason, /still cancelled/);
|
|
206
|
+
assert.ok(!s2.log.some((e) => e[0] === "ci-issue" || e[0] === "lane"));
|
|
207
|
+
});
|
|
208
|
+
|
|
195
209
|
it("blocks when the verdict is not a pass but there is nothing to fix", async () => {
|
|
196
210
|
assert.match((await fixStep(ctx(fakeSeam(), { review: { result: { ...failed, blocking: [], ciFailing: 0 } } }))).reason, /nothing to fix|neither/);
|
|
197
211
|
});
|
|
@@ -222,7 +222,7 @@ describe("release post-merge step (#5213)", () => {
|
|
|
222
222
|
const PKG = Buffer.from(JSON.stringify({ version: "1.2.3" })).toString("base64");
|
|
223
223
|
/** gh answers for the post-merge calls; `o` tunes them. */
|
|
224
224
|
const pmWorld = (o = {}) => {
|
|
225
|
-
const st = { runs: o.runs ?? [[{ databaseId: 5, status: "completed", conclusion: "success" }]], runCalls: 0, dispatched: 0, syncPrs: o.syncPrs ?? [], created: 0 };
|
|
225
|
+
const st = { runs: o.runs ?? [[{ databaseId: 5, status: "completed", conclusion: "success" }]], runCalls: 0, dispatched: 0, syncPrs: o.syncPrs ?? [], created: 0, bodies: [], views: 0 };
|
|
226
226
|
return {
|
|
227
227
|
st,
|
|
228
228
|
pm: (a) => {
|
|
@@ -230,19 +230,24 @@ describe("release post-merge step (#5213)", () => {
|
|
|
230
230
|
if (a[0] === "pr" && a[1] === "view" && j.includes("mergeCommit")) return JSON.stringify({ state: o.prState ?? "MERGED", mergeCommit: { oid: SHA } });
|
|
231
231
|
if (a[0] === "run" && a[1] === "list") { assert.ok(j.includes(`--commit ${SHA}`) && j.includes(`--workflow ${o.wf ?? "publish.yml"}`)); const r = st.runs[Math.min(st.runCalls++, st.runs.length - 1)]; return JSON.stringify(r); }
|
|
232
232
|
if (a[0] === "workflow" && a[1] === "run") { st.dispatched++; assert.ok(a.includes("main")); return ""; }
|
|
233
|
-
if (a[0] === "api" && j.includes("contents/package.json")) return
|
|
233
|
+
if (a[0] === "api" && j.includes("contents/package.json?ref=staging") && a.includes("--jq")) return Buffer.from(JSON.stringify({ version: o.stagingVersion ?? "1.2.2" })).toString("base64");
|
|
234
|
+
if (a[0] === "api" && j.includes("contents/package.json") && a.includes("--jq")) return PKG;
|
|
235
|
+
if (a[0] === "api" && j.includes("git/ref/heads/staging")) return "s".repeat(40);
|
|
236
|
+
if (a[0] === "api" && a.includes("POST") && j.includes("git/refs")) { st.refs = (st.refs ?? 0) + 1; return ""; }
|
|
237
|
+
if (a[0] === "api" && a.includes("PUT")) { (st.puts ??= []).push(a); return ""; }
|
|
238
|
+
if (a[0] === "api" && j.includes("contents/") && j.includes("ref=staging")) return JSON.stringify({ sha: "f".repeat(40), content: Buffer.from(JSON.stringify({ name: "x", version: "1.2.2" })).toString("base64") });
|
|
234
239
|
if (a[0] === "api" && j.includes("branches/chore/sync-version-1.2.3")) { if (o.noBranch) throw new Error("404"); return "x"; }
|
|
235
240
|
if (a[0] === "pr" && a[1] === "list" && j.includes("chore/sync-version")) return JSON.stringify(st.syncPrs);
|
|
236
|
-
if (a[0] === "pr" && a[1] === "create") { st.created++; assert.ok(a.includes("staging") && a.includes("chore/sync-version-1.2.3")); return "https://github.com/o/r/pull/30"; }
|
|
237
|
-
if (a[0] === "pr" && a[1] === "view" && j.includes("
|
|
238
|
-
if (a[0] === "pr" && a[1] === "merge" && Number(a[2]) >= 30) return "";
|
|
241
|
+
if (a[0] === "pr" && a[1] === "create") { st.created++; st.bodies.push(a[a.indexOf("--body") + 1]); assert.ok(a.includes("staging") && a.includes("chore/sync-version-1.2.3")); return "https://github.com/o/r/pull/30"; }
|
|
242
|
+
if (a[0] === "pr" && a[1] === "view" && j.includes("--json state") && Number(a[2]) >= 30) return JSON.stringify({ state: st.views++ >= (o.mergesAfter ?? 0) ? (o.final ?? "MERGED") : "OPEN" });
|
|
243
|
+
if (a[0] === "pr" && a[1] === "merge" && Number(a[2]) >= 30) { if (o.autoFails) throw new Error("auto merge is not allowed"); return ""; }
|
|
239
244
|
return undefined;
|
|
240
245
|
},
|
|
241
246
|
};
|
|
242
247
|
};
|
|
243
248
|
const run = (o = {}, config = {}) => {
|
|
244
249
|
const w = pmWorld(o), io = fakeIo({ pm: w.pm, ...o });
|
|
245
|
-
const ctx = { io, repo: REPO, def: "main", staging: "staging", config: { postMerge: { publishPolls: 2, runPolls: 2, branchPolls: 2,
|
|
250
|
+
const ctx = { io, repo: REPO, def: "main", staging: "staging", config: { postMerge: { publishPolls: 2, runPolls: 2, branchPolls: 2, autoPolls: 2, artifactTries: 3 }, ...config }, state: { steps: { "release-pr": { result: { pr: 7 } } } } };
|
|
246
251
|
return postMergeStep(ctx).then((out) => ({ out, io, st: w.st }));
|
|
247
252
|
};
|
|
248
253
|
|
|
@@ -290,27 +295,46 @@ describe("release post-merge step (#5213)", () => {
|
|
|
290
295
|
assert.match(b.out.reason, /artifact_check/);
|
|
291
296
|
});
|
|
292
297
|
|
|
293
|
-
it("R4: version_sync opens the sync PR
|
|
298
|
+
it("R4: version_sync opens the sync PR then enables auto-merge; staging already synced makes no calls", async () => {
|
|
294
299
|
const { out, st, io } = await run({}, { versionSync: true });
|
|
295
300
|
assert.equal(st.created, 1);
|
|
301
|
+
assert.match(st.bodies[0], /^docs-not-needed: \S/m);
|
|
296
302
|
assert.equal(out.sync.merged, true);
|
|
297
|
-
assert.
|
|
303
|
+
assert.equal(out.sync.pr, 30);
|
|
304
|
+
const kinds = io.calls.filter((a) => a[0] === "pr" && (a[1] === "create" || a[1] === "merge")).map((a) => a[1]);
|
|
305
|
+
assert.deepEqual(kinds, ["create", "merge"]);
|
|
306
|
+
assert.ok(io.calls.some((a) => a[1] === "merge" && a.includes("--merge") && a.includes("--auto") && !a.includes("--match-head-commit")));
|
|
307
|
+
const synced = await run({ stagingVersion: "1.2.3" }, { versionSync: true });
|
|
308
|
+
assert.equal(synced.out.sync.skipped, true);
|
|
309
|
+
assert.ok(!synced.io.calls.some((a) => (a[0] === "pr" && ["create", "merge", "list"].includes(a[1])) || a[0] === "api" && a.join(" ").includes("branches/")));
|
|
310
|
+
assert.equal(synced.st.created, 0);
|
|
298
311
|
});
|
|
299
312
|
|
|
300
|
-
it("version_sync reuses an open sync PR
|
|
313
|
+
it("version_sync reuses an open sync PR and skips a merged one", async () => {
|
|
301
314
|
const open = await run({ syncPrs: [{ number: 31, state: "OPEN" }] }, { versionSync: true });
|
|
302
315
|
assert.equal(open.st.created, 0);
|
|
303
|
-
assert.ok(open.io.calls.some((a) => a[1] === "merge" && a.includes("31")));
|
|
316
|
+
assert.ok(open.io.calls.some((a) => a[1] === "merge" && a.includes("31") && a.includes("--auto")));
|
|
304
317
|
const merged = await run({ syncPrs: [{ number: 32, state: "MERGED" }] }, { versionSync: true });
|
|
305
318
|
assert.equal(merged.out.sync.merged, true);
|
|
306
319
|
assert.ok(!merged.io.calls.some((a) => a[1] === "merge"));
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
it("R5: a missing sync branch is cut from staging with a version-only commit, then the PR opens", async () => {
|
|
323
|
+
const { out, st } = await run({ noBranch: true }, { versionSync: true });
|
|
324
|
+
assert.equal(st.refs, 1);
|
|
325
|
+
assert.deepEqual(st.puts.map((a) => a.find((x) => x.startsWith("sha="))), ["sha=" + "f".repeat(40), "sha=" + "f".repeat(40)]);
|
|
326
|
+
assert.equal(st.created, 1);
|
|
327
|
+
assert.equal(out.sync.merged, true);
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
it("R4: an auto-merge that is not done in time, is closed, or cannot be enabled is a warning, not blocked", async () => {
|
|
331
|
+
for (const o of [{ mergesAfter: 99 }, { final: "CLOSED" }, { autoFails: true }]) {
|
|
332
|
+
const { out, io } = await run(o, { versionSync: true });
|
|
333
|
+
assert.equal(out.published, true, JSON.stringify(o));
|
|
334
|
+
assert.equal(out.sync.merged, false);
|
|
335
|
+
assert.match(out.sync.warning, /version-sync PR #30/);
|
|
336
|
+
assert.ok(io.printed.some((l) => l.includes("WARNING")));
|
|
311
337
|
}
|
|
312
|
-
const nb = await run({ noBranch: true }, { versionSync: true });
|
|
313
|
-
assert.equal(nb.out.blocked, true);
|
|
314
338
|
});
|
|
315
339
|
|
|
316
340
|
it("R1: through the job, a blocked post-merge is retried on resume and finishes once the run exists", async () => {
|
package/bin/review-staging.mjs
CHANGED
|
@@ -142,7 +142,7 @@ function defaultIo() {
|
|
|
142
142
|
};
|
|
143
143
|
}
|
|
144
144
|
|
|
145
|
-
function readConfig(io) {
|
|
145
|
+
export function readConfig(io) {
|
|
146
146
|
const path = io.env.FORGE_CONFIG || join(io.cwd, "forge.yaml");
|
|
147
147
|
let cfg = {};
|
|
148
148
|
try { cfg = parseForgeYaml(io.readFile(path)) ?? {}; } catch { /* absent config: owner/repo check below fails */ }
|
|
@@ -524,7 +524,8 @@ export const CI_EXCLUDED_CHECKS = ["forgedock/verify", "forge/deploy-gate", "Che
|
|
|
524
524
|
|
|
525
525
|
const parseChecks = (out) => { try { const j = JSON.parse(out); return Array.isArray(j) ? j : null; } catch { return null; } };
|
|
526
526
|
|
|
527
|
-
|
|
527
|
+
/** An unfinished (`pending`) check is not green: a rerun that outlives its poll must not read as a pass (#5510). */
|
|
528
|
+
const isRed = (k) => k?.bucket === "fail" || k?.bucket === "cancel" || k?.bucket === "pending";
|
|
528
529
|
|
|
529
530
|
/**
|
|
530
531
|
* The required-check set classifyChecks gets. An unreadable protection read (e.g. a non-admin token) must not let
|
|
@@ -540,11 +541,50 @@ export function requiredSet({ checks = [], unreadable = false } = {}, extra = []
|
|
|
540
541
|
* (no protection, or a failed read: indistinguishable) keeps every red check blocking (fail closed).
|
|
541
542
|
*/
|
|
542
543
|
export function classifyChecks(checks, required = []) {
|
|
543
|
-
const
|
|
544
|
+
const { blockRows, warnings } = redChecks(checks, required);
|
|
545
|
+
return { blocking: blockRows.length, warnings };
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* classifyChecks' rows. A name with any `pass` on the head is green whatever cancelled duplicates it has (push-event and
|
|
550
|
+
* pull_request-event runs share a concurrency group, which cancels one of them: #5502).
|
|
551
|
+
*/
|
|
552
|
+
function redChecks(checks, required = []) {
|
|
553
|
+
const passed = new Set(checks.filter((k) => k?.bucket === "pass").map((k) => k.name));
|
|
554
|
+
const red = checks.filter((k) => !CI_EXCLUDED_CHECKS.includes(k?.name) && isRed(k) && !((k.bucket === "cancel" || k.bucket === "pending") && passed.has(k.name)));
|
|
544
555
|
const req = new Set(required);
|
|
545
|
-
if (!req.size) return {
|
|
546
|
-
|
|
547
|
-
|
|
556
|
+
if (!req.size) return { blockRows: red, warnings: [] };
|
|
557
|
+
return { blockRows: red.filter((k) => req.has(k.name)), warnings: [...new Set(red.filter((k) => !req.has(k.name)).map((k) => String(k.name)))] };
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/** Blocking checks whose only results are `cancel` (no pass, no fail): infrastructure, worth one rerun. @returns [{name, link}] */
|
|
561
|
+
export function cancelOnlyChecks(checks, required = []) {
|
|
562
|
+
const { blockRows } = redChecks(checks, required);
|
|
563
|
+
const failed = new Set(blockRows.filter((k) => k.bucket === "fail").map((k) => k.name));
|
|
564
|
+
const seen = new Map();
|
|
565
|
+
for (const k of blockRows) if (k.bucket === "cancel" && !failed.has(k.name) && !seen.has(k.name)) seen.set(k.name, { name: k.name, link: k.link ?? "" });
|
|
566
|
+
return [...seen.values()];
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
const CI_POLL_MS = 20_000, CI_POLL_MAX = 45;
|
|
570
|
+
|
|
571
|
+
/** One `gh run rerun` per cancelled run of the cancel-only required checks, then wait until none of them is pending. @returns the re-read checks, or `checks` when nothing could be rerun. */
|
|
572
|
+
async function rerunCancelled(io, c, pr, env, checks, only) {
|
|
573
|
+
const ids = [...new Set(only.map((k) => /\/actions\/runs\/(\d+)/.exec(k.link)?.[1]).filter(Boolean))];
|
|
574
|
+
if (!ids.length) return checks;
|
|
575
|
+
for (const id of ids) await io.run("gh", ["run", "rerun", id, "-R", c.ghRepo], { env, cwd: io.cwd });
|
|
576
|
+
const sleep = io.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
577
|
+
const names = new Set(only.map((k) => k.name));
|
|
578
|
+
let cur = checks;
|
|
579
|
+
for (let i = 0; i < CI_POLL_MAX; i++) {
|
|
580
|
+
await sleep(CI_POLL_MS);
|
|
581
|
+
const r = await io.run("gh", ["pr", "checks", String(pr), "-R", c.ghRepo, "--json", "name,bucket,link"], { env, cwd: io.cwd });
|
|
582
|
+
const next = r.code === 0 ? parseChecks(r.stdout) : null;
|
|
583
|
+
if (!next) continue;
|
|
584
|
+
cur = next;
|
|
585
|
+
if (!cur.some((k) => names.has(k.name) && k.bucket === "pending")) break;
|
|
586
|
+
}
|
|
587
|
+
return cur;
|
|
548
588
|
}
|
|
549
589
|
|
|
550
590
|
/** Failing (fail/cancel) checks outside CI_EXCLUDED_CHECKS. */
|
|
@@ -591,13 +631,16 @@ async function summary(a, io) {
|
|
|
591
631
|
// Phase 1E read: forgedock/verify is excluded; an unreadable result counts as failing (fail closed). forge/deploy-gate
|
|
592
632
|
// and the gate-marker check are excluded too: they report this review's own marker, so an earlier GATE_FAILURE must not block the re-run that clears it.
|
|
593
633
|
let ciFailing = 1;
|
|
594
|
-
const ci = await io.run("gh", ["pr", "checks", String(pr), "-R", c.ghRepo, "--json", "name,bucket"], { env, cwd: io.cwd });
|
|
595
|
-
|
|
596
|
-
let warnings = [];
|
|
634
|
+
const ci = await io.run("gh", ["pr", "checks", String(pr), "-R", c.ghRepo, "--json", "name,bucket,link"], { env, cwd: io.cwd });
|
|
635
|
+
let checks = ci.code === 0 ? parseChecks(ci.stdout) : null;
|
|
636
|
+
let warnings = [], ciCancelOnly = false;
|
|
597
637
|
if (checks) {
|
|
598
638
|
const read = await requiredChecksRead({ gh: io.gh, repo: c.ghRepo, lane: c.defaultBranch });
|
|
599
639
|
const required = requiredSet(read, c.extraRequiredChecks);
|
|
640
|
+
const only = cancelOnlyChecks(checks, required);
|
|
641
|
+
if (only.length) checks = await rerunCancelled(io, c, pr, env, checks, only);
|
|
600
642
|
({ blocking: ciFailing, warnings } = classifyChecks(checks, required));
|
|
643
|
+
ciCancelOnly = ciFailing > 0 && redChecks(checks, required).blockRows.every((k) => k.bucket === "cancel");
|
|
601
644
|
}
|
|
602
645
|
|
|
603
646
|
const acceptanceBlocked = await acceptanceBlock(io, c, pr, tg);
|
|
@@ -654,7 +697,7 @@ async function summary(a, io) {
|
|
|
654
697
|
} catch (e) {
|
|
655
698
|
throw new Stop(1, [`REVIEW_RESULT: status: BLOCKED, blocker: could not post the Phase 8 summary and gate marker (${e.message})`, BLOCK_DEPLOY]);
|
|
656
699
|
}
|
|
657
|
-
if (a.json) io.out(JSON.stringify({ pr, headSha: head, verdict: v.verdict, why: v.why, marker, ciFailing, warnings, testGate: tg.verdict, filed: a.filed }));
|
|
700
|
+
if (a.json) io.out(JSON.stringify({ pr, headSha: head, verdict: v.verdict, why: v.why, marker, ciFailing, ciCancelOnly, warnings, testGate: tg.verdict, filed: a.filed }));
|
|
658
701
|
else io.out([`VERDICT: ${v.verdict} (${v.why})`, ...(warnings.length ? [`WARNING: ${warnings.length} non-required check(s) red, non-blocking: ${warnings.join(", ")}`] : []), `GATE: ${marker} posted on PR #${pr}`, ...(pass ? [] : [BLOCK_DEPLOY])].join("\n"));
|
|
659
702
|
return pass ? 0 : 1;
|
|
660
703
|
}
|
|
@@ -181,6 +181,10 @@ RUN_ID=$(gh run list --workflow={deploy.workflow} --limit 1 --json databaseId --
|
|
|
181
181
|
gh run view $RUN_ID --json status,conclusion,jobs
|
|
182
182
|
```
|
|
183
183
|
|
|
184
|
+
#### Step 3A2: Keep the issue open until the backport merges (#5505)
|
|
185
|
+
|
|
186
|
+
A hotfix that ships from a `hotfix/*` branch needs a backport PR to `staging`. Do not close the incident issue at hotfix time: label it `backport-pending` (`gh issue edit {NUMBER} --add-label backport-pending`) and leave it open. The orphan-pr sweep (`forgedock probe --due`, schedd timer) keeps that issue's PRs open, and when the `hotfix/*` or `backport/*` PR naming the issue merges it removes the label and closes the issue.
|
|
187
|
+
|
|
184
188
|
#### Step 3B: Post deploy status
|
|
185
189
|
|
|
186
190
|
```bash
|
|
@@ -154,6 +154,19 @@ gh pr list $GH_FLAG \
|
|
|
154
154
|
2>/dev/null || echo " (none)"
|
|
155
155
|
|
|
156
156
|
echo ""
|
|
157
|
+
|
|
158
|
+
# Orphan PRs (#5505): lane PRs (feat/issue-N-lean) whose issue is closed; alert when the oldest is over 24h
|
|
159
|
+
ORPHANS=0; OLDEST=0
|
|
160
|
+
for ROW in $(gh pr list $GH_FLAG --state open --limit 100 --json number,headRefName,createdAt \
|
|
161
|
+
--jq '.[] | select(.headRefName | test("^feat/issue-[0-9]+-lean$")) | "\(.headRefName|capture("issue-(?<n>[0-9]+)").n):\(.createdAt)"' 2>/dev/null); do
|
|
162
|
+
N=${ROW%%:*}; AGE=$(( $(date +%s) - $(date -d "${ROW#*:}" +%s 2>/dev/null || echo 0) ))
|
|
163
|
+
[ "$(gh issue view "$N" $GH_FLAG --json state --jq .state 2>/dev/null)" = "CLOSED" ] || continue
|
|
164
|
+
gh issue view "$N" $GH_FLAG --json labels --jq '.labels[].name' | grep -qx backport-pending && continue
|
|
165
|
+
ORPHANS=$((ORPHANS+1)); [ "$AGE" -gt "$OLDEST" ] && OLDEST=$AGE
|
|
166
|
+
done
|
|
167
|
+
echo "Orphan PRs (open, issue closed): $ORPHANS"
|
|
168
|
+
[ "$ORPHANS" -gt 0 ] && [ "$OLDEST" -gt 86400 ] && echo "ALERT: orphan PR open for $((OLDEST/3600))h; run: forgedock probe --due"
|
|
169
|
+
echo ""
|
|
157
170
|
```
|
|
158
171
|
|
|
159
172
|
---
|