CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 | /**
* Block E5 — Merge queue helpers.
*
* A merge queue serialises merges on `(repository_id, base_branch)`: instead
* of merging a PR immediately, it's enqueued. A worker (or the manual
* "process next" button surfaced on the queue UI) pops the head of the queue,
* re-runs gates against the latest base, and — if green — performs the merge.
*
* This module is deliberately minimal: no side-effects on gate execution or
* the actual git merge (those are owned by `pulls.tsx`). We just manage
* the queue state + ordering. Every DB path is wrapped to never throw.
*/
import { and, asc, eq, sql } from "drizzle-orm";
import { db } from "../db";
import { mergeQueueEntries, pullRequests } from "../db/schema";
import type { MergeQueueEntry } from "../db/schema";
export interface EnqueueArgs {
repositoryId: string;
pullRequestId: string;
baseBranch: string;
enqueuedBy?: string | null;
}
export interface EnqueueResult {
ok: boolean;
entry?: MergeQueueEntry;
reason?: string;
}
/**
* Append a PR to the end of the queue for its `(repo, baseBranch)`. No-op
* (returns ok:false with a reason) if the PR is already queued or running.
*/
export async function enqueuePr(args: EnqueueArgs): Promise<EnqueueResult> {
try {
// Check for existing active entry for this PR.
const existing = await db
.select()
.from(mergeQueueEntries)
.where(eq(mergeQueueEntries.pullRequestId, args.pullRequestId));
const active = existing.find(
(e) => e.state === "queued" || e.state === "running"
);
if (active) {
return { ok: false, reason: "Pull request is already in the queue." };
}
// Compute next position in this (repo, base) queue.
const rows = await db
.select({ maxPos: sql<number>`COALESCE(MAX(${mergeQueueEntries.position}), -1)` })
.from(mergeQueueEntries)
.where(
and(
eq(mergeQueueEntries.repositoryId, args.repositoryId),
eq(mergeQueueEntries.baseBranch, args.baseBranch),
sql`${mergeQueueEntries.state} IN ('queued','running')`
)
);
const nextPos = (rows[0]?.maxPos ?? -1) + 1;
const [entry] = await db
.insert(mergeQueueEntries)
.values({
repositoryId: args.repositoryId,
pullRequestId: args.pullRequestId,
baseBranch: args.baseBranch,
position: nextPos,
enqueuedBy: args.enqueuedBy || null,
state: "queued",
})
.returning();
return { ok: true, entry };
} catch (err) {
console.error("[merge-queue] enqueue:", err);
return { ok: false, reason: "Failed to enqueue pull request." };
}
}
/**
* Remove an active entry from the queue (user-initiated cancel, or a PR
* closed while queued). Marks it `dequeued` rather than deleting for audit.
*/
export async function dequeueEntry(entryId: string): Promise<boolean> {
try {
const res = await db
.update(mergeQueueEntries)
.set({ state: "dequeued", finishedAt: new Date() })
.where(
and(
eq(mergeQueueEntries.id, entryId),
sql`${mergeQueueEntries.state} IN ('queued','running')`
)
)
.returning({ id: mergeQueueEntries.id });
return res.length > 0;
} catch (err) {
console.error("[merge-queue] dequeue:", err);
return false;
}
}
/**
* Peek the head of the queue for a `(repo, baseBranch)` pair. Returns the
* oldest `queued` entry — the one that would be popped next by processNext.
*/
export async function peekHead(
repositoryId: string,
baseBranch: string
): Promise<MergeQueueEntry | null> {
try {
const rows = await db
.select()
.from(mergeQueueEntries)
.where(
and(
eq(mergeQueueEntries.repositoryId, repositoryId),
eq(mergeQueueEntries.baseBranch, baseBranch),
eq(mergeQueueEntries.state, "queued")
)
)
.orderBy(asc(mergeQueueEntries.position), asc(mergeQueueEntries.enqueuedAt))
.limit(1);
return rows[0] || null;
} catch {
return null;
}
}
/**
* List queue entries for a repo, newest-first per base branch. Includes
* terminal states so the queue UI can show recent merges/failures.
*/
export async function listQueue(
repositoryId: string,
opts: { limit?: number; baseBranch?: string } = {}
): Promise<MergeQueueEntry[]> {
const limit = opts.limit ?? 100;
try {
if (opts.baseBranch) {
return await db
.select()
.from(mergeQueueEntries)
.where(
and(
eq(mergeQueueEntries.repositoryId, repositoryId),
eq(mergeQueueEntries.baseBranch, opts.baseBranch)
)
)
.orderBy(asc(mergeQueueEntries.position), asc(mergeQueueEntries.enqueuedAt))
.limit(limit);
}
return await db
.select()
.from(mergeQueueEntries)
.where(eq(mergeQueueEntries.repositoryId, repositoryId))
.orderBy(asc(mergeQueueEntries.position), asc(mergeQueueEntries.enqueuedAt))
.limit(limit);
} catch {
return [];
}
}
/**
* Transition the head entry → `running`. Returns the entry (if any) so the
* caller can kick off gates + perform the merge. The caller must eventually
* call `completeEntry` with success/failure.
*/
export async function markHeadRunning(
repositoryId: string,
baseBranch: string
): Promise<MergeQueueEntry | null> {
const head = await peekHead(repositoryId, baseBranch);
if (!head) return null;
try {
const [updated] = await db
.update(mergeQueueEntries)
.set({ state: "running", startedAt: new Date() })
.where(
and(
eq(mergeQueueEntries.id, head.id),
eq(mergeQueueEntries.state, "queued")
)
)
.returning();
return updated || null;
} catch {
return null;
}
}
/**
* Mark a running entry as finished. `state` is the final state
* (`merged` | `failed`). Non-running entries are left untouched.
*/
export async function completeEntry(
entryId: string,
finalState: "merged" | "failed",
errorMessage?: string
): Promise<boolean> {
try {
const res = await db
.update(mergeQueueEntries)
.set({
state: finalState,
finishedAt: new Date(),
errorMessage: errorMessage || null,
})
.where(eq(mergeQueueEntries.id, entryId))
.returning({ id: mergeQueueEntries.id });
return res.length > 0;
} catch (err) {
console.error("[merge-queue] complete:", err);
return false;
}
}
/**
* Is this PR currently queued or running? Convenience helper for the merge
* UI (so we can swap the button label to "In queue…").
*/
export async function isQueued(pullRequestId: string): Promise<boolean> {
try {
const rows = await db
.select({ id: mergeQueueEntries.id })
.from(mergeQueueEntries)
.where(
and(
eq(mergeQueueEntries.pullRequestId, pullRequestId),
sql`${mergeQueueEntries.state} IN ('queued','running')`
)
)
.limit(1);
return rows.length > 0;
} catch {
return false;
}
}
/**
* Check queue depth for `(repo, baseBranch)` — number of `queued` + `running`.
*/
export async function queueDepth(
repositoryId: string,
baseBranch: string
): Promise<number> {
try {
const rows = await db
.select({ n: sql<number>`COUNT(*)` })
.from(mergeQueueEntries)
.where(
and(
eq(mergeQueueEntries.repositoryId, repositoryId),
eq(mergeQueueEntries.baseBranch, baseBranch),
sql`${mergeQueueEntries.state} IN ('queued','running')`
)
);
return Number(rows[0]?.n || 0);
} catch {
return 0;
}
}
/**
* Resolve PR metadata (number, title) for a list of entries — the queue UI
* needs those to render links. Kept in the helper so routes don't have to
* re-join.
*/
export interface QueueEntryWithPr extends MergeQueueEntry {
prNumber: number | null;
prTitle: string | null;
prState: string | null;
prHeadBranch: string | null;
prAuthorId: string | null;
}
export async function listQueueWithPrs(
repositoryId: string
): Promise<QueueEntryWithPr[]> {
try {
const rows = await db
.select({
id: mergeQueueEntries.id,
repositoryId: mergeQueueEntries.repositoryId,
pullRequestId: mergeQueueEntries.pullRequestId,
baseBranch: mergeQueueEntries.baseBranch,
state: mergeQueueEntries.state,
position: mergeQueueEntries.position,
enqueuedBy: mergeQueueEntries.enqueuedBy,
enqueuedAt: mergeQueueEntries.enqueuedAt,
startedAt: mergeQueueEntries.startedAt,
finishedAt: mergeQueueEntries.finishedAt,
errorMessage: mergeQueueEntries.errorMessage,
prNumber: pullRequests.number,
prTitle: pullRequests.title,
prState: pullRequests.state,
prHeadBranch: pullRequests.headBranch,
prAuthorId: pullRequests.authorId,
})
.from(mergeQueueEntries)
.leftJoin(
pullRequests,
eq(mergeQueueEntries.pullRequestId, pullRequests.id)
)
.where(eq(mergeQueueEntries.repositoryId, repositoryId))
.orderBy(asc(mergeQueueEntries.position), asc(mergeQueueEntries.enqueuedAt))
.limit(200);
return rows as QueueEntryWithPr[];
} catch {
return [];
}
}
|