diff --git a/.changes/pr-pipeline/feat-15410-merge-lane-stack-bottom-layer-89c44141.md b/.changes/pr-pipeline/feat-15410-merge-lane-stack-bottom-layer-89c44141.md new file mode 100644 index 00000000000..a349e20e1fe --- /dev/null +++ b/.changes/pr-pipeline/feat-15410-merge-lane-stack-bottom-layer-89c44141.md @@ -0,0 +1,8 @@ +--- +bump: minor +--- + +### Added + +- The merge lane lands the bottom layer of a native GitHub stack whose stack base is `main` (owner decision on #15410, option B). GitHub refuses native auto-merge for every stack member, so where `enable-auto-merge.mjs` would arm such a layer it sends the asynchronous merge instead, pinned to the head it read, into main's merge queue when there is one, and only once the newest `CI Status` run at that head passed and every hold the arm checks is clear. A layer with an open layer below it is never merged, so no lower layer lands without its own holds checked. A merge GitHub refuses leaves the layer unmerged with a refusal comment for a person; the lane adds no credential. Into a merge queue GitHub refuses the lanes App's async merge today ("Enqueuer is not authorized to merge"), so there the layer goes to a person. +- The pin comment posted before a stack layer's async merge says the merge path is about to ask GitHub to merge it and that GitHub can still refuse it, instead of saying it is about to arm native auto-merge. The pin's first line is unchanged. diff --git a/.changes/source-control/feat-15410-merge-lane-stack-bottom-layer-465e5643.md b/.changes/source-control/feat-15410-merge-lane-stack-bottom-layer-465e5643.md new file mode 100644 index 00000000000..a71629dfd8f --- /dev/null +++ b/.changes/source-control/feat-15410-merge-lane-stack-bottom-layer-465e5643.md @@ -0,0 +1,8 @@ +--- +bump: patch +--- + +### Changed + +- `reference/stacked-prs.md` says this marketplace's merge lane now lands only a stack's bottom layer, through the async merge once its `CI Status` is green, and that the issue lane does not stack yet. +- The babysit merge path's pin comment, posted before it asks GitHub to enqueue, says it is about to ask GitHub to enqueue the pull request and that GitHub can still refuse it. It used to say the pull request was enqueued, which stood beside a refusal GitHub sent in the same second. The pin's first line is unchanged, so `PIN_RE` still reads it. diff --git a/.github/scripts/pr-merge/enable-auto-merge.mjs b/.github/scripts/pr-merge/enable-auto-merge.mjs index 34d40b1d09a..517312fa494 100755 --- a/.github/scripts/pr-merge/enable-auto-merge.mjs +++ b/.github/scripts/pr-merge/enable-auto-merge.mjs @@ -178,6 +178,13 @@ // `pull_request: edited` run delays the queue. Whatever happens, the arm goes // on, and no rule here or in ci-status reads the record. It logs a // `merge-risk` notice per arm and adds its token to the step summary. +// A layer of a native stack into main is never armed, since GitHub refuses +// native auto-merge for stacks (stackPlace). Only the bottom layer, with no +// open layer below it, reads on; every rule above judges it alike. Where it +// would arm, it is merged instead through the async merge, pinned to the head +// read, once its newest CI Status run there passed; a layer above the bottom is +// left. A merge GitHub refuses leaves it unmerged with a person's refusal +// comment, and the lane adds no credential (owner decision on #15410). // // Environment: // GH_TOKEN the lane App token (contents and pull-requests write) @@ -292,6 +299,7 @@ export const PULLS_QUERY = `query($owner: String!, $name: String!, $after: Strin pageInfo { hasNextPage endCursor } nodes { id number isDraft isCrossRepository headRefName headRefOid baseRefOid body updatedAt mergeStateStatus + stack { baseRefName entries(first: 100) { totalCount nodes { position pullRequest { number state } } } } author { __typename login } userContentEdits(first: 100) { totalCount nodes { editor { __typename login } } } labels(first: 100) { totalCount nodes { name } } @@ -347,6 +355,59 @@ export const AUTO_MERGE_STATE_QUERY = `query($id: ID!) { node(id: $id) { ... on PullRequest { state headRefOid autoMergeRequest { enabledAt } } } }`; +// Native stack layers (owner decision on #15410, option B). GitHub refuses +// native auto-merge for every stack member ("Auto-merge is not supported for +// stacked pull requests", pr-pipeline-sandbox run 44776470784), so the lane +// lands only a stack's bottom layer, and through the async merge +// (https://docs.github.com/en/rest/pulls/pulls?apiVersion=2022-11-28#merge-a-pull-request-asynchronously), +// which "includes all open downstack pull requests": the bottom has none, so +// it lands alone, after its own holds. Into a merge queue, GitHub refuses the +// lanes App's async merge too ("Enqueuer is not authorized to merge", +// pr-pipeline-sandbox run 44680029102), so there the layer goes to a person +// through the refusal comment. +export const STACK_BOTTOM = "bottom"; +export function stackPlace(pull) { + const stack = pull.stack; + if (stack == null) { + return null; + } + const entries = stack.entries; + if (!Array.isArray(entries?.nodes) || !(entries.totalCount <= entries.nodes.length)) { + return "its stack's layers could not all be read"; + } + const own = entries.nodes.find((entry) => entry?.pullRequest?.number === pull.number); + if (stack.baseRefName !== "main" || own === undefined) { + return "it is a layer of a stack that does not target main"; + } + const below = entries.nodes.filter((entry) => entry?.position < own.position && entry.pullRequest?.state === "OPEN"); + return below.length === 0 ? STACK_BOTTOM : `it is a layer above the bottom of its stack (open below it: ${below.map((entry) => `#${entry.pullRequest.number}`).join(", ")}), and only the bottom layer is merged`; +} +export const CI_CHECK = "CI Status"; +export async function ciStatusAt(actions, repo, head) { + const runs = (await actions("GET", `/repos/${repo}/commits/${head}/check-runs?check_name=${encodeURIComponent(CI_CHECK)}&filter=latest&per_page=100`))?.check_runs; + if (!Array.isArray(runs)) { + throw new Error("its check runs did not read"); + } + const newest = runs.toSorted((a, b) => Number(a?.id) - Number(b?.id)).at(-1); + return newest === undefined ? "missing" : newest.status === "completed" ? String(newest.conclusion) : String(newest.status); +} +export const ciWait = (status) => `its ${CI_CHECK} at the head is ${status ?? "unread"}, not success, and a stack layer is merged only once it passes`; +export const MERGE_QUEUE_QUERY = `query($owner: String!, $name: String!) { + repository(owner: $owner, name: $name) { mergeQueue(branch: "main") { id } } +}`; +export const mergeAsyncBody = (head, queued) => + queued ? { sha: head, merge_action: "merge_queue", bypass_rules: false } : { sha: head, merge_action: "direct_merge", merge_method: "squash", bypass_rules: false }; +export const mergeRefused = (error, limited = false) => error instanceof GitHubError && !limited && error.status >= 400 && error.status < 500 && ![401, 409, 429].includes(error.status); +export const mergeRefusedReason = (cause, said) => + `GitHub refused the async merge of this stack layer (${cause}${said ? `: ${escapeCommand(said)}` : ""}), so it stays unmerged; the lane adds no credential, and a person merges it or clears the cause`; +export const STACK_QUEUED = "its async merge already put it in main's merge queue"; +// A 202 is only accepted: the merge runs in the background and can still end +// "failed" (https://docs.github.com/en/rest/pulls/pulls?apiVersion=2022-11-28#get-the-result-of-an-asynchronous-merge), +// so its result is read this many times, MERGE_RESULT_WAIT_MS apart. One still +// pending after them is left: the next run's send answers 409 while it is. +export const MERGE_RESULT_READS = 6; +export const MERGE_RESULT_WAIT_MS = 5_000; + const escapeCommand = (text) => String(text).replaceAll(/[\r\n%]/g, " "); const firstLine = (body) => bodyLines(body)[0]; @@ -999,8 +1060,12 @@ function renderRefusal(fence, person, reason, head, label, since, partial, recor // owes the read-back no pin; any other rung leaves it unnamed (babysit_merge.py). // PIN_RE is merge-holds.mjs's, whose pinHold holds a queued head no pin names. export { PIN_RE }; -export const pinBody = (sha, rung) => - `\nThe unattended merge path is about to arm native auto-merge at head \`${sha}\`, the head its arming checks judged. The arm fails if the head moves first.`; +export const pinBody = (sha, rung, stacked = false) => + `\n${ + stacked + ? `The unattended merge path is about to ask GitHub to merge this stack layer through the async merge at head \`${sha}\`, the head its checks judged. GitHub can still refuse it after accepting the request.` + : `The unattended merge path is about to arm native auto-merge at head \`${sha}\`, the head its arming checks judged. The arm fails if the head moves first.` + }`; // The lanes App's newest pin in `comments` (DETAIL_QUERY's), or undefined. const newestPin = (comments, bot) => newestAppComment(comments, bot, (c) => PIN_RE.test(firstLine(c.body))); @@ -1483,6 +1548,10 @@ export function decide(pull, { bot, humanGated, holdPaths = null, pathHolds = tr return { action: "none", reason: "not the lanes App's" }; } const armed = pull.autoMergeRequest != null; + const place = stackPlace(pull); + if (place !== null && place !== STACK_BOTTOM) { + return { action: armed ? "disarm" : "none", reason: place }; + } const held = pull.isDraft !== false ? "it is a draft" @@ -1600,6 +1669,9 @@ export function decide(pull, { bot, humanGated, holdPaths = null, pathHolds = tr // A push resets the count: the lanes clear it, with the gate's comment. return { action: "none", reason: ejected.reason, ...(ejected.comment ? { clears: "lane", comment: ejected.comment } : {}) }; } + if (!armed && place === STACK_BOTTOM && detail.ciStatus !== "success") { + return { action: "none", reason: ciWait(detail.ciStatus) }; + } return armed ? { action: "none", reason: "already armed" } : { action: "arm", reason: "no hold" }; } @@ -2307,7 +2379,15 @@ export async function main({ env = process.env, github, actions, laneReads, veri } catch (error) { console.log(`enable-auto-merge: #${pull.number} head statuses did not read: ${describe(error)}`); } - detail = { ...detail, files, filesCapped: capped, costDecision: decision, lifters, unblockStops: stops }; + let ciStatus = null; + if (stackPlace(pull) === STACK_BOTTOM) { + try { + ciStatus = await ciStatusAt(actions, repo[0], pull.headRefOid); + } catch (error) { + console.log(`enable-auto-merge: #${pull.number} ${CI_CHECK} did not read: ${describe(error)}`); + } + } + detail = { ...detail, files, filesCapped: capped, costDecision: decision, lifters, unblockStops: stops, ciStatus }; // A hold-path escalation a trusted person's approval of the head // lifts: the lane takes its label off, which re-runs ci-status at // the head (pr-require-checks.yml runs on unlabeled), and judges @@ -2475,6 +2555,19 @@ export async function main({ env = process.env, github, actions, laneReads, veri if (action === "verify") { ({ action, reason, clears, comment, withdraw } = { action: "none", reason: "its verifier verdict is not read yet" }); } + if (action === "arm" && stackPlace(pull) === STACK_BOTTOM) { + let queued; + try { + queued = (await github("POST", "/graphql", { query: QUEUE_ENTRY_QUERY, variables: { owner: repo[1], name: repo[2], pr: pull.number } }))?.data?.repository?.pullRequest; + } catch (error) { + console.log(`enable-auto-merge: #${pull.number} merge queue entry did not read: ${describe(error)}`); + } + if (typeof queued?.id !== "string") { + ({ action, reason } = { action: "none", reason: "its merge queue entry did not read, so its async merge is not sent this run" }); + } else if (queued.mergeQueueEntry != null) { + ({ action, reason } = { action: "none", reason: STACK_QUEUED }); + } + } // A pull request armed earlier in this run counts toward the cap. const full = action === "arm" ? roomHold(pull) : null; if (full !== null) { @@ -2524,7 +2617,7 @@ export async function main({ env = process.env, github, actions, laneReads, veri } if (action === "arm" && !pinned(detail?.comments?.nodes, slug, pull.headRefOid, lane?.rung)) { try { - await github("POST", `/repos/${repo[0]}/issues/${pull.number}/comments`, { body: pinBody(pull.headRefOid, lane?.rung) }); + await github("POST", `/repos/${repo[0]}/issues/${pull.number}/comments`, { body: pinBody(pull.headRefOid, lane?.rung, stackPlace(pull) === STACK_BOTTOM) }); console.log(`enable-auto-merge: #${pull.number} pinned at ${pull.headRefOid}`); } catch (error) { // No pin, no arm: an immediate enqueue would have no read-back. @@ -2547,6 +2640,60 @@ export async function main({ env = process.env, github, actions, laneReads, veri console.log(`enable-auto-merge: #${pull.number} merge-risk line not written: ${describe(error)}`); } } + if (action === "arm" && stackPlace(pull) === STACK_BOTTOM) { + leave(pull, "refused: its async merge failed"); + let queue; + try { + queue = (await github("POST", "/graphql", { query: MERGE_QUEUE_QUERY, variables: { owner: repo[1], name: repo[2] } }))?.data?.repository; + } catch (error) { + console.log(`enable-auto-merge: #${pull.number} main's merge queue did not read: ${describe(error)}`); + } + if (queue == null) { + failed += 1; + console.log(`::error title=enable-auto-merge::#${pull.number} async merge not sent: main's merge queue did not read`); + continue; + } + try { + let result = await github("PUT", `/repos/${repo[0]}/pulls/${pull.number}/merge-async`, mergeAsyncBody(pull.headRefOid, queue.mergeQueue != null)); + const uuid = result?.details?.uuid; + for (let read = 0; result?.status === "pending" && typeof uuid === "string" && read < MERGE_RESULT_READS; read += 1) { + await sleep(MERGE_RESULT_WAIT_MS); + try { + result = await github("GET", `/repos/${repo[0]}/pulls/${pull.number}/merge-async/${encodeURIComponent(uuid)}`); + } catch (error) { + console.log(`enable-auto-merge: #${pull.number} async merge result did not read: ${describe(error)}`); + break; + } + } + if (result?.status === "failed") { + inFlight -= 1; + const why = mergeRefusedReason("its result: failed", result.details?.message); + console.log(`::warning title=enable-auto-merge::#${pull.number} ${escapeCommand(why)}`); + leave(pull, `refused: ${why}`); + await note(pull, detail, { clears: "person", reason: why }); + continue; + } + leave(pull, "merge requested"); + console.log(`enable-auto-merge: #${pull.number} stack bottom layer: async merge requested at ${pull.headRefOid} (${escapeCommand(result?.status ?? "no status")})`); + statuses.push({ sha: pull.headRefOid, state: "success", description: "async merge requested for its stack's bottom layer" }); + } catch (error) { + if (error instanceof GitHubError && error.status === 409) { + leave(pull, "merge requested"); + console.log(`enable-auto-merge: #${pull.number} stack bottom layer: an async merge is already pending`); + } else if (mergeRefused(error, answer?.limited)) { + inFlight -= 1; + const { said } = answer === null ? { said: "" } : await answerBody(answer.text); + const why = mergeRefusedReason(`status ${error.status}`, said); + console.log(`::warning title=enable-auto-merge::#${pull.number} ${escapeCommand(why)}`); + leave(pull, `refused: ${why}`); + await note(pull, detail, { clears: "person", reason: why }); + } else { + failed += 1; + console.log(`::error title=enable-auto-merge::#${pull.number} async merge: ${describe(error)}`); + } + } + continue; + } if (action === "disarm" && disarmStop() !== null) { failed += 1; leave(pull, `refused: ${reason}`); diff --git a/.github/scripts/pr-merge/enable-auto-merge.test.mjs b/.github/scripts/pr-merge/enable-auto-merge.test.mjs index ef4c38f4811..b0aadc44659 100644 --- a/.github/scripts/pr-merge/enable-auto-merge.test.mjs +++ b/.github/scripts/pr-merge/enable-auto-merge.test.mjs @@ -21,6 +21,7 @@ import { DETAIL_QUERY, DISARM_MUTATION, DISCUSSION_PAGE_QUERIES, + MERGE_QUEUE_QUERY, rotated, oldestFirst, HUMAN_VETO, @@ -154,7 +155,7 @@ const labels = (...names) => ({ totalCount: names.length, nodes: names.map((name // filesError: what every changed-files GET throws. // A pull request's `after` is its auto-merge state as the read-back sees it // (AUTO_MERGE_STATE_QUERY), else its listed state; `after: "error"` fails the read. -function world(pulls, { failArm = false, armErrors = {}, disarmErrors = {}, filesError = null, noteErrors = [], closeErrors = [], disarmError = null, pinError = null, dequeueError = null } = {}) { +function world(pulls, { failArm = false, armErrors = {}, disarmErrors = {}, filesError = null, noteErrors = [], closeErrors = [], disarmError = null, pinError = null, dequeueError = null, mergeQueue = false } = {}) { const pins = []; const noteThrows = [...noteErrors]; const closeThrows = [...closeErrors]; @@ -162,6 +163,7 @@ function world(pulls, { failArm = false, armErrors = {}, disarmErrors = {}, file const disarmThrows = Object.fromEntries(Object.entries(disarmErrors).map(([id, errors]) => [id, [...errors]])); const calls = []; const notes = []; + const merges = []; const github = async (method, path, body, headers) => { calls.push({ method, path, body, headers }); // A pull request's own REST answers (`rest`, by path), such as the @@ -256,6 +258,24 @@ function world(pulls, { failArm = false, armErrors = {}, disarmErrors = {}, file } return {}; } + const ciRuns = /^\/repos\/melodic-software\/claude-code-plugins\/commits\/([0-9a-f]{40})\/check-runs\?check_name=CI%20Status&filter=latest&per_page=100$/.exec(path); + if (method === "GET" && ciRuns) { + return { check_runs: pulls.find((candidate) => candidate.headRefOid === ciRuns[1] && candidate.stack)?.ci ?? [] }; + } + const mergeAsync = /^\/repos\/melodic-software\/claude-code-plugins\/pulls\/([0-9]+)\/merge-async$/.exec(path); + if (method === "PUT" && mergeAsync) { + merges.push({ number: Number(mergeAsync[1]), body }); + const found = pulls.find((candidate) => candidate.number === Number(mergeAsync[1])); + if (found?.mergeError) { + throw found.mergeError; + } + return found?.mergeResults ? { status: "pending", details: { uuid: `U${found.number}` } } : { status: "pending" }; + } + const mergeResult = /^\/repos\/melodic-software\/claude-code-plugins\/pulls\/([0-9]+)\/merge-async\/U([0-9]+)$/.exec(path); + if (method === "GET" && mergeResult) { + const results = pulls.find((candidate) => candidate.number === Number(mergeResult[1])).mergeResults; + return results.length > 1 ? results.shift() : results[0]; + } // The lane lifting the human-gated label (approvalLift). if (method === "DELETE" && /^\/repos\/melodic-software\/claude-code-plugins\/issues\/[0-9]+\/labels\/[^/]+$/.test(path)) { notes.push({ method, path }); @@ -335,6 +355,9 @@ function world(pulls, { failArm = false, armErrors = {}, disarmErrors = {}, file const found = pulls.find((candidate) => candidate.number === body.variables.pr); return { data: { repository: { pullRequest: { id: found?.id, mergeQueueEntry: found?.queued ? { id: `MQE_${found.number}` } : null } } } }; } + if (body.query === MERGE_QUEUE_QUERY) { + return { data: { repository: { mergeQueue: mergeQueue ? { id: "MQ_main" } : null } } }; + } if (body.query === DEQUEUE_MUTATION && dequeueError) { throw dequeueError; } @@ -376,9 +399,9 @@ function world(pulls, { failArm = false, armErrors = {}, disarmErrors = {}, file }; const writes = () => calls - .filter(({ method, path, body }) => method === "POST" && path === "/graphql" && ![PULLS_QUERY, DETAIL_QUERY, PULL_OPENED_QUERY, COMMENT_EDITED_QUERY, UNLABELED_QUERY, DISCUSSION_PAGE_QUERIES.comments, THREAD_PAGE_QUERY, AUTO_MERGE_STATE_QUERY, QUEUE_ENTRY_QUERY].includes(body.query) && !String(body.query).startsWith(SKIP_STATE_PREFIX)) + .filter(({ method, path, body }) => method === "POST" && path === "/graphql" && ![PULLS_QUERY, DETAIL_QUERY, PULL_OPENED_QUERY, COMMENT_EDITED_QUERY, UNLABELED_QUERY, DISCUSSION_PAGE_QUERIES.comments, THREAD_PAGE_QUERY, AUTO_MERGE_STATE_QUERY, QUEUE_ENTRY_QUERY, MERGE_QUEUE_QUERY].includes(body.query) && !String(body.query).startsWith(SKIP_STATE_PREFIX)) .map(({ body }) => ({ mutation: body.query === ARM_MUTATION ? "arm" : body.query === DISARM_MUTATION ? "disarm" : body.query === DEQUEUE_MUTATION ? "dequeue" : "?", ...body.variables })); - return { github, writes, verify, verified, calls, notes, pins }; + return { github, writes, verify, verified, calls, notes, pins, merges }; } // babysit_whole_review.py stood in for: each call in order, as @@ -407,7 +430,7 @@ function wholeReview(options, notes) { } async function run(pulls, env = {}, options = {}, lane = ROOM) { - const { github, writes, verify, verified, calls, notes, pins } = world(pulls, options); + const { github, writes, verify, verified, calls, notes, pins, merges } = world(pulls, options); const whole = wholeReview(options, notes); const lines = []; const slept = []; @@ -428,7 +451,7 @@ async function run(pulls, env = {}, options = {}, lane = ROOM) { const statuses = line === undefined ? [] : JSON.parse(line.slice(UNARMED_OUTPUT.length + 1)); // A PR-scoped run's outcome line (WAKE_OUTPUT), if any. const outcome = readFileSync(output, "utf8").split("\n").find((text) => text.startsWith(`${WAKE_OUTPUT}=`))?.slice(WAKE_OUTPUT.length + 1); - return { code, writes: writes(), lines, verified, slept, calls, notes, pins, statuses, closed, asked: whole.asked, outcome }; + return { code, writes: writes(), lines, verified, slept, calls, notes, pins, statuses, closed, asked: whole.asked, outcome, merges }; } finally { console.log = log; } @@ -4542,3 +4565,130 @@ test("the Merge-Risk line is written only before an arm, never under report-only await run([pull(3)], {}, { mergeRisk }); assert.deepEqual(seen, [3]); }); + +// Expected values from the owner's decision on #15410 (option B): +// https://github.com/melodic-software/claude-code-plugins/issues/15410#issuecomment-6953991792 +const stackOf = (layers, baseRefName = "main") => ({ + baseRefName, + entries: { totalCount: layers.length, nodes: layers.map(([number, position, state = "OPEN"]) => ({ position, pullRequest: { number, state } })) }, +}); +const ciRun = (id, status, conclusion = null) => ({ id, name: "CI Status", status, conclusion }); +const GREEN = [ciRun(1, "completed", "failure"), ciRun(2, "completed", "success")]; +const ASYNC_DIRECT = { sha: HEAD, merge_action: "direct_merge", merge_method: "squash", bypass_rules: false }; + +test("a green stack bottom layer is merged through the async merge at its head, never armed; a pull request in no stack still arms", async () => { + const bottom = pull(7, { stack: stackOf([[7, 1], [8, 2]]), ci: GREEN }); + const next = pull(9, { stack: stackOf([[6, 1, "MERGED"], [9, 2]]), ci: GREEN }); + const { code, writes, merges, pins, statuses } = await run([bottom, next, pull(10)]); + assert.equal(code, 0); + assert.deepEqual(merges, [ + { number: 7, body: ASYNC_DIRECT }, + { number: 9, body: ASYNC_DIRECT }, + ]); + assert.deepEqual(writes, [{ mutation: "arm", id: "PR_10", head: HEAD }]); + assert.deepEqual(pins.map((pin) => pin.path), [`${ISSUES}/7/comments`, `${ISSUES}/9/comments`, `${ISSUES}/10/comments`]); + const [layerPin, , plainPin] = pins.map((pin) => pin.body.split("\n")); + assert.equal(layerPin[0], pinLine("C2")); + assert.equal(layerPin[1], `The unattended merge path is about to ask GitHub to merge this stack layer through the async merge at head \`${HEAD}\`, the head its checks judged. GitHub can still refuse it after accepting the request.`); + assert.doesNotMatch(layerPin[1], /enqueued|arm native auto-merge/); + assert.match(plainPin[1], /about to arm native auto-merge/); + assert.ok(statuses.some((status) => status.description === "async merge requested for its stack's bottom layer")); +}); + +test("into a merge queue, the async merge enqueues the bottom layer with no merge method", async () => { + const { merges } = await run([pull(7, { stack: stackOf([[7, 1]]), ci: GREEN })], {}, { mergeQueue: true }); + assert.deepEqual(merges, [{ number: 7, body: { sha: HEAD, merge_action: "merge_queue", bypass_rules: false } }]); +}); + +test("a held stack bottom layer is not merged: a hold label, a body hold, a member veto, or a CI Status not green at its head", async () => { + const stack = stackOf([[1, 1]]); + const veto = said("kyle-sexton", "Please do not merge this yet.", "2026-10-23T09:00:00Z"); + for (const held of [ + pull(1, { stack, ci: GREEN, labels: labels("do-not-merge") }), + pull(1, { stack, ci: GREEN, body: "Closes #5\n\nHold: a human merges this\n" }), + pull(1, { stack, ci: GREEN, discussion: { comments: [veto] } }), + pull(1, { stack, ci: [ciRun(3, "in_progress")] }), + pull(1, { stack, ci: [ciRun(3, "completed", "failure")] }), + pull(1, { stack }), + ]) { + const { merges, writes } = await run([held]); + assert.deepEqual(merges, [], JSON.stringify(held.labels ?? held.body ?? held.ci)); + assert.deepEqual(writes.filter((write) => write.mutation === "arm"), []); + } + assert.equal(decide(pull(1, { stack }), { bot: LANES.login, humanGated: "needs-human", holdPaths: [] }, { ...detail(), files: ["docs/a.md"], verify: PASSED, ciStatus: "in_progress" }).reason, "its CI Status at the head is in_progress, not success, and a stack layer is merged only once it passes"); +}); + +test("a layer above the bottom is not merged, nor one of a stack into another branch or a stack not read whole", async () => { + const cut = { baseRefName: "main", entries: { totalCount: 3, nodes: [{ position: 2, pullRequest: { number: 8, state: "OPEN" } }] } }; + for (const [stack, reason] of [ + [stackOf([[7, 1], [8, 2]]), "it is a layer above the bottom of its stack (open below it: #7), and only the bottom layer is merged"], + [stackOf([[8, 1]], "release"), "it is a layer of a stack that does not target main"], + [cut, "its stack's layers could not all be read"], + ]) { + const { merges, writes, verified, lines } = await run([pull(8, { stack, ci: GREEN })]); + assert.deepEqual(merges, []); + assert.deepEqual(writes, []); + assert.deepEqual(verified, []); + assert.ok(lines.includes(`enable-auto-merge: #8 left: ${reason}`), reason); + } +}); + +test("a refused async merge leaves the layer unmerged with a person's explanatory comment, and the run goes on", async () => { + const refused = new GitHubError(403, "PUT /repos/melodic-software/claude-code-plugins/pulls/7/merge-async"); + const { code, merges, notes, writes } = await run([pull(7, { stack: stackOf([[7, 1]]), ci: GREEN, mergeError: refused }), pull(10)]); + assert.equal(code, 0); + assert.equal(merges.length, 1); + const reason = "GitHub refused the async merge of this stack layer (status 403), so it stays unmerged; the lane adds no credential, and a person merges it or clears the cause"; + assert.deepEqual( + notes.map(({ method, path, body }) => ({ method, path, body: body.body === undefined ? body : body.body.replaceAll("\n ", " ") })), + [ + { method: "POST", path: `${ISSUES}/7/comments`, body: personNote(reason) }, + { method: "POST", path: `${ISSUES}/7/labels`, body: { labels: ["needs-human"] } }, + ], + ); + assert.deepEqual(writes, [{ mutation: "arm", id: "PR_10", head: HEAD }]); +}); + +test("a bottom layer already in main's merge queue is neither sent again nor counted again toward the room", async () => { + const queued = pull(7, { stack: stackOf([[7, 1]]), ci: GREEN, queued: true }); + const { code, merges, pins, writes, lines, notes } = await run([queued, pull(10)], {}, { mergeQueue: true }, { ...ROOM, count: 1, cap: 2, queued: [7] }); + assert.equal(code, 0); + assert.deepEqual(merges, []); + assert.deepEqual(pins.map((pin) => pin.path), [`${ISSUES}/10/comments`]); + assert.deepEqual(writes, [{ mutation: "arm", id: "PR_10", head: HEAD }]); + assert.deepEqual(notes, []); + assert.ok(lines.includes("enable-auto-merge: #7 left: its async merge already put it in main's merge queue")); +}); + +test("an accepted async merge whose result ends failed leaves the layer with a person's explanatory comment; one that merges or enqueues does not", async () => { + const pending = { status: "pending", details: { uuid: "U7" } }; + const failed = { status: "failed", details: { message: "Merge conflict" } }; + const { code, merges, notes, slept } = await run([pull(7, { stack: stackOf([[7, 1]]), ci: GREEN, mergeResults: [pending, failed] })]); + assert.equal(code, 0); + assert.equal(merges.length, 1); + assert.deepEqual(slept, [5000, 5000]); + const reason = "GitHub refused the async merge of this stack layer (its result: failed: Merge conflict), so it stays unmerged; the lane adds no credential, and a person merges it or clears the cause"; + assert.deepEqual( + notes.map(({ method, path, body }) => ({ method, path, body: body.body === undefined ? body : body.body.replaceAll("\n ", " ") })), + [ + { method: "POST", path: `${ISSUES}/7/comments`, body: personNote(reason) }, + { method: "POST", path: `${ISSUES}/7/labels`, body: { labels: ["needs-human"] } }, + ], + ); + for (const status of ["merged", "enqueued"]) { + const done = await run([pull(7, { stack: stackOf([[7, 1]]), ci: GREEN, mergeResults: [{ status }] })]); + assert.deepEqual(done.notes, [], status); + assert.ok(done.statuses.some((line) => line.description === "async merge requested for its stack's bottom layer"), status); + } + const waiting = await run([pull(7, { stack: stackOf([[7, 1]]), ci: GREEN, mergeResults: [pending] })]); + assert.deepEqual(waiting.slept, [5000, 5000, 5000, 5000, 5000, 5000]); + assert.deepEqual(waiting.notes, []); +}); + +test("an async merge already pending is neither a refusal nor sent again", async () => { + const pending = new GitHubError(409, "PUT /repos/melodic-software/claude-code-plugins/pulls/7/merge-async"); + const { code, merges, notes } = await run([pull(7, { stack: stackOf([[7, 1]]), ci: GREEN, mergeError: pending })]); + assert.equal(code, 0); + assert.equal(merges.length, 1); + assert.deepEqual(notes, []); +}); diff --git a/plugins/source-control/reference/stacked-prs.md b/plugins/source-control/reference/stacked-prs.md index 9cb7d86a086..b5a6bf2ee9c 100644 --- a/plugins/source-control/reference/stacked-prs.md +++ b/plugins/source-control/reference/stacked-prs.md @@ -37,9 +37,13 @@ In this marketplace the review and run lanes accept a native stack layer whose s default branch, and still fail any other non-default base ([pr-run-activity.md](https://github.com/melodic-software/claude-code-plugins/blob/main/docs/conventions/pr-pipeline/pr-run-activity.md), "The run job"; [#15400](https://github.com/melodic-software/claude-code-plugins/pull/15400)). The -merge and issue lanes do not handle layers yet -([#15410](https://github.com/melodic-software/claude-code-plugins/issues/15410)), so an attended -session may stack, and an unattended lane does not stack until that work lands. +merge lane sends only a stack's bottom layer to the async merge, once its `CI Status` is green, and +never a layer above it +([#15410](https://github.com/melodic-software/claude-code-plugins/issues/15410)). Into a merge queue +GitHub refuses that merge from the lanes App, so there the layer gets a refusal comment and a person +merges it. The issue lane +does not stack yet ([#17539](https://github.com/melodic-software/claude-code-plugins/issues/17539)), +so an attended session may stack, and an unattended lane does not. - **Pointer**: for why and when GitHub recommends a stack, fetch [About stacked pull requests](https://docs.github.com/en/pull-requests/get-started/about-stacked-prs#why-use-github-stacked-pull-requests) @@ -48,7 +52,7 @@ session may stack, and an unattended lane does not stack until that work lands. Correlate with the probe results in the pull request that closed [#7664](https://github.com/melodic-software/claude-code-plugins/issues/7664). - **Recheck trigger**: [#15410](https://github.com/melodic-software/claude-code-plugins/issues/15410) - closes. + or [#17539](https://github.com/melodic-software/claude-code-plugins/issues/17539) closes. ## Create diff --git a/plugins/source-control/skills/babysit-loop/scripts/fixtures/publish-promotion-evidence/github-fake.mjs b/plugins/source-control/skills/babysit-loop/scripts/fixtures/publish-promotion-evidence/github-fake.mjs index 8f3cc444d9e..173cac69909 100644 --- a/plugins/source-control/skills/babysit-loop/scripts/fixtures/publish-promotion-evidence/github-fake.mjs +++ b/plugins/source-control/skills/babysit-loop/scripts/fixtures/publish-promotion-evidence/github-fake.mjs @@ -105,7 +105,7 @@ export const wfRun = (id, event, sha, created, { conclusion = "success", status // 404; `discussions`: discussion number to author login, whose numbers also read 404 as issues; // `lateRuns`: run ids the run listing shows on every page but the first, as if listed mid-read. // babysit_postmerge.py pin_comment: the old shape names no rung, the new one `rung=C2|C3`. -export const pinComment = (sha, rung) => ({ author: actorOf(LANE), body: `\nThe unattended merge path enqueued this pull request at head \`${sha}\`.`, lastEditedAt: null }); +export const pinComment = (sha, rung) => ({ author: actorOf(LANE), body: `\nThe unattended merge path is about to ask GitHub to enqueue this pull request at head \`${sha}\`. GitHub can still refuse it after accepting the request.`, lastEditedAt: null }); export const demotionIssue = (number, createdAt, { author = "github-actions[bot]", body = REC.demotionIssue.body, updatedAt = createdAt, comments = [], edits = [], editCount = edits.length } = {}) => ({ ...REC.demotionIssue, number, diff --git a/plugins/source-control/skills/babysit-prs/scripts/babysit_postmerge.py b/plugins/source-control/skills/babysit-prs/scripts/babysit_postmerge.py index 63ce744cfe2..fd783b507a5 100755 --- a/plugins/source-control/skills/babysit-prs/scripts/babysit_postmerge.py +++ b/plugins/source-control/skills/babysit-prs/scripts/babysit_postmerge.py @@ -3744,7 +3744,8 @@ def pin_comment(sha: str, rung: str | None = None) -> str: named = f" rung={rung}" if rung else "" return ( f"\n" - f"The unattended merge path enqueued this pull request at head `{sha}`." + f"The unattended merge path is about to ask GitHub to enqueue this pull request at head `{sha}`. " + "GitHub can still refuse it after accepting the request." ) diff --git a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_postmerge_pins.py b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_postmerge_pins.py index 0cad64822d0..3501f331aa1 100644 --- a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_postmerge_pins.py +++ b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_postmerge_pins.py @@ -227,6 +227,18 @@ def test_the_new_pin_names_the_rung_on_its_first_line(self) -> None: f"", ) + def test_the_pin_claims_only_the_request_since_github_can_still_refuse( + self, + ) -> None: + said = pm.pin_comment(sha(1)).split("\n", 1)[1] + self.assertEqual( + said, + "The unattended merge path is about to ask GitHub to enqueue this pull " + f"request at head `{sha(1)}`. GitHub can still refuse it after " + "accepting the request.", + ) + self.assertNotIn("enqueued", said) + def test_old_and_new_pins_read_back_their_sha(self) -> None: for line in ( f"",