Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
6 changes: 4 additions & 2 deletions ts/src/agents/pr_assistant/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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; }
Expand Down
15 changes: 15 additions & 0 deletions ts/src/agents/pr_assistant/merge-block.ts
Original file line number Diff line number Diff line change
@@ -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;
}
4 changes: 4 additions & 0 deletions ts/src/agents/pr_assistant/merge-flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
const repo = pr.base.repo.full_name, gh: GithubClient = a.githubClient;
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion ts/src/notifications/telegram-format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { TelegramNotifier } from "./telegram.ts";
export const esc = TelegramNotifier.escapeHtml;
export const SEP = "──────────────────────";
const REASON_LABELS: Record<string, string> = {
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)",
Expand Down
62 changes: 62 additions & 0 deletions ts/tests/merge-block-label.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
2 changes: 1 addition & 1 deletion ts/tests/pr-assistant.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
Loading