PR Merge Queue (part 2)
The deeper half of the PR Merge Queue page: what the feature persists, the in-flight guard that stops a PR being merged twice, custom and per-repo merge instructions, editing the merge prompt, the pure-logic triage modules, the IPC channels and the auto-merge daemon; the optional AI summary on each PR is part 3.
On this page
What it is
This is part 2 of the PR Merge Queue page. That page covers what the queue is, where to find it, and the day-to-day path — reading the lanes, starting a merge, archiving a PR, batching several. This half carries the machinery behind it: what the feature persists, the guards and instructions that shape a merge prompt, the modules triage runs in, and the auto-merge daemon.
Where to find it
Everything here is reached from the same two places as the main page — the Settings → PR Merge Queue form, which holds the stored config, the standing instructions and the editable prompts, and the queue view itself, whose Merge and Merge batch together buttons the sections below describe.
How it behaves
What gets persisted
AppSettings.prMergeQueueRepos: PrMergeQueueRepoConfig[]— the repo configs. Lives inconfig.json, encrypted via OS keyring only if individual fields are sensitive (no secrets in the config shape itself —ghauth lives in the system'sghconfig). Each config now carries an optionalstandingInstructions: string(the per-repo standing merge guidance, capped at 4000 chars) plus optional per-repo prompt overridesmergePromptTemplate/batchPromptTemplate(capped 20,000 chars each — see Editing the merge prompt).AppSettings.prMergeQueueMergePromptTemplate/prMergeQueueBatchPromptTemplate— the global editable merge / batch prompt overrides (capped 20,000 chars each). Unset = use the built-in default. See Editing the merge prompt.AppSettings.prMergeQueueArchivedPrs: Record<projectId, prNumber[]>— the PRs you've archived (personally dismissed), keyed per repo. Lives inconfig.json. Archived PRs are hidden from the lanes and excluded from both the InboxreviewNeededCountandstuckCount(the 2026-06-02archive-clears-both-inbox-countsreversal — archiving now clears a PR everywhere, stuck merges included). Zod-capped at 500 PRs per repo (and 100 repos in the map). See Archiving (dismissing) a PR.- Per-merge: a regular Omniscio session row with
source: 'pr-merge-queue'(single PR) orsource: 'pr-merge-queue-batch'(batch). Worktree path, name (Merge PR #N: <title>orMerge batch: #a #b …), and the standard session lifecycle. Daemon-spawned merges usesource: 'pr-merge-queue-auto'. - Per-repo snapshot cache: one row per configured repo in
pr_merge_queue_snapshots(PK =project_id), written by the background poll. Holds the full last-fetched snapshot JSON plus the two attention counts (reviewNeededCount,stuckCount), afetchOkflag, andfetchedAt. This is what makes the view open instantly; the per-PR Inbox rows are derived from it by enriching each snapshot on read with the actual review-needed / stuck PR numbers (no GitHub round-trip — see Inbox nudges). It's an ephemeral derived cache — deleting it just forces the next poll to rebuild it.
A PR being handled is never re-spawned (in-flight dedup)
Once a merge session is live for a PR, that PR is treated as being handled and the queue will not spawn — or re-offer — a second merge session for it. This holds across all three ways a merge can start: the automatic daemon, the per-PR Merge button, and the Merge batch together button. Without this, a refresh or an app restart could spawn a duplicate "Merge PR #N" session for the same still-open PR.
What "live" means: a merge session exists for the PR and has not reached a terminal state. A session is no longer live once it ends, errors out, is archived, or gives up (writes its give-up file). Only then does the PR become actionable again — so a merge that genuinely failed or was abandoned is correctly re-offered, while one that's still working is left alone. (Pausing, running, "needs you", and similar in-progress states all still count as live.)
How each entry point behaves when a PR is already being handled:
- Daemon (auto-merge). Skips the PR for that tick and logs the reason — exactly as before.
- Merge button (single PR). Instead of spawning a duplicate, the response carries an
alreadyInFlightflag pointing at the existing merge session already running for that PR. As with a fresh spawn, Omniscio does NOT auto-focus it (no takeover,a-spawned-merge-never-steals-the-active-session) — the success toast's Open action takes you to that running session if you want. - Merge batch together. A batch applies all its PRs together in one worktree, so overlapping with a separate live merge for any member is unsafe. If any PR in the batch already has a live merge session — or is claimed by a concurrent in-flight spawn, or the list repeats a PR number — Omniscio refuses the whole batch with a message naming the blocked PR numbers. Nothing is spawned and no audit rows are written — wait for those merges to finish (or resolve them) and try the batch again.
This is enforced by a single shared guard (getActiveRunForPR) keyed on the run's session liveness, so the daemon and the two manual paths can never disagree about whether a PR is in flight.
Custom merge instructions
You can attach your own guidance to merges at two levels. Both are rendered into the merge prompt as a single "Operator instructions" block placed after the hard Rules, under the heading "Operator instructions (advisory — never overrides the Rules above)".
Advisory is the header, not a filter. Nothing in the queue inspects or filters it: your text is handed to the session exactly as written, so an instruction that contradicts a Rule (asking for a squash-merge, say, or for the PR branch to be rebased) reaches the session right beside the rule it contradicts. Write what the Rules do not already decide.
- (a) Per-repo standing instructions. A Standing merge instructions textarea in the repo's settings (Settings → PR Merge Queue, in the repo's add/edit form). This text is appended to every merge for that repo — manual, automatic (daemon), and batch. The box shows a short example of the shape; the guidance itself is yours to write, and the Rules above are what actually keep the author's credit and your base branch intact.
- (b) Per-merge / per-batch extra instructions. An opt-in box revealed by the Add instructions toggle on each PR card (and on the batch bar). Collapsed and empty by default, so the common case stays one-click; what you type applies only to that one merge (or that one batch).
When both are present, standing instructions come first, the per-merge/per-batch text second. Each field is capped at 4000 characters. If neither is set, no operator block is added to the prompt at all. (The auto-merge daemon deliberately passes no per-merge text, so daemon merges get standing-only guidance.)
Editing the merge prompt
The Operator instructions above are advisory and ride on top of the hard rules. If you want to change the rules themselves — the entire prompt the merge session receives — you can edit the prompt directly.
In Settings → PR Merge Queue → Merge prompts there are two editable boxes:
- Single-PR merge prompt — sent on every Merge click.
- Batch merge prompt — sent when you use Merge batch together.
Each box is pre-filled with the built-in default text. Edit it freely and it saves when you click away; a Reset to default button restores the built-in version (the one that prepares the worktree and never touches your base branch). PR-specific details are injected wherever a {{placeholder}} appears — the legend under each box lists them ({{pr_number}}, {{pr_title}}, {{base_branch}}, {{worktree_path}}, plus {{pr_list}} / {{pr_count}} for batches, etc.). A {{token}} you delete simply doesn't get filled; an unknown token is left as-is so you can spot a typo. PR data is substituted in a single pass, so a {{token}}-looking string inside a PR title can't itself be re-substituted.
Per-repo override. Each repo's add/edit form has an Override the merge prompt for this repo (advanced) disclosure with its own single-PR and batch boxes. A non-blank override wins over the global prompt for that repo; leave it blank to inherit the global one. Resolution at merge time is per-repo override → global custom → built-in default.
Two cautions.
- The boxes edit the whole prompt, including the safety rules. The built-in default is the version that never advances or pushes your base branch (
master); if you delete those rules, nothing else stops a merge session from doing so. A small "custom prompt in use" warning shows whenever an override is active. - A few pieces are required and cannot be edited away: the immutable-head check, the never-touch-the-base and never-push rules, and — since 2026-09-23 — the bounded merge and the merge-scope check that go with them. If your saved prompt is missing any of them, the box flags it in red and names exactly what is missing, and Omniscio quietly keeps using the built-in default instead of your text until you put the lines back. A prompt customised before this date that predates the two merge lines therefore needs one re-save; the warning above the box tells you when.
- A saved custom prompt is a frozen copy — if a future Omniscio update improves the built-in default (e.g. a new safety rule), your custom text will not pick it up automatically. Reset to default re-syncs you to the current built-in.
- The built-in default also tells the session to end with a plain-language "What this PR does" summary (plus an "anything to watch out for" line) for a non-technical reader, above the technical details (contract
the-default-prompts-demand-a-plain-language-report). If you rewrite the prompt and want that plain-English write-up, keep that section.
Stored as AppSettings.prMergeQueueMergePromptTemplate / prMergeQueueBatchPromptTemplate (global) and PrMergeQueueRepoConfig.mergePromptTemplate / batchPromptTemplate (per-repo), each capped at 20,000 characters — the textarea itself stops at the cap, so an over-long paste is trimmed as you paste instead of being refused on save with a generic "Could not save that setting". Both numbers live in one place, PR_MERGE_PROMPT_TEMPLATE_MAX_LENGTH / PR_MERGE_STANDING_INSTRUCTIONS_MAX_LENGTH in src/shared/types/pr-merge-queue.ts, read by both the input bound and the Zod rule so the two cannot drift. The default text + placeholder legend live in src/shared/pr-merge-queue-prompt-templates.ts; token substitution + compose in src/main/services/pr-merge-queue/prompt.ts.
How it works
The implementation is split between four pure-logic modules (testable in pure Node) and an I/O boundary:
triage.ts—profilePR(repo, summary, { log, fetchFullPR })enriches a PR list summary with size / risk / CI status / overlapping-PR detection, anddetectOverlaps()/detectDependencies()run a second pass to wireoverlapsWith[]anddependsOn[]between PRs in the snapshot.orchestration.ts—planLanes(profiles, repo, { log })runs the 8-lane decision tree, andpackBatch()/nextExecutableGroup()group the non-overlapping batch members (they back the Merge batch together button). It also owns the fast-lane size thresholds.minimatch-lite.ts— a tiny glob matcher forriskyPaths, so the app avoids pulling inminimatchfor one code path.prompt.ts—composeMergePrompt({ pr, lane, baseBranch, worktreePath, extraInstructions, ... })builds the single-PR merge instructions andcomposeBatchMergePrompt({ prs, ... })the batch ones (PRs in apply order, "test once" rules). Both pure, both rendering the operator-instructions block from a byte-identical shared header. What Claude sees is what these return.spawn-merge-session.ts—spawnMergeSession()andspawnBatchMergeSession(), the single source that readsrepo.standingInstructionsand concats standing-first + per-merge/per-batch-second into the operator block (D8). Omniscio runs no git — it names the worktree viacomputeWorktreeTarget(pure) and records it withsetSessionWorktree, and the spawned agent builds it (prompt RULE 1).auto-merge-daemon.ts— despite the name, the queue-poll daemon: each tick refreshes + persists every repo's snapshot (always, when the feature is on) and then runs the gated auto-merge step for autonomous repos. See Background auto-refresh and Auto-Merge Daemon.attention-summary.ts— the single source for "what counts as needing a human":countReviewNeeded(snapshot, archived?)andrecomputeAndPersistFromCache(repo, archived), which re-derives a repo's counts from the saved snapshot and pushes on change with no GitHub fetch — what makes archiving quiet the Inbox instantly.- I/O boundary:
gh-cli.tswrapsgh pr list/gh pr viewwith timeouts;queue-service.tsis the top-level orchestrator (refreshQueue(cfg),fetchOnePR(slug, n));queries-pr-merge-queue-snapshots.tsowns the snapshot-cache reads/writes;pr-merge-queue-handlers.tsis the IPC handlers (LIST_REPOS/REFRESH/MERGE_PR/MERGE_BATCH/DETECT_REPO_INFO/LIST_SNAPSHOTS).
The decision tree in orchestration.ts (assignLane), in the order it is checked. The first match wins:
- hold — the PR depends on another PR that is still open in the snapshot.
- reject — its own CI is failing.
- risky — a draft, a file list that came back incomplete, or a risk score at or above the bar.
- conflict-likely — it overlaps another open PR.
- hold — its CI is still pending, or its status is unknown.
- fast — fast-lane sized; a repo whose trust level is
pause-and-askescalates it instead. - standard — within the standard size;
pause-and-askandfast-lane-onlyescalate it instead. - escalate — everything else.
The merge spawn is the interesting one, and its whole point is what it does not do. spawnMergeSession():
- Creates the session with
isolationOverride: falseand noinitialPrompt— deliberately WITHOUT Omniscio worktree isolation, so it spawns idle and Omniscio never runs the checkout. - Names (does not build) the worktree via
computeWorktreeTarget(...)and records it withsetSessionWorktree(...). Pure — no git, no fs. - Attaches the give-up monitor before sending the prompt (it polls, so attaching before the directory exists is fine) — an immediate give-up is never missed.
- Concats the operator block standing-first / per-merge-second (D8), composes the prompt, and sends it via
sessionService.sendResponse({ sessionId, text: prompt }).
The spawned agent then builds the worktree itself and checks out the PR branch, per prompt RULE 1. Omniscio runs no git for the merge at all — no git fetch, no git switch, no git worktree add. Pre-2026-06-02 it did build the worktree in-process; that ~17k-file checkout timed out under load and made merges fail to even start (contract the-agent-builds-its-own-worktree). Do not "restore" it.
Pure-logic injection: the three pure modules don't import electron-log directly — they take an injected MqLogger via a parameter. queue-service.ts wires the real electron-log instance in. This lets the unit tests run in pure Node without Electron's main process in scope.
IPC channels
PR_MERGE_QUEUE_LIST_REPOS— readAppSettings.prMergeQueueRepos. Returns{ repos: PrMergeQueueRepoConfig[] }.PR_MERGE_QUEUE_REFRESH({ projectId })— fetch a snapshot for one repo. ReturnsPrMergeQueueSnapshotDTOwithprofiles[]+decisions[]+partialFetches[](PR numbers whose enrichment fetch failed). A refresh already running for that repo is joined, not started again: a double-click or a retry costs oneghfan-out, and the view's "N of M enriched" counter cannot move backwards. The join covers IPC callers only — the daemon tick and the CLI runs route callrefreshQueuedirectly, so a manual refresh landing inside a tick is still a second fetch.PR_MERGE_QUEUE_MERGE_PR({ projectId, prNumber, extraInstructions? })— spawn the single-PR merge session.extraInstructions(optional, ≤4000 chars) is the per-merge guidance from the card's Add instructions box. Returns{ sessionId, alreadyInFlight? }: when a merge session for this PR is already live, no second one is spawned and the existingsessionIdcomes back withalreadyInFlight: true. The renderer never auto-focuses a spawn; the success toast's Open action takes you there.PR_MERGE_QUEUE_MERGE_BATCH({ projectId, prNumbers, extraInstructions? })— spawn ONE session that merges a related group together.prNumbersrequires ≥2 (a 1-PR batch is justMERGE_PR) and is capped at 100;extraInstructions(optional, ≤4000) is the per-batch guidance. Returns{ sessionId }. The call is refused ({ success: false, error: 'Cannot batch-merge: PR(s) #12, #15 already have a running or starting merge session. Wait for them to finish or resolve them first.' }) without spawning when any member already has a live merge session, is claimed by another in-flight spawn, or the list names a duplicate PR number.
Both merge channels write their pr_merge_queue_runs row BEFORE the billable spawn, exactly as the daemon does: MERGE_PR inserts one outcome: 'spawning' marker and MERGE_BATCH inserts one per member in a single transaction, then each promotes that same row (or set) to spawned once the session id is known. Only a spawn that throws closes them as failed. That ordering is what keeps a live merge session visible to the in-flight guard, the stuck count and the daily budget across a crash or a rejected bookkeeping write.
PR_MERGE_QUEUE_DETECT_REPO_INFO({ projectId })— local-git inspection of an Omniscio project's folder, returning{ ghSlug, defaultBranch, projectName }with any field nullable. Fired by the Settings form when you pick a project in create mode, and never throws:projectNameis the project's display name whenever the project exists, while only an unknown project id nulls all three fields, andghSlug/defaultBranchstaynullfor a non-GitHub remote, a missing folder, or a git failure. Pure git, noghauth needed.PR_MERGE_QUEUE_LIST_SNAPSHOTS— takes an optionalprojectIdand returns that repo's last-persisted cached row, or every configured repo's when it is omitted: the full last-fetchedsnapshotJsonplus the on-readreviewNeededPrNumbers/stuckPrNumberslists the Inbox renders one row per PR from (no GitHub fetch). Hydrates the view's freshness/count state on open. The open view reads it on EVERY project change, even when the Inbox store already holds a row for that repo: the store is a cache fed only by pushes, and the daemon pushes only when the counts or the pull requests move, so a refresh that changes nothing but the fetch stamp writes this row and pushes nothing. The store's copy paints the first frame, then this read corrects it — and a row is never allowed to replace a newer snapshot already on screen (:156-165 ofuse-pr-merge-queue-data.ts).PR_MERGE_QUEUE_CHANGED— push event signalling the repo set / config changed.PR_MERGE_QUEUE_GIVE_UP— push event emitted when a merge session gives up.PR_MERGE_QUEUE_SNAPSHOT_UPDATED— push event emitted by the background poll (and by a manual Refresh) whenever the PULL REQUESTS in a repo's snapshot change, or its attention summary moves. Payload:{ projectId, reviewNeededCount, stuckCount, fetchOk, fetchedAt }. The persisted snapshot IS the payload the view and the inbox load, so gating it on the three counts alone left an open view rendering the previous tick's cards whenever the queue's composition changed without moving a total (one PR merged out of review-needed while another entered). The comparison ignores the fetch stamp, so a poll that re-read the same PRs — every one of them carries a freshfetchedAtand rewrites the row — wakes nobody.PR_MERGE_QUEUE_REFRESH_PROGRESS— push event streamed during a manual Refresh:{ projectId, enriched, total, prNumber }per enriched PR, surfaced as the "Refreshing… (enriched/total)" count on the button.PR_MERGE_QUEUE_AUTO_MERGE_FIRED— push event emitted by the auto-merge daemon every time it spawns a merge session (also fired in dry-run mode). Payload (strict):{ ghSlug, prNumber, lane, dryRun: boolean, sessionId?: string }— noreasonfield, andlaneis'fast'for the single-PR path and'batch'when the auto-batch path spawned the session, so a consumer must handle both.
CLI routes
Eight routes on the local CLI control server (127.0.0.1:19519), from src/main/services/cli/cli-server-pr-merge-queue-routes.ts. Seven answer 403 { ok: false, disabled: true } while prMergeQueueEnabled is off — on the four GETs that check runs before auth, on the three writes auth runs first. The eighth, PATCH /pr-merge-queue/arming, is deliberately not behind that gate: it is the switch itself.
GET /pr-merge-queue/snapshots— every configured repo's persisted snapshot, enriched on read with the per-PR attention lists. Pure read.GET /pr-merge-queue/runs— the daemon's decision log; see below.GET /pr-merge-queue/repos— the configured repos.GET /pr-merge-queue/detect-repo-info— a project's ghSlug + default branch, read from its LOCAL git remote.POST /pr-merge-queue/refresh— re-fetch ONE repo and return the fresh snapshot. It persists the result through the background poll's own writer, so the inbox counts and the in-app view move with the fetch. One refresh per repo runs at a time (a second concurrent call is a409), and it is on the per-source heavy-op budget (3/min) on top of the10/minmutation bucket.POST /pr-merge-queue/archive— archive (dismiss) ONE PR.DELETE /pr-merge-queue/archive/:projectId/:prNumber— un-archive ONE PR.PATCH /pr-merge-queue/arming— switch the whole feature on or off ({ enabled }). This is the only headless write ontoprMergeQueueEnabled, soPATCH /settings/:keyrefuses it, and it requires the machine's own full-trust CLI token (never a per-session agent token) plus a source session, answering with the state actually applied.
GET /pr-merge-queue/runs is the ONLY reader of the pr_merge_queue_runs table — no IPC channel exposes it and no UI renders it, so it is the only answer to what has the daemon attempted lately?. ?sinceHours= defaults to 24 (max 720), ?limit= to 200 (max 1000), and ?ghSlug= (?repo= is the older alias) narrows to one ghSlug in SQL; a value that is not an owner/name slug is a 400. The response carries hasMore, which is true when the row cap cut the window short — page further back with a wider ?sinceHours= rather than reading a capped tail as the whole log. Each row carries the outcome — spawning / spawned / dry-run / skipped-budget / skipped-conflict / failed — which is how a skipped PR is explained when the UI says nothing. Run rows carry no money field at all — a per-run cost would read as a confident $0; getDailySpendForRepo is the authoritative spend read.
MERGE_PR / MERGE_BATCH are deliberately absent — they spawn a billable merge session, so they stay off this surface.
Auto-Merge Daemon
⚠️ Behavior note (2026-05-30 master-safety change). Spawned merge sessions now prepare a worktree and stop — they never advance, merge into, or push the base branch (see What it is). The daemon still spawns a session for fast-lane PRs (one per PR by default, or one per group when auto-batch is on), but that session no longer completes the merge, so the PR stays open and a later tick can spawn for it again. Recommendation: keep the Auto-Merge Daemon OFF (its default) until it is reworked into a prepare-and-notify flow — auto-spawning sessions that can't close their own PR just burns budget. The background auto-refresh + Inbox layer is independent of this and remains useful on its own.
This is the same periodic task as the Background auto-refresh poll — each tick refreshes + persists every repo's snapshot, then runs the gated auto-merge step below only for autonomous repos with the master flag on, reusing the snapshot the refresh step already fetched. The auto-merge gate chain is byte-for-byte the prior daemon's logic; the refresh/persist/Inbox layer is what's new around it.
Gate chain per repo per tick (failing any gate logs the reason and moves on — never throws):
Master flag check —
AppSettings.prMergeQueueAutoMergeEnabledmust betrue. The flag default isfalse.Trust check — repo's
trustLevelmust be'autonomous'. The two other levels ('pause-and-ask','fast-lane-only') never trigger an auto-spawn even though'fast-lane-only'sounds related — that level is reserved for a future per-card "click to merge fast lane only" UX.Snapshot — reuses the snapshot the tick's refresh step already fetched (the same
refreshQueue(toRepoQueueConfig(repo))the view calls) rather than re-fetching, so the always-on poll and the auto-merge step share oneghround-trip per tick.Eligibility pick — a PR is auto-mergeable when its decision is in the
fastorbatchlane, this machine's shard owns it, and the snapshot's own profile for it reads fast-lane sized andmergeStateStatus === 'CLEAN'.isAutoMergeEligible(decision, profile, shard)inauto-select.tsis the ONE predicate;selectAutoMergeTargetapplies it to the single pick and to the auto-batch members alike, so the lane label no longer decides eligibility on its own.- Why
batchcounts at all (F034).batchis a promotion offast+standardPRs (see the lane tree on the hub). Before F034 the only eligibility test waslane === 'fast', so a repo with two or more clean small PRs had every one relabelledbatch, nofastdecision was left, and auto-merge silently never fired while the liveness heartbeat stayed fresh. The predicate now reads both labels, which describe one PR population. - The promotion does not widen the safety margin. A batch member qualifies only when its own profile is fast-lane sized under the same
isFastLaneSizedthresholdsassignLaneuses to choosefast(one definition, two readers), so only fast-sized PRs are auto-mergeable and astandardPR stays click-to-merge however it got labelled. CLEANis required (F073/RT-F017). The single-PR pre-flight also demandsCLEAN, and this predicate keeps a non-CLEANPR from becoming the first pick and being re-rejected every tick — oneBEHINDPR used to starve everyfastPR behind it.BEHIND/BLOCKED/UNSTABLE/UNKNOWNtherefore cannot be auto-merged.- The LANE is deliberately not gated on the merge state (F073). Triage keeps such a PR in
fast/standard, because a spawned merge session cherry-picks it onto the base locally and stops without pushing, so GitHub's "is this branch mergeable right now" does not stop it — and the card shows mergeability separately. Routing those PRs toholdwould empty thebatchlane (taking the manual Merge batch together bar with it) and count every one of them as review-needed. The merge state decides what may auto-merge; it never decides what a human may prepare. - A decision whose profile is missing can only come from a hand-built snapshot, and is judged on its
fastlane label alone, with the pre-flight below the authority. Abatchlabel is never trusted on its own.
4a. Target selection — sharding + auto-batch. Both shipped 2026-08-16 and both default to
false, so with default settings this step is a pass-through and steps 5–8 read exactly as written. With either on,selectAutoMergeTarget({ decisions, profiles, shard, autoBatch, isInFlight })runs BEFORE the per-PR gates below and changes what "the target" even is:- Sharding splits the queue across machines: this box only auto-spawns for PRs whose number modulo the shard count equals its shard index. An eligible PR another shard owns is a benign no-op (
notThisShard), not a failure, so an idle minority shard never trips the stall alert. Mechanism + settings: settings-reference.md. - Auto-batch combines several eligible (fast-lane-sized, clean, non-overlapping, this-shard, not-in-flight) PRs into ONE merge session that applies them together and runs the gate ONCE — up to
prMergeQueueAutoBatchMaxSize(default 8). It returnsselected.kind === 'batch'and takes thespawnAutoBatchpath: claims all, budget-checks once, spawns one session, records N audit rows. So with auto-batch on, step 8's singlespawnMergeSessionis not what runs. Every member carries a profile by construction (packing needs one), so a member that is notCLEANor is not fast-lane sized can never join a batch — and because this path has no per-PR pre-flight (it merges from the poll's snapshot), that snapshot-time reading is the whole gate it gets.
Manual merges (
MERGE_PR/MERGE_BATCH) are never sharded or auto-batched.- Why
Active-run check —
getActiveRunForPR(slug, prNumber)queriespr_merge_queue_runsfor an in-flight row, which is either (a) aspawnedrow not yet completed whose session is still live (a real session row that isn't deleted and isn'tended/error/archived), or (b) an openspawningwrite-ahead marker (see step 8) that is inside its 15-minute grace window measured from its last lease heartbeat — the marker's lease is renewed for as long as the spawn is actually running, so a slow spawn (a cold cloud bring-up, a hunggh pr view) never expires its own claim, and a marker whose process died stops renewing and frees the PR one window later. Itssession_idis stillNULLbecause the spawn has not returned yet. Skips if found. This same guard is shared by the manual Merge and Batch buttons — see A PR being handled is never re-spawned below.Budget check —
getDailySpendForRepo(slug, startOfDayUtcIso())sums the spend of the DISTINCT sessions the daemon spawned for this repo since the start of the UTC day, reading each session's owncost_micro_usd(whatupdateSessionCostmeters a merge turn onto), scoped totriggered_by = 'auto'so a manualMERGE_PRspawn doesn't eat the daemon's budget. Skips ifdailySpend >= dailyBudgetUsd.This gate used to be INERT. The original query joined
pr_merge_queue_runstoapi_cost_logfilteringsource = 'pr-merge-queue-auto'— a label nothing ever writes, because a merge session's spend is metered onto thesessionsrow. The JOIN matched zero rows and the advertised daily autonomous-spend ceiling did not exist. Two things worth carrying: merge spend is not inapi_cost_log, and the sum is over DISTINCT SESSIONS on purpose, because an auto-batch spawns ONE session but writes N run rows, which a per-run sum would count N times.Pre-flight
gh pr viewre-fetch — guards against staleness. Ifstate !== 'OPEN'(closed/merged since refresh), orisDraftflipped on, ormergeStateStatusis anything other than'CLEAN', skip."Anything other than CLEAN" is wider than the four states this page used to list (
DIRTY/BLOCKED/BEHIND/UNKNOWN): the code also skipsHAS_HOOKSandUNSTABLE. A state we have not reasoned about should not auto-merge, but GitHub documentsHAS_HOOKSas a MERGEABLE state, so a repo with pre-receive hooks never auto-merges anything — the operator sees a permanently idle daemon and askipped-conflictaudit row with no hint why. If that is you, the fix is not to widen this gate blindly: decide deliberately whether a hook-gated repo should auto-merge at all.Spawn (or dry-run log) —
dryRun: trueemits the push event withdryRun: true, logs, returns. Otherwise the spawn is write-ahead: it first inserts apr_merge_queue_runsrow withoutcome: 'spawning'(a real spawn is in progress —session_idstillNULL), THEN callsspawnMergeSession({ repo, prNumber, lane, laneReasons, triggeredBy: 'auto' }), then promotes that same row tooutcome: 'spawned'with the realsession_id— one audit row per decision whether the spawn succeeds or throws (a throw closes the same row asfailed). Finally it emitsPR_MERGE_QUEUE_AUTO_MERGE_FIREDand callstrackEvent('pr_merge_queue_auto', 'fired', { ghSlug, lane }). Thespawningmarker exists so a crash between the insert and the spawn cannot leave a live merge session with no record of it — the active-run gate reads the open marker as in-flight. All three paid spawn paths use this ordering — the daemon's single-PR and auto-batch paths and the manualMERGE_PR/MERGE_BATCHhandlers; the manual paths park a rejected promotion for the daemon's next tick, so a promotion that does not land is retried on the next daemon tick rather than rethrown as a merge failure (invarianta-paid-spawn-is-recorded-before-it-runs).
Crash recovery. On daemon startup, reconcileCrashedRuns() closes two shapes of stale row by setting completed_at: a spawned row whose linked session has reached a terminal status (ended / error / archived) or was soft-deleted, and a spawning write-ahead marker that outlived its 15-minute grace window (its process died before promoting it) — measured from its last lease heartbeat, so a live but slow spawn is never swept out from under itself. A spawned row whose session still EXISTS in a non-terminal status is never aged out: paused (a deliberate park) and waiting (a rate-limit capacity park) both outlast any age cap by design, and closing their run would free the PR for a second paid spawn while the parked session was still the live merge. It's a tidy-up of the audit ledger; the active-run gate itself no longer depends on it to avoid wedging, because the gate (getActiveRunForPR) is session-aware — a run whose session is terminal/deleted/missing is already treated as not-in-flight even before reconcile runs, so a crash mid-merge can't permanently block the PR.
Cost tracking. Daemon-spawned merge sessions carry triggered_by: 'auto' on their run row (a manual MERGE_PR spawn does not), which is what makes the daily-budget query unambiguous. Their SPEND lives on the sessions row as cost_micro_usd, metered by updateSessionCost — not in api_cost_log (see the note on gate 6).
Settings shape — the daemon-facing settings, all optional in AppSettings, all exposed in Settings → PR Merge Queue. Ranges below are the enforced Zod bounds from ipc-schemas/settings/agent-tools-settings.ts; settings-reference.md is the exhaustive per-setting reference for the whole app.
| Field | Type | Default | Range |
|---|---|---|---|
prMergeQueueAutoMergeEnabled |
boolean |
false |
— |
prMergeQueueAutoMergePollMinutes |
number |
10 |
1–120 |
prMergeQueueAutoMergeDryRun |
boolean |
false |
— |
prMergeQueueDailyBudgetUsd |
number |
5.0 |
0–100 |
prMergeQueueShardEnabled |
boolean |
false |
— |
prMergeQueueShardCount |
number |
2 |
1–64 |
prMergeQueueShardIndex |
number |
0 |
0–63 |
prMergeQueueAutoBatchEnabled |
boolean |
true |
— |
prMergeQueueAutoBatchMaxSize |
number |
8 |
2–32 |
Multi-machine split (sharding). With prMergeQueueShardEnabled on and prMergeQueueShardCount >= 2, this install only auto-spawns for PRs whose number modulo the shard count equals prMergeQueueShardIndex, so several independent installs partition the same repo's open PRs with no overlap and never both merge the same PR. Give each box a distinct index (box A = 0, box B = 1); an index outside 0 <= index < count is fail-safe and auto-spawns nothing, which is why a misconfigured index looks like "the daemon does nothing". Sharding off = pass-through. Locked by the rule the-shard-gate-filters-the-daemon-only in pr-merge-queue-invariants-contract.md; the config is also exported to a small local flag file (shard-export.ts). The nightly PR janitor has a reader written for it but does not call it yet, so the janitor is not shard-filtered today.
Auto-batch. With prMergeQueueAutoBatchEnabled on, the daemon groups several eligible (fast-lane, disjoint-file-set, non-overlapping, this-shard, not-in-flight) PRs into ONE merge session that applies them together and runs the gate once, instead of one session per PR — cutting the duplicated test/build cost, and the disjoint file sets are what make the single gate run trustworthy. prMergeQueueAutoBatchMaxSize caps the group (default 8). It ships on (prMergeQueueAutoBatchEnabled defaults to true, and an unset field reads as on) so a box that enables auto-merge does not pay one spawn, one worktree and one full gate per PR; an explicit false restores one PR per tick. A stored false from the old default survives applyDefaultsDeep, so the one-shot config migration pr-merge-queue-auto-batch-default-on-for-existing-users flips it once for existing installs (the setting had no panel control, so a false is what "never touched" looks like) and stamps a sentinel, leaving a later deliberate switch-off alone. Locked by invariant auto-batch-packs-one-session.
Manual merges are never sharded or auto-batched — an explicit human click (MERGE_PR / MERGE_BATCH) always works, on every box.
Daemon idempotency: startAutoMergeDaemon() is safe to call multiple times — the second call no-ops if a periodic task is already running. stopAutoMergeDaemon() is also idempotent.
DB shape. Migration v210 adds pr_merge_queue_runs (id, gh_slug, pr_number, session_id?, outcome, reason?, triggered_by, lane, dry_run, created_at, completed_at?, cost_usd?) with indexes on (gh_slug, pr_number) and created_at. cost_usd is a v210 column nothing reads or writes — merge spend lives on the session row's cost_micro_usd, and getDailySpendForRepo is the one reader of it. All mutations live in src/main/db/queries-pr-merge-queue-runs.ts. Manual merges (from the view's Merge button) ALSO write here on the same write-ahead shape the daemon uses — a spawning marker before the paid spawn, promoted to spawned on the same row once it resolves — so the audit table reflects every queue-driven merge; triggered_by: 'manual' distinguishes them. All three spawn paths park a rejected promotion for the daemon's next tick, so a post-spawn bookkeeping failure on a manual merge parks the promotion for retry instead of labelling a live session failed (invariant a-paid-spawn-is-recorded-before-it-runs).
pr-merge-queue-handlers.ts holds exactly six wrapHandler-wrapped ipcMain.handle calls, one per invoke channel (LIST_REPOS / LIST_SNAPSHOTS / REFRESH / MERGE_PR / MERGE_BATCH / DETECT_REPO_INFO); the PR_MERGE_QUEUE_CHANGED / GIVE_UP / SNAPSHOT_UPDATED / REFRESH_PROGRESS / AUTO_MERGE_FIRED channels above are push events, not handlers.
They are wired by auto-discovery, not an explicit call: registerDiscoveredHandlers() in src/main/ipc/register.ts picks up every *-handlers.ts module, so the exported registerPrMergeQueueHandlers() has no call site anywhere in src/. Grepping register.ts for it finds nothing — that is expected, not dead code. Zod schemas live in src/shared/ipc-schemas/pr-merge-queue.ts (re-exported through the src/shared/ipc-schemas.ts barrel).
Related
- PR Merge Queue — the user-facing half of this feature: the lanes, the merge buttons, the Inbox nudges and the archiving rules.
- PR Merge Queue (part 3) — the optional one-line AI summary shown as each PR's headline.
The contracts named above hold the invariants behind what this half describes.
Last verified 2026-10-14