diff --git a/src/fixup/candidates.ts b/src/fixup/candidates.ts index 881bd574..1a8d32fe 100644 --- a/src/fixup/candidates.ts +++ b/src/fixup/candidates.ts @@ -10,6 +10,7 @@ import { FORMAT_REASONS, safePath } from "./patch.ts"; import { longLivedOf, pushable } from "./pushable.ts"; import { classifyConflicts, type ConflictCandidate } from "./conflict-state.ts"; import { pilotSql } from "../pilot.ts"; +import { buildQueue, type QueueEntry } from "../merge/queue.ts"; import { findingsOf, premergeAt, premergeFixUsed } from "../premerge/store.ts"; /** Fix-up tries per PR (pushed, failed, refused or rejected) before the step leaves it to a person. */ @@ -66,12 +67,12 @@ export type FixupBucket = "fix" | "unapproved" | "cannot-push" | "ask" | "asked" export type Classified = { c: FixCandidate; bucket: FixupBucket; done: boolean }; /** - * The PR's pre-merge round, when its review at this head has defects that all carry a fix and the round is unused. - * Only `fix` is acted on; every other case is `done` so the step leaves it to the queue's Merge? question. + * The PR's pre-merge round, for a queue entry in needs-fix-up from its pre-merge review: the queue decides eligibility + * (stale reviews, open questions, holds, answers, the rule), this only adds the head, push and fix-list guards. */ -function premergeCandidate(db: DatabaseSync, r: Row, head: string, approved: boolean, longLived: ReturnType): Classified | null { +function premergeCandidate(db: DatabaseSync, r: Row, head: string, approved: boolean, longLived: ReturnType, entry: QueueEntry | undefined): Classified | null { if (r.mergeable === "CONFLICTING") return null; - if (!db.prepare("SELECT 1 FROM final_reviews WHERE repo = ? AND number = ? AND head_oid = ? AND verdict = 'take'").get(r.repo, r.number, head)) return null; + if (!entry || entry.held || entry.head !== head || entry.state !== "needs-fix-up" || entry.premerge?.state !== "fix") return null; const row = premergeAt(db, r.repo, r.number, head); const defects = findingsOf(row).filter((f) => f.severity === "defect"); if (!row || !defects.length || !defects.every((f) => f.fix) || premergeFixUsed(db, r.repo, r.number)) return null; @@ -100,6 +101,9 @@ export function classifyFixups(db: DatabaseSync, repo: string): Classified[] { const approved = pushApprovalOf(db, repo) !== null; const stale = staleReviews(db, repo); const longLived = longLivedOf(db, repo); + // Built once: the queue is the single source of which PRs get a pre-merge round. + let queue: Map | null = null; + const entryOf = (n: number) => (queue ??= new Map(buildQueue(db, { repo, merged: "exclude" }).map((e) => [e.number, e] as const))).get(n); const out: Classified[] = []; for (const r of rows) { const fresh = r.c_at && (!r.updated_at || r.c_at > r.updated_at); @@ -111,7 +115,7 @@ export function classifyFixups(db: DatabaseSync, repo: string): Classified[] { const review = db.prepare("SELECT reason, fixes, model FROM final_reviews WHERE repo = ? AND number = ? AND head_oid = ? AND verdict = 'take-fix'").get(r.repo, r.number, head) as { reason: string; fixes: string | null; model: string | null } | undefined; if (!review) { - const pm = premergeCandidate(db, r, head, approved, longLived); + const pm = premergeCandidate(db, r, head, approved, longLived, entryOf(r.number)); if (pm) out.push(pm); continue; } diff --git a/src/merge/index.ts b/src/merge/index.ts index 89e97d91..82beaf5e 100644 --- a/src/merge/index.ts +++ b/src/merge/index.ts @@ -160,7 +160,7 @@ export function mergeQuestion(e: QueueEntry, why: string | null = null): Record< const fixes = e.fixes ? `; ${e.fixes} fix${e.fixes === 1 ? "" : "es"} listed` : ""; const pre = [ ...(e.premerge?.defects ?? []).filter(() => e.outsideRule.includes(PREMERGE_DEFECT_REASON)).map((f) => `pre-merge defect: ${f.file}:${f.line} ${f.title}: ${f.scenario}`), - ...(e.outsideRule.includes(PREMERGE_FAILED_REASON) ? [`pre-merge review failed: ${e.premerge?.error ?? "no review stored"}`] : []), + ...(e.outsideRule.includes(PREMERGE_FAILED_REASON) ? [`pre-merge review failed: ${(e.premerge?.error ?? "no review stored").replace(/^retry: /, "")}`] : []), ]; const where = `size ${e.size}, label ${e.label ?? "not settled"}; author: ${e.author ?? "unknown"}, ${TIER_LABEL[e.tier]}`; const ci = `CI ${e.noCi ? "none: the repo has no CI checks" : e.ci}, mergeable ${e.mergeable.toLowerCase()}`; diff --git a/src/merge/queue.ts b/src/merge/queue.ts index 8b973093..ab187018 100644 --- a/src/merge/queue.ts +++ b/src/merge/queue.ts @@ -293,9 +293,10 @@ export function buildQueue(db: DatabaseSync, opts: QueueOptions = {}): QueueEntr // Only a merge answer is set aside at an unsure head; a hold or close still counts. const given = (answers.get(id) as string | undefined) ?? null; const answer = given === "merge" && unsure && !answeredAfter.get(id, r.r_at) ? null : given; - // The pre-merge review gates only what the rule would merge; an operator's Merge answer skips it. Its blocking reasons go to outsideRule before stateOf decides the path. + // The pre-merge review gates what the rule would merge. Its blocking reasons go to outsideRule before stateOf decides the path, also + // after a Merge answer, so that the merge runs as an operator merge with its checks. let premerge: QueueEntry["premerge"] = null; - if (r.state === "OPEN" && !mergedByUs && !outsideRule.length && answer !== "merge") { + if (r.state === "OPEN" && !mergedByUs && !outsideRule.length) { const row = premergeAt(db, r.repo, r.number, r.r_head); const all = findingsOf(row); const defects = all.filter((f) => f.severity === "defect"); @@ -305,7 +306,8 @@ export function buildQueue(db: DatabaseSync, opts: QueueOptions = {}): QueueEntr else if (row.findings === null) premerge = { state: row.tries >= PREMERGE_MAX_TRIES ? "failed" : "retry", defects, minor, error }; else if (!defects.length) premerge = { state: "clean", defects, minor, error }; else { - const fixable = defects.every((f) => f.fix) && !premergeFixUsed(db, r.repo, r.number) && pushApprovalOf(db, r.repo) !== null && pushableAt(r, checksHere); + // A Merge? decision at this head (a Hold, say) is never replaced by a fix-up. + const fixable = !asked && defects.every((f) => f.fix) && !premergeFixUsed(db, r.repo, r.number) && pushApprovalOf(db, r.repo) !== null && pushableAt(r, checksHere); premerge = { state: fixable ? "fix" : "defect", defects, minor, error }; } if (premerge.state === "defect") outsideRule.push(PREMERGE_DEFECT_REASON); @@ -330,7 +332,8 @@ export function buildQueue(db: DatabaseSync, opts: QueueOptions = {}): QueueEntr e.conflictNote = conflictNote(conflictBucket(db, { repo: r.repo, number: r.number, head: r.r_head, pushable: pushableAt(r, checksHere) }, approvalOf(r.repo)), r.base_ref); } const batch = inBatch.get(`${r.repo}#${r.number}@${r.r_head}`); - if (batch && BATCHABLE.includes(e.state)) e.state = batch; + // A rule-path PR without a clean pre-merge review keeps its own state: a batch must not land it. + if (batch && BATCHABLE.includes(e.state) && (e.path !== "rule" || e.premerge?.state === "clean")) e.state = batch; // A red main fails every PR's CI: ready PRs wait for it, except the PRs AutoCraft opened to fix it. Batch members keep their batch state; the batch just is not merged (see batch.ts). else if (open && mainRed.has(r.repo) && MAIN_RED_HELD.includes(e.state) && !e.mainFix) e.state = "waiting-main-ci"; out.push(e); diff --git a/src/premerge/review.ts b/src/premerge/review.ts index 613f79ba..0e9944d9 100644 --- a/src/premerge/review.ts +++ b/src/premerge/review.ts @@ -16,6 +16,7 @@ import { REPO_PATH } from "../sandbox/command.ts"; import { checkoutForPr } from "../sandbox/index.ts"; import { lintPremerge, parsePremerge, premergeTexts, type PremergeReview } from "./parse.ts"; import { RETRY_AFTER_MS } from "../postmerge/select.ts"; +import { mergeApprovalOf } from "../merge/approval.ts"; import { PREMERGE_MAX_TRIES, premergeAt, premergeRetryDue, savePremerge } from "./store.ts"; const PROMPT = CLAUDE_PROMPTS["premerge.opus"]; @@ -42,6 +43,7 @@ export function defaultPremergeDeps(): PremergeDeps { * failed tries are due again (ms): nothing in the data changes then, so the planner must be told. */ export function premergeCandidates(db: DatabaseSync, repo: string, at = Date.now(), wake?: number[], queue?: QueueEntry[]): QueueEntry[] { + if (!mergeApprovalOf(db, repo)) return []; return (queue ?? buildQueue(db, { repo, merged: "exclude" })).filter((e) => { if (e.repo !== repo || e.state !== "waiting-premerge") return false; const row = premergeAt(db, repo, e.number, e.head); @@ -77,14 +79,14 @@ export async function runPremerge(db: DatabaseSync, params: PremergeParams, log: let handled = 0; await pool(cands.map((e) => async () => { const start = now(), ref = refOf(e), head = e.head; - const fail = (error: string) => { + const fail = (error: string, final = false) => { log(` ${ref}: ${error}`); - savePremerge(db, { repo, number: e.number, head, at: now(), runId, model: deps.model, error }); + savePremerge(db, { repo, number: e.number, head, at: now(), runId, model: deps.model, error, final }); s.failed.push(ref); }; const p = await prepareOpusInput(db, repo, candidateOf(db, e), opusDeps, log, { independent: true }); if (p.kind === "no-diff") fail(`retry: no diff: ${p.error}`); - else if (p.kind === "large") fail("retry: too large to review automatically"); + else if (p.kind === "large") fail("too large to review automatically", true); else if (p.kind === "no-threads") fail(`retry: ${p.error}`); else { const { input } = p; diff --git a/src/premerge/store.ts b/src/premerge/store.ts index 6fcea473..9958e94c 100644 --- a/src/premerge/store.ts +++ b/src/premerge/store.ts @@ -29,6 +29,8 @@ export type PremergeSave = { findings?: PremergeFinding[]; searched?: string | null; error?: string | null; + /** The failure is final: no more tries (the head cannot be reviewed at all). */ + final?: boolean; }; /** Stores a review (clears the error) or counts a failed try. */ @@ -40,9 +42,9 @@ export function savePremerge(db: DatabaseSync, s: PremergeSave): void { findings = excluded.findings, searched = excluded.searched, error = NULL`).run(...args, JSON.stringify(s.findings), s.searched ?? null); return; } - db.prepare(`INSERT INTO premerge_reviews (repo, number, head_oid, at, run_id, model, error, tries) VALUES (?, ?, ?, ?, ?, ?, ?, 1) + db.prepare(`INSERT INTO premerge_reviews (repo, number, head_oid, at, run_id, model, error, tries) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (repo, number, head_oid) DO UPDATE SET at = excluded.at, run_id = excluded.run_id, model = excluded.model, - error = excluded.error, tries = tries + 1`).run(...args, s.error ?? "failed"); + error = excluded.error, tries = CASE WHEN ? THEN excluded.tries ELSE tries + 1 END`).run(...args, s.error ?? "failed", s.final ? PREMERGE_MAX_TRIES : 1, s.final ? 1 : 0); } export function premergeAt(db: DatabaseSync, repo: string, number: number, head: string): PremergeRow | null { diff --git a/src/runner/autopilot.ts b/src/runner/autopilot.ts index 7879bfef..0f656b61 100644 --- a/src/runner/autopilot.ts +++ b/src/runner/autopilot.ts @@ -401,10 +401,11 @@ const LANE_CODE: Omit[] = [ name: "premerge", perRepo: true, detect: (db, { tracked, wake, run }) => { - if (!tracked.length) return []; + const repos = tracked.filter((repo) => mergeApprovalOf(db, repo)); + if (!repos.length) return []; // One queue for every repo, with the planner's run: buildQueue per repo would look the run up each time. const queue = buildQueue(db, { run, merged: "exclude" }); - return tracked.filter((repo) => premergeCandidates(db, repo, Date.now(), wake, queue).length > 0).sort().map((repo) => ({ step: "premerge", params: { repo } })); + return repos.filter((repo) => premergeCandidates(db, repo, Date.now(), wake, queue).length > 0).sort().map((repo) => ({ step: "premerge", params: { repo } })); }, }, { diff --git a/test/premerge-fixup.test.ts b/test/premerge-fixup.test.ts index 3f093a7b..8ade060a 100644 --- a/test/premerge-fixup.test.ts +++ b/test/premerge-fixup.test.ts @@ -6,6 +6,8 @@ import type { DatabaseSync } from "node:sqlite"; import { connect } from "../src/db.ts"; import { setPushApproval } from "../src/fixup/approval.ts"; import { attemptsOf, classifyFixups, selectFixups } from "../src/fixup/candidates.ts"; +import { holdMerge } from "../src/merge/controls.ts"; +import { mergeDecisionId } from "../src/merge/queue.ts"; import { savePremerge, type PremergeFinding } from "../src/premerge/store.ts"; import { SCRATCH } from "./scratch.ts"; @@ -23,6 +25,11 @@ function take(headRepo = "storytold/app", findings: PremergeFinding[] = [defect( db.prepare(`INSERT INTO pr_checks (repo, number, head_oid, state, is_draft, overall, checks, mergeable, maintainer_can_modify, fetched_at) VALUES ('app', 7, 'h1', 'OPEN', 0, 'success', '[]', 'MERGEABLE', 0, '${T1}')`).run(); db.prepare("INSERT INTO tracked_repos (name, added_by, added_at, pipeline) VALUES ('app', 'op', ?, 1)").run(T0); + // What the merge queue needs to treat the PR as one the rule would merge. + db.prepare(`INSERT INTO classifications (repo, number, classifier, run_id, at, type_label, flags, probs) VALUES ('app', 7, 'jev', 'r1', '${T0}', 'bugfix', '[]', '{"top":0.95}')`).run(); + db.prepare(`INSERT INTO verifications (repo, number, head_sha, kind, reason, state, created_at) VALUES ('app', 7, 'h1', 'tests', 'r', 'passed', '${T0}')`).run(); + db.prepare("INSERT INTO whitelist_overrides (login, status, by, at) VALUES ('someone', 'allow', 'op', ?)").run(T0); + db.prepare("INSERT INTO main.settings (key, value) VALUES ('merge_approved:app', ?)").run(JSON.stringify({ by: "op", at: T0 })); setPushApproval(db, "op", "app", true); savePremerge(db, { repo: "app", number: 7, head: "h1", at: T1, model: "opus", findings }); return db; @@ -40,6 +47,27 @@ describe("pre-merge fix-up round", () => { assert.deepEqual(sel[0]!.fixes.map((f) => f.file), ["src/a.rs", "src/b.rs"]); }); + test("the queue decides: a merge hold, an open Merge? question or a Hold answer leaves no pre-merge round", () => { + assert.equal(selectFixups(take(), "app").fix.length, 1); + const held = take(); + holdMerge(held, "op", "app", 7); + assert.equal(selectFixups(held, "app").fix.length, 0); + const asked = take(); + const id = mergeDecisionId("app", 7, "h1"); + const ins = `INSERT INTO decisions (id, kind, repo, number, question, options, asked_at, answer, answered_by, answered_at) VALUES (?, 'merge', 'app', 7, 'Merge?', '[]', '${T1}', ?, ?, ?)`; + asked.prepare(ins).run(id, null, null, null); + assert.equal(selectFixups(asked, "app").fix.length, 0); + const declined = take(); + declined.prepare(ins).run(id, "hold", "op", "2099-01-01T00:00:00Z"); + assert.equal(selectFixups(declined, "app").fix.length, 0); + }); + + test("a stale review sends no pre-merge round", () => { + const db = take(); + db.prepare("INSERT INTO comments (id, repo, number, kind, author, author_association, body, created_at, counted) VALUES ('c1', 'app', 7, 'comment', 'rabbit', 'CONTRIBUTOR', 'new finding', '2026-03-01T00:00:00Z', 1)").run(); + assert.equal(selectFixups(db, "app").fix.length, 0); + }); + test("a defect without a fix, or only minor findings, is not selected", () => { const noFix = { ...defect("src/b.rs"), fix: undefined }; assert.equal(classifyFixups(take("storytold/app", [defect("src/a.rs"), noFix]), "app").length, 0); @@ -75,10 +103,10 @@ describe("pre-merge fix-up round", () => { assert.equal(x!.c.attempt, 1); }); - test("an unpushable branch is never asked and never recorded as held", () => { + test("an unpushable branch is never asked, held or selected: the queue asks a person", () => { const db = take("someone/app"); const sel = selectFixups(db, "app"); assert.equal(sel.fix.length + sel.ask.length + sel.cannotPush.length, 0); - assert.equal(classifyFixups(db, "app")[0]!.bucket, "cannot-push"); + assert.equal(classifyFixups(db, "app").length, 0); }); }); diff --git a/test/premerge-queue.test.ts b/test/premerge-queue.test.ts index 3e2c5e05..33a5d96e 100644 --- a/test/premerge-queue.test.ts +++ b/test/premerge-queue.test.ts @@ -66,8 +66,32 @@ test("a defect without a fix is asked about with its facts and no merge recommen const q = db.prepare("SELECT * FROM decisions WHERE id = ?").get(mergeDecisionId("app", 1, HEAD)) as Record; assert.equal(q.recommended, null, "no merge recommendation"); db.prepare("UPDATE decisions SET answer = 'merge', answered_by = 'op', answered_at = '2099-01-01T00:00:00Z' WHERE id = ?").run(mergeDecisionId("app", 1, HEAD)); - assert.equal(entry(db).state, "ready"); - assert.equal(entry(db).path, "rule"); + assert.equal(entry(db).state, "decision-answered-merge"); + assert.equal(entry(db).path, "operator", "the operator's checks apply to a merge past a defect"); + assert.equal(eligible(entry(db)), true); +}); + +test("a Hold answer on a pre-merge question stays when push approval arrives later", () => { + const db = world(); + store(db, [defect({ fix })]); + assert.equal(entry(db).state, "needs-decision"); + askedQuestion(db); + db.prepare("UPDATE decisions SET answer = 'hold', answered_by = 'op', answered_at = '2099-01-01T00:00:00Z' WHERE id = ?").run(mergeDecisionId("app", 1, HEAD)); + assert.equal(entry(db).state, "declined"); + setPushApproval(db, "op", "app", true); + const e = entry(db); + assert.equal(e.state, "declined"); + assert.equal(e.premerge?.state, "defect"); +}); + +test("a batch member in waiting-ci without a clean pre-merge review keeps its own state", () => { + const db = world(); + db.prepare("UPDATE pr_checks SET overall = 'pending' WHERE repo = 'app' AND number = 1").run(); + db.prepare("INSERT INTO merge_batches (id, repo, branch, state, base_sha, commit_sha, pr_number, created_at, updated_at) VALUES (1, 'app', 'integration-app-1', 'open', 'a', 'b', 5, ?, ?)").run(T1, T1); + db.prepare("INSERT INTO merge_batch_prs (batch_id, number, head_oid, position) VALUES (1, 1, ?, 0)").run(HEAD); + assert.equal(entry(db).state, "waiting-ci"); + seedPremergeClean(db, "app", 1, HEAD); + assert.equal(entry(db).state, "in-batch"); }); test("three failed tries make the head failed and ask a person", () => { @@ -77,5 +101,5 @@ test("three failed tries make the head failed and ask a person", () => { fail(db, 1); assert.equal(entry(db).state, "needs-decision"); assert.deepEqual(entry(db).outsideRule, ["the pre-merge review failed"]); - assert.ok(askedQuestion(db).includes("pre-merge review failed: retry: the model timed out")); + assert.ok(askedQuestion(db).includes("pre-merge review failed: the model timed out")); }); diff --git a/test/premerge-review.test.ts b/test/premerge-review.test.ts index 1687c952..1fffdeae 100644 --- a/test/premerge-review.test.ts +++ b/test/premerge-review.test.ts @@ -6,8 +6,10 @@ import { setRunner } from "../src/classify/run.ts"; import { buildQueue } from "../src/merge/queue.ts"; import { parseArgs } from "../src/premerge/index.ts"; import { lintPremerge, parsePremerge } from "../src/premerge/parse.ts"; -import { premergeCandidates, runPremerge, type PremergeDeps } from "../src/premerge/review.ts"; +import { candidateOf, premergeCandidates, runPremerge, type PremergeDeps } from "../src/premerge/review.ts"; import { findingsOf, PREMERGE_MAX_TRIES, premergeAt, savePremerge } from "../src/premerge/store.ts"; +import { prepareOpusInput } from "../src/review/opus.ts"; +import { mergeApprovalOf } from "../src/merge/approval.ts"; import { OPUS_MAX_FIXES } from "../src/review/opus-parse.ts"; import { useTestAccount } from "./accounts-fixture.ts"; import { fresh as freshDb } from "./batch-fixture.ts"; @@ -91,6 +93,43 @@ describe("premerge step", () => { assert.equal(state(db), "ready"); }); + test("the review input carries no discussion, earlier review or unapplied fixes, though the PR has them", async () => { + const db = world(); + const e = buildQueue(db, { merged: "exclude" }).find((x) => x.number === 1)!; + db.prepare("INSERT INTO comments (id, repo, number, kind, author, author_association, body, created_at, counted) VALUES ('c1', 'app', 1, 'comment', 'rabbit', 'CONTRIBUTOR', 'please rename this', '2026-02-01T00:00:00Z', 1)").run(); + db.prepare(`INSERT INTO opus_reviews (repo, number, head_oid, run_id, at, model, verdict, reason, fixes, sure, mode) VALUES ('app', 1, 'old', 'rv0', '2026-01-01T00:00:00Z', 'm', 'take-fix', 'needs work', ?, 1, 'full')`) + .run(JSON.stringify([{ file: "src/lib.rs", change: "rename a" }])); + const quiet = () => {}; + const normal = await prepareOpusInput(db, "app", candidateOf(db, e), { ...deps, fetchDelta: async () => ({ ok: false, tooLarge: false, error: "unused" }) }, quiet); + assert.equal(normal.kind, "ready"); + if (normal.kind === "ready") assert.ok(normal.input.discussion?.length && normal.input.unapplied_fixes?.length, "the fixture has discussion and unapplied fixes"); + const p = await prepareOpusInput(db, "app", candidateOf(db, e), { ...deps, fetchDelta: async () => ({ ok: false, tooLarge: false, error: "unused" }) }, quiet, { independent: true }); + assert.equal(p.kind, "ready"); + if (p.kind !== "ready") return; + assert.equal(p.input.discussion, undefined); + assert.equal(p.input.earlier_opus, null); + assert.equal(p.input.unapplied_fixes, undefined); + assert.equal(p.input.mode, "full"); + }); + + test("a repo without merge approval gets no pre-merge candidates", () => { + const db = world(); + assert.equal(premergeCandidates(db, "app").length, 1); + db.prepare("DELETE FROM main.settings WHERE key = 'merge_approved:app'").run(); + assert.equal(mergeApprovalOf(db, "app"), null); + assert.deepEqual(premergeCandidates(db, "app"), []); + }); + + test("a diff too large to review fails the head at once, without retries", async () => { + const db = world(); + const restore = model([], reply([])); + try { await runPremerge(db, { repo: "app" }, () => {}, { ...deps, maxChars: 10 }); } finally { restore(); } + const row = premergeAt(db, "app", 1, "sha1")!; + assert.equal(row.tries, PREMERGE_MAX_TRIES); + assert.match(row.error ?? "", /too large/); + assert.equal(state(db), "needs-decision"); + }); + test("a head that moved during the call is not saved", async () => { const db = world(); const calls: string[] = [];