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