import { listAgents } from "../agents.ts"; import { now } from "../auth.ts"; import { mergeBase, readCommit, readTree, rowsInRange } from "../diff.ts"; import { commitBody, gitObject, mergeTrees, pushRef, treeBody } from "../gitwrite.ts"; import type { Outcome } from "../contract/common.ts"; import type { ReviewVerdict } from "../contract/handles.ts"; import type { Pull } from "../contract/handles.ts"; import { decorateMentions, deliverMentions, mentionStates, onPull } from "../mentions.ts"; import { pullStream, recordEvent, readStream, repoStream, withPushers } from "../events.ts"; import { type Refs as GitRefs } from "../git.ts"; import { conflict, firstInvalid, invalid, ok, problem, raise } from "../outcomes.ts"; import { Policy, type RepoFacts } from "../policy.ts"; import { pendingPermissions } from "../permissions.ts"; import * as pulls from "../pulls.ts"; import { bodyError, requiredBodyError, titleError } from "../text.ts"; import { codeChanges, codeMapSummaryAt } from "../code-maps.ts"; import { cachedChanges, type Deps } from "./context.ts"; import { startPullCi } from "./ci.ts"; import { findRepoRecordById } from "../repos.ts"; import { parseDecisions } from "@refs/protocol"; const REVIEW_LABELS: Record = { comment: "Reviewed", approve: "Approved", "request-changes": "Requested changes" }; export function openPull(deps: Deps, policy: Policy, row: pulls.PullRecord, facts: RepoFacts, namespaceId: string, handle: () => Promise, gitRefs: () => Promise): Pull { const db = deps.env.DB; const actor = policy.actor; async function liveTips(): Promise<{ base: string; head: string } | null> { const branches = (await gitRefs()).branches; const base = branches.get(row.base_ref); const head = branches.get(row.head_ref); return base && head ? { base, head } : null; } /** While open, the live branches; once merged or closed, the commits they pointed at then. */ async function reviewedTips(): Promise<{ base: string; head: string }> { const tips = row.base_sha && row.head_sha ? { base: row.base_sha, head: row.head_sha } : await liveTips(); return tips ?? raise("not_found", `The ${row.head_ref} or ${row.base_ref} branch no longer exists.`); } async function reopenProblem(): Promise { if (row.status === "merged") return invalid("A merged pull request can't be closed or reopened."); 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"); return clash ? invalid(`Pull request #${clash} is already open for these branches.`) : null; } const subject = onPull(row); /** A branch name from `title` that the repository doesn't have yet and that agents may push. */ async function freshBranch(title: string): Promise { const [{ branches }, base] = await Promise.all([gitRefs(), db.prepare("SELECT default_branch FROM repos WHERE id = ?").bind(row.repo_id).first("default_branch")]); return pulls.freshBranchName(title, branches, base!); } const canResolve = () => policy.actor.kind === "human" && policy.canWriteRepo(facts); /** What merging would produce right now: the tips it was computed from and the merged tree, or why it can't. */ async function planMerge() { if (row.status !== "open") return { problem: "This pull request is not open." } as const; const tips = await liveTips(); if (!tips) return { problem: `The ${row.head_ref} or ${row.base_ref} branch no longer exists.` } as const; const opened = await handle(); const common = await mergeBase(opened, tips.base, tips.head); if (common === tips.head) return { problem: `${row.base_ref} already contains every commit on ${row.head_ref}.` } as const; const [baseCommit, ourCommit, theirCommit] = await Promise.all([readCommit(opened, common), readCommit(opened, tips.base), readCommit(opened, tips.head)]); if (!baseCommit || !ourCommit || !theirCommit) return { problem: "A commit of this pull request could not be read." } as const; const merged = await mergeTrees((hash) => readTree(opened, hash), baseCommit.treeHash, ourCommit.treeHash, theirCommit.treeHash); return { opened, tips, merged } as const; } const pull: Pull = { detail: pulls.toPullDetail(row), async timeline() { const [events, agents] = await Promise.all([readStream(db, pullStream(row.id)), listAgents(db, namespaceId, row.repo_id)]); const hosted = agents.filter((agent) => !agent.replaced).map((agent) => agent.handle); return Promise.all(events.map(async (event) => (event.kind === "pull.commented" ? { ...event, data: { ...event.data, html: await decorateMentions(db, event.data.html, hosted) } } : event))); }, async permissions() { return policy.person ? pendingPermissions(db, row.repo_id, policy.person.id, row.head_ref) : []; }, async mentions() { return (await mentionStates(db, row.repo_id, row.number)).filter((mention) => mention.comment !== null); }, async changes() { const tips = await reviewedTips(); const changes = await cachedChanges(deps, row.repo_id, await handle(), tips.base, tips.head); return { ...changes, commits: await withPushers(db, row.repo_id, changes.commits) }; }, async codeMap() { const tips = await reviewedTips(); const opened = await handle(); 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)]); return { head: tips.head, map, changes: codeChanges(changes) }; }, async comment(body, then, assign) { const text = body.trim(); if (!text && !then) return invalid("Write a comment first.", "body"); const bodyProblem = firstInvalid({ body: bodyError(text, "Comment") }); if (bodyProblem) return bodyProblem; if (then && then !== row.status) { const problem = then === "open" || row.status === "merged" ? await reopenProblem() : null; if (problem) return problem; } const change = then && then !== row.status ? { status: then, tips: then === "closed" ? await liveTips() : null } : undefined; if (!text) { if (change) await pulls.setPullStatus(db, actor, row, change.status, change.tips); return ok(); } const comment = await pulls.commentOnPull(db, actor, row, text, change); await deliverMentions(deps.env, deps.ctx, actor, subject, pulls.mentionText(row, deps.origin, text), comment, { assign }); return ok(); }, async setStatus(status) { if (status === row.status) return ok(); const problem = status === "open" || row.status === "merged" ? await reopenProblem() : null; if (problem) return problem; await pulls.setPullStatus(db, actor, row, status, status === "closed" ? await liveTips() : null); return ok(); }, async rename(title) { const text = title.trim(); const titleProblem = firstInvalid({ title: titleError(text) }); if (titleProblem) return titleProblem; await pulls.renamePull(db, actor, row, text); return ok(); }, async reviewComment({ revision, path, range, body, assign }) { const text = body.trim(); const bodyProblem = firstInvalid({ body: requiredBodyError(text, "Comment", "Write a comment first.") }); if (bodyProblem) return bodyProblem; const changes = await pull.changes(); if (revision !== changes.head) return invalid("A newer revision was pushed while you were reviewing. Reload the diff and try again."); const file = changes.files.find((candidate) => candidate.path === path); const rows = file?.kind === "text" ? rowsInRange(file.before ?? "", file.after ?? "", range) : null; if (!rows?.length) return invalid(`Those lines are not part of the diff of ${path}.`); const created = await pulls.startThread(db, actor, row, { path, range, revision, code: rows.map((line) => line.text).join("\n"), body: text }); const thread = (await pulls.findThread(db, row.id, created.thread))!; await deliverMentions(deps.env, deps.ctx, actor, subject, pulls.threadMentionText(row, deps.origin, thread, text), created.comment, { assign, thread: thread.id }); return ok({ thread: created.thread }); }, async steer({ revision, decision, body, assign }) { const text = body.trim(); const bodyProblem = firstInvalid({ body: requiredBodyError(text, "Comment", "Write a comment first.") }); if (bodyProblem) return bodyProblem; const changes = await pull.changes(); if (revision !== changes.head) return invalid("A newer revision was pushed while you were reading. Reload and try again."); const record = changes.commits.flatMap((commit) => parseDecisions(commit.message ?? "", commit.hash).decisions).find((candidate) => candidate.decisionId === decision); if (!record) return invalid(`${decision} is not a decision on ${row.head_ref}.`); const created = await pulls.startThread(db, actor, row, { decision, revision, code: record.decision, body: text }); const thread = (await pulls.findThread(db, row.id, created.thread))!; await deliverMentions(deps.env, deps.ctx, actor, subject, pulls.threadMentionText(row, deps.origin, thread, text), created.comment, { assign, thread: thread.id }); return ok({ thread: created.thread }); }, async review({ revision, verdict, body }) { if (actor.kind !== "human") return invalid("Only humans can submit a review verdict."); const changes = await pull.changes(); if (revision !== changes.head) return conflict("A newer revision was pushed. Reload it before submitting your review."); const summary = body.trim(); return pull.comment(`**${REVIEW_LABELS[verdict]} revision \`${revision.slice(0, 12)}\`**${summary ? `\n\n${summary}` : ""}`); }, async branch({ from, title, instruction, assign }) { const person = policy.person; if (!canResolve() || !person) return invalid("Only a person with write access can branch from a pull request."); const name = title.trim(); const text = instruction.trim(); const inputProblem = firstInvalid({ title: titleError(name), instruction: requiredBodyError(text, "Instruction", "Say what to try from here.") }); if (inputProblem) return inputProblem; const changes = await pull.changes(); const step = changes.commits.findIndex((commit) => commit.hash === from); if (from !== changes.base && step === -1) return invalid(`${from.slice(0, 7)} is not a step of this pull request.`); 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}`; const body = `Branched from ${point}.\n\n${text}`; const head = await freshBranch(name); const pushed = await pushRef(await handle(), `refs/heads/${head}`, "0".repeat(40), from, []); if (!pushed.ok) return invalid(`Couldn't create ${head}: ${pushed.reason}.`); await recordEvent(db, actor, repoStream(row.repo_id), "repo.pushed", { updates: [{ ref: `refs/heads/${head}`, from: null, to: from }] }, now()).run(); 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 } }); if (created.kind === "already_open") return conflict(`A pull request already proposes ${head} into ${row.base_ref}.`); const number = created.number; const record = await findRepoRecordById(db, row.repo_id); if (record) startPullCi(deps, policy, record, { number, base: row.base_ref, head, sha: from }); const fresh = (await pulls.findPull(db, row.repo_id, number))!; 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.`; await deliverMentions(deps.env, deps.ctx, actor, onPull(fresh), pulls.mentionText(fresh, deps.origin, briefing), null, { assign }); return ok({ pull: number }); }, async branches() { return (await pulls.listBranches(db, row)).map((branch) => ({ commit: branch.branched_at!, pull: pulls.toPullSummary(branch) })); }, async threads() { const [records, events] = await Promise.all([pulls.listThreads(db, row.id), readStream(db, pullStream(row.id))]); const changes = records.length ? await pull.changes().catch(() => null) : null; const outdated = (thread: pulls.ThreadRecord) => { if (!changes || thread.revision === changes.head) return false; const file = changes.files.find((candidate) => candidate.path === thread.path); const range = pulls.threadRange(thread); if (!range) return false; const rows = file?.kind === "text" ? rowsInRange(file.before ?? "", file.after ?? "", range) : null; return rows?.map((line) => line.text).join("\n") !== thread.code; }; const threadOf = (event: (typeof events)[number]) => (event.data as { thread?: number }).thread; return records.map((thread) => { const mine = events.filter((event) => threadOf(event) === thread.id); const addressed = mine.findLast((event) => event.kind === "pull.thread_addressed"); const resolved = mine.findLast((event) => event.kind === "pull.thread_resolved"); return { id: thread.id, path: thread.path, range: pulls.threadRange(thread), decision: thread.decision_id, revision: thread.revision, code: thread.code, status: thread.status, addressed: thread.status === "addressed" && addressed ? { commit: thread.addressed_commit!, by: addressed.by, at: addressed.at } : null, resolved: thread.status === "resolved" && resolved ? { by: resolved.by, at: resolved.at } : null, comments: mine.filter((event) => event.kind === "pull.commented").map((event) => event.id), outdated: outdated(thread), }; }); }, async replyToThread(id, body, assign) { const thread = await pulls.findThread(db, row.id, id); if (!thread) raise("not_found", `No review thread ${id} on pull request #${row.number}.`); const text = body.trim(); const bodyProblem = firstInvalid({ body: requiredBodyError(text, "Reply", "Write a reply first.") }); if (bodyProblem) return bodyProblem; const comment = await pulls.commentOnPull(db, actor, row, text, undefined, thread.id); await deliverMentions(deps.env, deps.ctx, actor, subject, pulls.threadMentionText(row, deps.origin, thread, text), comment, { assign, thread: thread.id }); return ok(); }, async mergeability() { const plan = await planMerge(); if ("problem" in plan) return { state: "unavailable", reason: plan.problem! }; return plan.merged.conflicts.length ? { state: "conflicts", paths: plan.merged.conflicts } : { state: "clean" }; }, async merge() { const person = policy.person; if (!canResolve() || !person) return invalid("Only a person with write access can merge a pull request."); const plan = await planMerge(); if ("problem" in plan) return invalid(plan.problem!); const { opened, tips, merged } = plan; 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.`); const empty = merged.tree === null ? await gitObject("tree", treeBody([])) : null; const at = now(); const commit = await gitObject( "commit", 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}` }), ); const ref = `refs/heads/${row.base_ref}`; const pushed = await pushRef(opened, ref, tips.base, commit.hash, [...merged.objects, ...(empty ? [empty] : []), commit]); if (!pushed.ok) return invalid(`Couldn't merge: ${pushed.reason}. If ${row.base_ref} just moved, reload and try again.`); 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)]); return ok({ commit: commit.hash }); }, async resolveThread(id) { if (!canResolve()) return invalid("Only a person with write access can resolve a review thread."); const thread = await pulls.findThread(db, row.id, id); if (!thread) raise("not_found", `No review thread ${id} on pull request #${row.number}.`); if (thread.status !== "resolved") await pulls.setThreadStatus(db, actor, row, thread, "resolved"); return ok(); }, async reopenThread(id) { if (!canResolve()) return invalid("Only a person with write access can reopen a review thread."); const thread = await pulls.findThread(db, row.id, id); if (!thread) raise("not_found", `No review thread ${id} on pull request #${row.number}.`); if (thread.status !== "open") await pulls.setThreadStatus(db, actor, row, thread, "open"); return ok(); }, }; return pull; }