From 4a793376ff72f9a3e8035b9045ec131822e65ac2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 01:49:38 +0000 Subject: [PATCH] fix(pr-assistant): honour do-not-merge and wip labels before merging juninmd/mika#77 carried `do-not-merge` and was squash-merged: the skip only matched the exact `auto-merge-skip` label. Hold labels now match in any case or separator, are re-checked on the fresh PR right before the merge (a label added mid-run still wins) and block owner `/merge` too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Cn6JQKXBbpr22WLfj9njv4 --- docs/ARCHITECTURE.md | 4 +- ts/src/agents/pr_assistant/agent.ts | 6 ++- ts/src/agents/pr_assistant/merge-block.ts | 15 ++++++ ts/src/agents/pr_assistant/merge-flow.ts | 4 ++ ts/src/notifications/telegram-format.ts | 2 +- ts/tests/merge-block-label.test.ts | 62 +++++++++++++++++++++++ ts/tests/pr-assistant.test.ts | 2 +- 7 files changed, 90 insertions(+), 5 deletions(-) create mode 100644 ts/src/agents/pr_assistant/merge-block.ts create mode 100644 ts/tests/merge-block-label.test.ts diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 09a00adc..7f2148e6 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -150,7 +150,9 @@ A model's claim never blocks or approves a PR on its own word. Each review runs: ## 7.1.1 Merge gate (`agent.ts`, `merge-flow.ts`) -Order per PR: skips (age, `auto-merge-skip`, untrusted author by **exact** login, +Order per PR: skips (age, hold label from `merge-block.ts`: `do-not-merge`, +`wip`, `auto-merge-skip`, any case or separator; re-checked right before the +merge and not overridden by `/merge`; untrusted author by **exact** login, owner `/hold`) → conflicts → red pipeline (fixed, not reviewed) → owner `/merge` → model review → pipeline pending → merge step. diff --git a/ts/src/agents/pr_assistant/agent.ts b/ts/src/agents/pr_assistant/agent.ts index 8a97d07f..085449bc 100644 --- a/ts/src/agents/pr_assistant/agent.ts +++ b/ts/src/agents/pr_assistant/agent.ts @@ -27,6 +27,7 @@ import { laneAllowsMerge } from "./dependency-lane.ts"; import { runLocalChecks, type LocalChecks } from "./local-checks.ts"; import { headCommitAt, mergeCommandValid, ownerCommands, type OwnerCommands } from "./owner-commands.ts"; import { OPENCODE_REVIEW_MARKER } from "./opencode-reviewer.ts"; +import { mergeBlockLabel } from "./merge-block.ts"; import { withPrLock } from "./pr-lock.ts"; import { ReviewRunner, type ReviewOutcome } from "./review-runner.ts"; import { buildAndSendSummary } from "./telegram-summary.ts"; @@ -191,8 +192,9 @@ export class PRAssistantAgent extends BaseAgent { isOldEnough(pr: PR): boolean { return !pr.created_at || Date.now() - new Date(pr.created_at).getTime() >= this.minPrAgeMinutes * 60_000; } skipYoung(pr: PR, r: Results, repo: string) { if (this.isOldEnough(pr)) return false; this.recordSkip(r, pr.number, pr.title, repo, "pr_too_young"); return true; } skipLabeled(pr: PR, r: Results, repo: string) { - if (!(pr.labels ?? []).some((l: any) => (typeof l === "string" ? l : l.name) === "auto-merge-skip")) return false; - this.recordSkip(r, pr.number, pr.title, repo, "auto-merge-skip"); return true; + const label = mergeBlockLabel(pr); + if (!label) return false; + this.recordSkip(r, pr.number, pr.title, repo, `merge_block_label: ${label}`); return true; } isTrusted = (login: string) => isTrustedAuthor(login); skipUntrusted(pr: PR, r: Results, repo: string) { if (this.isTrusted(pr.user?.login ?? "unknown")) return false; this.recordSkip(r, pr.number, pr.title, repo, "untrusted_author"); return true; } diff --git a/ts/src/agents/pr_assistant/merge-block.ts b/ts/src/agents/pr_assistant/merge-block.ts new file mode 100644 index 00000000..213e6d20 --- /dev/null +++ b/ts/src/agents/pr_assistant/merge-block.ts @@ -0,0 +1,15 @@ +/** Labels the owner uses to hold a PR: any of them blocks every merge path, owner `/merge` included (remove the label to merge). */ +import type { PR } from "../../github/client.ts"; + +const MERGE_BLOCK_LABELS = new Set(["auto-merge-skip", "do-not-merge", "dont-merge", "wip", "work-in-progress"]); +// "DO NOT MERGE", "do_not_merge", "don't merge" all normalise to the kebab form. +const normalise = (name: string) => name.toLowerCase().replace(/['’]/g, "").trim().replace(/[\s_]+/g, "-"); + +/** The first hold label on the PR, as written on GitHub, or null. */ +export function mergeBlockLabel(pr: PR): string | null { + for (const l of pr.labels ?? []) { + const name = typeof l === "string" ? l : l?.name ?? ""; + if (MERGE_BLOCK_LABELS.has(normalise(name))) return name; + } + return null; +} diff --git a/ts/src/agents/pr_assistant/merge-flow.ts b/ts/src/agents/pr_assistant/merge-flow.ts index a0ba5222..3611dbd7 100644 --- a/ts/src/agents/pr_assistant/merge-flow.ts +++ b/ts/src/agents/pr_assistant/merge-flow.ts @@ -6,6 +6,7 @@ import * as notify from "./notifications.ts"; import { checkPipelineStatus } from "./pipeline.ts"; import { agentsMdState, noteAgentsMdMissing } from "./agents-md-gate.ts"; import { approvalFor } from "./review-approval.ts"; +import { mergeBlockLabel } from "./merge-block.ts"; export async function tryMerge(a: PRAssistantAgent, pr: PR, results: Results, comments: any[], reviewExempt = false): Promise { const repo = pr.base.repo.full_name, gh: GithubClient = a.githubClient; @@ -34,6 +35,9 @@ export async function tryMerge(a: PRAssistantAgent, pr: PR, results: Results, co newSha = sha; } try { pr = await gh.getPull(repo, pr.number); } catch (e) { a.recordBlocked(results, pr, repo, `refresh_failed: ${e}`); return; } + // Labels on the fresh PR: a hold label added while the review ran still wins. + const held = mergeBlockLabel(pr); + if (held) { a.recordBlocked(results, pr, repo, `merge_block_label: ${held}`, pr.head.sha); return; } if (!newSha && pr.head.sha !== approvedSha) { a.recordBlocked(results, pr, repo, "sha_changed_after_review", pr.head.sha); return; } const expected = newSha || pr.head.sha; const status = await checkPipelineStatus(gh, pr); diff --git a/ts/src/notifications/telegram-format.ts b/ts/src/notifications/telegram-format.ts index 80c5ab75..209634a7 100644 --- a/ts/src/notifications/telegram-format.ts +++ b/ts/src/notifications/telegram-format.ts @@ -4,7 +4,7 @@ import { TelegramNotifier } from "./telegram.ts"; export const esc = TelegramNotifier.escapeHtml; export const SEP = "──────────────────────"; const REASON_LABELS: Record = { - pr_too_young: "PR recente (aguardando idade mínima)", checks_pending: "checks ainda rodando (aguardando)", "auto-merge-skip": "label auto-merge-skip", untrusted_author: "autor não confiável", + pr_too_young: "PR recente (aguardando idade mínima)", checks_pending: "checks ainda rodando (aguardando)", merge_block_label: "label de bloqueio (do-not-merge/wip)", untrusted_author: "autor não confiável", has_conflicts: "conflito de merge", mergeable_unknown: "GitHub ainda calculando mergeabilidade", pipeline_failure: "pipeline falhou", pipeline_fix_attempted: "correção de pipeline enviada", pipeline_pending: "pipeline em andamento", pipeline_queued: "pipeline na fila", review_blocked: "revisão encontrou problema crítico", review_pending: "revisão ainda não executada (tenta na próxima rodada)", diff --git a/ts/tests/merge-block-label.test.ts b/ts/tests/merge-block-label.test.ts new file mode 100644 index 00000000..5e56f549 --- /dev/null +++ b/ts/tests/merge-block-label.test.ts @@ -0,0 +1,62 @@ +import { expect, test } from "bun:test"; +import { PRAssistantAgent } from "../src/agents/pr_assistant/agent.ts"; +import { mergeBlockLabel } from "../src/agents/pr_assistant/merge-block.ts"; +import { RepositoryAllowlist } from "../src/config/allowlist.ts"; +import { tmp } from "./helpers.ts"; +import { join } from "node:path"; +import { writeFileSync } from "node:fs"; + +const pr = (o: any = {}) => ({ number: 77, title: "t", html_url: "u", mergeable: true, mergeable_state: "clean", created_at: "2020-01-01T00:00:00Z", labels: [], user: { login: "juninmd" }, draft: false, + head: { sha: "abc", ref: "f", repo: { full_name: "o/r" } }, base: { ref: "main", repo: { full_name: "o/r" } }, ...o }); +function fakeGh(p: any, over: any = {}) { + const calls: any[] = []; + const gh: any = { + calls, pathExists: async () => true, getIssueComments: async () => [], getCombinedStatus: async () => ({ statuses: [] }), getCheckRuns: async () => [{ name: "ci", status: "completed", conclusion: "success" }], + getPull: async () => p, commentOnPr: async () => {}, addLabelToPr: async () => {}, getLabels: async () => [], createLabel: async () => {}, + updatePrBranch: async () => [true, "", "abc"], mergePr: async (_p: any, m: string, sha: string) => { calls.push(["merge", m, sha]); return [true, "ok"]; }, + acceptReviewSuggestions: async () => [true, "", 0], addAssigneeToPr: async () => [true, "ok"], requestReviewerOnPr: async () => [true, "ok"], getFiles: async () => [], + createStatus: async () => {}, setDraft: async () => {}, removeLabel: async () => {}, + ...over, + }; + return gh; +} +const mk = (gh: any) => { + const pol = join(tmp(), "a.json"); + writeFileSync(pol, JSON.stringify({ defaults: { mode: "merge", merge: true, require_evidence: true } })); + return new PRAssistantAgent({ githubClient: gh, allowlist: new RepositoryAllowlist("/nonexistent.json"), telegram: { sendMessage: async () => true, sendPrNotification: async () => {} } as any, + autonomyPolicyPath: pol, aiClient: null, opencodeReviewActive: false, requireReview: false, + localChecks: async () => [true, "stub"], resolveConflicts: async () => [false, "stub"] }); +}; +const results = () => ({ merged: [], conflicts_resolved: [], pipeline_failures: [], skipped: [], blocked: [] }) as any; +const merged = (gh: any) => gh.calls.some((c: any) => c[0] === "merge"); + +test("owner's hold labels are recognised in any spelling the owner is likely to type", () => { + for (const name of ["do-not-merge", "DO NOT MERGE", "do_not_merge", "Do-Not-Merge", "dont-merge", "don't merge", "wip", "WIP", "work in progress", "auto-merge-skip"]) + expect(mergeBlockLabel(pr({ labels: [{ name }] }))).toBe(name); + expect(mergeBlockLabel(pr({ labels: ["do-not-merge"] }))).toBe("do-not-merge"); +}); +test("unrelated labels that only contain a hold word do not block the merge", () => { + for (const name of ["merge-conflict", "wipe-cache", "docs", "dependencies", "keep-draft"]) + expect(mergeBlockLabel(pr({ labels: [{ name }] }))).toBeNull(); + expect(mergeBlockLabel(pr({ labels: undefined }))).toBeNull(); +}); +// Regression: juninmd/mika#77 carried `do-not-merge` and was squash-merged anyway. +test("a green, trusted PR labeled do-not-merge is never merged", async () => { + const p = pr({ labels: [{ name: "do-not-merge" }] }), gh = fakeGh(p), r = results(); + await mk(gh).processPr(p, r); + expect(merged(gh)).toBe(false); + expect(r.merged).toHaveLength(0); + expect(r.skipped[0].reason).toBe("merge_block_label: do-not-merge"); +}); +test("an owner /merge does not override a do-not-merge label", async () => { + const p = pr({ labels: [{ name: "WIP" }] }); + const gh = fakeGh(p, { getIssueComments: async () => [{ user: { login: "juninmd" }, body: "/merge", created_at: new Date().toISOString() }] }); + await mk(gh).processPr(p, results()); + expect(merged(gh)).toBe(false); +}); +test("a label added while the run is in progress still stops the merge", async () => { + const snapshot = pr(), fresh = pr({ labels: [{ name: "do not merge" }] }), gh = fakeGh(fresh), r = results(); + await mk(gh).processPr(snapshot, r); + expect(merged(gh)).toBe(false); + expect(r.blocked.at(-1)?.reason ?? r.skipped.at(-1)?.reason).toBe("merge_block_label: do not merge"); +}); diff --git a/ts/tests/pr-assistant.test.ts b/ts/tests/pr-assistant.test.ts index 7eb30655..bf3028ed 100644 --- a/ts/tests/pr-assistant.test.ts +++ b/ts/tests/pr-assistant.test.ts @@ -51,7 +51,7 @@ test("young, labeled, untrusted skip", async () => { const a = mk(fakeGh(pr()), tg()); const r = () => ({ merged: [], conflicts_resolved: [], pipeline_failures: [], skipped: [], blocked: [] }) as any; let x = r(); await a.processPr(pr({ created_at: new Date().toISOString() }), x); expect(x.skipped[0].reason).toBe("pr_too_young"); - x = r(); await a.processPr(pr({ labels: [{ name: "auto-merge-skip" }] }), x); expect(x.skipped[0].reason).toBe("auto-merge-skip"); + x = r(); await a.processPr(pr({ labels: [{ name: "auto-merge-skip" }] }), x); expect(x.skipped[0].reason).toBe("merge_block_label: auto-merge-skip"); x = r(); await a.processPr(pr({ user: { login: "rando" } }), x); expect(x.skipped[0].reason).toBe("untrusted_author"); }); test("failing CI warns once and skips; no merge", async () => {