131 lines · 9.0 KBRaw
| 1 | import { parseDecisions, reviewCommits, type CommitReview, type ReviewedCommit } from "@refs/protocol"; |
| 2 | import { dropBytes, EMPTY_PACK, receivePack, reportPush, ZERO_OID, type ReceiveCommands } from "./git.ts"; |
| 3 | import { setThreadStatus, type ThreadRecord } from "./pulls.ts"; |
| 4 | import { now } from "./auth.ts"; |
| 5 | import { recordPushers, type Recorder } from "./events.ts"; |
| 6 | import type { RefUpdate } from "./git.ts"; |
| 7 | import type { RepoRecord } from "./repos.ts"; |
| 8 | |
| 9 | const MAX_COMMITS_PER_UPDATE = 200; |
| 10 | |
| 11 | /** Commits an update added to its branch, oldest first: back to the history of `from`, or for a new branch, of the default branch. */ |
| 12 | async function addedCommits(repo: ArtifactsRepo, update: RefUpdate, defaultBranch: string): Promise<ReviewedCommit[]> { |
| 13 | if (!update.to) return []; |
| 14 | const base = new Set((await repo.log({ ref: update.from ?? defaultBranch, limit: 1000 })).map((commit) => commit.hash)); |
| 15 | const added: ReviewedCommit[] = []; |
| 16 | for (const commit of await repo.log({ ref: update.to, limit: MAX_COMMITS_PER_UPDATE })) { |
| 17 | if (base.has(commit.hash)) break; |
| 18 | added.push({ hash: commit.hash, message: commit.message, parents: commit.parents }); |
| 19 | } |
| 20 | return added.reverse(); |
| 21 | } |
| 22 | |
| 23 | /** The decision ids the records in `commits` supersede that the origin already holds from other commits. */ |
| 24 | async function knownDecisions(db: D1Database, commits: readonly ReviewedCommit[]): Promise<Set<string>> { |
| 25 | const referenced = commits.flatMap((commit) => parseDecisions(commit.message, commit.hash).decisions.flatMap((record) => record.supersedes)); |
| 26 | const { results } = await db |
| 27 | .prepare("SELECT id FROM decisions WHERE id IN (SELECT value FROM json_each(?)) AND commit_sha NOT IN (SELECT value FROM json_each(?))") |
| 28 | .bind(JSON.stringify(referenced), JSON.stringify(commits.map((commit) => commit.hash))) |
| 29 | .all<{ id: string }>(); |
| 30 | return new Set(results.map((row) => row.id)); |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Indexes the decision records a push added to its branches. Agent pushes were checked before they landed; |
| 35 | * records that still fail the check, from human pushes or pushes refs found itself, are skipped. |
| 36 | * Records belong to the pushing agent's session, or to no session otherwise. |
| 37 | * Safe to repeat for the same push: a record is not a duplicate of itself from the same commit. |
| 38 | */ |
| 39 | export async function indexPush(env: Env, actor: Recorder, repo: RepoRecord, updates: readonly RefUpdate[]): Promise<{ commits: number; decisions: number }> { |
| 40 | const db = env.DB; |
| 41 | const branches = updates.filter((update) => update.ref.startsWith("refs/heads/")); |
| 42 | if (!branches.length) return { commits: 0, decisions: 0 }; |
| 43 | using artifacts = await env.ARTIFACTS.get(repo.artifacts_name); |
| 44 | const commits = (await Promise.all(branches.map((update) => addedCommits(artifacts, update, repo.default_branch)))).flat(); |
| 45 | if (!commits.length) return { commits: 0, decisions: 0 }; |
| 46 | const pushers = recordPushers(db, actor, repo.id, commits.map((commit) => commit.hash)); |
| 47 | if (pushers.length) await db.batch(pushers); |
| 48 | |
| 49 | const review = reviewCommits(commits, { known: await knownDecisions(db, commits) }); |
| 50 | const indexed = { commits: commits.length, decisions: review.records.length }; |
| 51 | if (!review.records.length) return indexed; |
| 52 | const at = now(); |
| 53 | await db.batch( |
| 54 | review.records.flatMap(({ commit, record }) => [ |
| 55 | db.prepare("INSERT OR IGNORE INTO decisions (id, session_id, commit_sha, data, created_at) VALUES (?, ?, ?, ?, ?)").bind(record.decisionId, actor.kind === "agent" ? actor.sessionId : null, commit, JSON.stringify(record), at), |
| 56 | db.prepare("UPDATE decisions SET superseded_by = ? WHERE id IN (SELECT value FROM json_each(?)) AND superseded_by IS NULL").bind(record.decisionId, JSON.stringify(record.supersedes)), |
| 57 | ]), |
| 58 | ); |
| 59 | await addressSteers(db, actor, repo, review.records); |
| 60 | return indexed; |
| 61 | } |
| 62 | |
| 63 | const TEMPLATE = ["```decision", "decision: <what you chose, in one or two full sentences that a person who does not code understands>", "reason:", " - <why, in one full sentence: say who does what, and give the real case>", "to_reverse: <what people must do if this decision changes later>", "```"]; |
| 64 | |
| 65 | /** More decisions than this in one push make refs remind the agent what a decision is. */ |
| 66 | const MANY_DECISIONS = 3; |
| 67 | |
| 68 | /** The `remote:` lines that tell an agent why its push was refused and how to fix it. */ |
| 69 | export function explainProblems(commits: readonly ReviewedCommit[], problems: CommitReview["problems"]): string[] { |
| 70 | const subject = new Map(commits.map((commit) => [commit.hash, commit.message.split("\n", 1)[0]])); |
| 71 | const order = [...new Set(problems.map((problem) => problem.commit))]; |
| 72 | return [ |
| 73 | "refs did not accept this push: a decision record in it is not valid.", |
| 74 | "", |
| 75 | ...order.flatMap((commit) => [`${commit.slice(0, 7)} ${subject.get(commit) ?? ""}`, ...problems.filter((problem) => problem.commit === commit).map((problem) => ` ${problem.message}`)]), |
| 76 | "", |
| 77 | "A decision record is a block like this at the end of the commit message:", |
| 78 | "", |
| 79 | ...TEMPLATE, |
| 80 | "", |
| 81 | "Optional lists: alternatives_considered, assumptions, affected_components, evidence, supersedes.", |
| 82 | 'rejected takes "name: reason" lines. A commit that decides nothing needs no block.', |
| 83 | "Record a decision only when the owner of the work would want to make the choice themselves.", |
| 84 | "Fix the last commit with git commit --amend, then push again.", |
| 85 | "Push after every commit, so that only the last commit can need a fix.", |
| 86 | ]; |
| 87 | } |
| 88 | |
| 89 | /** |
| 90 | * Lands an agent's push on its branch only if every decision record in its new commits is valid. The pack goes |
| 91 | * to a quarantine ref first, so the commits can be read; then the branch moves to them atomically, or |
| 92 | * the push is refused with `remote:` lines that explain the fix. Human pushes never come here. |
| 93 | */ |
| 94 | export async function admitAgentPush(env: Env, repo: RepoRecord, commands: ReceiveCommands, body: ReadableStream<Uint8Array>): Promise<{ response: Response; landed: boolean }> { |
| 95 | const [update] = commands.updates; |
| 96 | const refuse = (reason: string, messages: string[] = []) => ({ response: reportPush(commands, new Map([[update.ref, reason]]), messages), landed: false }); |
| 97 | using artifacts = await env.ARTIFACTS.get(repo.artifacts_name); |
| 98 | const quarantine = `refs/quarantine/${crypto.randomUUID()}`; |
| 99 | |
| 100 | const staged = await receivePack(artifacts, [`${ZERO_OID} ${update.to} ${quarantine}`], commands.capabilities, dropBytes(body, commands.length)); |
| 101 | if (staged.unpack !== "ok") return refuse(`unpack failed: ${staged.unpack}`); |
| 102 | if (staged.refs.get(quarantine) !== null) return refuse(staged.refs.get(quarantine) ?? "refs could not store the pack"); |
| 103 | |
| 104 | let released = false; |
| 105 | try { |
| 106 | const commits = await addedCommits(artifacts, update, repo.default_branch); |
| 107 | const review = reviewCommits(commits, { known: await knownDecisions(env.DB, commits), strict: true }); |
| 108 | if (review.problems.length) return refuse(`${review.problems[0].commit.slice(0, 7)} ${review.problems[0].message}`, explainProblems(commits, review.problems)); |
| 109 | |
| 110 | const moved = await receivePack(artifacts, [`${update.from ?? ZERO_OID} ${update.to} ${update.ref}`, `${update.to} ${ZERO_OID} ${quarantine}`], [], EMPTY_PACK); |
| 111 | released = moved.refs.get(quarantine) === null; |
| 112 | const reason = moved.refs.has(update.ref) ? moved.refs.get(update.ref)! : `refs could not update the branch: ${moved.unpack}`; |
| 113 | if (reason !== null) return refuse(reason === "stale ref" ? "fetch first: the branch moved while refs checked this push" : reason); |
| 114 | const recorded = review.records.map(({ commit, record }) => `${record.decisionId} ${commit.slice(0, 7)} ${record.decision}`); |
| 115 | const reminder = recorded.length > MANY_DECISIONS ? ["", `This push records ${recorded.length} decisions for a person to read. Most pull requests need 0 to ${MANY_DECISIONS}.`, "Record only a choice that the owner of the work would want to make themselves."] : []; |
| 116 | return { response: reportPush(commands, new Map([[update.ref, null]]), recorded.length ? ["refs recorded these decisions:", ...recorded, ...reminder] : []), landed: true }; |
| 117 | } finally { |
| 118 | if (!released) await receivePack(artifacts, [`${update.to} ${ZERO_OID} ${quarantine}`], [], new Uint8Array()).catch((error) => console.error(`quarantine ${quarantine} not released`, error)); |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | /** Marks open threads on the decisions these records supersede as addressed by the commit that carries each record. */ |
| 123 | export async function addressSteers(db: D1Database, actor: Recorder, repo: RepoRecord, records: CommitReview["records"]): Promise<void> { |
| 124 | const superseding = new Map(records.flatMap(({ commit, record }) => record.supersedes.map((id) => [id, commit] as const))); |
| 125 | if (!superseding.size) return; |
| 126 | const { results } = await db |
| 127 | .prepare("SELECT t.* FROM review_threads t JOIN pulls p ON p.id = t.pull_id WHERE p.repo_id = ? AND t.status = 'open' AND t.decision_id IN (SELECT value FROM json_each(?))") |
| 128 | .bind(repo.id, JSON.stringify([...superseding.keys()])) |
| 129 | .all<ThreadRecord>(); |
| 130 | for (const thread of results) await setThreadStatus(db, actor, { id: thread.pull_id }, thread, "addressed", superseding.get(thread.decision_id!)!); |
| 131 | } |