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