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