Skip to content
refs
History
302 lines · 18.3 KBRaw
1import { listAgents } from "../agents.ts";
2import { now } from "../auth.ts";
3import { mergeBase, readCommit, readTree, rowsInRange } from "../diff.ts";
4import { commitBody, gitObject, mergeTrees, pushRef, treeBody } from "../gitwrite.ts";
5import type { Outcome } from "../contract/common.ts";
6import type { ReviewVerdict } from "../contract/handles.ts";
7import type { Pull } from "../contract/handles.ts";
8import { captureWorkEvent } from "../analytics.ts";
9import { decorateMentions, deliverMentions, mentionStates, onPull } from "../mentions.ts";
10import { pullStream, recordEvent, readStream, repoStream, withPushers } from "../events.ts";
11import { type Refs as GitRefs } from "../git.ts";
12import { conflict, firstInvalid, invalid, ok, problem, raise } from "../outcomes.ts";
13import { Policy, type RepoFacts } from "../policy.ts";
14import { pendingPermissions } from "../permissions.ts";
15import * as pulls from "../pulls.ts";
16import { bodyError, requiredBodyError, titleError } from "../text.ts";
17import { codeChanges, codeMapSummaryAt } from "../code-maps.ts";
18import { cachedChanges, type Deps } from "./context.ts";
19import { startPullCi } from "./ci.ts";
20import { findRepoRecordById } from "../repos.ts";
21import { branchProblem, parseDecisions } from "@refs/protocol";
22
23const REVIEW_LABELS: Record<ReviewVerdict, string> = { comment: "Reviewed", approve: "Approved", "request-changes": "Requested changes" };
24
25export function openPull(deps: Deps, policy: Policy, row: pulls.PullRecord, facts: RepoFacts, namespaceId: string, handle: () => Promise<ArtifactsRepo>, gitRefs: () => Promise<GitRefs>): Pull {
26 const db = deps.env.DB;
27 const actor = policy.actor;
28
29 async function liveTips(): Promise<{ base: string; head: string } | null> {
30 const branches = (await gitRefs()).branches;
31 const base = branches.get(row.base_ref);
32 const head = branches.get(row.head_ref);
33 return base && head ? { base, head } : null;
34 }
35
36 /** While open, the live branches; once merged or closed, the commits they pointed at then. */
37 async function reviewedTips(): Promise<{ base: string; head: string }> {
38 const tips = row.base_sha && row.head_sha ? { base: row.base_sha, head: row.head_sha } : await liveTips();
39 return tips ?? raise("not_found", `The ${row.head_ref} or ${row.base_ref} branch no longer exists.`);
40 }
41
42 async function reopenProblem(): Promise<Outcome | null> {
43 if (row.status === "merged") return invalid("A merged pull request can't be closed or reopened.");
44 const clash = await db.prepare("SELECT number FROM pulls WHERE repo_id = ? AND base_ref = ? AND head_ref = ? AND status = 'open' AND id != ?").bind(row.repo_id, row.base_ref, row.head_ref, row.id).first<number>("number");
45 return clash ? invalid(`Pull request #${clash} is already open for these branches.`) : null;
46 }
47
48 const subject = onPull(row);
49 /** A branch name from `title` that the repository doesn't have yet and that agents may push. */
50 async function freshBranch(title: string): Promise<string> {
51 const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "branch";
52 const [{ branches }, base] = await Promise.all([gitRefs(), db.prepare("SELECT default_branch FROM repos WHERE id = ?").bind(row.repo_id).first<string>("default_branch")]);
53 let name = slug;
54 for (let n = 2; branches.has(name) || branchProblem(name, base!) !== null; n++) name = `${slug}-${n}`;
55 return name;
56 }
57 const canResolve = () => policy.actor.kind === "human" && policy.canWriteRepo(facts);
58 const captureReview = (name: "work.rejected" | "review.thread_resolved") => {
59 if (actor.kind === "human") captureWorkEvent(deps.env, deps.ctx, actor, { name, repoId: row.repo_id, namespaceId, branch: row.head_ref });
60 };
61
62 /** What merging would produce right now: the tips it was computed from and the merged tree, or why it can't. */
63 async function planMerge() {
64 if (row.status !== "open") return { problem: "This pull request is not open." } as const;
65 const tips = await liveTips();
66 if (!tips) return { problem: `The ${row.head_ref} or ${row.base_ref} branch no longer exists.` } as const;
67 const opened = await handle();
68 const common = await mergeBase(opened, tips.base, tips.head);
69 if (common === tips.head) return { problem: `${row.base_ref} already contains every commit on ${row.head_ref}.` } as const;
70 const [baseCommit, ourCommit, theirCommit] = await Promise.all([readCommit(opened, common), readCommit(opened, tips.base), readCommit(opened, tips.head)]);
71 if (!baseCommit || !ourCommit || !theirCommit) return { problem: "A commit of this pull request could not be read." } as const;
72 const merged = await mergeTrees((hash) => readTree(opened, hash), baseCommit.treeHash, ourCommit.treeHash, theirCommit.treeHash);
73 return { opened, tips, merged } as const;
74 }
75
76 const pull: Pull = {
77 detail: pulls.toPullDetail(row),
78
79 async timeline() {
80 const [events, agents] = await Promise.all([readStream(db, pullStream(row.id)), listAgents(db, namespaceId, row.repo_id)]);
81 const hosted = agents.filter((agent) => !agent.replaced).map((agent) => agent.handle);
82 return Promise.all(events.map(async (event) => (event.kind === "pull.commented" ? { ...event, data: { ...event.data, html: await decorateMentions(db, event.data.html, hosted) } } : event)));
83 },
84
85 async permissions() {
86 return policy.person ? pendingPermissions(db, row.repo_id, policy.person.id, row.head_ref) : [];
87 },
88
89 async mentions() {
90 return (await mentionStates(db, row.repo_id, row.number)).filter((mention) => mention.comment !== null);
91 },
92
93 async changes() {
94 const tips = await reviewedTips();
95 const changes = await cachedChanges(deps, row.repo_id, await handle(), tips.base, tips.head);
96 return { ...changes, commits: await withPushers(db, row.repo_id, changes.commits) };
97 },
98
99 async codeMap() {
100 const tips = await reviewedTips();
101 const opened = await handle();
102 const [changes, map] = await Promise.all([cachedChanges(deps, row.repo_id, opened, tips.base, tips.head), codeMapSummaryAt(deps.env, deps.ctx, row.repo_id, opened, tips.head)]);
103 return { head: tips.head, map, changes: codeChanges(changes) };
104 },
105
106 async comment(body, then, assign) {
107 const text = body.trim();
108 if (!text && !then) return invalid("Write a comment first.", "body");
109 const bodyProblem = firstInvalid({ body: bodyError(text, "Comment") });
110 if (bodyProblem) return bodyProblem;
111 if (then && then !== row.status) {
112 const problem = then === "open" || row.status === "merged" ? await reopenProblem() : null;
113 if (problem) return problem;
114 }
115 const change = then && then !== row.status ? { status: then, tips: then === "closed" ? await liveTips() : null } : undefined;
116 if (!text) {
117 if (change) await pulls.setPullStatus(db, actor, row, change.status, change.tips);
118 if (change?.status === "closed") captureReview("work.rejected");
119 return ok();
120 }
121 const comment = await pulls.commentOnPull(db, actor, row, text, change);
122 if (change?.status === "closed") captureReview("work.rejected");
123 await deliverMentions(deps.env, deps.ctx, actor, subject, pulls.mentionText(row, deps.origin, text), comment, { assign });
124 return ok();
125 },
126
127 async setStatus(status) {
128 if (status === row.status) return ok();
129 const problem = status === "open" || row.status === "merged" ? await reopenProblem() : null;
130 if (problem) return problem;
131 await pulls.setPullStatus(db, actor, row, status, status === "closed" ? await liveTips() : null);
132 if (status === "closed") captureReview("work.rejected");
133 return ok();
134 },
135
136 async rename(title) {
137 const text = title.trim();
138 const titleProblem = firstInvalid({ title: titleError(text) });
139 if (titleProblem) return titleProblem;
140 await pulls.renamePull(db, actor, row, text);
141 return ok();
142 },
143
144 async reviewComment({ revision, path, range, body, assign }) {
145 const text = body.trim();
146 const bodyProblem = firstInvalid({ body: requiredBodyError(text, "Comment", "Write a comment first.") });
147 if (bodyProblem) return bodyProblem;
148 const changes = await pull.changes();
149 if (revision !== changes.head) return invalid("A newer revision was pushed while you were reviewing. Reload the diff and try again.");
150 const file = changes.files.find((candidate) => candidate.path === path);
151 const rows = file?.kind === "text" ? rowsInRange(file.before ?? "", file.after ?? "", range) : null;
152 if (!rows?.length) return invalid(`Those lines are not part of the diff of ${path}.`);
153 const created = await pulls.startThread(db, actor, row, { path, range, revision, code: rows.map((line) => line.text).join("\n"), body: text });
154 const thread = (await pulls.findThread(db, row.id, created.thread))!;
155 await deliverMentions(deps.env, deps.ctx, actor, subject, pulls.threadMentionText(row, deps.origin, thread, text), created.comment, { assign, thread: thread.id });
156 return ok({ thread: created.thread });
157 },
158
159 async steer({ revision, decision, body, assign }) {
160 const text = body.trim();
161 const bodyProblem = firstInvalid({ body: requiredBodyError(text, "Comment", "Write a comment first.") });
162 if (bodyProblem) return bodyProblem;
163 const changes = await pull.changes();
164 if (revision !== changes.head) return invalid("A newer revision was pushed while you were reading. Reload and try again.");
165 const record = changes.commits.flatMap((commit) => parseDecisions(commit.message ?? "", commit.hash).decisions).find((candidate) => candidate.decisionId === decision);
166 if (!record) return invalid(`${decision} is not a decision on ${row.head_ref}.`);
167 const created = await pulls.startThread(db, actor, row, { decision, revision, code: record.decision, body: text });
168 const thread = (await pulls.findThread(db, row.id, created.thread))!;
169 await deliverMentions(deps.env, deps.ctx, actor, subject, pulls.threadMentionText(row, deps.origin, thread, text), created.comment, { assign, thread: thread.id });
170 return ok({ thread: created.thread });
171 },
172
173 async review({ revision, verdict, body }) {
174 if (actor.kind !== "human") return invalid("Only humans can submit a review verdict.");
175 const changes = await pull.changes();
176 if (revision !== changes.head) return conflict("A newer revision was pushed. Reload it before submitting your review.");
177 const summary = body.trim();
178 return pull.comment(`**${REVIEW_LABELS[verdict]} revision \`${revision.slice(0, 12)}\`**${summary ? `\n\n${summary}` : ""}`);
179 },
180
181 async branch({ from, title, instruction, assign }) {
182 const person = policy.person;
183 if (!canResolve() || !person) return invalid("Only a person with write access can branch from a pull request.");
184 const name = title.trim();
185 const text = instruction.trim();
186 const inputProblem = firstInvalid({ title: titleError(name), instruction: requiredBodyError(text, "Instruction", "Say what to try from here.") });
187 if (inputProblem) return inputProblem;
188 const changes = await pull.changes();
189 const step = changes.commits.findIndex((commit) => commit.hash === from);
190 if (from !== changes.base && step === -1) return invalid(`${from.slice(0, 7)} is not a step of this pull request.`);
191 const point = step === -1 ? `the start of #${row.number}, before its first step` : `step ${step + 1} of #${row.number}, ${from.slice(0, 7)} ${changes.commits[step].title}`;
192 const body = `Branched from ${point}.\n\n${text}`;
193 const head = await freshBranch(name);
194 const pushed = await pushRef(await handle(), `refs/heads/${head}`, "0".repeat(40), from, []);
195 if (!pushed.ok) return invalid(`Couldn't create ${head}: ${pushed.reason}.`);
196 await recordEvent(db, actor, repoStream(row.repo_id), "repo.pushed", { updates: [{ ref: `refs/heads/${head}`, from: null, to: from }] }, now()).run();
197 const created = await pulls.createPull(db, actor, { repoId: row.repo_id, title: name, body, authorId: person.id, base: row.base_ref, head, branchedFrom: { pull: row.id, commit: from } });
198 if (created.kind === "already_open") return conflict(`A pull request already proposes ${head} into ${row.base_ref}.`);
199 const number = created.number;
200 const record = await findRepoRecordById(db, row.repo_id);
201 if (record) startPullCi(deps, policy, record, { number, base: row.base_ref, head, sha: from });
202 const fresh = (await pulls.findPull(db, row.repo_id, number))!;
203 const briefing = `${text}\n\nThe branch ${head} already exists and starts at ${from} (${point}). Check it out and continue from there: decisions made after that point on ${row.head_ref} don't bind this branch.`;
204 await deliverMentions(deps.env, deps.ctx, actor, onPull(fresh), pulls.mentionText(fresh, deps.origin, briefing), null, { assign });
205 return ok({ pull: number });
206 },
207
208 async branches() {
209 return (await pulls.listBranches(db, row)).map((branch) => ({ commit: branch.branched_at!, pull: pulls.toPullSummary(branch) }));
210 },
211
212 async threads() {
213 const [records, events] = await Promise.all([pulls.listThreads(db, row.id), readStream(db, pullStream(row.id))]);
214 const changes = records.length ? await pull.changes().catch(() => null) : null;
215 const outdated = (thread: pulls.ThreadRecord) => {
216 if (!changes || thread.revision === changes.head) return false;
217 const file = changes.files.find((candidate) => candidate.path === thread.path);
218 const range = pulls.threadRange(thread);
219 if (!range) return false;
220 const rows = file?.kind === "text" ? rowsInRange(file.before ?? "", file.after ?? "", range) : null;
221 return rows?.map((line) => line.text).join("\n") !== thread.code;
222 };
223 const threadOf = (event: (typeof events)[number]) => (event.data as { thread?: number }).thread;
224 return records.map((thread) => {
225 const mine = events.filter((event) => threadOf(event) === thread.id);
226 const addressed = mine.findLast((event) => event.kind === "pull.thread_addressed");
227 const resolved = mine.findLast((event) => event.kind === "pull.thread_resolved");
228 return {
229 id: thread.id,
230 path: thread.path,
231 range: pulls.threadRange(thread),
232 decision: thread.decision_id,
233 revision: thread.revision,
234 code: thread.code,
235 status: thread.status,
236 addressed: thread.status === "addressed" && addressed ? { commit: thread.addressed_commit!, by: addressed.by, at: addressed.at } : null,
237 resolved: thread.status === "resolved" && resolved ? { by: resolved.by, at: resolved.at } : null,
238 comments: mine.filter((event) => event.kind === "pull.commented").map((event) => event.id),
239 outdated: outdated(thread),
240 };
241 });
242 },
243
244 async replyToThread(id, body, assign) {
245 const thread = await pulls.findThread(db, row.id, id);
246 if (!thread) raise("not_found", `No review thread ${id} on pull request #${row.number}.`);
247 const text = body.trim();
248 const bodyProblem = firstInvalid({ body: requiredBodyError(text, "Reply", "Write a reply first.") });
249 if (bodyProblem) return bodyProblem;
250 const comment = await pulls.commentOnPull(db, actor, row, text, undefined, thread.id);
251 await deliverMentions(deps.env, deps.ctx, actor, subject, pulls.threadMentionText(row, deps.origin, thread, text), comment, { assign, thread: thread.id });
252 return ok();
253 },
254
255 async mergeability() {
256 const plan = await planMerge();
257 if ("problem" in plan) return { state: "unavailable", reason: plan.problem! };
258 return plan.merged.conflicts.length ? { state: "conflicts", paths: plan.merged.conflicts } : { state: "clean" };
259 },
260
261 async merge() {
262 const person = policy.person;
263 if (!canResolve() || !person) return invalid("Only a person with write access can merge a pull request.");
264 const plan = await planMerge();
265 if ("problem" in plan) return invalid(plan.problem!);
266 const { opened, tips, merged } = plan;
267 if (merged.conflicts.length) return invalid(`${merged.conflicts.length === 1 ? "A file conflicts" : `${merged.conflicts.length} files conflict`} with ${row.base_ref}: ${merged.conflicts.slice(0, 5).join(", ")}. Merge ${row.base_ref} into ${row.head_ref} locally and push to resolve.`);
268 const empty = merged.tree === null ? await gitObject("tree", treeBody([])) : null;
269 const at = now();
270 const commit = await gitObject(
271 "commit",
272 commitBody({ tree: merged.tree ?? empty!.hash, parents: [tips.base, tips.head], author: { name: person.name, email: person.email }, at, message: `Merge pull request #${row.number} from ${row.head_ref}\n\n${row.title}` }),
273 );
274 const ref = `refs/heads/${row.base_ref}`;
275 const pushed = await pushRef(opened, ref, tips.base, commit.hash, [...merged.objects, ...(empty ? [empty] : []), commit]);
276 if (!pushed.ok) return invalid(`Couldn't merge: ${pushed.reason}. If ${row.base_ref} just moved, reload and try again.`);
277 await db.batch([...pulls.markMerged(db, actor, row, tips, at), recordEvent(db, actor, repoStream(row.repo_id), "repo.pushed", { updates: [{ ref, from: tips.base, to: commit.hash }] }, at)]);
278 captureWorkEvent(deps.env, deps.ctx, actor, { name: "work.landed", repoId: row.repo_id, namespaceId, branch: row.head_ref, mergeMethod: "web" });
279 return ok({ commit: commit.hash });
280 },
281
282 async resolveThread(id) {
283 if (!canResolve()) return invalid("Only a person with write access can resolve a review thread.");
284 const thread = await pulls.findThread(db, row.id, id);
285 if (!thread) raise("not_found", `No review thread ${id} on pull request #${row.number}.`);
286 if (thread.status !== "resolved") {
287 await pulls.setThreadStatus(db, actor, row, thread, "resolved");
288 captureReview("review.thread_resolved");
289 }
290 return ok();
291 },
292
293 async reopenThread(id) {
294 if (!canResolve()) return invalid("Only a person with write access can reopen a review thread.");
295 const thread = await pulls.findThread(db, row.id, id);
296 if (!thread) raise("not_found", `No review thread ${id} on pull request #${row.number}.`);
297 if (thread.status !== "open") await pulls.setThreadStatus(db, actor, row, thread, "open");
298 return ok();
299 },
300 };
301 return pull;
302}