forgedock 1.63.0 → 1.65.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 +3 -0
- package/bin/engine/outcome-codes.mjs +5 -0
- package/bin/engine-cli.mjs +88 -12
- package/bin/env/cli.mjs +18 -1
- package/bin/lean/basered.mjs +56 -11
- package/bin/lean/basered.test.mjs +58 -5
- package/bin/lean/batch-health.mjs +46 -4
- package/bin/lean/batch-health.test.mjs +55 -1
- package/bin/lean/batch.mjs +8 -1
- package/bin/lean/batch.test.mjs +71 -6
- package/bin/lean/ceiling.mjs +47 -3
- package/bin/lean/ceiling.test.mjs +32 -1
- package/bin/lean/clear-breaker.mjs +15 -0
- package/bin/lean/clear-breaker.test.mjs +100 -0
- package/bin/lean/conformance.e2e.test.mjs +32 -6
- package/bin/lean/conformance.mjs +57 -13
- package/bin/lean/conformance.test.mjs +93 -1
- package/bin/lean/execution.mjs +18 -8
- package/bin/lean/execution.test.mjs +44 -3
- package/bin/lean/issuewatch-reconcile.mjs +2 -0
- package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
- package/bin/lean/issuewatch.mjs +3 -0
- package/bin/lean/lanecheck.test.mjs +13 -1
- package/bin/lean/lean.mjs +157 -28
- package/bin/lean/lean.test.mjs +289 -21
- package/bin/lean/live-execution.mjs +25 -0
- package/bin/lean/live-execution.test.mjs +35 -1
- package/bin/lean/merged-park.mjs +76 -0
- package/bin/lean/merged-park.test.mjs +64 -0
- package/bin/lean/mergetrain.mjs +357 -0
- package/bin/lean/mergetrain.test.mjs +348 -0
- package/bin/lean/mirror-bundle.mjs +84 -0
- package/bin/lean/orchestrate-envhold.test.mjs +62 -0
- package/bin/lean/orchestrate-stacking.test.mjs +23 -1
- package/bin/lean/orchestrate-train.test.mjs +130 -0
- package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
- package/bin/lean/orchestrate.mjs +170 -13
- package/bin/lean/prompts.mjs +4 -3
- package/bin/lean/release-review.mjs +8 -1
- package/bin/lean/release-review.test.mjs +42 -2
- package/bin/lean/release-status.test.mjs +53 -1
- package/bin/lean/release.mjs +6 -3
- package/bin/lean/render.mjs +6 -1
- package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
- package/bin/lean/sandbox-remote.mjs +43 -3
- package/bin/lean/sched.mjs +19 -2
- package/bin/lean/sched.test.mjs +33 -1
- package/bin/lean/schedd-health.mjs +2 -1
- package/bin/lean/schedd-health.test.mjs +7 -0
- package/bin/lean/schedd.mjs +58 -7
- package/bin/lean/schedd.test.mjs +78 -1
- package/bin/lean/stacking.mjs +45 -0
- package/bin/lean/stacking.test.mjs +25 -1
- package/bin/lean/statuscomment.mjs +14 -8
- package/bin/lean/statuscomment.test.mjs +18 -1
- package/bin/lean/validate-catalog.mjs +1 -1
- package/bin/lean/validate-catalog.test.mjs +3 -0
- package/bin/lean/worktree.mjs +8 -3
- package/bin/lean/worktree.test.mjs +18 -0
- package/bin/pool/agent.mjs +309 -33
- package/bin/pool/cache-sweep.mjs +4 -2
- package/bin/pool/cli.mjs +125 -6
- package/bin/pool/disk.mjs +43 -0
- package/bin/pool/docker.mjs +11 -0
- package/bin/pool/health.mjs +95 -0
- package/bin/pool/mirror-seed.mjs +103 -0
- package/bin/pool/router.mjs +301 -27
- package/bin/runner.mjs +3 -1
- package/bin/stats/chains.mjs +101 -0
- package/bin/stats/chains.test.mjs +53 -0
- package/bin/stats/efficiency.mjs +7 -6
- package/bin/stats/efficiency.test.mjs +48 -7
- package/bin/stats/index.mjs +11 -3
- package/bin/stats/stats.test.mjs +9 -0
- package/docs/CONFIG.md +8 -1
- package/docs/OUTCOME-CODES.md +4 -0
- package/package.json +1 -1
- package/pool/README.md +10 -0
- package/pool/image/Dockerfile +2 -1
- package/pool/image/entrypoint.sh +25 -6
- package/pool/image/mirror.sh +71 -0
- package/pool/install/install-agent-linux.sh +57 -5
- package/pool/install/install-agent-macos.sh +148 -0
- package/pool/install/install-agent.ps1 +11 -0
- package/pool/install/install-agent.sh +59 -7
- package/pool/install/uninstall-agent-linux.sh +75 -0
- package/pool/install/uninstall-agent-macos.sh +60 -0
- package/pool/install/uninstall-agent.ps1 +1 -0
- package/scripts/transition-label.sh +11 -0
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* #5759: merge evidence for an OPEN issue, so no park writer labels a delivered issue and a repair pass clears the park labels a
|
|
5
|
+
* merged issue still carries. Evidence is a merged PR on any head (closing references on the issue, `FORGE:STATE.pr`) or the
|
|
6
|
+
* `workflow:merged` label. An issue reopened after the merge (a failed acceptance probe, #4500) is new work: no evidence.
|
|
7
|
+
* Gh is injected; anything unreadable is "no evidence" (the park proceeds as before).
|
|
8
|
+
*/
|
|
9
|
+
import { stateOf } from "./context.mjs";
|
|
10
|
+
import { clearPipelineLabels, pipelineLabels } from "./statuscomment.mjs";
|
|
11
|
+
|
|
12
|
+
const MERGED_LABEL = "workflow:merged";
|
|
13
|
+
const nameOf = (l) => (typeof l === "string" ? l : l?.name);
|
|
14
|
+
|
|
15
|
+
/** Latest event times (ms) from the issue events: `{reopened, merged}` (0 = none), null when unreadable. */
|
|
16
|
+
async function eventTimes({ gh, repo, issue }) {
|
|
17
|
+
try {
|
|
18
|
+
const out = String(await gh(["api", `repos/${repo}/issues/${issue}/events`, "--paginate", "--jq", '.[] | [.event, .created_at, (.label.name // "")] | @tsv']));
|
|
19
|
+
const t = { reopened: 0, merged: 0 };
|
|
20
|
+
for (const line of out.split("\n")) {
|
|
21
|
+
const [ev, at, name] = line.split("\t");
|
|
22
|
+
const ms = Date.parse(at);
|
|
23
|
+
if (!Number.isFinite(ms)) continue;
|
|
24
|
+
if (ev === "reopened") t.reopened = Math.max(t.reopened, ms);
|
|
25
|
+
if (ev === "labeled" && name === MERGED_LABEL) t.merged = Math.max(t.merged, ms);
|
|
26
|
+
}
|
|
27
|
+
return t;
|
|
28
|
+
} catch { return null; }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* `{source, pr?}` when the open issue's fix merged and was not reopened afterwards, else null. `view` is an already-read
|
|
33
|
+
* `{state, body, labels, closedByPullRequestsReferences}` (read here when null).
|
|
34
|
+
*/
|
|
35
|
+
export async function mergedEvidence({ gh, repo, issue, view = null }) {
|
|
36
|
+
try {
|
|
37
|
+
const v = view ?? JSON.parse(String(await gh(["issue", "view", String(issue), "-R", repo, "--json", "state,body,labels,closedByPullRequestsReferences"])));
|
|
38
|
+
const labelled = (v?.labels ?? []).map(nameOf).includes(MERGED_LABEL);
|
|
39
|
+
const cand = new Set([...(v?.closedByPullRequestsReferences ?? []).map((p) => p?.number), stateOf(v?.body)?.pr].map(Number).filter(Number.isInteger));
|
|
40
|
+
let pr = null, mergedAt = 0;
|
|
41
|
+
for (const n of cand) {
|
|
42
|
+
try {
|
|
43
|
+
const p = JSON.parse(String(await gh(["pr", "view", String(n), "-R", repo, "--json", "state,mergedAt"])));
|
|
44
|
+
const at = Date.parse(p?.mergedAt ?? "");
|
|
45
|
+
if (String(p?.state).toUpperCase() === "MERGED" && Number.isFinite(at) && (pr === null || at > mergedAt)) { pr = n; mergedAt = at; }
|
|
46
|
+
} catch { /* an unreadable PR is not evidence */ }
|
|
47
|
+
}
|
|
48
|
+
if (pr === null && !labelled) return null;
|
|
49
|
+
const t = await eventTimes({ gh, repo, issue });
|
|
50
|
+
if (t === null) return null;
|
|
51
|
+
const at = pr !== null ? mergedAt : t.merged;
|
|
52
|
+
if (t.reopened > 0 && (at === 0 || t.reopened > at)) return null;
|
|
53
|
+
return pr !== null ? { source: "pr", pr } : { source: "label" };
|
|
54
|
+
} catch { return null; }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Open issues carrying `workflow:merged` plus a pipeline label (needs-human*, parked:*, remediation-queue) are inconsistent: the park
|
|
59
|
+
* labels come off unless the issue was reopened after the merge. `issues` is a list of `{number, labels}` (listed through the issues API when null; its pull requests are skipped).
|
|
60
|
+
* @returns {Promise<{issue:number, flagged:string[], removed:string[]}[]>} one row per repaired issue.
|
|
61
|
+
*/
|
|
62
|
+
export async function repairMergedParked({ gh, repo, issues = null, onFail = null }) {
|
|
63
|
+
let list = issues;
|
|
64
|
+
if (!list) {
|
|
65
|
+
try { list = JSON.parse(String(await gh(["api", `repos/${repo}/issues?state=open&labels=${encodeURIComponent(MERGED_LABEL)}&per_page=100`]))); } catch { return []; }
|
|
66
|
+
}
|
|
67
|
+
const out = [];
|
|
68
|
+
for (const i of Array.isArray(list) ? list : []) {
|
|
69
|
+
const flagged = pipelineLabels(i?.labels);
|
|
70
|
+
if (!flagged.length || !Number.isInteger(i?.number) || i.pull_request) continue;
|
|
71
|
+
if (!(await mergedEvidence({ gh, repo, issue: i.number, view: { labels: i.labels } }))) continue;
|
|
72
|
+
const removed = await clearPipelineLabels({ gh, repo, issue: i.number, labels: i.labels, onFail });
|
|
73
|
+
out.push({ issue: i.number, flagged, removed });
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
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 { mergedEvidence, repairMergedParked } from "./merged-park.mjs";
|
|
6
|
+
|
|
7
|
+
/** gh over a scripted issue: view, pr view, events, edit (records removals). */
|
|
8
|
+
const ghFor = ({ view = {}, prs = {}, events = "", failRemove = [] } = {}) => {
|
|
9
|
+
const calls = [];
|
|
10
|
+
const gh = async (a) => {
|
|
11
|
+
calls.push(a.join(" "));
|
|
12
|
+
if (a[0] === "issue" && a[1] === "view") return JSON.stringify(view);
|
|
13
|
+
if (a[0] === "pr" && a[1] === "view") return JSON.stringify(prs[a[2]] ?? {});
|
|
14
|
+
if (a[0] === "api") return events;
|
|
15
|
+
if (a[0] === "issue" && a[1] === "edit") { if (failRemove.includes(a[a.indexOf("--remove-label") + 1])) throw new Error("no such label"); return ""; }
|
|
16
|
+
return "";
|
|
17
|
+
};
|
|
18
|
+
return { gh, calls };
|
|
19
|
+
};
|
|
20
|
+
const STATE = (pr) => `x\n<!-- FORGE:STATE\n${JSON.stringify({ v: 1, issue: 7, pr })}\n-->`;
|
|
21
|
+
const T = (s) => new Date(s).toISOString();
|
|
22
|
+
|
|
23
|
+
describe("merged-park", () => {
|
|
24
|
+
it("merged evidence from workflow:merged label, closing refs and FORGE:STATE pr", async () => {
|
|
25
|
+
const lbl = ghFor({ view: { state: "OPEN", labels: [{ name: "workflow:merged" }] } });
|
|
26
|
+
assert.equal((await mergedEvidence({ gh: lbl.gh, repo: "o/r", issue: 7 }))?.source, "label");
|
|
27
|
+
const prs = { 41: { state: "MERGED", mergedAt: T("2026-11-17T15:43:35Z") } };
|
|
28
|
+
const ref = ghFor({ view: { state: "OPEN", closedByPullRequestsReferences: [{ number: 41 }] }, prs });
|
|
29
|
+
assert.equal((await mergedEvidence({ gh: ref.gh, repo: "o/r", issue: 7 }))?.pr, 41);
|
|
30
|
+
const st = ghFor({ view: { state: "OPEN", body: STATE(41) }, prs });
|
|
31
|
+
assert.equal((await mergedEvidence({ gh: st.gh, repo: "o/r", issue: 7 }))?.pr, 41);
|
|
32
|
+
const open = ghFor({ view: { state: "OPEN", body: STATE(41) }, prs: { 41: { state: "OPEN" } } });
|
|
33
|
+
assert.equal(await mergedEvidence({ gh: open.gh, repo: "o/r", issue: 7 }), null);
|
|
34
|
+
assert.equal(await mergedEvidence({ gh: ghFor({ view: { state: "OPEN" } }).gh, repo: "o/r", issue: 7 }), null);
|
|
35
|
+
});
|
|
36
|
+
it("a reopen after the merge voids the evidence", async () => {
|
|
37
|
+
const prs = { 41: { state: "MERGED", mergedAt: T("2026-11-17T15:43:35Z") } };
|
|
38
|
+
const view = { state: "OPEN", closedByPullRequestsReferences: [{ number: 41 }] };
|
|
39
|
+
const later = ghFor({ view, prs, events: `reopened\t${T("2026-11-18T00:00:00Z")}\t` });
|
|
40
|
+
assert.equal(await mergedEvidence({ gh: later.gh, repo: "o/r", issue: 7 }), null);
|
|
41
|
+
const earlier = ghFor({ view, prs, events: `reopened\t${T("2026-11-16T00:00:00Z")}\t` });
|
|
42
|
+
assert.equal((await mergedEvidence({ gh: earlier.gh, repo: "o/r", issue: 7 }))?.pr, 41);
|
|
43
|
+
});
|
|
44
|
+
it("repair flags and clears a merged issue that keeps park labels", async () => {
|
|
45
|
+
const labels = [{ name: "workflow:merged" }, { name: "remediation-queue" }, { name: "parked:env.tool_missing" }, { name: "bug" }];
|
|
46
|
+
const h = ghFor();
|
|
47
|
+
const out = await repairMergedParked({ gh: h.gh, repo: "o/r", issues: [{ number: 7, labels }, { number: 8, labels: [{ name: "workflow:merged" }] }] });
|
|
48
|
+
assert.deepEqual(out, [{ issue: 7, flagged: ["remediation-queue", "parked:env.tool_missing"], removed: ["remediation-queue", "parked:env.tool_missing"] }]);
|
|
49
|
+
assert.ok(h.calls.some((c) => c.includes("--remove-label remediation-queue")));
|
|
50
|
+
assert.ok(!h.calls.some((c) => c.includes("issue edit 8")));
|
|
51
|
+
});
|
|
52
|
+
it("repair leaves an issue reopened after the merge parked", async () => {
|
|
53
|
+
const h = ghFor({ events: `labeled\t${T("2026-11-17T00:00:00Z")}\tworkflow:merged\nreopened\t${T("2026-11-18T00:00:00Z")}\t` });
|
|
54
|
+
const out = await repairMergedParked({ gh: h.gh, repo: "o/r", issues: [{ number: 7, labels: ["workflow:merged", "remediation-queue"] }] });
|
|
55
|
+
assert.deepEqual(out, []);
|
|
56
|
+
assert.ok(!h.calls.some((c) => c.includes("issue edit")));
|
|
57
|
+
});
|
|
58
|
+
it("repair lists open workflow:merged issues itself and skips pull requests", async () => {
|
|
59
|
+
const calls = [];
|
|
60
|
+
const gh = async (a) => { calls.push(a.join(" ")); return a[0] === "api" && a[1].includes("?state=open") ? JSON.stringify([{ number: 7, labels: [{ name: "workflow:merged" }, { name: "needs-human:external" }] }, { number: 9, pull_request: {}, labels: [{ name: "needs-human" }] }]) : ""; };
|
|
61
|
+
const out = await repairMergedParked({ gh, repo: "o/r" });
|
|
62
|
+
assert.deepEqual(out.map((r) => r.issue), [7]);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
//
|
|
4
|
+
// bin/lean/mergetrain.mjs — the phase-1 merge train (#5836, epic #5823), behind `orchestration.merge_train: off|on`.
|
|
5
|
+
// A lane whose reviewed PR has pending required checks ends `pr-ready` and frees its slot; the train, run by the batch
|
|
6
|
+
// runner (orchestrate.mjs), merges the green ones serially per base at the reviewed head. Red, conflicting and moved-head
|
|
7
|
+
// PRs are handed back as needs-human `ci.red` / `base.conflict` / `merge.head_mismatch` (in-batch recovery requeues a fix
|
|
8
|
+
// lane). #5837 batches PRs onto one candidate; #5838 bisects a red candidate to its culprit (rerun once, bare-base-tip probe,
|
|
9
|
+
// FIFO halves, at most ceil(log2 N)+1 CI runs, then serial). All I/O goes through the injected `gh`; state is plain JSON (batch state.json `train`).
|
|
10
|
+
|
|
11
|
+
import { closeMergedIssue } from "./lean.mjs";
|
|
12
|
+
|
|
13
|
+
const CONFLICT_RE = /not mergeable|merge conflict|conflict/i;
|
|
14
|
+
const HEAD_RE = /head branch was modified|match-head-commit|expected head|does not match/i;
|
|
15
|
+
const FAIL = new Set(["FAILURE", "ERROR", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE"]);
|
|
16
|
+
const OK = new Set(["SUCCESS", "NEUTRAL", "SKIPPED"]);
|
|
17
|
+
|
|
18
|
+
const sameHead = (a, b) => Boolean(a) && Boolean(b) && (String(a).startsWith(String(b)) || String(b).startsWith(String(a)));
|
|
19
|
+
|
|
20
|
+
/** `[{name, state: success|failure|pending, url}]` from a `statusCheckRollup`. */
|
|
21
|
+
export function rollupStates(rollup) {
|
|
22
|
+
return (rollup ?? []).map((c) => {
|
|
23
|
+
const v = String(c.conclusion || c.state || "").toUpperCase();
|
|
24
|
+
return { name: c.name ?? c.context, state: OK.has(v) ? "success" : FAIL.has(v) ? "failure" : "pending", url: c.detailsUrl || c.targetUrl || null };
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Required (or, with policy `all`, every) check state of a PR: {green, failed: [{name, url}]}. */
|
|
29
|
+
export function judgeChecks(states, { required = [], policy = "required" } = {}) {
|
|
30
|
+
const watched = policy === "all" ? states : states.filter((s) => required.includes(s.name));
|
|
31
|
+
const failed = watched.filter((s) => s.state === "failure").map((s) => ({ name: s.name, url: s.url }));
|
|
32
|
+
const seen = new Set(watched.map((s) => s.name));
|
|
33
|
+
const green = !failed.length && watched.every((s) => s.state === "success") && (policy === "all" ? watched.length > 0 : required.every((n) => seen.has(n)));
|
|
34
|
+
return { green, failed };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Median (nearest rank) of a number list; null when empty. */
|
|
38
|
+
export const p50 = (xs) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.ceil(s.length / 2) - 1] : null; };
|
|
39
|
+
|
|
40
|
+
/** 90th percentile (nearest rank); null when empty. */
|
|
41
|
+
export const waitP90 = (xs) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.ceil(s.length * 0.9) - 1] : null; };
|
|
42
|
+
|
|
43
|
+
/** The batch report line, or null when the train never held a PR. */
|
|
44
|
+
export function formatTrainSummary(stats) {
|
|
45
|
+
if (!stats || (!stats.merged && !Object.keys(stats.handedBack ?? {}).length && !stats.syncs && !stats.batches && !stats.waits?.length)) return null;
|
|
46
|
+
const hb = Object.entries(stats.handedBack ?? {}).sort(([a], [b]) => a.localeCompare(b));
|
|
47
|
+
const total = hb.reduce((n, [, c]) => n + c, 0);
|
|
48
|
+
const w = p50(stats.waits ?? []), w90 = waitP90(stats.waits ?? []), ls = stats.laneSide;
|
|
49
|
+
return `merge train: merged ${stats.merged ?? 0}, handed back ${total}${hb.length ? ` (${hb.map(([k, c]) => `${k} ${c}`).join(", ")})` : ""}, wait p50 ${w === null ? "n/a" : `${(w / 60000).toFixed(1)} min`} p90 ${w90 === null ? "n/a" : `${(w90 / 60000).toFixed(1)} min`}, base-syncs ${stats.syncs ?? 0} (lane ${ls?.syncs ?? 0}), base.conflict ${stats.baseConflicts ?? stats.handedBack?.["base.conflict"] ?? 0} (lane ${ls?.baseConflicts ?? 0})${stats.batches ? `, batches ${stats.batches}, candidate CI runs ${stats.candidateRuns ?? 0}${stats.candidateRed ? ` (${stats.candidateRed} red)` : ""}${stats.bisections ? `, bisections ${stats.bisections}` : ""}${stats.culprits ? `, culprits ${stats.culprits}` : ""}${stats.redBase ? `, red base ${stats.redBase}` : ""}` : ""}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* @param {object} o
|
|
54
|
+
* @param {(args: string[]) => Promise<string>} o.gh gh runner (stdout)
|
|
55
|
+
* @param {string} o.repo
|
|
56
|
+
* @param {() => number} [o.now]
|
|
57
|
+
* @param {object|null} [o.saved] a prior `snapshot()` (resume)
|
|
58
|
+
* @param {number} [o.batchSize] #5837: PRs per candidate batch (1 = the serial phase-1 train)
|
|
59
|
+
* @param {string|null} [o.dispatch] workflow file to `workflow_dispatch` on the candidate (else the repo's push trigger runs CI)
|
|
60
|
+
* @param {string[]} [o.flaky] #5838: `verify.flaky` names; a failing check named there is labelled known-flaky (every red candidate is rerun once)
|
|
61
|
+
* @param {((r: {base, baseSha, checks, batch}) => Promise<unknown>)|null} [o.onBaseRed] #5838: a red base tip (the batch hands back no PR)
|
|
62
|
+
*/
|
|
63
|
+
export function createMergeTrain({ gh, repo, now = () => Date.now(), saved = null, batchSize = 1, dispatch = null, batchTimeoutMs = 90 * 60000, flaky = [], onBaseRed = null }) {
|
|
64
|
+
const entries = new Map((saved?.entries ?? []).map((e) => [e.issue, { ...e }]));
|
|
65
|
+
const stats = { merged: saved?.stats?.merged ?? 0, handedBack: { ...(saved?.stats?.handedBack ?? {}) }, waits: [...(saved?.stats?.waits ?? [])], syncs: saved?.stats?.syncs ?? 0, baseConflicts: saved?.stats?.baseConflicts ?? 0, laneSide: { syncs: saved?.stats?.laneSide?.syncs ?? 0, baseConflicts: saved?.stats?.laneSide?.baseConflicts ?? 0 }, batches: saved?.stats?.batches ?? 0, candidateRuns: saved?.stats?.candidateRuns ?? 0, candidateRed: saved?.stats?.candidateRed ?? 0,
|
|
66
|
+
bisections: saved?.stats?.bisections ?? 0, culprits: saved?.stats?.culprits ?? 0, redBase: saved?.stats?.redBase ?? 0 };
|
|
67
|
+
const copyBatch = (b) => ({ ...b, prs: b.prs.map((p) => ({ ...p })), ...(b.bisect ? { bisect: JSON.parse(JSON.stringify(b.bisect)) } : {}) });
|
|
68
|
+
const batches = (saved?.batches ?? []).map(copyBatch); // [{id, base, baseSha, prs, candidate, state, bisect?}]
|
|
69
|
+
const redBases = { ...(saved?.redBases ?? {}) }; // #5838: base -> tip sha reported red; no candidate is built on it again
|
|
70
|
+
let batchSeq = 0;
|
|
71
|
+
|
|
72
|
+
const handBack = (e, code, detail, extra = {}) => {
|
|
73
|
+
entries.delete(e.issue);
|
|
74
|
+
stats.handedBack[code] = (stats.handedBack[code] ?? 0) + 1;
|
|
75
|
+
if (code === "base.conflict") stats.baseConflicts += 1;
|
|
76
|
+
return { kind: "handback", issue: e.issue, pr: e.pr, code, detail, entry: e, ...extra };
|
|
77
|
+
};
|
|
78
|
+
const landed = (e, detail) => {
|
|
79
|
+
entries.delete(e.issue);
|
|
80
|
+
stats.merged += 1;
|
|
81
|
+
stats.waits.push(Math.max(0, now() - e.since));
|
|
82
|
+
return { kind: "merged", issue: e.issue, pr: e.pr, detail, entry: e };
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
/** #5839: replays the lane's persisted post-merge record (notes, then close unless the record keeps the issue open). */
|
|
86
|
+
const postMerge = async (e) => {
|
|
87
|
+
const rec = e.postMerge;
|
|
88
|
+
for (const n of rec?.notes ?? []) { try { await gh(["issue", "comment", String(e.issue), "-R", repo, "--body", `<!-- ${n.marker} -->\n${n.body}`]); } catch { /* the lane result carries it too */ } }
|
|
89
|
+
if (rec?.keepOpen) { if (e.branch) { try { await gh(["api", "-X", "DELETE", `repos/${repo}/git/refs/heads/${e.branch}`]); } catch { /* already gone */ } } return; }
|
|
90
|
+
await closeMergedIssue({ gh, repo, issue: e.issue, branch: e.branch }); // the lane's shared post-merge helper
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const ref = (b) => `repos/${repo}/git/refs/heads/${b}`;
|
|
94
|
+
const json = async (args) => JSON.parse(String(await gh(args)));
|
|
95
|
+
const dropRef = async (b) => { try { await gh(["api", "-X", "DELETE", ref(b.candidate)]); } catch { /* already gone */ } };
|
|
96
|
+
const dropHalf = async (b) => { const h = b.bisect?.half; if (!h?.ref) return; try { await gh(["api", "-X", "DELETE", ref(h.ref)]); } catch { /* already gone */ } };
|
|
97
|
+
const endBatch = async (b) => { await dropRef(b); await dropHalf(b); const i = batches.indexOf(b); if (i >= 0) batches.splice(i, 1); };
|
|
98
|
+
const inBatch = (issue) => batches.some((b) => b.prs.some((p) => p.issue === issue));
|
|
99
|
+
/** A member leaves its batch (landed or handed back): a validating batch no longer matches its candidate, so it dissolves. */
|
|
100
|
+
const leaveBatch = async (issue) => {
|
|
101
|
+
const b = batches.find((x) => x.prs.some((p) => p.issue === issue)); if (!b) return;
|
|
102
|
+
b.prs = b.prs.filter((p) => p.issue !== issue);
|
|
103
|
+
if (b.state === "validating" || b.state === "bisecting" || !b.prs.length) await endBatch(b);
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/** Merge one PR at its reviewed head: "merged" | "handed" | "kept" (transient or protection refusal: retried next poll). */
|
|
107
|
+
async function mergeOne(e, events) {
|
|
108
|
+
try {
|
|
109
|
+
await gh(["pr", "merge", String(e.pr), "-R", repo, "--merge", "--match-head-commit", e.head]);
|
|
110
|
+
} catch (err) {
|
|
111
|
+
const msg = `${err?.stderr ?? ""}${err?.message ?? ""}`;
|
|
112
|
+
try { if (JSON.parse(String(await gh(["pr", "view", String(e.pr), "-R", repo, "--json", "state"]))).state === "MERGED") { await postMerge(e); events.push(landed(e, `PR #${e.pr} merged`)); return "merged"; } } catch { /* fall through */ }
|
|
113
|
+
if (HEAD_RE.test(msg)) { events.push(handBack(e, "merge.head_mismatch", `gh pr merge refused PR #${e.pr}: the head is not the reviewed ${String(e.head).slice(0, 12)}`)); return "handed"; }
|
|
114
|
+
if (CONFLICT_RE.test(msg)) { events.push(handBack(e, "base.conflict", `gh pr merge reported a conflict on PR #${e.pr}`)); return "handed"; }
|
|
115
|
+
return "kept";
|
|
116
|
+
}
|
|
117
|
+
await postMerge(e);
|
|
118
|
+
events.push(landed(e, `PR #${e.pr} merged by the train at ${String(e.head).slice(0, 12)}`));
|
|
119
|
+
return "merged";
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Build `forge-train/<base>/<id>` by merging the PRs (FIFO) onto the base tip; a conflicting PR is handed back and the rest go on. */
|
|
123
|
+
async function build(base, group, events) {
|
|
124
|
+
const baseSha = (await json(["api", `repos/${repo}/git/ref/heads/${base}`])).object?.sha;
|
|
125
|
+
if (!baseSha || redBases[base] === baseSha) return; // #5838: a red base tip builds no candidate until it moves
|
|
126
|
+
const id = `${now().toString(36)}-${batchSeq++}`;
|
|
127
|
+
const b = { id, base, baseSha, prs: [], candidate: `forge-train/${base}/${id}`, state: "building", startedAt: now() };
|
|
128
|
+
await gh(["api", "-X", "POST", `repos/${repo}/git/refs`, "-f", `ref=refs/heads/${b.candidate}`, "-f", `sha=${baseSha}`]);
|
|
129
|
+
try {
|
|
130
|
+
for (const { e } of group) {
|
|
131
|
+
try { await gh(["api", "-X", "POST", `repos/${repo}/merges`, "-f", `base=${b.candidate}`, "-f", `head=${e.head}`, "-f", `commit_message=forge-train ${id}: PR #${e.pr}`]); } // a merge, never a rebase
|
|
132
|
+
catch (err) {
|
|
133
|
+
if (!/409|conflict/i.test(`${err?.stderr ?? ""}${err?.message ?? ""}`)) throw err; // transient: abandon this attempt
|
|
134
|
+
events.push(handBack(e, "base.conflict", `PR #${e.pr} conflicts with ${base} or an earlier PR in train batch ${id}; conflicting files: ${(await conflictFiles(e, b, baseSha)).join(", ") || "unknown"}`));
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
b.prs.push({ issue: e.issue, pr: e.pr, head: e.head });
|
|
138
|
+
}
|
|
139
|
+
if (b.prs.length < 2) { await dropRef(b); return; } // nothing to share a CI run: serial handling
|
|
140
|
+
b.candSha = (await json(["api", ref(b.candidate).replace("/git/refs/", "/git/ref/")])).object?.sha;
|
|
141
|
+
if (dispatch) { try { await gh(["api", "-X", "POST", `repos/${repo}/actions/workflows/${dispatch}/dispatches`, "-f", `ref=${b.candidate}`]); } catch { /* the push trigger may cover it */ } }
|
|
142
|
+
b.state = "validating"; stats.batches += 1; stats.candidateRuns += 1;
|
|
143
|
+
batches.push(b);
|
|
144
|
+
} catch { await dropRef(b); }
|
|
145
|
+
}
|
|
146
|
+
async function conflictFiles(e, b, baseSha) {
|
|
147
|
+
try {
|
|
148
|
+
const mine = (await json(["pr", "view", String(e.pr), "-R", repo, "--json", "files"])).files?.map((f) => f.path) ?? [];
|
|
149
|
+
const taken = new Set((await json(["api", `repos/${repo}/compare/${baseSha}...${b.candidate}`])).files?.map((f) => f.filename) ?? []);
|
|
150
|
+
const both = mine.filter((f) => taken.has(f));
|
|
151
|
+
return both.length ? both : mine;
|
|
152
|
+
} catch { return []; }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Poll a validating batch's candidate checks (re-read, never rebuilt, after a resume); red starts bisection (#5838), a timeout dissolves it to serial handling. */
|
|
156
|
+
async function validate(b, members) {
|
|
157
|
+
let runs;
|
|
158
|
+
try { runs = (await json(["api", `repos/${repo}/commits/${b.candSha}/check-runs`])).check_runs ?? []; } catch { return; }
|
|
159
|
+
const states = rollupStates(runs.map((r) => ({ name: r.name, conclusion: r.status === "completed" ? r.conclusion : "", detailsUrl: r.html_url })));
|
|
160
|
+
const first = members[0] ?? {};
|
|
161
|
+
const { green, failed } = judgeChecks(states, { required: [...new Set(members.flatMap((m) => m.required ?? []))], policy: first.policy ?? "required" });
|
|
162
|
+
if (green) { b.state = "merging"; return; }
|
|
163
|
+
if (failed.length) { stats.candidateRed += 1; await startBisect(b, failed, runs); return; }
|
|
164
|
+
if (now() - b.startedAt > batchTimeoutMs) { stats.candidateRed += 1; await serial(b, members); }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Every member goes to the serial phase-1 path (never re-batched): the budget ran out, a step timed out or a half could not be built. */
|
|
168
|
+
async function serial(b, members = b.prs.map((p) => entries.get(p.issue)).filter(Boolean)) {
|
|
169
|
+
for (const m of members) m.noBatch = true;
|
|
170
|
+
await endBatch(b);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The latest run per check name on `sha`, restricted to `names`: {state: green|red|pending, failed, missing}; a `stale` run id reads pending. */
|
|
174
|
+
async function readChecks(sha, names, stale = []) {
|
|
175
|
+
const runs = (await json(["api", `repos/${repo}/commits/${sha}/check-runs`])).check_runs ?? [];
|
|
176
|
+
const latest = new Map();
|
|
177
|
+
for (const r of runs) if (names.includes(r.name) && (!latest.has(r.name) || (r.id ?? 0) >= (latest.get(r.name).id ?? 0))) latest.set(r.name, r);
|
|
178
|
+
const st = names.map((n) => { const r = latest.get(n); if (!r) return { name: n, state: "missing" }; if (stale.includes(r.id) || r.status !== "completed") return { name: n, state: "pending" }; return { name: n, ...rollupStates([{ name: n, conclusion: r.conclusion, detailsUrl: r.html_url }])[0] }; });
|
|
179
|
+
const failed = st.filter((x) => x.state === "failure").map((x) => ({ name: x.name, url: x.url }));
|
|
180
|
+
return { failed, pending: st.some((x) => x.state === "pending"), missing: st.filter((x) => x.state === "missing").map((x) => x.name), green: st.every((x) => x.state === "success") };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* #5838: a red candidate. Rerun the failing checks once (a known-flaky or rerun-green failure merges without bisection),
|
|
185
|
+
* then probe the bare base tip (the same checks red there = red base: report it, hand back no PR), then split the batch
|
|
186
|
+
* FIFO into halves until one PR is left. The budget `ceil(log2 N)+1` counts every CI run it starts (the rerun and each
|
|
187
|
+
* half; the probe reads the base tip's own runs); spent, the batch goes serial. State lives on `b.bisect` (resume re-reads).
|
|
188
|
+
*/
|
|
189
|
+
async function startBisect(b, failed, runs) {
|
|
190
|
+
const names = failed.map((f) => f.name);
|
|
191
|
+
const ids = runs.filter((r) => names.includes(r.name) && r.status === "completed" && FAIL.has(String(r.conclusion ?? "").toUpperCase())).map((r) => r.id).filter((id) => id != null);
|
|
192
|
+
b.state = "bisecting";
|
|
193
|
+
b.bisect = { runs: 0, budget: Math.ceil(Math.log2(b.prs.length)) + 1, failed, flaky: names.filter((n) => flaky.includes(n)), frame: b.prs.map((p) => p.issue), step: "rerun", stale: ids, at: now(), halves: 0 };
|
|
194
|
+
let rerun = 0;
|
|
195
|
+
for (const id of ids) { try { await gh(["api", "-X", "POST", `repos/${repo}/actions/jobs/${id}/rerun`]); rerun += 1; } catch { /* not an Actions job */ } }
|
|
196
|
+
if (rerun) { b.bisect.runs += 1; stats.candidateRuns += 1; } else b.bisect.step = "probe"; // nothing could rerun: probe at once
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Build a candidate of the base tip plus the `issues` PRs (FIFO) for one bisection half; null when it cannot be built. */
|
|
200
|
+
async function buildHalf(b, issues) {
|
|
201
|
+
const k = (b.bisect.halves += 1);
|
|
202
|
+
const h = { ref: `${b.candidate}-h${k}`, prs: issues, at: now() };
|
|
203
|
+
try {
|
|
204
|
+
await gh(["api", "-X", "POST", `repos/${repo}/git/refs`, "-f", `ref=refs/heads/${h.ref}`, "-f", `sha=${b.baseSha}`]);
|
|
205
|
+
b.bisect.half = h;
|
|
206
|
+
for (const i of issues) { const p = b.prs.find((x) => x.issue === i); await gh(["api", "-X", "POST", `repos/${repo}/merges`, "-f", `base=${h.ref}`, "-f", `head=${p.head}`, "-f", `commit_message=forge-train ${b.id} bisect ${k}: PR #${p.pr}`]); }
|
|
207
|
+
h.sha = (await json(["api", ref(h.ref).replace("/git/refs/", "/git/ref/")])).object?.sha;
|
|
208
|
+
if (!h.sha) return null;
|
|
209
|
+
if (dispatch) { try { await gh(["api", "-X", "POST", `repos/${repo}/actions/workflows/${dispatch}/dispatches`, "-f", `ref=${h.ref}`]); } catch { /* the push trigger may cover it */ } }
|
|
210
|
+
return h;
|
|
211
|
+
} catch { return null; }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Narrow the frame: one PR left is the culprit; else spend one run on the first FIFO half (or go serial when the budget is spent). */
|
|
215
|
+
async function split(b, events) {
|
|
216
|
+
const bs = b.bisect;
|
|
217
|
+
if (bs.frame.length === 1) return culprit(b, bs.frame[0], events);
|
|
218
|
+
if (bs.runs >= bs.budget) return serial(b);
|
|
219
|
+
const h = await buildHalf(b, bs.frame.slice(0, Math.ceil(bs.frame.length / 2)));
|
|
220
|
+
if (!h) return serial(b);
|
|
221
|
+
bs.runs += 1; stats.candidateRuns += 1; bs.step = "half"; bs.at = now();
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function culprit(b, issue, events) {
|
|
225
|
+
const bs = b.bisect, e = entries.get(issue), p = b.prs.find((x) => x.issue === issue);
|
|
226
|
+
const f = bs.evidence ?? bs.failed[0] ?? { name: "unknown", url: null };
|
|
227
|
+
stats.culprits += 1;
|
|
228
|
+
if (e) {
|
|
229
|
+
const c = { pr: p.pr, check: f.name, url: f.url ?? null, batch: b.id };
|
|
230
|
+
events.push(handBack(e, "ci.red", `PR #${p.pr} broke the merged tree of train batch ${b.id} on ${b.base} (its own head is green): required check ${f.name} failed${f.url ? ` ${f.url}` : ""}.\n${bs.failed.map((x) => `- ${x.name}${x.url ? ` ${x.url}` : ""}`).join("\n")}`, { culprit: c }));
|
|
231
|
+
}
|
|
232
|
+
for (const q of b.prs) { const m = entries.get(q.issue); if (m) delete m.noBatch; } // innocents re-batch next poll
|
|
233
|
+
await endBatch(b);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** One poll of a bisecting batch: reads the pending step's checks (never rebuilds after a resume) and advances at most one step. */
|
|
237
|
+
async function bisectStep(b, events) {
|
|
238
|
+
const bs = b.bisect, names = bs.failed.map((f) => f.name);
|
|
239
|
+
const late = now() - (bs.at ?? b.startedAt) > batchTimeoutMs;
|
|
240
|
+
let r;
|
|
241
|
+
try { r = await readChecks(bs.step === "probe" ? b.baseSha : bs.step === "half" ? bs.half.sha : b.candSha, names, bs.step === "rerun" ? bs.stale : []); } catch { return; }
|
|
242
|
+
if (bs.step === "rerun") {
|
|
243
|
+
if (r.green) { b.state = "merging"; delete b.bisect; return; } // a flake: the batch merges, no bisection
|
|
244
|
+
if (r.failed.length) { bs.failed = r.failed; bs.step = "probe"; bs.at = now(); return; }
|
|
245
|
+
if (late) await serial(b);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if (bs.step === "probe") {
|
|
249
|
+
if (r.pending && !late) return;
|
|
250
|
+
if (r.failed.length === names.length) { // every failing check is red on the bare base tip: a red base, not a culprit
|
|
251
|
+
stats.redBase += 1; redBases[b.base] = b.baseSha;
|
|
252
|
+
if (onBaseRed) { try { await onBaseRed({ base: b.base, baseSha: b.baseSha, checks: r.failed, batch: b.id }); } catch { /* reported best effort */ } }
|
|
253
|
+
await endBatch(b);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
stats.bisections += 1;
|
|
257
|
+
return split(b, events);
|
|
258
|
+
}
|
|
259
|
+
if (r.pending || r.missing.length) { if (late) await serial(b); return; }
|
|
260
|
+
const red = r.failed.length > 0, half = bs.half.prs;
|
|
261
|
+
if (red) bs.evidence = r.failed[0];
|
|
262
|
+
await dropHalf(b); delete bs.half;
|
|
263
|
+
bs.frame = red ? half : bs.frame.filter((i) => !half.includes(i));
|
|
264
|
+
return split(b, events);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** One poll: at most one merge per base (a validated batch merges its PRs in order); returns the events (merged / handback). */
|
|
268
|
+
async function tick() {
|
|
269
|
+
const events = [];
|
|
270
|
+
const baseBusy = new Set();
|
|
271
|
+
const ready = [];
|
|
272
|
+
for (const e of [...entries.values()]) {
|
|
273
|
+
let v;
|
|
274
|
+
try { v = JSON.parse(String(await gh(["pr", "view", String(e.pr), "-R", repo, "--json", "state,headRefOid,headRefName,mergeable,mergeStateStatus,baseRefName,statusCheckRollup"]))); } catch { continue; } // unreadable: next poll
|
|
275
|
+
if (v.headRefName) e.branch = v.headRefName;
|
|
276
|
+
if (v.state === "MERGED") { events.push(landed(e, `PR #${e.pr} merged outside the train`)); await leaveBatch(e.issue); continue; }
|
|
277
|
+
if (v.state === "CLOSED") { events.push(handBack(e, "pr.closed", `PR #${e.pr} was closed without merging`)); await leaveBatch(e.issue); continue; }
|
|
278
|
+
if (!sameHead(v.headRefOid, e.head)) {
|
|
279
|
+
events.push(handBack(e, "merge.head_mismatch", `PR #${e.pr} head moved to ${String(v.headRefOid).slice(0, 12)} after review at ${String(e.head).slice(0, 12)}; refusing to merge an unreviewed head.`));
|
|
280
|
+
await leaveBatch(e.issue);
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
if (v.mergeable === "CONFLICTING") { events.push(handBack(e, "base.conflict", `PR #${e.pr} conflicts with ${v.baseRefName ?? e.lane}`)); await leaveBatch(e.issue); continue; }
|
|
284
|
+
const { green, failed } = judgeChecks(rollupStates(v.statusCheckRollup), e);
|
|
285
|
+
if (failed.length) {
|
|
286
|
+
events.push(handBack(e, "ci.red", `Required CI failed on PR #${e.pr}:\n${failed.map((f) => `- ${f.name}${f.url ? ` ${f.url}` : ""}`).join("\n")}`));
|
|
287
|
+
await leaveBatch(e.issue);
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
if (!green) continue;
|
|
291
|
+
ready.push({ e, v, base: v.baseRefName ?? e.lane ?? "" });
|
|
292
|
+
}
|
|
293
|
+
for (const b of [...batches]) { // batches first: they own their base for this poll
|
|
294
|
+
baseBusy.add(b.base);
|
|
295
|
+
const members = b.prs.map((p) => entries.get(p.issue)).filter(Boolean);
|
|
296
|
+
if (b.state === "validating") { await validate(b, members); continue; }
|
|
297
|
+
if (b.state === "bisecting") { await bisectStep(b, events); continue; }
|
|
298
|
+
for (const p of b.prs) { // merging: in order, stop at the first refusal so FIFO holds
|
|
299
|
+
const e = entries.get(p.issue); if (!e) { await leaveBatch(p.issue); continue; }
|
|
300
|
+
if (!ready.some((r) => r.e === e)) break;
|
|
301
|
+
const r = await mergeOne(e, events);
|
|
302
|
+
if (r === "kept") break;
|
|
303
|
+
await leaveBatch(e.issue);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
if (batchSize > 1) {
|
|
307
|
+
for (const base of new Set(ready.map((r) => r.base))) {
|
|
308
|
+
if (baseBusy.has(base)) continue;
|
|
309
|
+
const group = ready.filter((r) => r.base === base && !r.e.noBatch && !inBatch(r.e.issue)).sort((x, y) => x.e.since - y.e.since).slice(0, batchSize);
|
|
310
|
+
if (group.length < 2) continue;
|
|
311
|
+
try { await build(base, group, events); } catch { /* next poll */ }
|
|
312
|
+
if (batches.some((b) => b.base === base)) baseBusy.add(base);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
for (const { e, v, base } of ready) {
|
|
316
|
+
if (!entries.has(e.issue) || inBatch(e.issue)) continue;
|
|
317
|
+
if (baseBusy.has(base)) continue; // one merge or sync per base per poll
|
|
318
|
+
if (v.mergeStateStatus === "BEHIND") {
|
|
319
|
+
baseBusy.add(base);
|
|
320
|
+
try {
|
|
321
|
+
await gh(["pr", "update-branch", String(e.pr), "-R", repo]);
|
|
322
|
+
stats.syncs += 1;
|
|
323
|
+
e.head = null; // the update moves the head: adopt the new one next poll, after its checks restart
|
|
324
|
+
try { e.head = JSON.parse(String(await gh(["pr", "view", String(e.pr), "-R", repo, "--json", "headRefOid"]))).headRefOid ?? null; } catch { /* adopted below */ }
|
|
325
|
+
if (!e.head) e.head = v.headRefOid;
|
|
326
|
+
} catch { /* a conflict shows on the next poll's mergeable */ }
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
baseBusy.add(base);
|
|
330
|
+
await mergeOne(e, events);
|
|
331
|
+
}
|
|
332
|
+
return events;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
return {
|
|
336
|
+
/** A lane's `pr-ready` result: `{issue, pr, head, required, policy, lane, milestone?}`. */
|
|
337
|
+
add(r) { entries.set(r.issue, { issue: r.issue, pr: r.pr, head: r.head, required: r.required ?? [], policy: r.policy ?? "required", lane: r.lane ?? null, ...(r.milestone ? { milestone: r.milestone } : {}), ...(r.postMerge ? { postMerge: r.postMerge } : {}), since: now() });
|
|
338
|
+
if (r.laneSide) { stats.laneSide.syncs += Number(r.laneSide.syncs) || 0; stats.laneSide.baseConflicts += Number(r.laneSide.baseConflicts) || 0; }
|
|
339
|
+
},
|
|
340
|
+
drop(issue) { entries.delete(issue); },
|
|
341
|
+
/** Resume: replace the held PRs and the counters with a prior `snapshot()`. */
|
|
342
|
+
restore(snap) {
|
|
343
|
+
entries.clear();
|
|
344
|
+
for (const e of snap?.entries ?? []) entries.set(e.issue, { ...e });
|
|
345
|
+
stats.merged = snap?.stats?.merged ?? 0; stats.handedBack = { ...(snap?.stats?.handedBack ?? {}) }; stats.waits = [...(snap?.stats?.waits ?? [])]; stats.syncs = snap?.stats?.syncs ?? 0; stats.baseConflicts = snap?.stats?.baseConflicts ?? 0; stats.laneSide = { syncs: snap?.stats?.laneSide?.syncs ?? 0, baseConflicts: snap?.stats?.laneSide?.baseConflicts ?? 0 };
|
|
346
|
+
stats.batches = snap?.stats?.batches ?? 0; stats.candidateRuns = snap?.stats?.candidateRuns ?? 0; stats.candidateRed = snap?.stats?.candidateRed ?? 0;
|
|
347
|
+
stats.bisections = snap?.stats?.bisections ?? 0; stats.culprits = snap?.stats?.culprits ?? 0; stats.redBase = snap?.stats?.redBase ?? 0;
|
|
348
|
+
for (const k of Object.keys(redBases)) delete redBases[k]; Object.assign(redBases, snap?.redBases ?? {});
|
|
349
|
+
batches.length = 0; for (const b of snap?.batches ?? []) batches.push(copyBatch(b));
|
|
350
|
+
},
|
|
351
|
+
has: (issue) => entries.has(issue),
|
|
352
|
+
size: () => entries.size,
|
|
353
|
+
tick,
|
|
354
|
+
stats: () => ({ merged: stats.merged, handedBack: { ...stats.handedBack }, waits: [...stats.waits], syncs: stats.syncs, baseConflicts: stats.baseConflicts, laneSide: { ...stats.laneSide }, batches: stats.batches, candidateRuns: stats.candidateRuns, candidateRed: stats.candidateRed, bisections: stats.bisections, culprits: stats.culprits, redBase: stats.redBase }),
|
|
355
|
+
snapshot: () => ({ entries: [...entries.values()], batches: batches.map(copyBatch), ...(Object.keys(redBases).length ? { redBases: { ...redBases } } : {}), stats: { ...stats, handedBack: { ...stats.handedBack }, waits: [...stats.waits], laneSide: { ...stats.laneSide } } }),
|
|
356
|
+
};
|
|
357
|
+
}
|