import { now } from "./auth.ts"; import { captureWorkEvent } from "./analytics.ts"; import { recordEvent, repoStream } from "./events.ts"; import { parseGitRoute, proxyGit, readReceiveCommands, rejectPush, scopeFor, type RefUpdate } from "./git.ts"; import { admitAgentPush } from "./decisions.ts"; import type { Actor } from "./contract/actor.ts"; import { resolveActor } from "./identity.ts"; import { oauth } from "./oauth.ts"; import { ok } from "./outcomes.ts"; import { heldBranch, Policy } from "./policy.ts"; import { findRepoRecord, namespacePolicy, repoFacts } from "./repos.ts"; import { pusher, type PushMessage } from "./pushes.ts"; import { claimableBranch, refProblem } from "@refs/protocol"; export async function serveGit(env: Env, ctx: ExecutionContext, request: Request): Promise { const route = parseGitRoute(request.method, new URL(request.url)); if (!route) return null; const unauthorized = () => new Response("Authentication required\n", { status: 401, headers: { "www-authenticate": 'Basic realm="refs"' } }); const { actor, badCredentials } = await resolveActor(env.DB, ctx, request, oauth(env)); if (badCredentials) return unauthorized(); const record = await findRepoRecord(env.DB, route.repo); const policy = record ? await namespacePolicy(env.DB, new Policy(actor, null), record.namespace_id) : new Policy(actor, null); const facts = record ? repoFacts(record) : null; const allowed = facts !== null && policy.canSeeRepo(facts) && (scopeFor(route.service) === "read" || policy.canWriteRepo(facts)); if (!allowed) return policy.signedIn ? new Response("Repository not found\n", { status: 404 }) : unauthorized(); if (route.suffix !== "/git-receive-pack" || !request.body) return proxyGit(request, env.ARTIFACTS, record!.artifacts_name, route); const [forwarded, inspected] = request.body.tee(); const commands = readReceiveCommands(inspected); if (actor.kind === "agent") { const received = await commands; const branch = heldBranch(actor.grant); const claim = branch === null ? claimableBranch(received.updates, record!.default_branch) : null; const reasons = new Map(); for (const update of received.updates) { const reason = claim ? null : refProblem(branch, update); if (reason) reasons.set(update.ref, reason); } if (reasons.size) { ctx.waitUntil(forwarded.cancel()); return rejectPush(received, reasons); } const admitted = await admitAgentPush(env, record!, received, forwarded); if (admitted.landed && claim) await claimBranch(env.DB, actor, record!.id, claim); if (admitted.landed) { ctx.waitUntil(queuePush(env, record!.id, actor, received.updates)); captureWorkEvent(env, ctx, actor, { name: "agent.push_accepted", repoId: record!.id, namespaceId: record!.namespace_id, branch: claim ?? branch }); } return admitted.response; } const response = await proxyGit(new Request(request, { body: forwarded }), env.ARTIFACTS, record!.artifacts_name, route); if (response.ok) { ctx.waitUntil( commands.then(async ({ updates }) => { const corrected = await agentBranch(env.DB, record!.id, updates); if (corrected) captureWorkEvent(env, ctx, actor, { name: "work.corrected", repoId: record!.id, namespaceId: record!.namespace_id, ...corrected }); return queuePush(env, record!.id, actor, updates); }), ); } return response; } /** The agent work a person's push changed: an existing branch a live agent session works on. */ async function agentBranch(db: D1Database, repoId: string, updates: readonly RefUpdate[]): Promise<{ branch: string } | null> { const branches = updates.flatMap((update) => (update.from !== null && update.to !== null && update.ref.startsWith("refs/heads/") ? [update.ref.slice("refs/heads/".length)] : [])); if (!branches.length) return null; const branch = await db .prepare("SELECT branch FROM agent_sessions WHERE repo_id = ? AND ended_at IS NULL AND branch IN (SELECT value FROM json_each(?)) LIMIT 1") .bind(repoId, JSON.stringify(branches)) .first("branch"); return branch === null ? null : { branch }; } /** Makes the branch an agent just created by pushing it the session's branch, unless the session claimed another one meanwhile. */ async function claimBranch(db: D1Database, actor: Extract, repoId: string, branch: string): Promise { const { meta } = await db.prepare("UPDATE agent_sessions SET branch = ? WHERE id = ? AND branch IS NULL AND ended_at IS NULL").bind(branch, actor.sessionId).run(); if (meta.changes) await recordEvent(db, actor, repoStream(repoId), "session.tasked", { session: actor.sessionId, branch }, now()).run(); } async function queuePush(env: Env, repoId: string, actor: Actor, updates: RefUpdate[]): Promise { if (updates.length) await env.PUSHES.send({ repoId, actor: pusher(actor), updates, at: now() } satisfies PushMessage).catch((error) => console.error(`push not queued for repo ${repoId}`, error)); }