forgedock 1.55.1 → 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.
@@ -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/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
- checkPolls: 30, checkPollMs: 20_000, // wait for the sync PR's checks
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 pkg = JSON.parse(Buffer.from(String(await io.gh(["api", `repos/${repo}/contents/package.json?ref=${sha}`, "--jq", ".content"])).replace(/\s/g, ""), "base64").toString("utf8"));
70
- const branch = `chore/sync-version-${pkg.version}`;
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) return { err: `version-sync branch ${branch} did not appear; publish.yml may have skipped the sync, open it by hand` };
77
- const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", staging, "--head", branch, "--title", `chore: sync version ${pkg.version} to ${staging}`, "--body", `Version-only sync of the ${pkg.version} release back to ${staging} (forgedock release).`])).trim();
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
- let red = null;
83
- const green = await poll(io, b.checkPolls, b.checkPollMs, async () => {
84
- const v = json(await io.gh(["pr", "view", String(pr.number), "--repo", repo, "--json", "state,headRefOid,statusCheckRollup"]));
85
- if (v?.state === "MERGED") return { head: null, already: true };
86
- const res = (v?.statusCheckRollup ?? []).map((c) => String(c.conclusion || c.state || "").toUpperCase());
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 (green?.already) return { pr: pr.number, merged: true };
91
- if (green?.red) return { err: `version-sync PR #${pr.number} has a failing check (${red}); fix and merge it by hand` };
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
  }
@@ -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 PKG;
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("statusCheckRollup")) return JSON.stringify({ state: "OPEN", headRefOid: "c".repeat(40), statusCheckRollup: o.checks ?? [{ conclusion: "SUCCESS" }] });
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, checkPolls: 2, artifactTries: 3 }, ...config }, state: { steps: { "release-pr": { result: { pr: 7 } } } } };
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 to staging and merges it with --match-head-commit when green", async () => {
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.ok(io.calls.some((a) => a[1] === "merge" && a.includes("30") && a.includes("--match-head-commit") && a.includes("c".repeat(40))));
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, skips a merged one, and never merges red or check-less PRs", async () => {
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
- for (const checks of [[], [{ conclusion: "FAILURE" }], [{ conclusion: "SUCCESS" }, { status: "IN_PROGRESS", state: "PENDING" }]]) {
308
- const r = await run({ syncPrs: [{ number: 33, state: "OPEN" }], checks }, { versionSync: true });
309
- assert.equal(r.out.blocked, true, JSON.stringify(checks));
310
- assert.ok(!r.io.calls.some((a) => a[1] === "merge"));
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 () => {
@@ -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
- const isRed = (k) => k?.bucket === "fail" || k?.bucket === "cancel";
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
@@ -550,7 +551,7 @@ export function classifyChecks(checks, required = []) {
550
551
  */
551
552
  function redChecks(checks, required = []) {
552
553
  const passed = new Set(checks.filter((k) => k?.bucket === "pass").map((k) => k.name));
553
- const red = checks.filter((k) => !CI_EXCLUDED_CHECKS.includes(k?.name) && isRed(k) && !(k.bucket === "cancel" && passed.has(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)));
554
555
  const req = new Set(required);
555
556
  if (!req.size) return { blockRows: red, warnings: [] };
556
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)))] };
@@ -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
  ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "forgedock",
3
- "version": "1.55.1",
3
+ "version": "1.56.0",
4
4
  "description": "An AI engineering team that ships to production",
5
5
  "bin": {
6
6
  "forgedock": "bin/forgedock.mjs"