import { now } from "./auth.ts"; import type { Actor } from "./contract/actor.ts"; import type { LineRange, PullCounts, PullDetail, PullStatus, PullSummary } from "./contract/views.ts"; import { pullStream, recordEvent, type Recorder } from "./events.ts"; import { renderMarkdown } from "./markdown.ts"; export interface PullRecord { id: number; repo_id: string; repo_name: string; number: number; title: string; body: string; status: PullStatus; author_id: string; author: string; opened_by_agent: string | null; base_ref: string; head_ref: string; base_sha: string | null; head_sha: string | null; created_at: number; updated_at: number; closed_at: number | null; branched_from: number | null; branched_at: string | null; branched_from_number: number | null; branched_from_title: string | null; comments: number; } const SELECT_PULL = `SELECT p.*, (SELECT slug FROM namespaces WHERE id = r.namespace_id) || '/' || r.name AS repo_name, a.name AS author, src.number AS branched_from_number, src.title AS branched_from_title, (SELECT count(*) FROM events e WHERE e.stream = 'pull:' || p.id AND e.kind = 'pull.commented') AS comments, (SELECT coalesce(g.runtime, 'agent') FROM events e LEFT JOIN agent_sessions g ON g.id = e.actor_id WHERE e.stream = 'pull:' || p.id AND e.kind = 'pull.opened' AND e.actor_kind = 'agent' AND e.actor_id != 'refs') AS opened_by_agent FROM pulls p JOIN repos r ON r.id = p.repo_id JOIN users a ON a.id = p.author_id LEFT JOIN pulls src ON src.id = p.branched_from`; const NEXT_NUMBER = "(SELECT coalesce(max(number), 0) + 1 FROM pulls WHERE repo_id = ?1)"; export function toPullSummary(row: PullRecord): PullSummary { return { number: row.number, repo: row.repo_name, title: row.title, status: row.status, author: { id: row.author_id, name: row.author }, agent: row.opened_by_agent, base: row.base_ref, head: row.head_ref, comments: row.comments, createdAt: row.created_at, closedAt: row.closed_at, }; } export function toPullDetail(row: PullRecord): PullDetail { return { ...toPullSummary(row), body: row.body, bodyHtml: row.body ? renderMarkdown(row.body) : null, updatedAt: row.updated_at, branchedFrom: row.branched_from_number !== null ? { number: row.branched_from_number, title: row.branched_from_title!, commit: row.branched_at! } : null, }; } /** Pull requests branched from `pull`, oldest first. */ export async function listBranches(db: D1Database, pull: PullRecord): Promise { return (await db.prepare(`${SELECT_PULL} WHERE p.branched_from = ? ORDER BY p.number`).bind(pull.id).all()).results; } export async function listPulls(db: D1Database, repoId: string, status: "open" | "closed"): Promise<{ items: PullRecord[]; counts: PullCounts }> { const [counts, rows] = await db.batch([ db.prepare("SELECT sum(status = 'open') AS open, sum(status != 'open') AS closed FROM pulls WHERE repo_id = ?").bind(repoId), db.prepare(`${SELECT_PULL} WHERE p.repo_id = ? AND ${status === "open" ? "p.status = 'open'" : "p.status != 'open'"} ORDER BY p.number DESC LIMIT 100`).bind(repoId), ]); const totals = counts.results[0] as { open: number | null; closed: number | null }; return { items: rows.results as PullRecord[], counts: { open: totals.open ?? 0, closed: totals.closed ?? 0 } }; } export async function findPull(db: D1Database, repoId: string, number: number): Promise { if (!Number.isInteger(number) || number < 1) return null; return db.prepare(`${SELECT_PULL} WHERE p.repo_id = ? AND p.number = ?`).bind(repoId, number).first(); } export async function openPulls(db: D1Database, repoId: string): Promise { return (await db.prepare(`${SELECT_PULL} WHERE p.repo_id = ? AND p.status = 'open'`).bind(repoId).all()).results; } export async function createPull( db: D1Database, actor: Actor, input: { repoId: string; title: string; body: string; authorId: string; base: string; head: string; branchedFrom?: { pull: number; commit: string } }, ): Promise<{ kind: "created"; number: number } | { kind: "already_open" }> { const at = now(); try { const [inserted] = await db.batch<{ number: number }>([ db .prepare(`INSERT INTO pulls (repo_id, number, title, body, author_id, base_ref, head_ref, branched_from, branched_at, created_at, updated_at) VALUES (?1, ${NEXT_NUMBER}, ?2, ?3, ?4, ?5, ?6, ?8, ?9, ?7, ?7) RETURNING number`) .bind(input.repoId, input.title, input.body, input.authorId, input.base, input.head, at, input.branchedFrom?.pull ?? null, input.branchedFrom?.commit ?? null), recordEvent(db, actor, { newest: "pull", repoId: input.repoId }, "pull.opened", { title: input.title }, at), ]); return { kind: "created", number: inserted.results[0].number }; } catch (error) { if (error instanceof Error && /UNIQUE constraint failed: pulls\.repo_id, pulls\.base_ref, pulls\.head_ref/.test(error.message)) return { kind: "already_open" }; throw error; } } function statusChange(db: D1Database, actor: Actor, pull: PullRecord, status: "open" | "closed", at: number, tips: { base: string; head: string } | null): D1PreparedStatement[] { return [ db .prepare("UPDATE pulls SET status = ?, closed_at = ?, base_sha = ?, head_sha = ?, updated_at = ? WHERE id = ?") .bind(status, status === "closed" ? at : null, tips?.base ?? null, tips?.head ?? null, at, pull.id), recordEvent(db, actor, pullStream(pull.id), status === "closed" ? "pull.closed" : "pull.reopened", {}, at), ]; } /** Closing freezes the branch tips, so the pull request keeps its diff after the branches move or go away. */ export async function setPullStatus(db: D1Database, actor: Actor, pull: PullRecord, status: "open" | "closed", tips: { base: string; head: string } | null): Promise { if (status !== pull.status) await db.batch(statusChange(db, actor, pull, status, now(), tips)); } export async function commentOnPull(db: D1Database, actor: Actor, pull: PullRecord, body: string, then?: { status: "open" | "closed"; tips: { base: string; head: string } | null }, thread?: number): Promise { const at = now(); const [inserted] = await db.batch([ recordEvent(db, actor, pullStream(pull.id), "pull.commented", thread ? { body, thread } : { body }, at), db.prepare("UPDATE pulls SET updated_at = ? WHERE id = ?").bind(at, pull.id), ...(then && then.status !== pull.status ? statusChange(db, actor, pull, then.status, at, then.tips) : []), ]); return inserted.meta.last_row_id; } export async function renamePull(db: D1Database, actor: Actor, pull: PullRecord, title: string): Promise { if (title === pull.title) return; const at = now(); await db.batch([ db.prepare("UPDATE pulls SET title = ?, updated_at = ? WHERE id = ?").bind(title, at, pull.id), recordEvent(db, actor, pullStream(pull.id), "pull.renamed", { from: pull.title, to: title }, at), ]); } export function markMerged(db: D1Database, actor: Recorder, pull: PullRecord, tips: { base: string; head: string }, at: number): D1PreparedStatement[] { return [ db.prepare("UPDATE pulls SET status = 'merged', closed_at = ?, base_sha = ?, head_sha = ?, updated_at = ? WHERE id = ? AND status = 'open'").bind(at, tips.base, tips.head, at, pull.id), recordEvent(db, actor, pullStream(pull.id), "pull.merged", { head: tips.head }, at), ]; } /** What an agent mentioned on a pull request receives: the comment, with where it was made. */ export function mentionText(pull: Pick, origin: string, text: string): string { return `On pull request #${pull.number} (${pull.head_ref} → ${pull.base_ref}), ${origin}/${pull.repo_name}/pulls/${pull.number}:\n\n${text}`; } export interface ThreadRecord { id: number; pull_id: number; path: string | null; side: LineRange["side"] | null; start_line: number | null; end_side: LineRange["endSide"] | null; end_line: number | null; decision_id: string | null; revision: string; code: string; status: "open" | "addressed" | "resolved"; addressed_commit: string | null; created_at: number; updated_at: number; } export function threadRange(thread: ThreadRecord): LineRange | null { return thread.decision_id ? null : { start: thread.start_line!, side: thread.side!, end: thread.end_line!, endSide: thread.end_side! }; } export function rangeLabel(range: LineRange): string { const label = (side: LineRange["side"], line: number) => `${side === "deletions" ? "L" : "R"}${line}`; return range.start === range.end && range.side === range.endSide ? label(range.side, range.start) : `${label(range.side, range.start)}–${label(range.endSide, range.end)}`; } export function codeBlock(code: string): string { const fence = "`".repeat(Math.max(2, ...[...code.matchAll(/`+/g)].map((run) => run[0].length)) + 1); return `${fence}\n${code}\n${fence}`; } export async function listThreads(db: D1Database, pullId: number): Promise { return (await db.prepare("SELECT * FROM review_threads WHERE pull_id = ? ORDER BY id").bind(pullId).all()).results; } export async function findThread(db: D1Database, pullId: number, id: number): Promise { if (!Number.isInteger(id)) return null; return db.prepare("SELECT * FROM review_threads WHERE pull_id = ? AND id = ?").bind(pullId, id).first(); } /** * Starts a thread on `range` of `path`, or on a decision record, and posts its first comment; returns the thread * and comment ids. `code` is what the thread is about as it read when the thread started. */ export async function startThread( db: D1Database, actor: Actor, pull: PullRecord, input: ({ path: string; range: LineRange } | { decision: string }) & { revision: string; code: string; body: string }, ): Promise<{ thread: number; comment: number }> { const at = now(); const lines = "path" in input ? input : null; const created = await db .prepare("INSERT INTO review_threads (pull_id, path, side, start_line, end_side, end_line, decision_id, revision, code, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id") .bind(pull.id, lines?.path ?? null, lines?.range.side ?? null, lines?.range.start ?? null, lines?.range.endSide ?? null, lines?.range.end ?? null, "decision" in input ? input.decision : null, input.revision, input.code, at, at) .first<{ id: number }>(); const comment = await commentOnPull(db, actor, pull, input.body, undefined, created!.id); return { thread: created!.id, comment }; } export async function setThreadStatus(db: D1Database, actor: Recorder, pull: Pick, thread: ThreadRecord, status: ThreadRecord["status"], commit: string | null = null): Promise { const at = now(); const kind = status === "addressed" ? "pull.thread_addressed" : status === "resolved" ? "pull.thread_resolved" : "pull.thread_reopened"; await db.batch([ db.prepare("UPDATE review_threads SET status = ?, addressed_commit = ?, updated_at = ? WHERE id = ?").bind(status, status === "addressed" ? commit : null, at, thread.id), db.prepare("UPDATE pulls SET updated_at = ? WHERE id = ?").bind(at, pull.id), kind === "pull.thread_addressed" ? recordEvent(db, actor, pullStream(pull.id), kind, { thread: thread.id, commit: commit! }, at) : recordEvent(db, actor, pullStream(pull.id), kind, { thread: thread.id }, at), ]); } /** What an agent mentioned in a review thread receives: the comment, with the thread's file, lines and code, or its decision. */ export function threadMentionText(pull: Pick, origin: string, thread: ThreadRecord, text: string): string { const range = threadRange(thread); if (!range) return mentionText( pull, origin, `In review thread ${thread.id} on decision ${thread.decision_id}:\n\n> ${thread.code}\n\n${text}\n\nIf this changes your course, push a commit whose decision record lists ${thread.decision_id} in supersedes. The thread is marked addressed when it lands.`, ); return mentionText(pull, origin, `In review thread ${thread.id} on ${thread.path}:${rangeLabel(range)}\n\n${codeBlock(thread.code)}\n\n${text}`); }