Skip to content
refs
History
322 lines · 17.6 KBRaw
1import { listAgentRuns } from "../agent-runs.ts";
2import { openHostedAgents } from "../agents.ts";
3import { now } from "../auth.ts";
4import { defaultRef, imageType, isBinary, lastChanges, listRefs, loadCommits, loadFile, loadTree, locate, readFileAt, tipCommit } from "../browse.ts";
5import { codeMapAt, codeMapSummaryAt } from "../code-maps.ts";
6import { isCommitHash } from "../contract/links.ts";
7import { commitDetail, rememberReads } from "../diff.ts";
8import type { Outcome } from "../contract/common.ts";
9import type { Pull, Repo, RepoSettings } from "../contract/handles.ts";
10import type { RepoSummary } from "../contract/views.ts";
11import { ANONYMOUS, recordEvent, repoStream, taskStream, withPushers } from "../events.ts";
12import { readRefs, receivePack, ZERO_OID, type Refs as GitRefs } from "../git.ts";
13import { pusher, type PushMessage } from "../pushes.ts";
14import { conflict, firstInvalid, invalid, ok, raise } from "../outcomes.ts";
15import { Policy } from "../policy.ts";
16import { descriptionError, repoFacts, toSummary as repoSummary, type ProvisionInput, type RepoRecord } from "../repos.ts";
17import { decidePermission, pendingPermissions } from "../permissions.ts";
18import * as pulls from "../pulls.ts";
19import { bodyError, titleError } from "../text.ts";
20import { cachedChanges, type Deps } from "./context.ts";
21import { openPull } from "./pull.ts";
22import { openCiSettings, openRepoCi, startPullCi } from "./ci.ts";
23
24/** A session counts as online while it has called the origin within this window. */
25export const AGENT_ONLINE_SECONDS = 300;
26/** A session on a machine whose daemon is connected stays online, idle, this long after its last call. */
27export const AGENT_IDLE_SECONDS = 60 * 60;
28
29type Provision = (input: ProvisionInput, create: (id: string) => Promise<unknown>, event: "repo.forked", data: Record<string, string>, owner?: string) => Promise<Outcome<RepoSummary>>;
30
31export function openRepo(deps: Deps, policy: Policy, record: RepoRecord, provision: Provision): Repo {
32 const { env, ctx } = deps;
33 const db = env.DB;
34 const facts = repoFacts(record);
35
36 let artifacts: Promise<ArtifactsRepo> | undefined;
37 let advertised: Promise<GitRefs> | undefined;
38 const handle = () => (artifacts ??= env.ARTIFACTS.get(record.artifacts_name).then((opened) => rememberReads(opened, record.id)));
39 const gitRefs = () => (advertised ??= handle().then(readRefs));
40
41 async function at<T>(segments: readonly string[], load: (handle: ArtifactsRepo, ref: string, path: string[]) => Promise<T | null>) {
42 const opened = await handle().catch(() => raise("not_found", "The repository is not ready yet."));
43 const found = await locate(gitRefs(), [...segments], (ref, path) => load(opened, ref, path));
44 return found ?? raise("not_found", `Nothing at ${segments.join("/")} in ${record.full_name}.`);
45 }
46
47 const usesOf = async (): Promise<{ pulls: Map<string, number>; agents: Map<string, string> }> => {
48 const at = now();
49 const [pullRows, agentRows] = await Promise.all([
50 db.prepare("SELECT number, base_ref, head_ref FROM pulls WHERE repo_id = ? AND status = 'open' ORDER BY number DESC").bind(record.id).all<{ number: number; base_ref: string; head_ref: string }>(),
51 db
52 .prepare("SELECT branch, runtime FROM agent_sessions WHERE repo_id = ? AND branch IS NOT NULL AND ended_at IS NULL AND status = 'running' AND expires_at > ? AND last_seen_at > ?")
53 .bind(record.id, at, at - AGENT_IDLE_SECONDS)
54 .all<{ branch: string; runtime: string }>(),
55 ]);
56 return {
57 pulls: new Map(pullRows.results.flatMap((row) => [[row.base_ref, row.number], [row.head_ref, row.number]] as const)),
58 agents: new Map(agentRows.results.map((row) => [row.branch, row.runtime] as const)),
59 };
60 };
61
62 return {
63 summary: repoSummary(record, policy, deps.origin),
64
65 async permissions() {
66 return policy.person ? pendingPermissions(db, record.id, policy.person.id) : [];
67 },
68
69 async latest(task) {
70 const taskId = task ? await db.prepare("SELECT id FROM tasks WHERE repo_id = ? AND number = ?").bind(record.id, task).first<number>("id") : null;
71 const row = await db
72 .prepare("SELECT max(id) AS latest FROM events WHERE stream IN (?, ?)")
73 .bind(repoStream(record.id), taskId === null ? repoStream(record.id) : taskStream(taskId))
74 .first<number | null>("latest");
75 return row ?? 0;
76 },
77
78 async decidePermission(session, requestId, behavior) {
79 if (!(await decidePermission(db, policy.actor, record.id, session, requestId, behavior))) return invalid("Only the agent's own human can answer this, and only while it is waiting.");
80 await env.REPO_HUB.get(env.REPO_HUB.idFromName(record.id)).decide(session, requestId, behavior).catch(() => undefined);
81 return ok();
82 },
83
84 async agents() {
85 if (!policy.member) return [];
86 const at = now();
87 const { results } = await db
88 .prepare(
89 `SELECT s.id, s.runtime, s.created_at, s.last_seen_at, s.machine, s.branch, u.id AS person_id, u.name AS person_name
90 FROM agent_sessions s JOIN users u ON u.id = s.user_id LEFT JOIN machines m ON m.user_id = s.user_id AND m.name = s.machine
91 WHERE s.repo_id = ? AND s.parent_session IS NULL AND s.ended_at IS NULL AND s.status = 'running' AND s.expires_at > ? AND s.mcp_session IS NOT NULL AND ((m.connected = 1 AND s.last_seen_at > ?) OR s.last_seen_at > ?)
92 ORDER BY s.last_seen_at DESC`,
93 )
94 .bind(record.id, at, at - AGENT_IDLE_SECONDS, at - AGENT_ONLINE_SECONDS)
95 .all<{ id: string; runtime: string; created_at: number; last_seen_at: number; machine: string | null; branch: string | null; person_id: string; person_name: string }>();
96 return results.map((row) => ({
97 session: row.id,
98 runtime: row.runtime,
99 onBehalfOf: { id: row.person_id, name: row.person_name },
100 branch: row.branch,
101 since: row.created_at,
102 lastSeen: row.last_seen_at,
103 machine: row.machine,
104 }));
105 },
106
107 async home() {
108 const opened = await handle().catch((error) => {
109 console.error("repository not ready", record.artifacts_name, error);
110 return null;
111 });
112 if (!opened) return { kind: "preparing" };
113
114 const speculative = loadTree(opened, record.full_name, record.default_branch, []).catch(() => null);
115 const refs = await gitRefs();
116 const ref = defaultRef(refs);
117 if (ref && ref !== record.default_branch) ctx.waitUntil(db.prepare("UPDATE repos SET default_branch = ? WHERE id = ?").bind(ref, record.id).run());
118 const tree = ref && (ref === record.default_branch ? await speculative : (await Promise.all([speculative, loadTree(opened, record.full_name, ref, [])]))[1]);
119 if (!ref || !tree) {
120 await speculative;
121 return { kind: "empty" };
122 }
123 return { kind: "tree", refs: listRefs(refs), tree };
124 },
125
126 async refs() {
127 await handle().catch(() => raise("not_found", "The repository is not ready yet."));
128 return listRefs(await gitRefs());
129 },
130
131 async branches() {
132 const [opened, refs] = await Promise.all([handle().catch(() => raise("not_found", "The repository is not ready yet.")), gitRefs()]);
133 const base = defaultRef(refs);
134 const uses = policy.member ? await usesOf() : { pulls: new Map<string, number>(), agents: new Map<string, string>() };
135 // ponytail: one log call for each branch. Page the list when a repository has hundreds of branches.
136 const list = await Promise.all(
137 [...refs.branches.keys()].map(async (name) => ({
138 name,
139 isDefault: name === base,
140 commit: await tipCommit(opened, name).catch(() => null),
141 pull: uses.pulls.get(name) ?? null,
142 agent: uses.agents.get(name) ?? null,
143 })),
144 );
145 return list.sort((a, b) => Number(b.isDefault) - Number(a.isDefault) || (b.commit?.committedAt ?? 0) - (a.commit?.committedAt ?? 0));
146 },
147
148 async deleteBranch(name) {
149 if (policy.actor.kind !== "human" || !policy.canWriteRepo(facts)) return invalid("Only a person with write access can delete a branch.");
150 const [opened, refs] = await Promise.all([handle(), gitRefs()]);
151 const tip = refs.branches.get(name);
152 if (!tip) return invalid(`No branch named "${name}".`);
153 if (name === defaultRef(refs)) return invalid(`${name} is the default branch. It cannot be deleted.`);
154 const uses = await usesOf();
155 const pull = uses.pulls.get(name);
156 if (pull) return invalid(`Pull request #${pull} uses ${name}. Merge or close it first.`);
157 if (uses.agents.has(name)) return invalid(`An agent works on ${name} now. Wait until the agent releases the branch.`);
158 const ref = `refs/heads/${name}`;
159 const deleted = await receivePack(opened, [`${tip} ${ZERO_OID} ${ref}`], [], new Uint8Array()).catch(() => null);
160 if (deleted?.refs.get(ref) !== null) return invalid(`Couldn't delete ${name}. If the branch just moved, reload and try again.`);
161 await env.PUSHES.send({ repoId: record.id, actor: pusher(policy.actor), updates: [{ ref, from: tip, to: null }], at: now() } satisfies PushMessage).catch((error) => console.error(`branch deletion not queued for repo ${record.id}`, error));
162 return ok();
163 },
164
165 async tree(segments) {
166 return (await at(segments, (opened, ref, path) => loadTree(opened, record.full_name, ref, path))).data;
167 },
168
169 async file(segments) {
170 return (await at(segments, (opened, ref, path) => loadFile(opened, record.full_name, ref, path))).data;
171 },
172
173 async raw(segments) {
174 const found = await at(segments, (opened, ref, path) => readFileAt(opened, ref, path));
175 const name = found.path[found.path.length - 1];
176 const bytes = new Uint8Array(await found.data.arrayBuffer());
177 const contentType = imageType(name) ?? (isBinary(bytes) ? "application/octet-stream" : "text/plain; charset=utf-8");
178 return { name, contentType, body: new Response(bytes).body!, cacheable: record.visibility === "public" };
179 },
180
181 async history(segments, page) {
182 const number = Math.max(1, Number(page?.cursor) || 1);
183 const found = await at(segments, (opened, ref) => loadCommits(opened, ref, number));
184 return { location: { ref: found.ref, path: found.path }, page: { items: await withPushers(db, record.id, found.data.commits), next: found.data.hasOlder ? String(number + 1) : null } };
185 },
186
187 async lastChanges(segments) {
188 const found = await at(segments, (opened, ref, path) => lastChanges(opened, ref, path));
189 return { asOf: now(), changes: found.data };
190 },
191
192 async compare(base, head) {
193 const [opened, refs] = await Promise.all([handle(), gitRefs()]);
194 const baseTip = refs.branches.get(base);
195 const headTip = refs.branches.get(head);
196 if (!baseTip || !headTip) raise("not_found", `No branch named "${baseTip ? head : base}" in ${record.full_name}.`);
197 return cachedChanges(deps, record.id, opened, baseTip, headTip);
198 },
199
200 async pulls(query) {
201 if (!policy.member) raise("sign_in_required", "Sign in to see pull requests.");
202 const found = await pulls.listPulls(db, record.id, query.status);
203 return { items: found.items.filter((row) => policy.canOpenPull(record.full_name, { head: row.head_ref })).map(pulls.toPullSummary), counts: found.counts };
204 },
205
206 async pull(number) {
207 const row = await pulls.findPull(db, record.id, number);
208 if (!row || !policy.canOpenPull(record.full_name, { head: row.head_ref })) raise("not_found", `No pull request #${number} in ${record.full_name}.`);
209 return openPull(deps, policy, row, facts, record.namespace_id, handle, gitRefs);
210 },
211
212 async openPull(input) {
213 const person = policy.person ?? raise("sign_in_required", "Sign in to open a pull request.");
214 const title = input.title.trim();
215 const body = input.body.trim();
216 const textProblem = firstInvalid({ title: titleError(title), body: bodyError(body) });
217 if (textProblem) return textProblem;
218 if (input.base === input.head) return invalid("Choose two different branches.", "head");
219 if (!policy.canOpenPull(record.full_name, { head: input.head })) return invalid("You can only open pull requests from your branch.", "head");
220 const [opened, refs] = await Promise.all([handle(), gitRefs()]);
221 const baseTip = refs.branches.get(input.base);
222 const headTip = refs.branches.get(input.head);
223 if (!baseTip || !headTip) return invalid(`No branch named "${baseTip ? input.head : input.base}".`, baseTip ? "head" : "base");
224 const existing = await db.prepare("SELECT number FROM pulls WHERE repo_id = ? AND base_ref = ? AND head_ref = ? AND status = 'open'").bind(record.id, input.base, input.head).first<number>("number");
225 if (existing) return invalid(`Pull request #${existing} already proposes ${input.head} into ${input.base}.`, "head");
226 if (!(await cachedChanges(deps, record.id, opened, baseTip, headTip)).commits.length) return invalid(`${input.base} already contains every commit on ${input.head}.`, "head");
227 const created = await pulls.createPull(db, policy.actor, { repoId: record.id, title, body, authorId: person.id, base: input.base, head: input.head });
228 if (created.kind === "already_open") return conflict(`A pull request already proposes ${input.head} into ${input.base}.`, "head");
229 startPullCi(deps, policy, record, { number: created.number, base: input.base, head: input.head, sha: headTip });
230 return ok(pulls.toPullSummary((await pulls.findPull(db, record.id, created.number))!));
231 },
232
233 async codeMap(ref) {
234 const [opened, refs] = await Promise.all([handle().catch(() => raise("not_found", "The repository is not ready yet.")), gitRefs()]);
235 const name = ref ?? defaultRef(refs);
236 if (!name) return raise("not_found", `${record.full_name} has no commits yet.`);
237 const commit = refs.branches.get(name) ?? refs.tags.get(name) ?? (isCommitHash(name) ? name : null);
238 if (!commit) return raise("not_found", `No branch, tag or commit named ${name} in ${record.full_name}.`);
239 return { ref: name, map: await codeMapSummaryAt(env, ctx, record.id, opened, commit) };
240 },
241
242 async codeGraph(commit) {
243 if (!isCommitHash(commit)) return raise("not_found", `${commit} is not a commit hash.`);
244 const opened = await handle().catch(() => raise("not_found", "The repository is not ready yet."));
245 return codeMapAt(env, ctx, record.id, opened, commit);
246 },
247
248 async commit(hash) {
249 if (!/^[0-9a-f]{40}$/.test(hash)) raise("not_found", "Commit not found.");
250 return (await commitDetail(await handle(), hash)) ?? raise("not_found", "Commit not found.");
251 },
252
253 async fork(input) {
254 const values = { name: input.name.trim(), description: input.description.trim(), visibility: input.visibility, forkOf: record.id };
255 return provision(
256 values,
257 async (id) => {
258 const source = await handle();
259 await source.fork(id, { description: values.description || undefined });
260 },
261 "repo.forked",
262 { from: record.full_name },
263 input.owner,
264 );
265 },
266
267 async settings() {
268 if (!policy.canAdminRepo(facts)) raise("not_found", "Only admins can change repository settings.");
269 return openRepoSettings(env, policy, record);
270 },
271
272 ci: () => openRepoCi(env, policy, record),
273
274 async hostedAgents() {
275 if (!policy.member) raise("not_found", "Only members see a repository's agents.");
276 return openHostedAgents(env, policy, record.namespace_id, record.id, policy.canAdminRepo(facts));
277 },
278
279 async agentRuns(open) {
280 if (!policy.member) raise("not_found", "Only members see a repository's agents.");
281 return listAgentRuns(db, record.id, open);
282 },
283 };
284}
285
286function openRepoSettings(env: Env, policy: Policy, record: RepoRecord): RepoSettings {
287 const db = env.DB;
288 return {
289 description: record.description,
290 visibility: record.visibility,
291 ci: openCiSettings(env, policy, record),
292
293 async update(changes) {
294 const description = changes.description?.trim() ?? record.description;
295 const visibility = changes.visibility ?? record.visibility;
296 const descriptionProblem = firstInvalid({ description: descriptionError(description) });
297 if (descriptionProblem) return descriptionProblem;
298 if (description === record.description && visibility === record.visibility) return ok();
299
300 const at = now();
301 const changed = { ...(description !== record.description ? { description } : {}), ...(visibility !== record.visibility ? { visibility } : {}) };
302 await db.batch([
303 db.prepare("UPDATE repos SET description = ?, visibility = ? WHERE id = ?").bind(description, visibility, record.id),
304 recordEvent(db, policy.actor, repoStream(record.id), "repo.updated", changed, at),
305 ]);
306 if (visibility === "private" && record.visibility !== "private") await env.REPO_HUB.get(env.REPO_HUB.idFromName(record.id)).disconnect(ANONYMOUS).catch(() => undefined);
307 return ok();
308 },
309
310 async delete(confirmName) {
311 if (confirmName !== record.full_name) return invalid("The confirmation didn't match the repository name.", "confirm");
312 await db.batch([
313 db.prepare("DELETE FROM events WHERE stream IN (SELECT 'task:' || id FROM tasks WHERE repo_id = ?)").bind(record.id),
314 db.prepare("DELETE FROM events WHERE stream IN (SELECT 'pull:' || id FROM pulls WHERE repo_id = ?)").bind(record.id),
315 db.prepare("DELETE FROM repos WHERE id = ?").bind(record.id),
316 recordEvent(db, policy.actor, repoStream(record.id), "repo.deleted", { name: record.full_name }, now()),
317 ]);
318 await env.ARTIFACTS.delete(record.artifacts_name).catch((error) => console.error(`storage ${record.artifacts_name} of deleted repo ${record.full_name} not removed`, error));
319 return ok();
320 },
321 };
322}