Skip to content
refs
246 lines · 12.6 KBRaw
1import { now } from "./auth.ts";
2import type { Actor } from "./contract/actor.ts";
3import type { LineRange, PullCounts, PullDetail, PullStatus, PullSummary } from "./contract/views.ts";
4import { pullStream, recordEvent, type Recorder } from "./events.ts";
5import { renderMarkdown } from "./markdown.ts";
6import { branchProblem } from "@refs/protocol";
7
8export interface PullRecord {
9 id: number;
10 repo_id: string;
11 repo_name: string;
12 number: number;
13 title: string;
14 body: string;
15 status: PullStatus;
16 author_id: string;
17 author: string;
18 opened_by_agent: string | null;
19 base_ref: string;
20 head_ref: string;
21 base_sha: string | null;
22 head_sha: string | null;
23 created_at: number;
24 updated_at: number;
25 closed_at: number | null;
26 branched_from: number | null;
27 branched_at: string | null;
28 branched_from_number: number | null;
29 branched_from_title: string | null;
30 comments: number;
31}
32
33const SELECT_PULL = `SELECT p.*, (SELECT slug FROM namespaces WHERE id = r.namespace_id) || '/' || r.name AS repo_name, a.name AS author,
34 src.number AS branched_from_number, src.title AS branched_from_title,
35 (SELECT count(*) FROM events e WHERE e.stream = 'pull:' || p.id AND e.kind = 'pull.commented') AS comments,
36 (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
37 FROM pulls p JOIN repos r ON r.id = p.repo_id JOIN users a ON a.id = p.author_id
38 LEFT JOIN pulls src ON src.id = p.branched_from`;
39
40const NEXT_NUMBER = "(SELECT coalesce(max(number), 0) + 1 FROM pulls WHERE repo_id = ?1)";
41
42export function toPullSummary(row: PullRecord): PullSummary {
43 return {
44 number: row.number,
45 repo: row.repo_name,
46 title: row.title,
47 status: row.status,
48 author: { id: row.author_id, name: row.author },
49 agent: row.opened_by_agent,
50 base: row.base_ref,
51 head: row.head_ref,
52 comments: row.comments,
53 createdAt: row.created_at,
54 closedAt: row.closed_at,
55 };
56}
57
58export function toPullDetail(row: PullRecord): PullDetail {
59 return {
60 ...toPullSummary(row),
61 body: row.body,
62 bodyHtml: row.body ? renderMarkdown(row.body) : null,
63 updatedAt: row.updated_at,
64 branchedFrom: row.branched_from_number !== null ? { number: row.branched_from_number, title: row.branched_from_title!, commit: row.branched_at! } : null,
65 };
66}
67
68/** Pull requests branched from `pull`, oldest first. */
69export async function listBranches(db: D1Database, pull: PullRecord): Promise<PullRecord[]> {
70 return (await db.prepare(`${SELECT_PULL} WHERE p.branched_from = ? ORDER BY p.number`).bind(pull.id).all<PullRecord>()).results;
71}
72
73export async function listPulls(db: D1Database, repoId: string, status: "open" | "closed"): Promise<{ items: PullRecord[]; counts: PullCounts }> {
74 const [counts, rows] = await db.batch([
75 db.prepare("SELECT sum(status = 'open') AS open, sum(status != 'open') AS closed FROM pulls WHERE repo_id = ?").bind(repoId),
76 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),
77 ]);
78 const totals = counts.results[0] as { open: number | null; closed: number | null };
79 return { items: rows.results as PullRecord[], counts: { open: totals.open ?? 0, closed: totals.closed ?? 0 } };
80}
81
82export async function findPull(db: D1Database, repoId: string, number: number): Promise<PullRecord | null> {
83 if (!Number.isInteger(number) || number < 1) return null;
84 return db.prepare(`${SELECT_PULL} WHERE p.repo_id = ? AND p.number = ?`).bind(repoId, number).first<PullRecord>();
85}
86
87export async function openPulls(db: D1Database, repoId: string): Promise<PullRecord[]> {
88 return (await db.prepare(`${SELECT_PULL} WHERE p.repo_id = ? AND p.status = 'open'`).bind(repoId).all<PullRecord>()).results;
89}
90
91export async function createPull(
92 db: D1Database,
93 actor: Actor,
94 input: { repoId: string; title: string; body: string; authorId: string; base: string; head: string; branchedFrom?: { pull: number; commit: string } },
95): Promise<{ kind: "created"; number: number } | { kind: "already_open" }> {
96 const at = now();
97 try {
98 const [inserted] = await db.batch<{ number: number }>([
99 db
100 .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`)
101 .bind(input.repoId, input.title, input.body, input.authorId, input.base, input.head, at, input.branchedFrom?.pull ?? null, input.branchedFrom?.commit ?? null),
102 recordEvent(db, actor, { newest: "pull", repoId: input.repoId }, "pull.opened", { title: input.title }, at),
103 ]);
104 return { kind: "created", number: inserted.results[0].number };
105 } catch (error) {
106 if (error instanceof Error && /UNIQUE constraint failed: pulls\.repo_id, pulls\.base_ref, pulls\.head_ref/.test(error.message)) return { kind: "already_open" };
107 throw error;
108 }
109}
110
111function statusChange(db: D1Database, actor: Actor, pull: PullRecord, status: "open" | "closed", at: number, tips: { base: string; head: string } | null): D1PreparedStatement[] {
112 return [
113 db
114 .prepare("UPDATE pulls SET status = ?, closed_at = ?, base_sha = ?, head_sha = ?, updated_at = ? WHERE id = ?")
115 .bind(status, status === "closed" ? at : null, tips?.base ?? null, tips?.head ?? null, at, pull.id),
116 recordEvent(db, actor, pullStream(pull.id), status === "closed" ? "pull.closed" : "pull.reopened", {}, at),
117 ];
118}
119
120/** Closing freezes the branch tips, so the pull request keeps its diff after the branches move or go away. */
121export async function setPullStatus(db: D1Database, actor: Actor, pull: PullRecord, status: "open" | "closed", tips: { base: string; head: string } | null): Promise<void> {
122 if (status !== pull.status) await db.batch(statusChange(db, actor, pull, status, now(), tips));
123}
124
125export async function commentOnPull(db: D1Database, actor: Actor, pull: PullRecord, body: string, then?: { status: "open" | "closed"; tips: { base: string; head: string } | null }, thread?: number): Promise<number> {
126 const at = now();
127 const [inserted] = await db.batch([
128 recordEvent(db, actor, pullStream(pull.id), "pull.commented", thread ? { body, thread } : { body }, at),
129 db.prepare("UPDATE pulls SET updated_at = ? WHERE id = ?").bind(at, pull.id),
130 ...(then && then.status !== pull.status ? statusChange(db, actor, pull, then.status, at, then.tips) : []),
131 ]);
132 return inserted.meta.last_row_id;
133}
134
135export async function renamePull(db: D1Database, actor: Actor, pull: PullRecord, title: string): Promise<void> {
136 if (title === pull.title) return;
137 const at = now();
138 await db.batch([
139 db.prepare("UPDATE pulls SET title = ?, updated_at = ? WHERE id = ?").bind(title, at, pull.id),
140 recordEvent(db, actor, pullStream(pull.id), "pull.renamed", { from: pull.title, to: title }, at),
141 ]);
142}
143
144export function markMerged(db: D1Database, actor: Recorder, pull: PullRecord, tips: { base: string; head: string }, at: number): D1PreparedStatement[] {
145 return [
146 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),
147 recordEvent(db, actor, pullStream(pull.id), "pull.merged", { head: tips.head }, at),
148 ];
149}
150
151/** What an agent mentioned on a pull request receives: the comment, with where it was made. */
152/** A branch name from `title` that `branches` lacks and that agents may push. */
153export function freshBranchName(title: string, branches: ReadonlyMap<string, string>, base: string): string {
154 const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "branch";
155 let name = slug;
156 for (let n = 2; branches.has(name) || branchProblem(name, base) !== null; n++) name = `${slug}-${n}`;
157 return name;
158}
159
160export function mentionText(pull: Pick<PullRecord, "number" | "head_ref" | "base_ref" | "repo_name">, origin: string, text: string): string {
161 return `On pull request #${pull.number} (${pull.head_ref} → ${pull.base_ref}), ${origin}/${pull.repo_name}/pulls/${pull.number}:\n\n${text}`;
162}
163
164export interface ThreadRecord {
165 id: number;
166 pull_id: number;
167 path: string | null;
168 side: LineRange["side"] | null;
169 start_line: number | null;
170 end_side: LineRange["endSide"] | null;
171 end_line: number | null;
172 decision_id: string | null;
173 revision: string;
174 code: string;
175 status: "open" | "addressed" | "resolved";
176 addressed_commit: string | null;
177 created_at: number;
178 updated_at: number;
179}
180
181export function threadRange(thread: ThreadRecord): LineRange | null {
182 return thread.decision_id ? null : { start: thread.start_line!, side: thread.side!, end: thread.end_line!, endSide: thread.end_side! };
183}
184
185export function rangeLabel(range: LineRange): string {
186 const label = (side: LineRange["side"], line: number) => `${side === "deletions" ? "L" : "R"}${line}`;
187 return range.start === range.end && range.side === range.endSide ? label(range.side, range.start) : `${label(range.side, range.start)}–${label(range.endSide, range.end)}`;
188}
189
190export function codeBlock(code: string): string {
191 const fence = "`".repeat(Math.max(2, ...[...code.matchAll(/`+/g)].map((run) => run[0].length)) + 1);
192 return `${fence}\n${code}\n${fence}`;
193}
194
195export async function listThreads(db: D1Database, pullId: number): Promise<ThreadRecord[]> {
196 return (await db.prepare("SELECT * FROM review_threads WHERE pull_id = ? ORDER BY id").bind(pullId).all<ThreadRecord>()).results;
197}
198
199export async function findThread(db: D1Database, pullId: number, id: number): Promise<ThreadRecord | null> {
200 if (!Number.isInteger(id)) return null;
201 return db.prepare("SELECT * FROM review_threads WHERE pull_id = ? AND id = ?").bind(pullId, id).first<ThreadRecord>();
202}
203
204/**
205 * Starts a thread on `range` of `path`, or on a decision record, and posts its first comment; returns the thread
206 * and comment ids. `code` is what the thread is about as it read when the thread started.
207 */
208export async function startThread(
209 db: D1Database,
210 actor: Actor,
211 pull: PullRecord,
212 input: ({ path: string; range: LineRange } | { decision: string }) & { revision: string; code: string; body: string },
213): Promise<{ thread: number; comment: number }> {
214 const at = now();
215 const lines = "path" in input ? input : null;
216 const created = await db
217 .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")
218 .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)
219 .first<{ id: number }>();
220 const comment = await commentOnPull(db, actor, pull, input.body, undefined, created!.id);
221 return { thread: created!.id, comment };
222}
223
224export async function setThreadStatus(db: D1Database, actor: Recorder, pull: Pick<PullRecord, "id">, thread: ThreadRecord, status: ThreadRecord["status"], commit: string | null = null): Promise<void> {
225 const at = now();
226 const kind = status === "addressed" ? "pull.thread_addressed" : status === "resolved" ? "pull.thread_resolved" : "pull.thread_reopened";
227 await db.batch([
228 db.prepare("UPDATE review_threads SET status = ?, addressed_commit = ?, updated_at = ? WHERE id = ?").bind(status, status === "addressed" ? commit : null, at, thread.id),
229 db.prepare("UPDATE pulls SET updated_at = ? WHERE id = ?").bind(at, pull.id),
230 kind === "pull.thread_addressed"
231 ? recordEvent(db, actor, pullStream(pull.id), kind, { thread: thread.id, commit: commit! }, at)
232 : recordEvent(db, actor, pullStream(pull.id), kind, { thread: thread.id }, at),
233 ]);
234}
235
236/** What an agent mentioned in a review thread receives: the comment, with the thread's file, lines and code, or its decision. */
237export function threadMentionText(pull: Pick<PullRecord, "number" | "head_ref" | "base_ref" | "repo_name">, origin: string, thread: ThreadRecord, text: string): string {
238 const range = threadRange(thread);
239 if (!range)
240 return mentionText(
241 pull,
242 origin,
243 `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.`,
244 );
245 return mentionText(pull, origin, `In review thread ${thread.id} on ${thread.path}:${rangeLabel(range)}\n\n${codeBlock(thread.code)}\n\n${text}`);
246}