import { parseDecisions, reviewCommits, type CommitReview, type ReviewedCommit } from "@refs/protocol"; import { dropBytes, EMPTY_PACK, receivePack, reportPush, ZERO_OID, type ReceiveCommands } from "./git.ts"; import { setThreadStatus, type ThreadRecord } from "./pulls.ts"; import { now } from "./auth.ts"; import { recordPushers, type Recorder } from "./events.ts"; import type { RefUpdate } from "./git.ts"; import type { RepoRecord } from "./repos.ts"; const MAX_COMMITS_PER_UPDATE = 200; /** Commits an update added to its branch, oldest first: back to the history of `from`, or for a new branch, of the default branch. */ async function addedCommits(repo: ArtifactsRepo, update: RefUpdate, defaultBranch: string): Promise { if (!update.to) return []; const base = new Set((await repo.log({ ref: update.from ?? defaultBranch, limit: 1000 })).map((commit) => commit.hash)); const added: ReviewedCommit[] = []; for (const commit of await repo.log({ ref: update.to, limit: MAX_COMMITS_PER_UPDATE })) { if (base.has(commit.hash)) break; added.push({ hash: commit.hash, message: commit.message, parents: commit.parents }); } return added.reverse(); } /** The decision ids the records in `commits` supersede that the origin already holds from other commits. */ async function knownDecisions(db: D1Database, commits: readonly ReviewedCommit[]): Promise> { const referenced = commits.flatMap((commit) => parseDecisions(commit.message, commit.hash).decisions.flatMap((record) => record.supersedes)); const { results } = await db .prepare("SELECT id FROM decisions WHERE id IN (SELECT value FROM json_each(?)) AND commit_sha NOT IN (SELECT value FROM json_each(?))") .bind(JSON.stringify(referenced), JSON.stringify(commits.map((commit) => commit.hash))) .all<{ id: string }>(); return new Set(results.map((row) => row.id)); } /** * Indexes the decision records a push added to its branches. Agent pushes were checked before they landed; * records that still fail the check, from human pushes or pushes refs found itself, are skipped. * Records belong to the pushing agent's session, or to no session otherwise. * Safe to repeat for the same push: a record is not a duplicate of itself from the same commit. */ export async function indexPush(env: Env, actor: Recorder, repo: RepoRecord, updates: readonly RefUpdate[]): Promise<{ commits: number; decisions: number }> { const db = env.DB; const branches = updates.filter((update) => update.ref.startsWith("refs/heads/")); if (!branches.length) return { commits: 0, decisions: 0 }; using artifacts = await env.ARTIFACTS.get(repo.artifacts_name); const commits = (await Promise.all(branches.map((update) => addedCommits(artifacts, update, repo.default_branch)))).flat(); if (!commits.length) return { commits: 0, decisions: 0 }; const pushers = recordPushers(db, actor, repo.id, commits.map((commit) => commit.hash)); if (pushers.length) await db.batch(pushers); const review = reviewCommits(commits, { known: await knownDecisions(db, commits) }); const indexed = { commits: commits.length, decisions: review.records.length }; if (!review.records.length) return indexed; const at = now(); await db.batch( review.records.flatMap(({ commit, record }) => [ 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), 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)), ]), ); await addressSteers(db, actor, repo, review.records); return indexed; } const TEMPLATE = ["```decision", "decision: ", "reason:", " - ", "to_reverse: ", "```"]; /** More decisions than this in one push make refs remind the agent what a decision is. */ const MANY_DECISIONS = 3; /** The `remote:` lines that tell an agent why its push was refused and how to fix it. */ export function explainProblems(commits: readonly ReviewedCommit[], problems: CommitReview["problems"]): string[] { const subject = new Map(commits.map((commit) => [commit.hash, commit.message.split("\n", 1)[0]])); const order = [...new Set(problems.map((problem) => problem.commit))]; return [ "refs did not accept this push: a decision record in it is not valid.", "", ...order.flatMap((commit) => [`${commit.slice(0, 7)} ${subject.get(commit) ?? ""}`, ...problems.filter((problem) => problem.commit === commit).map((problem) => ` ${problem.message}`)]), "", "A decision record is a block like this at the end of the commit message:", "", ...TEMPLATE, "", "Optional lists: alternatives_considered, assumptions, affected_components, evidence, supersedes.", 'rejected takes "name: reason" lines. A commit that decides nothing needs no block.', "Record a decision only when the owner of the work would want to make the choice themselves.", "Fix the last commit with git commit --amend, then push again.", "Push after every commit, so that only the last commit can need a fix.", ]; } /** * Lands an agent's push on its branch only if every decision record in its new commits is valid. The pack goes * to a quarantine ref first, so the commits can be read; then the branch moves to them atomically, or * the push is refused with `remote:` lines that explain the fix. Human pushes never come here. */ export async function admitAgentPush(env: Env, repo: RepoRecord, commands: ReceiveCommands, body: ReadableStream): Promise<{ response: Response; landed: boolean }> { const [update] = commands.updates; const refuse = (reason: string, messages: string[] = []) => ({ response: reportPush(commands, new Map([[update.ref, reason]]), messages), landed: false }); using artifacts = await env.ARTIFACTS.get(repo.artifacts_name); const quarantine = `refs/quarantine/${crypto.randomUUID()}`; const staged = await receivePack(artifacts, [`${ZERO_OID} ${update.to} ${quarantine}`], commands.capabilities, dropBytes(body, commands.length)); if (staged.unpack !== "ok") return refuse(`unpack failed: ${staged.unpack}`); if (staged.refs.get(quarantine) !== null) return refuse(staged.refs.get(quarantine) ?? "refs could not store the pack"); let released = false; try { const commits = await addedCommits(artifacts, update, repo.default_branch); const review = reviewCommits(commits, { known: await knownDecisions(env.DB, commits), strict: true }); if (review.problems.length) return refuse(`${review.problems[0].commit.slice(0, 7)} ${review.problems[0].message}`, explainProblems(commits, review.problems)); const moved = await receivePack(artifacts, [`${update.from ?? ZERO_OID} ${update.to} ${update.ref}`, `${update.to} ${ZERO_OID} ${quarantine}`], [], EMPTY_PACK); released = moved.refs.get(quarantine) === null; const reason = moved.refs.has(update.ref) ? moved.refs.get(update.ref)! : `refs could not update the branch: ${moved.unpack}`; if (reason !== null) return refuse(reason === "stale ref" ? "fetch first: the branch moved while refs checked this push" : reason); const recorded = review.records.map(({ commit, record }) => `${record.decisionId} ${commit.slice(0, 7)} ${record.decision}`); 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."] : []; return { response: reportPush(commands, new Map([[update.ref, null]]), recorded.length ? ["refs recorded these decisions:", ...recorded, ...reminder] : []), landed: true }; } finally { if (!released) await receivePack(artifacts, [`${update.to} ${ZERO_OID} ${quarantine}`], [], new Uint8Array()).catch((error) => console.error(`quarantine ${quarantine} not released`, error)); } } /** Marks open threads on the decisions these records supersede as addressed by the commit that carries each record. */ export async function addressSteers(db: D1Database, actor: Recorder, repo: RepoRecord, records: CommitReview["records"]): Promise { const superseding = new Map(records.flatMap(({ commit, record }) => record.supersedes.map((id) => [id, commit] as const))); if (!superseding.size) return; const { results } = await db .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(?))") .bind(repo.id, JSON.stringify([...superseding.keys()])) .all(); for (const thread of results) await setThreadStatus(db, actor, { id: thread.pull_id }, thread, "addressed", superseding.get(thread.decision_id!)!); }