Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

2220 lines · 106.6 KBRaw History
1import { DurableObject } from "cloudflare:workers";
2import { normalizeCheckSources, requiredCheck } from "./required.js";
3import { REVIEW_APP, REVIEW_CHECK } from "../agentic/review.js";
4import { unsafeTreePath } from "../lib/tree-names.js";
5import {
6 CODE_TYPES,
7 EMPTY_TREE_OID,
8 ZERO_OID,
9 applyChanges,
10 DiffBudget,
11 diffTrees,
12 fileDiff,
13 formatUnified,
14 fromUtf8,
15 isAncestor,
16 isBinary,
17 isOid,
18 isTreeMode,
19 mergeBase,
20 parseCommit,
21 packStream,
22 parsePack,
23 parseTree,
24 planFetch,
25 peelToCommit,
26 readCommit,
27 readTree,
28 resolvePath,
29 TooMuchMemory,
30 MAX_HELD_BYTES,
31 serializeCommit,
32 walkCommits,
33 type Commit,
34 type FileChange,
35 type Signature,
36 utf8,
37} from "@diffinery/git-core";
38import type { DiffineryEvent } from "@diffinery/shared";
39import type { Env } from "../env.js";
40import {
41 advertiseReceivePack,
42 advertiseUploadPackV2,
43 errorPacket,
44 handleUploadPackV2,
45 parseReceivePack,
46 reportStatus,
47 type ReceiveRequest,
48 resetByDeploy,
49 unpackFailure,
50 UPLOAD_PACK_PATH,
51 type RefEntry,
52 type RefResult,
53} from "../git/protocol.js";
54import { memorySource, packedContents, readStagedHead, repositoryBases, stagedContents, streamedContents, type PushContents } from "../git/push-contents.js";
55import { scanForSecrets, secretBypassReason, type SecretHit } from "../git/secret-scan.js";
56import { Directory } from "../lib/directory.js";
57import { GHOST, HttpError, isValidRefName, noreplyEmail, now } from "../lib/util.js";
58import { R2Sink } from "../lib/r2-sink.js";
59import { archivePrefix, deletePrefixes, pushBodyKey, repoPrefixes, type SpilledBody } from "../lib/storage-keys.js";
60import { MemoryPool, type Lease } from "../lib/memory-pool.js";
61import { storageRefusal } from "../lib/quotas.js";
62import { Actions } from "./actions.js";
63import { AutoMerge, isPerson } from "./auto-merge.js";
64import { Collab } from "./collab.js";
65import { Deployments } from "./deployments.js";
66import { triggerWorkflows } from "./extra-triggers.js";
67import { GitData } from "./gitdata.js";
68import { IMPORT_REF_PREFIX, RepoImports } from "./imports.js";
69import { RepoObjectStore } from "./objects.js";
70import { MergeQueue, QUEUE_BRANCH_PREFIX, normalizeMergeQueue } from "./queue.js";
71import { Releases } from "./releases.js";
72import { REPO_SCHEMA, migrateRepoSchema } from "./schema.js";
73import { Runtime } from "./runtime.js";
74import { TokenPolicy } from "./token-policy.js";
75import { searchIssues } from "./search.js";
76import { MERGE_CHECKS_PER_SUMMARY, needsMergeCheck, repoToday } from "../agentic/today-repo.js";
77import { Social } from "./social.js";
78import { Statuses } from "./statuses.js";
79import { MAX_LOG_DEPTH, atLeast, globToRegExp, type AutoMergeAgent, type Caller, type ProtectionRules, type ProtectionRulesInput, type RepoMeta } from "./types.js";
80
81const MAX_PUSH_BYTES = 100 * 1024 * 1024;
82/** Agents one branch rule may auto-merge pull requests from (ProtectionRules.autoMergeAgents). */
83const MAX_AUTO_MERGE_AGENTS = 20;
84/** Pushed blobs this large are hashed, scanned and stored from their compressed bytes, never held inflated. */
85const LARGE_OBJECT_BYTES = 4 * 1024 * 1024;
86/**
87 * What pushes may hold at once in this object while they unpack: one push may hold MAX_HELD_BYTES, besides
88 * a body of up to 16 MiB passed in memory (http/git.ts IN_MEMORY_PUSH), and the object has 128 MB. Without
89 * it, two large pushes unpacking at once could go past that, and the reset drops every request in flight
90 * here, other pushes and fetches included. Each push reserves what it may hold and waits its turn.
91 */
92const PUSH_MEMORY_BYTES = MAX_HELD_BYTES + 16 * 1024 * 1024;
93/** A push with a body this small unpacks within SMALL_PUSH_HELD, beside others; one that needs more waits for a full share. */
94const SMALL_PUSH_BYTES = 1024 * 1024;
95const SMALL_PUSH_HELD = 8 * 1024 * 1024;
96/** A purge walks every reachable commit and tree while holding the repository: bounded so it finishes in time. */
97export const MAX_PURGE_OBJECTS = 300_000;
98/** Storage key that marks a deleted repository whose R2 objects are still being deleted. */
99const PURGE_KEY = "purge";
100/** How often jobs waiting on the account's hosted-job quota are retried. */
101const HELD_RETRY_MS = 60_000;
102
103export type TreeItem = {
104 name: string;
105 path: string;
106 type: "tree" | "blob" | "commit";
107 mode: string;
108 oid: string;
109 size?: number;
110};
111
112export type CommitInfo = {
113 sha: string;
114 tree: string;
115 parents: string[];
116 author: Signature;
117 committer: Signature;
118 message: string;
119 signed: boolean;
120};
121
122/**
123 * One Durable Object per repository. It is the single writer for the repo's
124 * refs, Git objects, issues, pull requests, reviews, checks and workflow runs,
125 * which gives strongly consistent ref updates and merges without locks.
126 */
127/** How long a live-update socket lives before the page must reconnect and pass the access check again. */
128const LIVE_REAUTH_MS = 10 * 60 * 1000;
129/** The close code that asks a page to reconnect at once (not a failure: no backoff, no reload). */
130export const LIVE_REAUTH_CODE = 4001;
131
132/** A row of what someone wrote (RepoDO.authoredBy): column name to value. */
133type AuthoredRow = Record<string, string | number | null>;
134
135export class RepoDO extends DurableObject<Env> {
136 readonly sql: SqlStorage;
137 store!: RepoObjectStore;
138 readonly collab: Collab;
139 readonly actions: Actions;
140 readonly queue: MergeQueue;
141 readonly autoMerge: AutoMerge;
142 readonly runtime: Runtime;
143 readonly policy: TokenPolicy;
144 private metaCache: RepoMeta | null = null;
145
146 constructor(ctx: DurableObjectState, env: Env) {
147 super(ctx, env);
148 this.sql = ctx.storage.sql;
149 this.sql.exec(REPO_SCHEMA);
150 migrateRepoSchema(this.sql);
151 const meta = this.readMeta();
152 if (meta) this.store = new RepoObjectStore(this.sql, env.BUCKET, meta.repoId, () => this.storageChanged());
153 this.collab = new Collab(this, env);
154 this.actions = new Actions(this, env);
155 this.queue = new MergeQueue(this);
156 this.autoMerge = new AutoMerge(this, env);
157 this.runtime = new Runtime(this, env);
158 this.policy = new TokenPolicy(this);
159 }
160
161 // ---------------------------------------------------------------- meta
162
163 private readMeta(): RepoMeta | null {
164 const row = this.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = 'meta'").toArray()[0];
165 this.metaCache = row ? (JSON.parse(row.value) as RepoMeta) : null;
166 return this.metaCache;
167 }
168
169 /** The noreply address of an account's commits made here (lib/util.ts noreplyEmail). */
170 noreply(login: string): string {
171 return noreplyEmail(this.env.PUBLIC_URL, login);
172 }
173
174 get meta(): RepoMeta {
175 const m = this.metaCache ?? this.readMeta();
176 if (!m) throw new HttpError(404, "repository not initialised");
177 return m;
178 }
179
180 async init(meta: RepoMeta): Promise<void> {
181 // A repository created now (not one whose meta is updated) starts with read-only workflow tokens.
182 if (!this.readMeta()) this.policy.initNewRepo();
183 this.sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES ('meta', ?)", JSON.stringify(meta));
184 this.metaCache = meta;
185 this.store = new RepoObjectStore(this.sql, this.env.BUCKET, meta.repoId, () => this.storageChanged());
186 }
187
188 async updateMeta(patch: Partial<RepoMeta>): Promise<RepoMeta> {
189 const next = { ...this.meta, ...patch };
190 await this.init(next);
191 return next;
192 }
193
194 /**
195 * Whether the repository is archived (read-only). The Worker refuses writes to an archived
196 * repository, but work this object does by itself (auto-merge, the merge queue) must ask here.
197 */
198 async isArchived(): Promise<boolean> {
199 const known = this.meta.archived;
200 if (typeof known === "boolean") return known;
201 const row = await this.env.DB.prepare("SELECT archived FROM repos WHERE id = ?").bind(this.meta.repoId).first<{ archived: number }>();
202 // setArchived may have run while D1 answered; what it set wins.
203 if (typeof this.meta.archived === "boolean") return this.meta.archived;
204 const archived = !!row?.archived;
205 await this.updateMeta({ archived });
206 return archived;
207 }
208
209 /** The repository was archived or unarchived (D1 already says so). Archiving ends auto-merge and empties the merge queues. */
210 async setArchived(archived: boolean): Promise<void> {
211 await this.updateMeta({ archived });
212 if (!archived) return;
213 await this.autoMerge.repositoryArchived();
214 await this.queue.repositoryArchived();
215 }
216
217 /**
218 * Wipe all storage (repository deletion), then its R2 objects: git objects, LFS, release
219 * assets, caches, artifacts, logs and archives. One call can't delete more than about
220 * 450,000 objects, so the alarm keeps going until they are all gone.
221 */
222 async destroy(): Promise<void> {
223 const repoId = this.readMeta()?.repoId;
224 await this.ctx.storage.deleteAlarm();
225 await this.ctx.storage.deleteAll();
226 this.metaCache = null;
227 if (!repoId) return;
228 await this.ctx.storage.put(PURGE_KEY, repoId);
229 await this.purge(repoId);
230 }
231
232 /** Delete a deleted repository's R2 objects; returns false while some remain (the alarm retries). */
233 private async purge(repoId: string): Promise<void> {
234 const done = await deletePrefixes(this.env.BUCKET, repoPrefixes(repoId)).catch((e) => {
235 console.error("could not delete the repository's objects", repoId, e);
236 return false;
237 });
238 if (done) await this.ctx.storage.deleteAll();
239 else await this.ctx.storage.setAlarm(Date.now() + 5_000);
240 }
241
242 async stats(): Promise<{ objects: number; bytes: number; refs: number; openIssues: number; openPulls: number }> {
243 const q = (s: string) => this.sql.exec<{ n: number }>(s).one().n;
244 return {
245 objects: this.store.count(),
246 bytes: this.store.sizeBytes(),
247 refs: q("SELECT count(*) AS n FROM refs"),
248 openIssues: q("SELECT count(*) AS n FROM issues WHERE kind = 'issue' AND state = 'open'"),
249 openPulls: q("SELECT count(*) AS n FROM issues WHERE kind = 'pull' AND state = 'open'"),
250 };
251 }
252
253 // ---------------------------------------------------------------- deleted and exported accounts (accounts/)
254
255 /**
256 * After an account is deleted its work here stays, attributed to the `ghost` user as on GitHub: issues and
257 * pull requests, comments, reviews, releases, statuses, deployments, events, workflow runs and reactions.
258 * Self-hosted runners it registered here (by login) are removed. Returns how many rows changed.
259 */
260 async forgetAccounts(ids: string[], logins: string[]): Promise<number> {
261 if (!ids.length) return 0;
262 const inIds = ids.map(() => "?").join(", ");
263 let changed = 0;
264 const run = (q: string, ...b: unknown[]) => void (changed += this.sql.exec(q, ...b).rowsWritten);
265 const people: Array<[table: string, prefix: string]> = [
266 ["issues", "author"],
267 ["comments", "author"],
268 ["reviews", "author"],
269 ["releases", "author"],
270 ["statuses", "creator"],
271 ["deployments", "creator"],
272 ["deployment_statuses", "creator"],
273 ["issue_events", "actor"],
274 ["checks", "creator"],
275 ["release_assets", "uploader"],
276 ["reactions", "user"],
277 ];
278 for (const [table, p] of people) {
279 // Reactions are one per person: where the ghost already reacted the same way, the deleted account's goes.
280 run(`UPDATE OR IGNORE ${table} SET ${p}_id = ?, ${p}_login = ?, ${p}_kind = ? WHERE ${p}_id IN (${inIds})`, GHOST.id, GHOST.login, GHOST.kind, ...ids);
281 }
282 run(`DELETE FROM reactions WHERE user_id IN (${inIds})`, ...ids);
283 run(`UPDATE deployment_reviews SET user_id = ?, user_login = ? WHERE user_id IN (${inIds})`, GHOST.id, GHOST.login, ...ids);
284 run(`UPDATE runs SET actor = json_object('id', ?, 'login', ?, 'kind', ?) WHERE json_extract(actor, '$.id') IN (${inIds})`, GHOST.id, GHOST.login, GHOST.kind, ...ids);
285 if (logins.length) {
286 const lower = logins.map((l) => l.toLowerCase());
287 const inLogins = lower.map(() => "?").join(", ");
288 run(`UPDATE pulls SET merged_by = ? WHERE lower(merged_by) IN (${inLogins})`, GHOST.login, ...lower);
289 run(`DELETE FROM runners WHERE lower(created_by) IN (${inLogins})`, ...lower);
290 run(`DELETE FROM runner_registrations WHERE lower(created_by) IN (${inLogins})`, ...lower);
291 }
292 return changed;
293 }
294
295 /** What these accounts wrote here, for an account export: issues and pull requests they opened, their comments and reviews (at most `limit` of each). */
296 async authoredBy(ids: string[], limit = 5000): Promise<{ issues: AuthoredRow[]; comments: AuthoredRow[]; reviews: AuthoredRow[] }> {
297 if (!ids.length || !this.readMeta()) return { issues: [], comments: [], reviews: [] };
298 const inIds = ids.map(() => "?").join(", ");
299 const rows = (q: string) => this.sql.exec<AuthoredRow>(q, ...ids, limit).toArray();
300 return {
301 issues: rows(`SELECT number, kind, title, body, state, state_reason, created_at, updated_at, closed_at FROM issues WHERE author_id IN (${inIds}) ORDER BY number LIMIT ?`),
302 comments: rows(`SELECT id, number, body, path, line, created_at, updated_at FROM comments WHERE author_id IN (${inIds}) ORDER BY created_at LIMIT ?`),
303 reviews: rows(`SELECT id, number, state, body, commit_id, submitted_at FROM reviews WHERE author_id IN (${inIds}) ORDER BY submitted_at LIMIT ?`),
304 };
305 }
306
307 /**
308 * Write a Git bundle (version 2) of the repository's branches and tags to R2 at `key`, for an account export.
309 * The pack streams out one object at a time, as a clone's does. Null for an empty repository; a bundle past
310 * `limit` bytes is refused with a 413 and nothing is kept.
311 */
312 async writeBundle(key: string, limit: number): Promise<{ size: number; refs: number } | null> {
313 if (!this.readMeta()) return null;
314 const refs = this.refs().filter((r) => r.name.startsWith("refs/heads/") || r.name.startsWith("refs/tags/"));
315 if (!refs.length) return null;
316 const plan = await planFetch(this.store, [...new Set(refs.map((r) => r.oid))], []);
317 const head = this.getRef(this.headRef);
318 const sink = new R2Sink(this.env.BUCKET, key, "application/x-git-bundle", limit, "the repository is too large to bundle");
319 const store = this.store;
320 async function* entries() {
321 for await (const raw of store.readRawAll(plan.oids)) yield { type: raw.type, size: raw.size, deflated: raw.deflated };
322 }
323 try {
324 await sink.write(utf8(`# v2 git bundle\n${head ? `${head} HEAD\n` : ""}${refs.map((r) => `${r.oid} ${r.name}\n`).join("")}\n`));
325 for await (const part of packStream(plan.oids.length, entries())) await sink.write(part);
326 return { size: await sink.close(), refs: refs.length };
327 } catch (e) {
328 await sink.abort();
329 throw e;
330 }
331 }
332
333 /** Keep the object alive for work that finishes after the current request. */
334 background(p: Promise<unknown>): void {
335 this.ctx.waitUntil(p.catch((e) => console.error("background task failed", e)));
336 }
337
338 /**
339 * Set (or with null, clear) the object's single alarm. The merge queue uses it for check timeouts;
340 * while jobs wait on the account's hosted-job quota it also fires every minute to retry them, and it
341 * fires at the earliest running job's deadline (Actions.enforceJobDeadlines).
342 */
343 armAlarm(at: number | null): void {
344 const next = this.earliest(at, this.actions.hasAccountHeldJobs() ? Date.now() + HELD_RETRY_MS : null, this.actions.nextJobDeadline(), this.actions.nextStuckRunCheck(), this.actions.nextImageRetry());
345 this.ctx.waitUntil(next === null ? this.ctx.storage.deleteAlarm() : this.ctx.storage.setAlarm(next));
346 }
347
348 /** Make sure the alarm fires by `at`, keeping an earlier one. */
349 alarmBy(at: number): void {
350 this.ctx.waitUntil(
351 (async () => {
352 const current = await this.ctx.storage.getAlarm();
353 if (current === null || current > at) await this.ctx.storage.setAlarm(at);
354 })(),
355 );
356 }
357
358 private earliest(...times: Array<number | null>): number | null {
359 const set = times.filter((t): t is number => t !== null);
360 return set.length ? Math.min(...set) : null;
361 }
362
363 override async alarm(): Promise<void> {
364 const purging = await this.ctx.storage.get<string>(PURGE_KEY);
365 if (purging) return this.purge(purging);
366 await this.queue.process();
367 if (this.actions.hasAccountHeldJobs()) await this.actions.releaseAccountHeld();
368 await this.actions.relaunchImageHeld();
369 await this.actions.enforceJobDeadlines();
370 await this.actions.repairStuckRuns();
371 // Wake up again for held jobs, rollout waits, running jobs' deadlines and stuck runs, keeping the queue's own alarm if it set an earlier one.
372 const want = this.earliest(this.actions.hasAccountHeldJobs() ? Date.now() + HELD_RETRY_MS : null, this.actions.nextJobDeadline(), this.actions.nextStuckRunCheck(), this.actions.nextImageRetry());
373 if (want !== null) {
374 const current = await this.ctx.storage.getAlarm();
375 if (current === null || current <= Date.now() || current > want) await this.ctx.storage.setAlarm(want);
376 }
377 }
378
379 /** Queue an event (webhooks, notifications) and show it live to open pages; `live: false` skips the pages (e.g. draft releases, which readers can't see). */
380 emit(event: DiffineryEvent, opts?: { live?: boolean }): void {
381 this.ctx.waitUntil(this.env.EVENTS.send(event).catch((e) => console.error("event send failed", e)));
382 // Open pages only learn that something changed and fetch it with the viewer's own access: the event
383 // itself (an audit entry's detail, a dispatch's payload) is not every reader's to see.
384 if (opts?.live !== false && event.type !== "audit") this.broadcast("repo", { kind: "event", type: event.type });
385 }
386
387 // ---------------------------------------------------------------- purging unreachable objects
388
389 /** Bumped by every purge; a push that started before one refuses its ref updates. */
390 private purgeEpoch = 0;
391
392 /**
393 * Delete every object no ref reaches, so a secret force-pushed away can't be fetched by its SHA any
394 * more (git keeps them until a gc, and so did Diffinery, forever). Also kept: the commits of open
395 * pull requests, of the merge queue and of unfinished workflow runs. Runs with every other request
396 * held, so nothing writes a ref meanwhile.
397 */
398 async purgeUnreachable(caller: Caller): Promise<{ objects: number; bytes: number }> {
399 if (caller.kind !== "user" || caller.permissions || !atLeast(caller.role, "admin")) throw new HttpError(403, "only repository admins can purge unreachable objects");
400 this.checkPurgeSize();
401 return this.ctx.blockConcurrencyWhile(() => this.purgeHeld());
402 }
403
404 /**
405 * Start over with fresh history: delete every closed and merged pull request (its conversation,
406 * reviews, review comments, events, reactions and refs/pull/<n>/* refs), then purge what nothing
407 * reaches any more. Without it, refs/pull keeps every old commit fetchable after the branches were
408 * rewritten. Issues, open pull requests (and those in the merge queue), branches, tags and workflow
409 * runs stay, and numbers are never reused. Runs with every other request held, like a purge.
410 */
411 async deleteClosedPullRequests(caller: Caller): Promise<{ pullRequests: number; objects: number; bytes: number }> {
412 if (caller.kind !== "user" || caller.permissions || !atLeast(caller.role, "admin")) throw new HttpError(403, "only repository admins can delete closed pull requests");
413 this.checkPurgeSize();
414 return this.ctx.blockConcurrencyWhile(async () => {
415 const numbers = this.sql
416 .exec<{ number: number }>("SELECT number FROM issues WHERE kind = 'pull' AND state = 'closed' AND number NOT IN (SELECT number FROM merge_queue) ORDER BY number")
417 .toArray()
418 .map((r) => r.number);
419 for (const n of numbers) this.forgetPull(n);
420 const purged = await this.purgeHeld();
421 return { pullRequests: numbers.length, ...purged };
422 });
423 }
424
425 /** Every row and ref a pull request left behind. */
426 private forgetPull(n: number): void {
427 const comments = this.sql.exec<{ id: string; review_id: string | null }>("SELECT id, review_id FROM comments WHERE number = ?", n).toArray();
428 for (const c of comments) this.sql.exec("DELETE FROM reactions WHERE subject = ?", `${c.review_id ? "review_comment" : "comment"}:${c.id}`);
429 this.sql.exec("DELETE FROM reactions WHERE subject = ?", `issue:${n}`);
430 for (const table of ["comments", "reviews", "issue_events", "issue_milestones", "pull_merge_state", "pulls", "issues"]) this.sql.exec(`DELETE FROM ${table} WHERE number = ?`, n);
431 this.sql.exec("DELETE FROM refs WHERE name >= ? AND name < ?", `refs/pull/${n}/`, `refs/pull/${n}/￿`);
432 }
433
434 private checkPurgeSize(): void {
435 const total = this.store.count();
436 if (total > MAX_PURGE_OBJECTS) throw new HttpError(422, `this repository has ${total} objects; purging works for up to ${MAX_PURGE_OBJECTS}. Ask a site administrator`);
437 }
438
439 /** The purge itself; the caller holds every other request (blockConcurrencyWhile). */
440 private async purgeHeld(): Promise<{ objects: number; bytes: number }> {
441 const roots = [
442 ...this.sql.exec<{ oid: string }>("SELECT oid FROM refs").toArray().map((r) => r.oid),
443 ...this.sql.exec<{ oid: string }>("SELECT head_sha AS oid FROM pulls UNION SELECT head_sha FROM merge_queue UNION SELECT group_sha FROM merge_queue WHERE group_sha IS NOT NULL UNION SELECT parent_sha FROM merge_queue WHERE parent_sha IS NOT NULL").toArray().map((r) => r.oid),
444 ...this.sql.exec<{ oid: string }>("SELECT sha AS oid FROM runs WHERE status != 'completed' UNION SELECT head_sha FROM runs WHERE status != 'completed' AND head_sha IS NOT NULL").toArray().map((r) => r.oid),
445 ];
446 const keep = new Set<string>();
447 const stack = [...roots];
448 while (stack.length) {
449 const oid = stack.pop()!;
450 if (keep.has(oid)) continue;
451 const row = this.sql.exec<{ type: number }>("SELECT type FROM objects WHERE oid = ?", oid).toArray()[0];
452 if (!row) continue;
453 keep.add(oid);
454 const type = CODE_TYPES[row.type];
455 if (type === "blob") continue;
456 const obj = await this.store.read(oid);
457 if (!obj) continue;
458 if (type === "commit") {
459 const c = parseCommit(obj.content);
460 stack.push(c.tree, ...c.parents);
461 } else if (type === "tree") {
462 // A gitlink (160000) names a commit in another repository.
463 for (const e of parseTree(obj.content)) if (e.mode !== "160000") stack.push(e.oid);
464 } else if (type === "tag") {
465 const target = /^object ([0-9a-f]{40})/.exec(fromUtf8(obj.content))?.[1];
466 if (target) stack.push(target);
467 }
468 }
469 const doomed = this.sql.exec<{ oid: string; r2: number; size: number }>("SELECT oid, r2, size FROM objects").toArray().filter((r) => !keep.has(r.oid));
470 for (let i = 0; i < doomed.length; i += 100) {
471 const chunk = doomed.slice(i, i + 100).map((r) => r.oid);
472 this.sql.exec(`DELETE FROM objects WHERE oid IN (${chunk.map(() => "?").join(",")})`, ...chunk);
473 }
474 this.store.forget();
475 this.store.recount();
476 this.storageChanged();
477 this.purgeEpoch++;
478 const r2 = doomed.filter((r) => r.r2).map((r) => this.store.r2KeyOf(r.oid));
479 for (let i = 0; i < r2.length; i += 1000) await this.env.BUCKET.delete(r2.slice(i, i + 1000));
480 // Cached zipballs and tarballs are rebuilt from what's left on the next download.
481 await deletePrefixes(this.env.BUCKET, [archivePrefix(this.meta.repoId)], 50);
482 return { objects: doomed.length, bytes: doomed.reduce((n, r) => n + r.size, 0) };
483 }
484
485 // ---------------------------------------------------------------- storage (the owner's storage quota, lib/quotas.ts)
486
487 /** The report to D1 waiting to run, and the last one started: reports run one at a time. */
488 private storageNext: Promise<void> | null = null;
489 private storageLast: Promise<void> = Promise.resolve();
490
491 /** Bytes the repository stores for its owner: git objects, Git LFS objects and release assets. */
492 async storageBytes(): Promise<number> {
493 await this.listLfs();
494 const q = (s: string) => this.sql.exec<{ n: number }>(s).one().n;
495 return this.store.sizeBytes() + q("SELECT coalesce(sum(size), 0) AS n FROM lfs_objects") + q("SELECT coalesce(sum(size), 0) AS n FROM release_assets");
496 }
497
498 /**
499 * Tell D1 what the repository stores now (repo_storage), where the owner's quota adds it up. Calls
500 * made while a report waits to run share it; one made while a report is under way gets the next.
501 */
502 reportStorage(): Promise<void> {
503 this.storageNext ??= this.storageLast.then(async () => {
504 this.storageNext = null;
505 const bytes = await this.storageBytes();
506 await this.env.DB.prepare("INSERT INTO repo_storage (repo_id, bytes, updated_at) VALUES (?, ?, ?) ON CONFLICT(repo_id) DO UPDATE SET bytes = excluded.bytes, updated_at = excluded.updated_at")
507 .bind(this.meta.repoId, bytes, now())
508 .run();
509 });
510 const next = this.storageNext;
511 this.storageLast = next.catch(() => {});
512 return next;
513 }
514
515 /** What the repository stores changed: report it in the background. */
516 storageChanged(): void {
517 this.background(this.reportStorage());
518 }
519
520 /** Why storing `adding` more bytes here must be refused (past the owner's storage quota), or null. */
521 async storageRefusal(adding = 0): Promise<string | null> {
522 const m = this.meta;
523 return storageRefusal(this.env, m.ownerId, m.owner, adding, { repoId: m.repoId, bytes: await this.storageBytes() });
524 }
525
526 /** Refuse storing `adding` more bytes past the owner's storage quota. */
527 async checkStorage(adding = 0): Promise<void> {
528 const refused = await this.storageRefusal(adding);
529 if (refused) throw new HttpError(403, refused);
530 }
531
532 /** A Git LFS object was stored in R2 (http/git.ts). */
533 recordLfs(oid: string, size: number): void {
534 if (this.sql.exec("INSERT OR IGNORE INTO lfs_objects (oid, size) VALUES (?, ?) RETURNING oid", oid, size).toArray().length) this.storageChanged();
535 }
536
537 /** Git LFS objects stored before lfs_objects existed: listed from R2, once. */
538 private async listLfs(): Promise<void> {
539 if (this.sql.exec("SELECT 1 FROM counters WHERE name = 'lfs_listed'").toArray().length) return;
540 let cursor: string | undefined;
541 do {
542 const page = await this.env.BUCKET.list({ prefix: `repos/${this.meta.repoId}/lfs/`, cursor, limit: 1000 });
543 for (const o of page.objects) this.sql.exec("INSERT OR IGNORE INTO lfs_objects (oid, size) VALUES (?, ?)", o.key.slice(o.key.lastIndexOf("/") + 1), o.size);
544 cursor = page.truncated ? page.cursor : undefined;
545 } while (cursor);
546 this.sql.exec("INSERT OR IGNORE INTO counters (name, value) VALUES ('lfs_listed', 1)");
547 }
548
549 // ---------------------------------------------------------------- refs
550
551 refs(prefix = "refs/"): RefEntry[] {
552 return this.sql.exec<RefEntry>("SELECT name, oid FROM refs WHERE name >= ? AND name < ? ORDER BY name", prefix, `${prefix}￿`).toArray();
553 }
554
555 getRef(name: string): string | null {
556 return this.sql.exec<{ oid: string }>("SELECT oid FROM refs WHERE name = ?", name).toArray()[0]?.oid ?? null;
557 }
558
559 /** Compare-and-swap a ref. `expected` = ZERO_OID means "must not exist". */
560 casRef(name: string, expected: string | null, next: string | null): boolean {
561 const current = this.getRef(name);
562 if (expected !== null && (current ?? ZERO_OID) !== expected) return false;
563 if (next === null || next === ZERO_OID) this.sql.exec("DELETE FROM refs WHERE name = ?", name);
564 else this.sql.exec("INSERT OR REPLACE INTO refs (name, oid) VALUES (?, ?)", name, next);
565 return true;
566 }
567
568 get headRef(): string {
569 return `refs/heads/${this.meta.defaultBranch}`;
570 }
571
572 /** Resolve a branch, tag, full ref, HEAD or (abbreviated) SHA to a commit SHA. */
573 async resolve(rev: string | undefined | null): Promise<string | null> {
574 const r = rev && rev.length ? rev : "HEAD";
575 // Ancestry suffixes, as git takes them: `main~2` (first parents back), `HEAD^2` (the second parent), `v1.0^`.
576 // Ref names can't hold `~` or `^`, so whatever is before the first one names the commit.
577 const at = r.search(/[~^]/);
578 if (at > 0) {
579 const ops = r.slice(at);
580 if (!/^([~^]\d{0,4})+$/.test(ops)) return null;
581 let oid = await this.resolve(r.slice(0, at));
582 for (const [, op, n] of ops.matchAll(/([~^])(\d*)/g)) {
583 const count = n === "" ? 1 : Number(n);
584 for (let i = 0; oid && i < (op === "~" ? count : 1); i++) {
585 if (op === "^" && count === 0) break;
586 const parents: string[] = (await readCommit(this.store, oid).catch(() => null))?.parents ?? [];
587 oid = (op === "~" ? parents[0] : parents[count - 1]) ?? null;
588 }
589 }
590 return oid;
591 }
592 let oid: string | null = null;
593 if (r === "HEAD") oid = this.getRef(this.headRef);
594 else if (isOid(r)) oid = this.store.has(r) ? r : null;
595 else if (r.startsWith("refs/")) oid = this.getRef(r);
596 else oid = this.getRef(`refs/heads/${r}`) ?? this.getRef(`refs/tags/${r}`);
597 if (!oid && /^[0-9a-f]{7,39}$/.test(r)) {
598 const rows = this.sql.exec<{ oid: string }>("SELECT oid FROM objects WHERE oid >= ? AND oid < ? LIMIT 2", r, `${r}g`).toArray();
599 if (rows.length === 1) oid = rows[0]!.oid;
600 }
601 if (!oid) return null;
602 return peelToCommit(this.store, oid);
603 }
604
605 async branches(): Promise<Array<{ name: string; sha: string; protected: boolean; isDefault: boolean }>> {
606 return this.refs("refs/heads/").map((r) => {
607 const name = r.name.slice(11);
608 return { name, sha: r.oid, protected: !!this.protectionFor(name), isDefault: name === this.meta.defaultBranch };
609 });
610 }
611
612 async tags(): Promise<Array<{ name: string; sha: string; target: string }>> {
613 const out = [];
614 for (const r of this.refs("refs/tags/")) out.push({ name: r.name.slice(10), sha: r.oid, target: await peelToCommit(this.store, r.oid).catch(() => r.oid) });
615 return out;
616 }
617
618 // ---------------------------------------------------------------- git smart HTTP
619
620 async gitInfoRefs(service: "git-upload-pack" | "git-receive-pack"): Promise<Uint8Array> {
621 if (service === "git-upload-pack") return advertiseUploadPackV2();
622 // Like GitHub, pull request refs are hidden from pushes (so `git push --mirror` leaves them alone).
623 return advertiseReceivePack(this.refs().filter((r) => !r.name.startsWith("refs/pull/")));
624 }
625
626 /** The response streams: the pack is read and sent one object at a time, as the client takes it. */
627 private async gitUploadPack(body: Uint8Array): Promise<ReadableStream<Uint8Array>> {
628 const { readable, writable } = new IdentityTransformStream();
629 const writer = writable.getWriter();
630 let started = false;
631 const sink = (b: Uint8Array) => ((started = true), writer.write(b));
632 const ctx = { store: this.store, refs: this.refs(), headTarget: this.headRef };
633 void handleUploadPackV2(body, ctx, sink)
634 .catch((e) => (started ? undefined : writer.write(errorPacket((e as Error).message))))
635 .then(
636 () => writer.close(),
637 () => writer.abort(),
638 )
639 .catch(() => {}); // the client went away
640 return readable;
641 }
642
643 /**
644 * `moved`: the push came in under an old name (a transfer or rename), so say where the repository
645 * lives now, like GitHub. `retry`: the Worker hands over a push a deploy cut off (http/git.ts
646 * receiveWithRetry), which may already have moved some refs. A body staged in R2 is the Worker's
647 * to delete: deleted here, a push cut off after this point would find it gone on its retry.
648 */
649 async gitReceivePack(input: Uint8Array | SpilledBody, caller: Caller, o: { moved?: boolean; retry?: boolean } = {}): Promise<Uint8Array> {
650 const size = input instanceof Uint8Array ? input.length : input.size;
651 const held = size <= SMALL_PUSH_BYTES ? SMALL_PUSH_HELD : MAX_HELD_BYTES;
652 // A large body that has to wait goes to R2 meanwhile, so pushes waiting their turn don't hold their bodies.
653 let staged: string | null = null;
654 if (input instanceof Uint8Array && size > SMALL_PUSH_BYTES && !this.pushMemory.fits(size + held)) {
655 staged = pushBodyKey(this.meta.repoId);
656 await this.env.BUCKET.put(staged, input);
657 input = { spilled: staged, size };
658 }
659 const body = input instanceof Uint8Array ? size : 0;
660 const lease = await this.pushMemory.take(body + held);
661 try {
662 return await this.receivePack(input, caller, o, { held, grow: () => lease.grow(body + MAX_HELD_BYTES) });
663 } finally {
664 lease.release();
665 if (staged) await this.env.BUCKET.delete(staged).catch(() => {});
666 }
667 }
668
669 /** What pushes in flight here hold while they unpack (see PUSH_MEMORY_BYTES). */
670 private readonly pushMemory = new MemoryPool(PUSH_MEMORY_BYTES);
671
672 /** `memory`: what this push may hold while it unpacks, and how to wait for a full share when a small push needs more. */
673 private async receivePack(input: Uint8Array | SpilledBody, caller: Caller, o: { moved?: boolean; retry?: boolean }, memory: { held: number; grow: () => Promise<void> }): Promise<Uint8Array> {
674 const size = input instanceof Uint8Array ? input.length : input.size;
675 if (size > MAX_PUSH_BYTES) {
676 const req = { commands: [], capabilities: new Set<string>(), pushOptions: [], pack: null };
677 return reportStatus(req, "push exceeds 100 MB; split it into smaller pushes", []);
678 }
679 // A push the Worker staged in R2 (over 16 MB) is read in ranges, never whole: its objects are
680 // unpacked one at a time (git/push-contents.ts), so its size doesn't decide the memory it takes.
681 let req: ReceiveRequest;
682 let packAt = 0;
683 if (input instanceof Uint8Array) req = parseReceivePack(input);
684 else {
685 try {
686 const head = await readStagedHead(this.env.BUCKET, input.spilled, input.size);
687 req = head.req;
688 packAt = head.packOffset;
689 } catch (e) {
690 // A deploy that stops this object mid-push is the Worker's to retry (http/git.ts receiveWithRetry).
691 if (resetByDeploy(e)) throw e;
692 return reportStatus({ commands: [], capabilities: new Set<string>(), pushOptions: [], pack: null }, unpackFailure(e), []);
693 }
694 }
695 // A purge of unreachable objects that ran while this push was in flight may have deleted objects
696 // the push counted on the repository having: refuse rather than point a ref at them.
697 const epoch = this.purgeEpoch;
698 // `git push -o diffinery-import` from a GitHub import's own token: no workflows, webhooks,
699 // pull request syncs or notifications (see apps/diffinery/src/imports).
700 const importMode = !!caller.importId && req.pushOptions.some((o) => o.trim() === "diffinery-import");
701 // H2: while an import holds the repository, only that import may push. Everything else waits
702 // until the import finalises, so protection, guardrails, CI and webhooks are never bypassed.
703 const lockHolder = this.importLockHolder();
704 if (lockHolder && (!importMode || caller.importId !== lockHolder)) {
705 const denied = req.commands.map((c) => ({ ref: c.ref, ok: false as const, reason: "repository is locked by an import in progress" }));
706 return reportStatus(req, "repository is locked by an import in progress", denied);
707 }
708 const messages: string[] = o.moved ? ["This repository moved. Please use the new location:", ` ${this.env.PUBLIC_URL}/${this.meta.owner}/${this.meta.name}.git`] : [];
709 let unpackError: string | null = null;
710 // Like git's quarantine: nothing from the pack is stored until push protection passes,
711 // so a blocked push leaves no objects behind for a retry to build on.
712 let contents: PushContents = packedContents(this.store, [], 0);
713 const unpack = async (maxHeldBytes: number): Promise<PushContents> => {
714 const opts = { largeObjectBytes: LARGE_OBJECT_BYTES, maxHeldBytes };
715 if (!(input instanceof Uint8Array)) return packAt < input.size ? stagedContents(this.store, this.env.BUCKET, input.spilled, packAt, input.size - packAt, opts) : contents;
716 const pack = req.pack;
717 if (!pack?.length) return contents;
718 return parsePack(pack, repositoryBases(this.store), opts).then(
719 (objects) => packedContents(this.store, objects, pack.length),
720 // Parsed whole, a pack holds every object at once: one that can't, such as a long history
721 // of a large file, is unpacked in pieces instead, holding only the objects in use.
722 (e: unknown) => {
723 if (!(e instanceof TooMuchMemory)) throw e;
724 return streamedContents(this.store, memorySource(pack), opts);
725 },
726 );
727 };
728 try {
729 try {
730 contents = await unpack(memory.held);
731 } catch (e) {
732 // A small push that needs more than its small share waits for a full one.
733 if (!(e instanceof TooMuchMemory) || memory.held >= MAX_HELD_BYTES) throw e;
734 await memory.grow();
735 contents = await unpack(MAX_HELD_BYTES);
736 }
737 } catch (e) {
738 if (resetByDeploy(e)) throw e;
739 unpackError = unpackFailure(e);
740 }
741 const results: RefResult[] = [];
742 if (unpackError) {
743 for (const c of req.commands) results.push({ ref: c.ref, ok: false, reason: "unpacker error" });
744 return reportStatus(req, unpackError, results);
745 }
746 // Like GitHub's receive.fsckObjects: no tree a git client would refuse, or that writes outside the work tree.
747 const bad = contents.fsck();
748 if (bad) {
749 for (const c of req.commands) results.push({ ref: c.ref, ok: false, reason: "fsck failed" });
750 return reportStatus(req, `fsck error: ${bad}`, results, [`Push refused: ${bad}`]);
751 }
752
753 const marked: SecretHit[] = [];
754 // Commit and tag messages are scanned too, not only files.
755 const leaks = contents.scan(marked);
756 // A file can opt out with `diffinery:allow-secret`; that it did is on the record.
757 if (marked.length) this.emit({ type: "audit", action: "push.secret_marked", actor: caller, target: `${this.meta.owner}/${this.meta.name}`, detail: { kinds: [...new Set(marked.map((l) => l.kind))], blobs: marked.slice(0, 50).map((l) => l.oid), refs: req.commands.map((c) => c.ref) }, at: now() });
758 if (leaks.length) {
759 const kinds = leaks.map((l) => l.kind);
760 const target = `${this.meta.owner}/${this.meta.name}`;
761 // Like GitHub's push protection bypass: a human repository admin may push anyway by
762 // giving a reason (`git push -o allow-secrets=<reason>`), and every bypass is audited.
763 const reason = secretBypassReason(req.pushOptions);
764 if (reason && caller.role === "admin" && caller.kind === "user") {
765 messages.push(`Push protection bypassed by ${caller.login}: ${reason}`);
766 for (const l of leaks.slice(0, 10)) messages.push(` ${l.kind} in blob ${l.oid.slice(0, 10)}`);
767 this.emit({ type: "audit", action: "push.secret_bypassed", actor: caller, target, detail: { kinds, reason, refs: req.commands.map((c) => c.ref), ...(importMode ? { import: caller.importId, blobs: leaks.slice(0, 50).map((l) => l.oid) } : {}) }, at: now() });
768 if (importMode) this.importsModule.recordFindings(leaks);
769 } else {
770 messages.push("Push blocked: possible secrets detected.");
771 for (const l of leaks.slice(0, 10)) messages.push(` ${l.kind} in blob ${l.oid.slice(0, 10)}`);
772 messages.push("Remove the secret from your commits, or rotate it and contact an admin.");
773 if (reason) messages.push("Only repository admins (people, not agents) can bypass push protection.");
774 for (const c of req.commands) results.push({ ref: c.ref, ok: false, reason: "secret detected (push protection)" });
775 this.emit({ type: "audit", action: "push.blocked_secret", actor: caller, target, detail: { kinds, refs: req.commands.map((c) => c.ref) }, at: now() });
776 return reportStatus(req, null, results, messages);
777 }
778 }
779
780 // Past the owner's storage quota nothing new is stored; a push that only deletes or moves refs still works.
781 const full = contents.anyNew() ? await this.storageRefusal(contents.bytes) : null;
782 if (full) {
783 for (const c of req.commands) results.push({ ref: c.ref, ok: false, reason: "storage limit reached" });
784 return reportStatus(req, null, results, [...messages, `Push refused: ${full}`]);
785 }
786
787 try {
788 await contents.write();
789 } catch (e) {
790 if (resetByDeploy(e)) throw e;
791 for (const c of req.commands) results.push({ ref: c.ref, ok: false, reason: "unpacker error" });
792 return reportStatus(req, unpackFailure(e), results);
793 }
794
795 // Validate every command before applying any, so `atomic` is honoured.
796 const checks: Array<RefResult & { cmd: (typeof req.commands)[number] }> = [];
797 for (const cmd of req.commands) checks.push({ cmd, ...(await this.checkRefUpdate(cmd.ref, cmd.oldOid, cmd.newOid, caller, importMode)) });
798 const atomic = req.capabilities.has("atomic");
799 const anyFailed = checks.some((c) => !c.ok);
800 let imported = 0;
801 for (const c of checks) {
802 if (!c.ok) {
803 results.push({ ref: c.ref, ok: false, reason: c.reason });
804 continue;
805 }
806 if (atomic && anyFailed) {
807 results.push({ ref: c.ref, ok: false, reason: "atomic transaction failed" });
808 continue;
809 }
810 if (epoch !== this.purgeEpoch) {
811 results.push({ ref: c.ref, ok: false, reason: "the repository's unreachable objects were purged during this push; push again" });
812 continue;
813 }
814 // On a retry, a ref the cut-off attempt already moved is where the push wants it: that is a
815 // success, not stale info. Its push event goes out (again), as the cut-off attempt may have
816 // stopped before sending it: a missing one would leave a pull request without its checks.
817 const applied = this.casRef(c.cmd.ref, c.cmd.oldOid, c.cmd.newOid) || (!!o.retry && (this.getRef(c.cmd.ref) ?? ZERO_OID) === c.cmd.newOid);
818 results.push(applied ? { ref: c.ref, ok: true } : { ref: c.ref, ok: false, reason: "fetch first (stale info)" });
819 if (applied && importMode) {
820 imported++;
821 // Record provenance so a later push may move this ref only if the import still owns it.
822 if (c.cmd.newOid === ZERO_OID) this.sql.exec("DELETE FROM import_refs WHERE ref = ?", c.cmd.ref);
823 else this.importsModule.recordImportRef(c.cmd.ref, c.cmd.newOid, caller.importId!);
824 } else if (applied) await this.afterRefUpdate(c.cmd.ref, c.cmd.oldOid, c.cmd.newOid, caller, messages);
825 }
826 // One audit entry per import push instead of push events.
827 if (imported) this.emit({ type: "audit", action: "import.push", actor: caller, target: `${this.meta.owner}/${this.meta.name}`, detail: { import: caller.importId, refs: imported }, at: now() });
828 return reportStatus(req, null, results, messages);
829 }
830
831 /** As on GitHub: a rule naming the branch exactly wins; otherwise the oldest matching pattern. */
832 protectionFor(branch: string): ProtectionRules | null {
833 return this.protectionRuleFor(branch)?.rules ?? null;
834 }
835
836 /** The rule that applies to `branch`, with its pattern: an exact name first, else the first matching pattern. */
837 protectionRuleFor(branch: string): { pattern: string; rules: ProtectionRules } | null {
838 const rows = this.sql.exec<{ pattern: string; rules: string }>("SELECT pattern, rules FROM protections ORDER BY rowid").toArray();
839 const row = rows.find((r) => r.pattern === branch) ?? rows.find((r) => globToRegExp(r.pattern).test(branch));
840 return row ? { pattern: row.pattern, rules: JSON.parse(row.rules) as ProtectionRules } : null;
841 }
842
843 /**
844 * Server-side rules for a ref update: permissions, protection, fast-forward, agent guardrails.
845 * `importMode`: a GitHub import filling the repository it created, which is the only writer
846 * until it finishes, so branch rules (copied from GitHub at its end) don't apply to it.
847 */
848 async checkRefUpdate(ref: string, oldOid: string, newOid: string, caller: Caller, importMode = false): Promise<RefResult> {
849 if (!isValidRefName(ref)) return { ref, ok: false, reason: "invalid ref name" };
850 if (!atLeast(caller.role, "write")) return { ref, ok: false, reason: "permission denied" };
851 const deleting = newOid === ZERO_OID;
852 if (ref.startsWith("refs/pull/")) return { ref, ok: false, reason: "refs/pull/ is managed by Diffinery for pull requests" };
853 if (ref.startsWith(`refs/heads/${QUEUE_BRANCH_PREFIX}`)) return { ref, ok: false, reason: "merge queue branches are read-only" };
854 if (!deleting && !this.store.has(newOid)) return { ref, ok: false, reason: "missing objects" };
855 if (ref.startsWith(IMPORT_REF_PREFIX) && !importMode) return { ref, ok: false, reason: `${IMPORT_REF_PREFIX} is reserved for GitHub imports` };
856 if (importMode) {
857 if (!/^refs\/(heads|tags|diffinery-import)\//.test(ref)) return { ref, ok: false, reason: "imports write branches and tags only" };
858 // H2: create a ref, or move one this import previously wrote — never a ref adopted since.
859 const current = this.getRef(ref);
860 if (current && !deleting) {
861 const owned = this.importsModule.importRefOid(ref, caller.importId!);
862 if (owned !== current) return { ref, ok: false, reason: "import may not overwrite a ref it did not write" };
863 }
864 return { ref, ok: true };
865 }
866 // A workflow's GITHUB_TOKEN never adds or changes workflow files (GitHub's `workflows` permission).
867 const workflowEdit = await this.policy.refuseWorkflowEdit(caller, oldOid, newOid);
868 if (workflowEdit) return { ref, ok: false, reason: workflowEdit };
869 if (!ref.startsWith("refs/heads/")) {
870 if (ref.startsWith("refs/tags/") && oldOid !== ZERO_OID && !atLeast(caller.role, "maintain")) return { ref, ok: false, reason: "only maintainers may move tags" };
871 return { ref, ok: true };
872 }
873 const branch = ref.slice(11);
874 const rules = this.protectionFor(branch);
875 const isDefault = branch === this.meta.defaultBranch;
876 // An empty repository's first commit: an agent that created a repository (or was given an empty one) may
877 // start its default branch, as GitHub's auto_init would; from then on it works through pull requests.
878 // A protection rule covering the branch still applies, and the commit may not add workflow files: those reach
879 // the default branch only through a pull request a person merges, as with auto-merge.
880 const seeding = caller.kind === "agent" && isDefault && !rules && oldOid === ZERO_OID && !this.sql.exec("SELECT 1 FROM refs WHERE name LIKE 'refs/heads/%' LIMIT 1").toArray().length;
881 if (seeding) {
882 const workflow = await this.policy.changedWorkflow(ZERO_OID, newOid);
883 if (workflow) return { ref, ok: false, reason: `an agent's first commit to an empty repository can't add workflow file \`${workflow}\`; push it without workflows, then add them in a pull request a person merges` };
884 }
885 if (caller.kind === "agent" && (isDefault || rules) && !rules?.agentsMayPush && !seeding) {
886 return { ref, ok: false, reason: "agents may not push to protected or default branches; open a pull request" };
887 }
888 if (deleting && isDefault) return { ref, ok: false, reason: "cannot delete the default branch" };
889 if (!rules) return { ref, ok: true };
890 const bypass = caller.role === "admin" && !rules.enforceAdmins;
891 if (bypass) return { ref, ok: true };
892 if (deleting) return rules.allowDeletion ? { ref, ok: true } : { ref, ok: false, reason: "protected branch: deletion not allowed" };
893 if (rules.requirePullRequest) return { ref, ok: false, reason: "protected branch: changes must be made through a pull request" };
894 // As on GitHub, required checks gate direct pushes too: the commit must already have passed them.
895 for (const name of rules.requiredChecks ?? []) {
896 const c = requiredCheck(name, [...this.collab.checks(newOid), ...this.statuses.asChecks(newOid)], rules.requiredCheckSources?.[name]);
897 if (c.state !== "success") {
898 const why = c.state === "missing" ? "has not run" : c.state === "pending" ? "has not finished" : `ended with ${c.conclusion}`;
899 return { ref, ok: false, reason: `protected branch: required check '${name}' ${why} on ${newOid.slice(0, 7)}; push to another branch and open a pull request` };
900 }
901 }
902 if (oldOid !== ZERO_OID && !rules.allowForcePush && !(await isAncestor(this.store, oldOid, newOid))) {
903 return { ref, ok: false, reason: "protected branch: force push not allowed" };
904 }
905 if (rules.requireLinearHistory) {
906 const fresh = await walkCommits(this.store, [newOid], { stop: new Set(oldOid === ZERO_OID ? [] : [oldOid]), limit: 1000 });
907 if (fresh.some((c) => c.commit.parents.length > 1)) return { ref, ok: false, reason: "protected branch: merge commits not allowed (linear history)" };
908 }
909 return { ref, ok: true };
910 }
911
912 /** Side effects after a ref moved: events, PR sync, workflow triggers. */
913 async afterRefUpdate(ref: string, oldOid: string, newOid: string, caller: Caller, messages: string[] = []): Promise<void> {
914 const at = now();
915 const forced = oldOid !== ZERO_OID && newOid !== ZERO_OID && !(await isAncestor(this.store, oldOid, newOid));
916 const ev: DiffineryEvent = {
917 type: "push",
918 repoId: this.meta.repoId,
919 owner: this.meta.owner,
920 repo: this.meta.name,
921 ref,
922 before: oldOid,
923 after: newOid,
924 actor: { id: caller.id, login: caller.login, kind: caller.kind, onBehalfOf: caller.onBehalfOf },
925 forced,
926 created: oldOid === ZERO_OID,
927 deleted: newOid === ZERO_OID,
928 at,
929 };
930 this.emit(ev);
931 this.policy.recordPush(ref, newOid, caller);
932 await this.policy.trackAgentCommits(ref, oldOid, newOid, caller).catch((e) => console.error("could not record an agent's commits", ref, e));
933 this.deploys.noteRefUpdate(ref, newOid, caller);
934 if (ref.startsWith("refs/heads/") && newOid !== ZERO_OID) {
935 const branch = ref.slice(11);
936 const synced = await this.collab.syncPullsForBranch(branch, newOid, caller);
937 for (const n of synced) messages.push(`Updated pull request #${n}: ${this.env.PUBLIC_URL}/${this.meta.owner}/${this.meta.name}/pull/${n}`);
938 if (oldOid === ZERO_OID && branch !== this.meta.defaultBranch && synced.length === 0) {
939 messages.push(`Create a pull request for '${branch}':`);
940 messages.push(` ${this.env.PUBLIC_URL}/${this.meta.owner}/${this.meta.name}/compare/${encodeURIComponent(branch)}`);
941 }
942 }
943 if (newOid !== ZERO_OID) await this.actions.onPush(ev, caller).catch((e) => messages.push(`Workflow trigger error: ${(e as Error).message}`));
944 // A base branch that moved (outside the queue, or by it) needs its merge groups checked,
945 // and pull requests into it waiting to auto-merge may now be up to date.
946 if (ref.startsWith("refs/heads/") && this.queue.hasEntries(ref.slice(11))) this.queue.schedule(ref.slice(11));
947 if (ref.startsWith("refs/heads/") && newOid !== ZERO_OID) this.autoMerge.schedule({ base: ref.slice(11) });
948 }
949
950 // ---------------------------------------------------------------- browsing
951
952 async commitInfo(sha: string): Promise<CommitInfo> {
953 const c = await readCommit(this.store, sha);
954 return toInfo(sha, c);
955 }
956
957 async tree(rev: string, path = ""): Promise<{ sha: string; items: TreeItem[] } | null> {
958 const sha = await this.resolve(rev);
959 if (!sha) return null;
960 const c = await readCommit(this.store, sha);
961 const entry = await resolvePath(this.store, c.tree, path);
962 if (!entry || !isTreeMode(entry.mode)) return null;
963 const items: TreeItem[] = [];
964 for (const e of await readTree(this.store, entry.oid)) {
965 const type = isTreeMode(e.mode) ? "tree" : e.mode === "160000" ? "commit" : "blob";
966 const raw = type === "blob" ? this.sql.exec<{ size: number }>("SELECT size FROM objects WHERE oid = ?", e.oid).toArray()[0] : undefined;
967 items.push({ name: e.name, path: path ? `${path}/${e.name}` : e.name, type, mode: e.mode, oid: e.oid, size: raw?.size });
968 }
969 items.sort((a, b) => (a.type === b.type ? a.name.localeCompare(b.name) : a.type === "tree" ? -1 : 1));
970 return { sha, items };
971 }
972
973 async blob(rev: string, path: string): Promise<{ sha: string; oid: string; mode: string; size: number; binary: boolean; content: Uint8Array } | null> {
974 const sha = await this.resolve(rev);
975 if (!sha) return null;
976 const c = await readCommit(this.store, sha);
977 const entry = await resolvePath(this.store, c.tree, path);
978 if (!entry || isTreeMode(entry.mode)) return null;
979 const o = await this.store.read(entry.oid);
980 if (!o) return null;
981 return { sha, oid: entry.oid, mode: entry.mode, size: o.content.length, binary: isBinary(o.content), content: o.content };
982 }
983
984 async log(rev: string, opts: { path?: string; limit?: number; skip?: number } = {}): Promise<CommitInfo[]> {
985 const sha = await this.resolve(rev);
986 if (!sha) return [];
987 const limit = Math.min(opts.limit ?? 30, 100);
988 const skip = Math.max(opts.skip ?? 0, 0);
989 if (!opts.path) {
990 // Paging past MAX_LOG_DEPTH lists nothing rather than walking the whole history for one page.
991 if (skip >= MAX_LOG_DEPTH) return [];
992 const commits = await walkCommits(this.store, [sha], { limit: Math.min(limit + skip, MAX_LOG_DEPTH) });
993 return commits.slice(skip).map((c) => toInfo(c.oid, c.commit));
994 }
995 // Path history: commits whose tree entry at `path` differs from their first parent's.
996 const out: CommitInfo[] = [];
997 let skipped = 0;
998 for (const c of await walkCommits(this.store, [sha], { limit: 2000 })) {
999 if (!(await this.changes(c.commit, opts.path))) continue;
1000 if (skipped++ < skip) continue;
1001 out.push(toInfo(c.oid, c.commit));
1002 if (out.length >= limit) break;
1003 }
1004 return out;
1005 }
1006
1007 /** How many commits `log` lists from a commit: up to MAX_LOG_DEPTH, or with `path`, those of the first 2000 that changed it. */
1008 async logCount(rev: string, path?: string): Promise<number> {
1009 const sha = await this.resolve(rev);
1010 if (!sha) return 0;
1011 if (!path) return (await walkCommits(this.store, [sha], { limit: MAX_LOG_DEPTH })).length;
1012 let n = 0;
1013 for (const c of await walkCommits(this.store, [sha], { limit: 2000 })) if (await this.changes(c.commit, path)) n++;
1014 return n;
1015 }
1016
1017 /** Whether a commit's tree entry at `path` differs from its first parent's. */
1018 private async changes(c: Commit, path: string): Promise<boolean> {
1019 const mine = await resolvePath(this.store, c.tree, path);
1020 const parent = c.parents[0] ? await readCommit(this.store, c.parents[0]).catch(() => null) : null;
1021 const theirs = parent ? await resolvePath(this.store, parent.tree, path) : null;
1022 return (mine?.oid ?? null) !== (theirs?.oid ?? null);
1023 }
1024
1025 /** Diff between two commits (or a commit and its first parent). */
1026 async diff(baseSha: string | null, headSha: string, opts: { patch?: boolean; maxFiles?: number } = {}) {
1027 const head = await readCommit(this.store, headSha);
1028 const baseTree = baseSha ? (await readCommit(this.store, baseSha)).tree : null;
1029 const changes = await diffTrees(this.store, baseTree, head.tree);
1030 const max = opts.maxFiles ?? 300;
1031 const files = [];
1032 const budget = new DiffBudget();
1033 for (const ch of changes.slice(0, max)) {
1034 const d = await fileDiff(this.store, ch, 3, budget);
1035 files.push({ ...d, patch: opts.patch === false ? undefined : formatUnified(d) });
1036 }
1037 return {
1038 files,
1039 totalFiles: changes.length,
1040 additions: files.reduce((s, f) => s + f.additions, 0),
1041 deletions: files.reduce((s, f) => s + f.deletions, 0),
1042 truncated: changes.length > max,
1043 };
1044 }
1045
1046 async commitWithDiff(rev: string) {
1047 const sha = await this.resolve(rev);
1048 if (!sha) throw new HttpError(404, "commit not found");
1049 const info = await this.commitInfo(sha);
1050 return { ...info, ...(await this.diff(info.parents[0] ?? null, sha)) };
1051 }
1052
1053 async compare(base: string, head: string) {
1054 const b = await this.resolve(base);
1055 const h = await this.resolve(head);
1056 if (!b || !h) throw new HttpError(404, "unknown base or head");
1057 const mb = await mergeBase(this.store, b, h);
1058 const commits = (await walkCommits(this.store, [h], { stop: new Set(mb ? (await walkCommits(this.store, [mb], { limit: 100000 })).map((c) => c.oid) : []), limit: 250 })).map((c) => toInfo(c.oid, c.commit));
1059 const ahead = commits.length;
1060 const behind = mb ? (await walkCommits(this.store, [b], { stop: new Set([mb]), limit: 1000 })).filter((c) => c.oid !== mb).length : 0;
1061 return { baseSha: b, headSha: h, mergeBase: mb, aheadBy: ahead, behindBy: behind, commits: commits.reverse(), ...(await this.diff(mb, h)) };
1062 }
1063
1064 /**
1065 * Push protection for commits made without a Git client: the same scan as `git push`, so the
1066 * web editor, the contents and commits APIs and MCP cannot be used to slip a credential in.
1067 */
1068 private protectCommit(changes: readonly FileChange[], allowSecrets: string | undefined, caller: Caller, message = ""): void {
1069 const blobs = changes.filter((ch) => !ch.delete && ch.content).map((ch) => ({ oid: ch.path, content: ch.content! }));
1070 if (message) blobs.push({ oid: "(commit message)", content: utf8(message) });
1071 const marked: SecretHit[] = [];
1072 const leaks = scanForSecrets(blobs, marked);
1073 const target = `${this.meta.owner}/${this.meta.name}`;
1074 if (marked.length) this.emit({ type: "audit", action: "api.secret_marked", actor: caller, target, detail: { kinds: [...new Set(marked.map((l) => l.kind))], paths: [...new Set(marked.map((l) => l.oid))].slice(0, 10) }, at: now() });
1075 if (!leaks.length) return;
1076 const kinds = [...new Set(leaks.map((l) => l.kind))];
1077 const paths = [...new Set(leaks.map((l) => l.oid))].slice(0, 10);
1078 const reason = allowSecrets?.trim().slice(0, 200);
1079 if (reason && caller.role === "admin" && caller.kind === "user") {
1080 this.emit({ type: "audit", action: "api.secret_bypassed", actor: caller, target, detail: { kinds, paths, reason }, at: now() });
1081 return;
1082 }
1083 this.emit({ type: "audit", action: "api.blocked_secret", actor: caller, target, detail: { kinds, paths }, at: now() });
1084 const hint = reason ? " Only repository admins (people, not agents) can bypass push protection." : "";
1085 throw new HttpError(422, `push protection: possible secret detected (${kinds.join(", ")}) in ${paths.join(", ")}. Remove it, or rotate it and ask an admin.${hint}`);
1086 }
1087
1088 /**
1089 * Create a commit from file changes without a Git client (used by the web
1090 * editor, the REST contents API and AI agents through MCP).
1091 */
1092 async commitFiles(input: {
1093 branch: string;
1094 message: string;
1095 changes: FileChange[];
1096 expectedHeadSha?: string;
1097 createBranchFrom?: string;
1098 author?: { name: string; email: string };
1099 committer?: { name: string; email: string };
1100 /** A human admin's reason for committing a detected secret anyway (like `git push -o allow-secrets=`). */
1101 allowSecrets?: string;
1102 }, caller: Caller): Promise<{ sha: string; branch: string }> {
1103 const ref = `refs/heads/${input.branch}`;
1104 let parent = this.getRef(ref);
1105 if (!parent) {
1106 if (input.createBranchFrom) parent = await this.resolve(input.createBranchFrom);
1107 else if (this.refs("refs/heads/").length > 0) throw new HttpError(404, `branch ${input.branch} not found`);
1108 }
1109 if (input.expectedHeadSha && parent !== input.expectedHeadSha) throw new HttpError(409, "branch moved; refresh and retry", { currentSha: parent });
1110 for (const ch of input.changes) {
1111 const why = ch.delete ? null : unsafeTreePath(ch.path);
1112 if (why) throw new HttpError(422, `invalid path ${JSON.stringify(ch.path)}: ${why}`);
1113 }
1114 const adding = input.changes.reduce((n, ch) => n + (ch.content?.length ?? 0), 0);
1115 if (adding) await this.checkStorage(adding);
1116 this.protectCommit(input.changes, input.allowSecrets, caller, input.message);
1117 const baseTree = parent ? (await readCommit(this.store, parent)).tree : null;
1118 const tree = await applyChanges(this.store, baseTree, input.changes);
1119 const ts = Math.floor(Date.now() / 1000);
1120 const committer = input.committer
1121 ? { ...input.committer, timestamp: ts, timezone: "+0000" }
1122 : { name: caller.login, email: this.noreply(caller.login), timestamp: ts, timezone: "+0000" };
1123 const author = input.author ? { ...input.author, timestamp: ts, timezone: "+0000" } : committer;
1124 const extra: [string, string][] = caller.kind === "agent" ? [["diffinery-agent", `${caller.login}${caller.onBehalfOf ? ` on-behalf-of ${caller.onBehalfOf}` : ""}`]] : [];
1125 const sha = await this.store.write(
1126 "commit",
1127 serializeCommit({ tree: tree === EMPTY_TREE_OID ? tree : tree, parents: parent ? [parent] : [], author, committer, message: input.message.endsWith("\n") ? input.message : `${input.message}\n`, extraHeaders: extra }),
1128 );
1129 const old = parent && this.getRef(ref) ? parent : ZERO_OID;
1130 const check = await this.checkRefUpdate(ref, old, sha, caller);
1131 if (!check.ok) throw new HttpError(403, check.reason ?? "rejected");
1132 if (!this.casRef(ref, old, sha)) throw new HttpError(409, "branch moved; refresh and retry");
1133 await this.afterRefUpdate(ref, old, sha, caller);
1134 return { sha, branch: input.branch };
1135 }
1136
1137 async createRef(ref: string, sha: string, caller: Caller): Promise<void> {
1138 if (!this.store.has(sha)) throw new HttpError(422, "object does not exist");
1139 const check = await this.checkRefUpdate(ref, ZERO_OID, sha, caller);
1140 if (!check.ok) throw new HttpError(403, check.reason ?? "rejected");
1141 if (!this.casRef(ref, ZERO_OID, sha)) throw new HttpError(422, "reference already exists");
1142 await this.afterRefUpdate(ref, ZERO_OID, sha, caller);
1143 }
1144
1145 async updateRef(ref: string, sha: string, force: boolean, caller: Caller): Promise<void> {
1146 const old = this.getRef(ref);
1147 if (!old) throw new HttpError(404, "reference not found");
1148 if (!force && !(await isAncestor(this.store, old, sha))) throw new HttpError(422, "update is not a fast-forward");
1149 const check = await this.checkRefUpdate(ref, old, sha, caller);
1150 if (!check.ok) throw new HttpError(403, check.reason ?? "rejected");
1151 if (!this.casRef(ref, old, sha)) throw new HttpError(409, "reference moved");
1152 await this.afterRefUpdate(ref, old, sha, caller);
1153 }
1154
1155 async deleteRef(ref: string, caller: Caller): Promise<void> {
1156 const old = this.getRef(ref);
1157 if (!old) throw new HttpError(404, "reference not found");
1158 const check = await this.checkRefUpdate(ref, old, ZERO_OID, caller);
1159 if (!check.ok) throw new HttpError(403, check.reason ?? "rejected");
1160 this.casRef(ref, old, null);
1161 await this.afterRefUpdate(ref, old, ZERO_OID, caller);
1162 }
1163
1164 // ---------------------------------------------------------------- protections
1165
1166 /**
1167 * What Settings → Merge on green (web/merge-on-green.tsx) suggests: the checks reported on the heads of the
1168 * latest pull requests, which are the names a required check must match, and the agents that opened pull
1169 * requests here. `latest`: the check ran on each of the last three pull requests that had checks, so
1170 * requiring it won't hold up a pull request whose workflows skip it. Reports by agents never count.
1171 */
1172 mergeOnGreenHints(): { pulls: number; checks: Array<{ name: string; pulls: number; latest: boolean }>; agents: Array<{ id: string; login: string }> } {
1173 const heads = this.sql.exec<{ head_sha: string }>("SELECT head_sha FROM pulls ORDER BY number DESC LIMIT 20").toArray();
1174 const count = new Map<string, number>();
1175 const recent: Array<Set<string>> = [];
1176 let pulls = 0;
1177 for (const h of heads) {
1178 const names = new Set([...this.collab.checks(h.head_sha), ...this.statuses.asChecks(h.head_sha)].filter((c) => c.creatorKind !== "agent").map((c) => c.name));
1179 if (!names.size) continue;
1180 pulls++;
1181 if (recent.length < 3) recent.push(names);
1182 for (const n of names) count.set(n, (count.get(n) ?? 0) + 1);
1183 }
1184 const checks = [...count]
1185 .map(([name, n]) => ({ name, pulls: n, latest: recent.every((r) => r.has(name)) }))
1186 .sort((a, b) => Number(b.latest) - Number(a.latest) || b.pulls - a.pulls || a.name.localeCompare(b.name))
1187 .slice(0, 50);
1188 const agents: Array<{ id: string; login: string }> = [];
1189 for (const a of this.sql.exec<{ author_id: string; author_login: string }>("SELECT author_id, author_login FROM issues WHERE kind = 'pull' AND author_kind = 'agent' ORDER BY number DESC LIMIT 200").toArray()) {
1190 if (agents.length >= 20) break;
1191 if (!agents.some((x) => x.id === a.author_id)) agents.push({ id: a.author_id, login: a.author_login });
1192 }
1193 return { pulls, checks, agents };
1194 }
1195
1196 listProtections(): Array<{ pattern: string; rules: ProtectionRules }> {
1197 return this.sql.exec<{ pattern: string; rules: string }>("SELECT pattern, rules FROM protections ORDER BY pattern").toArray().map((r) => ({ pattern: r.pattern, rules: JSON.parse(r.rules) }));
1198 }
1199
1200 /**
1201 * Create, replace or (with null) delete a rule. Only people who administer the repository change
1202 * branch protection: never agents, never a workflow's token. Turning `allowAgentAutoMerge`,
1203 * `agentAutoMergeWithoutApproval` or `autoMergeAgents` on or off is audited on its own, since they let
1204 * agents land changes.
1205 */
1206 async setProtection(pattern: string, input: ProtectionRulesInput | null, caller: Caller): Promise<void> {
1207 if (!isPerson(caller) || caller.role !== "admin") throw new HttpError(403, caller.kind === "agent" ? "agents cannot change branch protection" : "only people who administer the repository can change branch protection");
1208 let rules = input ? await this.resolveAutoMergeAgents(input) : null;
1209 if (rules?.mergeQueue) {
1210 const asked = typeof rules.mergeQueue === "object" ? rules.mergeQueue.method : undefined;
1211 const mergeQueue = normalizeMergeQueue(rules.mergeQueue);
1212 // A queue that makes merge commits could never merge into a branch that refuses them.
1213 if (rules.requireLinearHistory && mergeQueue.method === "merge") {
1214 if (asked !== undefined) throw new HttpError(422, "this branch requires linear history, so its merge queue must squash or rebase (mergeQueue.method), not create merge commits");
1215 mergeQueue.method = "squash";
1216 }
1217 rules = { ...rules, mergeQueue };
1218 }
1219 if (rules?.requiredCheckSources) rules = { ...rules, requiredCheckSources: normalizeCheckSources(rules.requiredCheckSources) };
1220 // A required "Agent review" means Diffinery's own check (agentic/review.ts), not one anyone with write access could post.
1221 if (rules?.requiredChecks?.includes(REVIEW_CHECK) && !rules.requiredCheckSources?.[REVIEW_CHECK]) rules = { ...rules, requiredCheckSources: { ...rules.requiredCheckSources, [REVIEW_CHECK]: REVIEW_APP } };
1222 if (rules && rules.allowAgentAutoMerge !== undefined && typeof rules.allowAgentAutoMerge !== "boolean") throw new HttpError(422, "allowAgentAutoMerge must be a boolean");
1223 if (rules && rules.agentAutoMergeWithoutApproval !== undefined && typeof rules.agentAutoMergeWithoutApproval !== "boolean") throw new HttpError(422, "agentAutoMergeWithoutApproval must be a boolean");
1224 if (rules?.agentAutoMergeWithoutApproval && !rules.allowAgentAutoMerge) throw new HttpError(422, "agentAutoMergeWithoutApproval needs allowAgentAutoMerge: it only applies to what Diffinery lands for agents");
1225 if (rules?.autoMergeAgents?.length && !rules.allowAgentAutoMerge) throw new HttpError(422, "autoMergeAgents needs allowAgentAutoMerge: Diffinery turns on auto-merge as those agents, under the same rules as their own");
1226 if (rules?.autoMergeMethod !== undefined && !(["merge", "squash", "rebase"] as const).includes(rules.autoMergeMethod)) throw new HttpError(422, "autoMergeMethod must be merge, squash or rebase");
1227 if (rules?.autoMergeMethod === "merge" && rules.requireLinearHistory) throw new HttpError(422, "this branch requires linear history, so autoMergeMethod must be squash or rebase");
1228 if (rules && !rules.allowAgentAutoMerge) {
1229 const { allowAgentAutoMerge: _, agentAutoMergeWithoutApproval: _w, autoMergeAgents: _a, autoMergeMethod: _m, ...rest } = rules;
1230 rules = rest;
1231 }
1232 if (rules && !rules.agentAutoMergeWithoutApproval) {
1233 const { agentAutoMergeWithoutApproval: _, ...rest } = rules;
1234 rules = rest;
1235 }
1236 if (rules && !rules.autoMergeAgents?.length) {
1237 const { autoMergeAgents: _, autoMergeMethod: _m, ...rest } = rules;
1238 rules = rest;
1239 }
1240 const before = this.sql.exec<{ rules: string }>("SELECT rules FROM protections WHERE pattern = ?", pattern).toArray()[0];
1241 const old = before ? (JSON.parse(before.rules) as ProtectionRules) : null;
1242 const was = !!old?.allowAgentAutoMerge;
1243 const waived = !!old?.agentAutoMergeWithoutApproval;
1244 const agentsKey = (r: ProtectionRules | null) => (r?.autoMergeAgents?.length ? `${r.autoMergeAgents.map((a) => a.id).join(",")}|${r.autoMergeMethod ?? ""}` : "");
1245 if (rules) this.sql.exec("INSERT INTO protections (pattern, rules) VALUES (?, ?) ON CONFLICT(pattern) DO UPDATE SET rules = excluded.rules", pattern, JSON.stringify(rules));
1246 else this.sql.exec("DELETE FROM protections WHERE pattern = ?", pattern);
1247 if (was !== !!rules?.allowAgentAutoMerge) {
1248 const m = this.meta;
1249 this.emit({ type: "audit", action: "repo.protection.agent_auto_merge", actor: { id: caller.id, login: caller.login, kind: caller.kind, onBehalfOf: caller.onBehalfOf }, target: `${m.owner}/${m.name}`, detail: { pattern, enabled: !!rules?.allowAgentAutoMerge, requiredChecks: rules?.requiredChecks ?? [] }, at: now() });
1250 }
1251 if (waived !== !!rules?.agentAutoMergeWithoutApproval) {
1252 const m = this.meta;
1253 this.emit({ type: "audit", action: "repo.protection.agent_approval_waiver", actor: { id: caller.id, login: caller.login, kind: caller.kind, onBehalfOf: caller.onBehalfOf }, target: `${m.owner}/${m.name}`, detail: { pattern, enabled: !!rules?.agentAutoMergeWithoutApproval, requiredChecks: rules?.requiredChecks ?? [] }, at: now() });
1254 }
1255 if (agentsKey(old) !== agentsKey(rules)) {
1256 const m = this.meta;
1257 this.emit({
1258 type: "audit",
1259 action: "repo.protection.agent_auto_merge_rule",
1260 actor: { id: caller.id, login: caller.login, kind: caller.kind, onBehalfOf: caller.onBehalfOf },
1261 target: `${m.owner}/${m.name}`,
1262 detail: { pattern, enabled: !!rules?.autoMergeAgents?.length, agents: (rules?.autoMergeAgents ?? []).map((a) => a.login), method: rules?.autoMergeMethod ?? null, withoutApproval: !!rules?.agentAutoMergeWithoutApproval, requiredChecks: rules?.requiredChecks ?? [] },
1263 at: now(),
1264 });
1265 }
1266 // Turning a queue off (or changing its checks) affects what is queued, and what may auto-merge.
1267 this.queue.schedule();
1268 this.autoMerge.schedule();
1269 }
1270
1271 /** `autoMergeAgents` names agent accounts, by login or as stored ({ id, login }); store them by id, with the login as it is now. */
1272 private async resolveAutoMergeAgents(input: ProtectionRulesInput): Promise<ProtectionRules> {
1273 const { autoMergeAgents: names, ...rest } = input;
1274 if (names === undefined || names === null) return rest;
1275 if (!Array.isArray(names)) throw new HttpError(422, "autoMergeAgents must be a list of agent logins");
1276 if (names.length > MAX_AUTO_MERGE_AGENTS) throw new HttpError(422, `autoMergeAgents can name at most ${MAX_AUTO_MERGE_AGENTS} agents`);
1277 const dir = new Directory(this.env);
1278 const agents: AutoMergeAgent[] = [];
1279 for (const n of names) {
1280 const login = typeof n === "string" ? n.trim().replace(/^@/, "") : n && typeof n === "object" && typeof n.login === "string" ? n.login : null;
1281 if (!login) throw new HttpError(422, "autoMergeAgents must be a list of agent logins");
1282 const account = typeof n === "object" && typeof n.id === "string" ? ((await dir.account(n.id)) ?? (await dir.accountByLogin(login))) : await dir.accountByLogin(login);
1283 if (!account) throw new HttpError(422, `autoMergeAgents: there is no account named ${login}`);
1284 if (account.kind !== "agent") throw new HttpError(422, `autoMergeAgents: ${account.login} is not an agent; only agents' pull requests can be auto-merged by a rule`);
1285 if (!agents.some((a) => a.id === account.id)) agents.push({ id: account.id, login: account.login });
1286 }
1287 return agents.length ? { ...rest, autoMergeAgents: agents } : rest;
1288 }
1289
1290 // ---------------------------------------------------------------- RPC passthroughs (collab + actions)
1291 // Workers RPC only exposes methods on the class itself, so the sub-modules are wrapped here.
1292
1293 issues(...a: Parameters<Collab["list"]>) {
1294 return this.collab.list(...a);
1295 }
1296 issue(...a: Parameters<Collab["get"]>) {
1297 return this.collab.get(...a);
1298 }
1299 createIssue(...a: Parameters<Collab["createIssue"]>) {
1300 return this.collab.createIssue(...a);
1301 }
1302 updateIssue(...a: Parameters<Collab["update"]>) {
1303 return this.collab.update(...a);
1304 }
1305 setPullDraft(...a: Parameters<Collab["setDraft"]>) {
1306 return this.collab.setDraft(...a);
1307 }
1308 addComment(...a: Parameters<Collab["addComment"]>) {
1309 return this.collab.addComment(...a);
1310 }
1311 editComment(...a: Parameters<Collab["editComment"]>) {
1312 return this.collab.editComment(...a);
1313 }
1314 minimizeComment(...a: Parameters<Collab["minimizeComment"]>) {
1315 return this.collab.minimizeComment(...a);
1316 }
1317 createPull(...a: Parameters<Collab["createPull"]>) {
1318 return this.collab.createPull(...a);
1319 }
1320 pullFiles(...a: Parameters<Collab["pullFiles"]>) {
1321 return this.collab.pullFiles(...a);
1322 }
1323 pullCommits(...a: Parameters<Collab["pullCommits"]>) {
1324 return this.collab.pullCommits(...a);
1325 }
1326 pullStats(...a: Parameters<Collab["pullStats"]>) {
1327 return this.collab.pullStats(...a);
1328 }
1329 reviewState(...a: Parameters<Collab["reviewState"]>) {
1330 return this.collab.reviewState(...a);
1331 }
1332 submitReview(...a: Parameters<Collab["submitReview"]>) {
1333 return this.collab.submitReview(...a);
1334 }
1335 resolveThread(...a: Parameters<Collab["resolveThread"]>) {
1336 return this.collab.resolveThread(...a);
1337 }
1338 mergeability(...a: Parameters<Collab["mergeability"]>) {
1339 return this.collab.mergeability(...a);
1340 }
1341 mergePull(...a: Parameters<Collab["merge"]>) {
1342 return this.collab.merge(...a);
1343 }
1344 requestReviewers(...a: Parameters<Collab["requestReviewers"]>) {
1345 return this.collab.requestReviewers(...a);
1346 }
1347 labels(...a: Parameters<Collab["labels"]>) {
1348 return this.collab.labels(...a);
1349 }
1350 setLabel(...a: Parameters<Collab["setLabel"]>) {
1351 return this.collab.setLabel(...a);
1352 }
1353 checks(...a: Parameters<Collab["checks"]>) {
1354 return this.collab.checks(...a);
1355 }
1356 upsertCheck(...a: Parameters<Collab["upsertCheck"]>) {
1357 return this.collab.upsertCheck(...a);
1358 }
1359 webhooks(...a: Parameters<Collab["webhooks"]>) {
1360 return this.collab.webhooks(...a);
1361 }
1362 deliverableWebhooks(...a: Parameters<Collab["deliverableWebhooks"]>) {
1363 return this.collab.deliverableWebhooks(...a);
1364 }
1365 createWebhook(url: string, events: string[], secret?: string) {
1366 return this.collab.createWebhook(url, events, secret, new URL(this.env.PUBLIC_URL).hostname);
1367 }
1368 deleteWebhook(...a: Parameters<Collab["deleteWebhook"]>) {
1369 return this.collab.deleteWebhook(...a);
1370 }
1371 recordDelivery(...a: Parameters<Collab["recordDelivery"]>) {
1372 return this.collab.recordDelivery(...a);
1373 }
1374
1375 enqueuePull(...a: Parameters<MergeQueue["enqueue"]>) {
1376 return this.queue.enqueue(...a);
1377 }
1378 dequeuePull(...a: Parameters<MergeQueue["dequeue"]>) {
1379 return this.queue.dequeue(...a);
1380 }
1381 mergeQueue(...a: Parameters<MergeQueue["list"]>) {
1382 return this.queue.list(...a);
1383 }
1384 mergeQueueSettings(...a: Parameters<MergeQueue["settings"]>) {
1385 return this.queue.settings(...a);
1386 }
1387 /** A caller's own auto-merge; only the server turns one on for a branch rule (AutoMerge.applyRule). */
1388 enableAutoMerge(number: number, input: Parameters<AutoMerge["enable"]>[1], caller: Caller) {
1389 return this.autoMerge.enable(number, input, caller);
1390 }
1391 disableAutoMerge(...a: Parameters<AutoMerge["disable"]>) {
1392 return this.autoMerge.disable(...a);
1393 }
1394
1395 runs(...a: Parameters<Actions["listRuns"]>) {
1396 return this.actions.listRuns(...a);
1397 }
1398 run(...a: Parameters<Actions["getRun"]>) {
1399 return this.actions.getRun(...a);
1400 }
1401 runJobs(...a: Parameters<Actions["jobs"]>) {
1402 return this.actions.jobs(...a);
1403 }
1404 claimJobAsRunner(...a: Parameters<Actions["claimJobAsRunner"]>) {
1405 return this.actions.claimJobAsRunner(...a);
1406 }
1407 runnerRegistrationToken(...a: Parameters<Actions["runnerRegistrationToken"]>) {
1408 return this.actions.runnerRegistrationToken(...a);
1409 }
1410 registerRunner(...a: Parameters<Actions["registerRunner"]>) {
1411 return this.actions.registerRunner(...a);
1412 }
1413 runners(...a: Parameters<Actions["runners"]>) {
1414 return this.actions.runners(...a);
1415 }
1416 deleteRunner(...a: Parameters<Actions["deleteRunner"]>) {
1417 return this.actions.deleteRunner(...a);
1418 }
1419 jobStatus(jobId: string): string {
1420 return this.actions.getJob(jobId).status;
1421 }
1422 job(...a: Parameters<Actions["getJob"]>) {
1423 return this.actions.getJob(...a);
1424 }
1425 jobLogs(...a: Parameters<Actions["logs"]>) {
1426 return this.actions.logs(...a);
1427 }
1428 cancelRun(...a: Parameters<Actions["cancel"]>) {
1429 return this.actions.cancel(...a);
1430 }
1431 deleteRunLogs(...a: Parameters<Actions["deleteLogs"]>) {
1432 return this.actions.deleteLogs(...a);
1433 }
1434 rerun(...a: Parameters<Actions["rerun"]>) {
1435 return this.actions.rerun(...a);
1436 }
1437 rerunJob(...a: Parameters<Actions["rerunJob"]>) {
1438 return this.actions.rerunJob(...a);
1439 }
1440 dispatchWorkflow(...a: Parameters<Actions["dispatch"]>) {
1441 return this.actions.dispatch(...a);
1442 }
1443 scheduleTick(...a: Parameters<Actions["schedule"]>) {
1444 return this.actions.schedule(...a);
1445 }
1446 onPullRequestEvent(...a: Parameters<Actions["onPullRequest"]>) {
1447 return this.actions.onPullRequest(...a);
1448 }
1449 workflows(...a: Parameters<Actions["listWorkflows"]>) {
1450 return this.actions.listWorkflows(...a);
1451 }
1452 runPlan(...a: Parameters<Actions["plan"]>) {
1453 return this.actions.plan(...a);
1454 }
1455 startJobKey(...a: Parameters<Actions["startJobKey"]>) {
1456 return this.actions.startJobKey(...a);
1457 }
1458 jobGate(...a: Parameters<Actions["jobGate"]>) {
1459 return this.actions.jobGate(...a);
1460 }
1461 pendingDeployments(...a: Parameters<Actions["pendingDeployments"]>) {
1462 return this.actions.pendingDeployments(...a);
1463 }
1464 reviewDeployments(...a: Parameters<Actions["reviewDeployments"]>) {
1465 return this.actions.reviewDeployments(...a);
1466 }
1467 deploymentReviews(...a: Parameters<Actions["deploymentReviews"]>) {
1468 return this.actions.deploymentReviews(...a);
1469 }
1470 jobTimedOut(...a: Parameters<Actions["jobTimedOut"]>) {
1471 return this.actions.jobTimedOut(...a);
1472 }
1473 finishRun(...a: Parameters<Actions["finishRun"]>) {
1474 return this.actions.finishRun(...a);
1475 }
1476 oidcClaims(...a: Parameters<Actions["oidcClaims"]>) {
1477 return this.actions.oidcClaims(...a);
1478 }
1479 runnerSpec(...a: Parameters<Actions["runnerSpec"]>) {
1480 return this.actions.runnerSpec(...a);
1481 }
1482 runnerLogs(...a: Parameters<Actions["runnerLogs"]>) {
1483 return this.actions.runnerLogs(...a);
1484 }
1485 runnerStep(...a: Parameters<Actions["runnerStep"]>) {
1486 return this.actions.runnerStep(...a);
1487 }
1488 runnerComplete(...a: Parameters<Actions["runnerComplete"]>) {
1489 return this.actions.runnerComplete(...a);
1490 }
1491 packagesPermission(...a: Parameters<Actions["packagesPermission"]>) {
1492 return this.actions.packagesPermission(...a);
1493 }
1494 runnerAuth(...a: Parameters<Actions["runnerAuth"]>) {
1495 return this.actions.runnerAuth(...a);
1496 }
1497 containerStopped(...a: Parameters<Actions["containerStopped"]>) {
1498 return this.actions.containerStopped(...a);
1499 }
1500 relaunchJob(...a: Parameters<Actions["relaunchJob"]>) {
1501 return this.actions.relaunchJob(...a);
1502 }
1503 setSecret(...a: Parameters<Actions["setSecret"]>) {
1504 return this.actions.setSecret(...a);
1505 }
1506 deleteSecret(...a: Parameters<Actions["deleteSecret"]>) {
1507 return this.actions.deleteSecret(...a);
1508 }
1509 secretNames(...a: Parameters<Actions["secretNames"]>) {
1510 return this.actions.secretNames(...a);
1511 }
1512 setVariable(...a: Parameters<Actions["setVariable"]>) {
1513 return this.actions.setVariable(...a);
1514 }
1515 variables(...a: Parameters<Actions["variables"]>) {
1516 return this.actions.variables(...a);
1517 }
1518 cacheLookup(...a: Parameters<Actions["cacheLookup"]>) {
1519 return this.actions.cacheLookup(...a);
1520 }
1521 cacheSaved(...a: Parameters<Actions["cacheSaved"]>) {
1522 return this.actions.cacheSaved(...a);
1523 }
1524 artifactUploadKeys(...a: Parameters<Actions["artifactUploadKeys"]>) {
1525 return this.actions.artifactUploadKeys(...a);
1526 }
1527 artifactSaved(...a: Parameters<Actions["artifactSaved"]>) {
1528 return this.actions.artifactSaved(...a);
1529 }
1530 artifacts(...a: Parameters<Actions["artifacts"]>) {
1531 return this.actions.artifacts(...a);
1532 }
1533 createSandbox(...a: Parameters<Actions["createSandbox"]>) {
1534 return this.actions.createSandbox(...a);
1535 }
1536 sandbox(...a: Parameters<Actions["getSandbox"]>) {
1537 return this.actions.getSandbox(...a);
1538 }
1539 closeSandbox(...a: Parameters<Actions["closeSandbox"]>) {
1540 return this.actions.closeSandbox(...a);
1541 }
1542 closeTaskSandbox(...a: Parameters<Actions["closeTaskSandbox"]>) {
1543 return this.actions.closeTaskSandbox(...a);
1544 }
1545 /** A kill switch was turned on (lib/killswitch.ts): stop what runs here now. */
1546 stopActions(...a: Parameters<Actions["stopActions"]>) {
1547 return this.actions.stopActions(...a);
1548 }
1549
1550 plannedRunError(runId: string, message: string) {
1551 return this.actions.plannedError(runId, message);
1552 }
1553 cacheSaveKeys(...a: Parameters<Actions["cacheSaveKeys"]>) {
1554 return this.actions.cacheSaveKeys(...a);
1555 }
1556 cacheReadKeys(...a: Parameters<Actions["cacheReadKeys"]>) {
1557 return this.actions.cacheReadKeys(...a);
1558 }
1559 artifactKeysFor(...a: Parameters<Actions["artifactKeysFor"]>) {
1560 return this.actions.artifactKeysFor(...a);
1561 }
1562 requireRunningJob(...a: Parameters<Actions["requireRunningJob"]>) {
1563 return this.actions.requireRunningJob(...a);
1564 }
1565 artifactQuota() {
1566 return this.runtime.artifactQuota;
1567 }
1568
1569 // ---------------------------------------------------------------- RPC passthroughs (Actions runtime services)
1570 // The cache and artifact services of repo/runtime.ts, called by http/actions-runtime.ts
1571 // with the job named by a runtime token, and by the REST caches/artifacts routes.
1572
1573 rtJob(...a: Parameters<Runtime["job"]>) {
1574 return this.runtime.job(...a);
1575 }
1576 rtGrantFor(...a: Parameters<Runtime["grantFor"]>) {
1577 return this.runtime.grantFor(...a);
1578 }
1579 rtCacheLookup(...a: Parameters<Runtime["cacheLookup"]>) {
1580 return this.runtime.cacheLookup(...a);
1581 }
1582 rtCacheReserve(...a: Parameters<Runtime["cacheReserve"]>) {
1583 return this.runtime.cacheReserve(...a);
1584 }
1585 rtCacheReservation(...a: Parameters<Runtime["cacheReservation"]>) {
1586 return this.runtime.cacheReservation(...a);
1587 }
1588 rtCacheWritable(...a: Parameters<Runtime["cacheWritable"]>) {
1589 return this.runtime.cacheWritable(...a);
1590 }
1591 rtCacheCommit(...a: Parameters<Runtime["cacheCommit"]>) {
1592 return this.runtime.cacheCommit(...a);
1593 }
1594 rtCacheGet(...a: Parameters<Runtime["cacheGet"]>) {
1595 return this.runtime.cacheGet(...a);
1596 }
1597 rtListCaches(...a: Parameters<Runtime["listCaches"]>) {
1598 return this.runtime.listCaches(...a);
1599 }
1600 rtDeleteCaches(...a: Parameters<Runtime["deleteCaches"]>) {
1601 return this.runtime.deleteCaches(...a);
1602 }
1603 rtCacheUsage(...a: Parameters<Runtime["cacheUsage"]>) {
1604 return this.runtime.cacheUsage(...a);
1605 }
1606 rtArtifactCreate(...a: Parameters<Runtime["artifactCreate"]>) {
1607 return this.runtime.artifactCreate(...a);
1608 }
1609 rtArtifactUpload(...a: Parameters<Runtime["artifactUpload"]>) {
1610 return this.runtime.artifactUpload(...a);
1611 }
1612 rtArtifactWritable(...a: Parameters<Runtime["artifactWritable"]>) {
1613 return this.runtime.artifactWritable(...a);
1614 }
1615 rtArtifactFinalize(...a: Parameters<Runtime["artifactFinalize"]>) {
1616 return this.runtime.artifactFinalize(...a);
1617 }
1618 rtArtifactGet(...a: Parameters<Runtime["artifactGet"]>) {
1619 return this.runtime.artifactGet(...a);
1620 }
1621 rtJobArtifacts(...a: Parameters<Runtime["jobArtifacts"]>) {
1622 return this.runtime.jobArtifacts(...a);
1623 }
1624 rtRunArtifacts(...a: Parameters<Runtime["runArtifacts"]>) {
1625 return this.runtime.runArtifacts(...a);
1626 }
1627 rtRepoArtifacts(...a: Parameters<Runtime["repoArtifacts"]>) {
1628 return this.runtime.repoArtifacts(...a);
1629 }
1630 rtArtifactDelete(...a: Parameters<Runtime["artifactDelete"]>) {
1631 return this.runtime.artifactDelete(...a);
1632 }
1633 rtArtifactDeleteByName(...a: Parameters<Runtime["artifactDeleteByName"]>) {
1634 return this.runtime.artifactDeleteByName(...a);
1635 }
1636 workflowSettings() {
1637 return this.policy.settings();
1638 }
1639 setWorkflowSettings(...a: Parameters<TokenPolicy["setSettings"]>) {
1640 return this.policy.setSettings(...a);
1641 }
1642 rtStage(...a: Parameters<Runtime["stage"]>) {
1643 return this.runtime.stage(...a);
1644 }
1645 rtUnstage(...a: Parameters<Runtime["unstage"]>) {
1646 return this.runtime.unstage(...a);
1647 }
1648 rtCheckCommitSize(...a: Parameters<Runtime["checkCommitSize"]>) {
1649 return this.runtime.checkCommitSize(...a);
1650 }
1651 rtCacheMissing(...a: Parameters<Runtime["cacheMissing"]>) {
1652 return this.runtime.cacheMissing(...a);
1653 }
1654 rtComposeStep(...a: Parameters<Runtime["composeStep"]>) {
1655 return this.runtime.composeStep(...a);
1656 }
1657
1658 // ---------------------------------------------------------------- RPC passthroughs (GitHub-compatible extras)
1659 // Releases, commit statuses, deployments and environments, issue sub-resources
1660 // (labels, reactions, events, locking), the Git data API, search and misc.
1661 // The modules are created on first use.
1662
1663 private extras: { releases?: Releases; statuses?: Statuses; deploys?: Deployments; social?: Social; gitdata?: GitData } = {};
1664 get releases(): Releases {
1665 return (this.extras.releases ??= new Releases(this, this.env));
1666 }
1667 get statuses(): Statuses {
1668 return (this.extras.statuses ??= new Statuses(this));
1669 }
1670 get deploys(): Deployments {
1671 return (this.extras.deploys ??= new Deployments(this, this.env));
1672 }
1673 get social(): Social {
1674 return (this.extras.social ??= new Social(this));
1675 }
1676 get gitdata(): GitData {
1677 return (this.extras.gitdata ??= new GitData(this, this.env));
1678 }
1679
1680 listReleases(...a: Parameters<Releases["list"]>) {
1681 return this.releases.list(...a);
1682 }
1683 getRelease(...a: Parameters<Releases["get"]>) {
1684 return this.releases.get(...a);
1685 }
1686 releaseByTag(...a: Parameters<Releases["byTag"]>) {
1687 return this.releases.byTag(...a);
1688 }
1689 latestRelease() {
1690 return this.releases.latest();
1691 }
1692 releaseSummary(...a: Parameters<Releases["summary"]>) {
1693 return this.releases.summary(...a);
1694 }
1695 createRelease(...a: Parameters<Releases["create"]>) {
1696 return this.releases.create(...a);
1697 }
1698 updateRelease(...a: Parameters<Releases["update"]>) {
1699 return this.releases.update(...a);
1700 }
1701 deleteRelease(...a: Parameters<Releases["remove"]>) {
1702 return this.releases.remove(...a);
1703 }
1704 generateReleaseNotes(...a: Parameters<Releases["generateNotes"]>) {
1705 return this.releases.generateNotes(...a);
1706 }
1707 releaseAssets(...a: Parameters<Releases["assets"]>) {
1708 return this.releases.assets(...a);
1709 }
1710 releaseAsset(...a: Parameters<Releases["asset"]>) {
1711 return this.releases.asset(...a);
1712 }
1713 updateReleaseAsset(...a: Parameters<Releases["updateAsset"]>) {
1714 return this.releases.updateAsset(...a);
1715 }
1716 deleteReleaseAsset(...a: Parameters<Releases["deleteAsset"]>) {
1717 return this.releases.deleteAsset(...a);
1718 }
1719 startReleaseAsset(...a: Parameters<Releases["startAsset"]>) {
1720 return this.releases.startAsset(...a);
1721 }
1722 finishReleaseAsset(...a: Parameters<Releases["finishAsset"]>) {
1723 return this.releases.finishAsset(...a);
1724 }
1725 abortReleaseAsset(...a: Parameters<Releases["abortAsset"]>) {
1726 return this.releases.abortAsset(...a);
1727 }
1728 releaseDownload(...a: Parameters<Releases["download"]>) {
1729 return this.releases.download(...a);
1730 }
1731 /** For the GitHub importer: a release with its original dates and author (no tag, events or workflows). */
1732 importRelease(...a: Parameters<Releases["importRelease"]>) {
1733 return this.releases.importRelease(...a);
1734 }
1735 /** For the GitHub importer: an asset copied from a public https URL, or from an R2 key under this repository's prefix. */
1736 importReleaseAsset(...a: Parameters<Releases["importAsset"]>) {
1737 return this.releases.importAsset(...a);
1738 }
1739
1740 createStatus(...a: Parameters<Statuses["create"]>) {
1741 return this.statuses.create(...a);
1742 }
1743 commitStatuses(...a: Parameters<Statuses["list"]>) {
1744 return this.statuses.list(...a);
1745 }
1746 combinedStatus(...a: Parameters<Statuses["combined"]>) {
1747 return this.statuses.combined(...a);
1748 }
1749 /** Check runs and commit statuses together, as pull request and commit pages show them. */
1750 checksAndStatuses(sha: string) {
1751 return [...this.collab.checks(sha), ...this.statuses.asChecks(sha)];
1752 }
1753
1754 /** This repository's part of the Today view (agentic/today.ts): open pull requests and what landed or failed since `since`. */
1755 /** Pull requests whose mergeability a Today summary is checking in the background. */
1756 private todayMergeChecks = new Set<number>();
1757
1758 todaySummary(since: string) {
1759 // Agents' auto-merges wait for a person's approval unless the base branch's rule waives it (repo/collab.ts mergeability).
1760 const waived = (base: string) => {
1761 const rules = this.protectionFor(base);
1762 return !!rules?.agentAutoMergeWithoutApproval && !rules.agentsMayMerge;
1763 };
1764 const summary = repoToday(this.sql, (sha) => this.checksAndStatuses(sha), since, waived);
1765 // After answering, find out whether agents' pull requests that may be waiting for a person conflict
1766 // or are already in their base, so the next Today leaves those out of "needs you".
1767 const unchecked = summary.pulls.filter((p) => needsMergeCheck(p) && !this.todayMergeChecks.has(p.number)).slice(0, MERGE_CHECKS_PER_SUMMARY);
1768 for (const p of unchecked) this.todayMergeChecks.add(p.number);
1769 if (unchecked.length)
1770 this.background(
1771 (async () => {
1772 for (const p of unchecked) {
1773 await this.collab.mergeability(p.number).catch((e) => console.error("today: mergeability check failed", p.number, e));
1774 this.todayMergeChecks.delete(p.number);
1775 }
1776 })(),
1777 );
1778 return summary;
1779 }
1780
1781 createDeployment(...a: Parameters<Deployments["create"]>) {
1782 return this.deploys.create(...a);
1783 }
1784 deployments(...a: Parameters<Deployments["list"]>) {
1785 return this.deploys.list(...a);
1786 }
1787 deployment(...a: Parameters<Deployments["get"]>) {
1788 return this.deploys.get(...a);
1789 }
1790 deleteDeployment(...a: Parameters<Deployments["remove"]>) {
1791 return this.deploys.remove(...a);
1792 }
1793 createDeploymentStatus(...a: Parameters<Deployments["createStatus"]>) {
1794 return this.deploys.createStatus(...a);
1795 }
1796 deploymentStatuses(...a: Parameters<Deployments["statuses"]>) {
1797 return this.deploys.statuses(...a);
1798 }
1799 deploymentStatus(...a: Parameters<Deployments["status"]>) {
1800 return this.deploys.status(...a);
1801 }
1802 environments() {
1803 return this.deploys.environments();
1804 }
1805 environment(...a: Parameters<Deployments["environment"]>) {
1806 return this.deploys.environment(...a);
1807 }
1808 upsertEnvironment(...a: Parameters<Deployments["upsertEnvironment"]>) {
1809 return this.deploys.upsertEnvironment(...a);
1810 }
1811 deleteEnvironment(...a: Parameters<Deployments["deleteEnvironment"]>) {
1812 return this.deploys.deleteEnvironment(...a);
1813 }
1814 addEnvironmentBranchPattern(...a: Parameters<Deployments["addBranchPattern"]>) {
1815 return this.deploys.addBranchPattern(...a);
1816 }
1817 removeEnvironmentBranchPattern(...a: Parameters<Deployments["removeBranchPattern"]>) {
1818 return this.deploys.removeBranchPattern(...a);
1819 }
1820 setEnvironmentSecret(...a: Parameters<Deployments["setSecret"]>) {
1821 return this.deploys.setSecret(...a);
1822 }
1823 deleteEnvironmentSecret(...a: Parameters<Deployments["deleteSecret"]>) {
1824 return this.deploys.deleteSecret(...a);
1825 }
1826 environmentSecretNames(...a: Parameters<Deployments["secretNames"]>) {
1827 return this.deploys.secretNames(...a);
1828 }
1829 setEnvironmentVariable(...a: Parameters<Deployments["setVariable"]>) {
1830 return this.deploys.setVariable(...a);
1831 }
1832 environmentVariables(...a: Parameters<Deployments["variables"]>) {
1833 return this.deploys.variables(...a);
1834 }
1835
1836 /** What the GitHub JSON builders need for a set of issues: label rows, reaction counts and lock reasons. */
1837 issueExtras(numbers: number[], subjects: string[] = []) {
1838 const lockReasons: Record<number, string | null> = {};
1839 for (const n of numbers) lockReasons[n] = this.social.lockReason(n);
1840 return { labels: this.social.labelRows(), reactions: this.social.reactionCounts([...numbers.map((n) => `issue:${n}`), ...subjects]), lockReasons };
1841 }
1842 issueEvents(...a: Parameters<Social["events"]>) {
1843 return this.social.events(...a);
1844 }
1845 repoIssueEvents(...a: Parameters<Social["repoEvents"]>) {
1846 return this.social.repoEvents(...a);
1847 }
1848 issueEvent(...a: Parameters<Social["event"]>) {
1849 return this.social.event(...a);
1850 }
1851 issueTimeline(...a: Parameters<Social["timeline"]>) {
1852 return this.social.timeline(...a);
1853 }
1854 labelRows() {
1855 return this.social.labelRows();
1856 }
1857 label(...a: Parameters<Social["label"]>) {
1858 return this.social.label(...a);
1859 }
1860 createLabel(...a: Parameters<Social["createLabel"]>) {
1861 return this.social.createLabel(...a);
1862 }
1863 updateLabel(...a: Parameters<Social["updateLabel"]>) {
1864 return this.social.updateLabel(...a);
1865 }
1866 deleteLabel(...a: Parameters<Social["deleteLabel"]>) {
1867 return this.social.deleteLabel(...a);
1868 }
1869 issueLabels(...a: Parameters<Social["issueLabels"]>) {
1870 return this.social.issueLabels(...a);
1871 }
1872 addIssueLabels(...a: Parameters<Social["addLabels"]>) {
1873 return this.social.addLabels(...a);
1874 }
1875 setIssueLabels(...a: Parameters<Social["setLabels"]>) {
1876 return this.social.setLabels(...a);
1877 }
1878 removeIssueLabel(...a: Parameters<Social["removeLabel"]>) {
1879 return this.social.removeLabel(...a);
1880 }
1881 assignIssue(...a: Parameters<Social["assign"]>) {
1882 return this.social.assign(...a);
1883 }
1884 lockIssue(...a: Parameters<Social["lock"]>) {
1885 return this.social.lock(...a);
1886 }
1887 unlockIssue(...a: Parameters<Social["unlock"]>) {
1888 return this.social.unlock(...a);
1889 }
1890 comment(...a: Parameters<Social["comment"]>) {
1891 return this.social.comment(...a);
1892 }
1893 deleteComment(...a: Parameters<Social["deleteComment"]>) {
1894 return this.social.deleteComment(...a);
1895 }
1896 repoComments(...a: Parameters<Social["repoComments"]>) {
1897 return this.social.repoComments(...a);
1898 }
1899 createReviewComment(...a: Parameters<Social["createReviewComment"]>) {
1900 return this.social.createReviewComment(...a);
1901 }
1902 review(...a: Parameters<Social["review"]>) {
1903 return this.social.review(...a);
1904 }
1905 dismissReview(...a: Parameters<Social["dismissReview"]>) {
1906 return this.social.dismissReview(...a);
1907 }
1908 removeReviewers(...a: Parameters<Social["removeReviewers"]>) {
1909 return this.social.removeReviewers(...a);
1910 }
1911 updatePullBranch(...a: Parameters<Social["updateBranch"]>) {
1912 return this.social.updateBranch(...a);
1913 }
1914 pullsForCommit(...a: Parameters<Social["pullsForCommit"]>) {
1915 return this.social.pullsForCommit(...a);
1916 }
1917 pullsForCommits(...a: Parameters<Social["pullsForCommits"]>) {
1918 return this.social.pullsForCommits(...a);
1919 }
1920 reactions(...a: Parameters<Social["reactions"]>) {
1921 return this.social.reactions(...a);
1922 }
1923 react(...a: Parameters<Social["react"]>) {
1924 return this.social.react(...a);
1925 }
1926 unreact(...a: Parameters<Social["unreact"]>) {
1927 return this.social.unreact(...a);
1928 }
1929 searchIssues(query: Parameters<typeof searchIssues>[1], limit: number) {
1930 return searchIssues(this, query, limit);
1931 }
1932 /** The issues for one page of search hits, in the order given (missing numbers are skipped). */
1933 issuesByNumber(numbers: number[], hide?: string[]) {
1934 return numbers.slice(0, 100).flatMap((n) => {
1935 try {
1936 return [this.collab.get(n, hide).issue];
1937 } catch {
1938 return [];
1939 }
1940 });
1941 }
1942
1943 objectType(...a: Parameters<GitData["objectType"]>) {
1944 return this.gitdata.objectType(...a);
1945 }
1946 refsWithTypes(...a: Parameters<GitData["refsWithTypes"]>) {
1947 return this.gitdata.refsWithTypes(...a);
1948 }
1949 createBlob(content: Uint8Array, caller: Caller) {
1950 return this.gitdata.createBlob(content, caller);
1951 }
1952 getBlob(...a: Parameters<GitData["getBlob"]>) {
1953 return this.gitdata.getBlob(...a);
1954 }
1955 createTree(...a: Parameters<GitData["createTree"]>) {
1956 return this.gitdata.createTree(...a);
1957 }
1958 getTree(...a: Parameters<GitData["getTree"]>) {
1959 return this.gitdata.getTree(...a);
1960 }
1961 createGitCommit(...a: Parameters<GitData["createCommit"]>) {
1962 return this.gitdata.createCommit(...a);
1963 }
1964 gitCommit(...a: Parameters<GitData["gitCommit"]>) {
1965 return this.gitdata.gitCommit(...a);
1966 }
1967 createGitTag(...a: Parameters<GitData["createTag"]>) {
1968 return this.gitdata.createTag(...a);
1969 }
1970 gitTag(...a: Parameters<GitData["getTag"]>) {
1971 return this.gitdata.getTag(...a);
1972 }
1973 putContents(...a: Parameters<GitData["putContents"]>) {
1974 return this.gitdata.putContents(...a);
1975 }
1976 deleteContents(...a: Parameters<GitData["deleteContents"]>) {
1977 return this.gitdata.deleteContents(...a);
1978 }
1979 readme(...a: Parameters<GitData["readme"]>) {
1980 return this.gitdata.readme(...a);
1981 }
1982 mergeBranches(...a: Parameters<GitData["merge"]>) {
1983 return this.gitdata.merge(...a);
1984 }
1985 languages() {
1986 return this.gitdata.languages();
1987 }
1988 archiveKey(...a: Parameters<GitData["archiveKey"]>) {
1989 return this.gitdata.archiveKey(...a);
1990 }
1991 buildArchive(...a: Parameters<GitData["buildArchive"]>) {
1992 return this.gitdata.buildArchive(...a);
1993 }
1994 runLogsZip(...a: Parameters<GitData["runLogsZip"]>) {
1995 return this.gitdata.runLogsZip(...a);
1996 }
1997 runAttemptId(...a: Parameters<GitData["runAttemptId"]>) {
1998 return this.gitdata.runAttemptId(...a);
1999 }
2000 checkRun(...a: Parameters<GitData["check"]>) {
2001 return this.gitdata.check(...a);
2002 }
2003 updateCheckRun(...a: Parameters<GitData["updateCheck"]>) {
2004 return this.gitdata.updateCheck(...a);
2005 }
2006 checkSuites(...a: Parameters<GitData["checkSuites"]>) {
2007 return this.gitdata.checkSuites(...a);
2008 }
2009 checkSuite(...a: Parameters<GitData["checkSuite"]>) {
2010 return this.gitdata.checkSuite(...a);
2011 }
2012
2013 /** repository_dispatch: an external event that starts workflows listening for its `event_type`. */
2014 async repositoryDispatch(eventType: string, clientPayload: Record<string, unknown>, caller: Caller): Promise<void> {
2015 if (!atLeast(caller.role, "write")) throw new HttpError(403, "write access is required to dispatch events");
2016 const sha = this.getRef(this.headRef);
2017 if (!sha) throw new HttpError(422, "the repository is empty");
2018 // Suspended Actions refuse the dispatch with the reason (triggerWorkflows would swallow it).
2019 await this.actions.refuseIfBlocked("run");
2020 const m = this.meta;
2021 const payload = { action: eventType, branch: m.defaultBranch, client_payload: clientPayload };
2022 this.emit({ type: "repository_dispatch", action: eventType, repoId: m.repoId, owner: m.owner, repo: m.name, payload: JSON.parse(JSON.stringify(payload)), actor: { id: caller.id, login: caller.login, kind: caller.kind, onBehalfOf: caller.onBehalfOf }, at: now() });
2023 await triggerWorkflows(this, { name: "repository_dispatch", action: eventType, ref: this.headRef, sha, payload, title: eventType }, caller);
2024 }
2025
2026 // ---------------------------------------------------------------- RPC passthroughs: GitHub imports and milestones (repo/imports.ts)
2027
2028 private importsCache?: RepoImports;
2029 private get importsModule(): RepoImports {
2030 return (this.importsCache ??= new RepoImports(this.sql));
2031 }
2032
2033 /** The import that currently holds this repository, or null. Other writes are refused meanwhile (loadRepo, gitReceivePack). */
2034 importLockHolder(): string | null {
2035 return this.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = 'import_lock'").toArray()[0]?.value ?? null;
2036 }
2037
2038 /**
2039 * Claim the repository for an import. Refuses if another import holds it, or if the repo
2040 * already holds any ref, issue, comment, milestone, protection or release this import did not write
2041 * (so a retry never adopts content people added in the meantime — H2).
2042 */
2043 importBegin(importId: string): void {
2044 const holder = this.importLockHolder();
2045 if (holder && holder !== importId) throw new HttpError(409, "another import is in progress for this repository");
2046 // A ref not written by this import, or any foreign row, means the repo was adopted since.
2047 for (const r of this.refs()) {
2048 if (r.name.startsWith("refs/diffinery-import/")) continue;
2049 if (this.importsModule.importRefOid(r.name, importId) === null) {
2050 if (holder !== importId) throw new HttpError(409, "repository already holds content not written by this import; start a new import");
2051 }
2052 }
2053 if (this.importsModule.hasForeignContent(importId)) throw new HttpError(409, "repository already holds content not written by this import; start a new import");
2054 this.sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES ('import_lock', ?)", importId);
2055 }
2056
2057 /** Release the import lock (on finalize, fail or cancel). */
2058 importEnd(importId: string): void {
2059 if (this.importLockHolder() === importId) this.sql.exec("DELETE FROM meta WHERE key = 'import_lock'");
2060 }
2061
2062 importProtection(pattern: string, rules: ProtectionRules | null, importId: string) {
2063 // What agents may do is a person's decision here, never something an import brings in.
2064 if (rules) {
2065 const { allowAgentAutoMerge: _a, agentAutoMergeWithoutApproval: _w, autoMergeAgents: _g, autoMergeMethod: _gm, agentsMayPush: _p, agentsMayMerge: _m, ...rest } = rules;
2066 rules = rest;
2067 }
2068 if (rules?.mergeQueue) rules = { ...rules, mergeQueue: normalizeMergeQueue(rules.mergeQueue) };
2069 if (rules?.requiredCheckSources) rules = { ...rules, requiredCheckSources: normalizeCheckSources(rules.requiredCheckSources) };
2070 if (rules) this.importsModule.protection(pattern, JSON.stringify(rules), importId);
2071 }
2072 importLabels(...a: Parameters<RepoImports["labels"]>) {
2073 return this.importsModule.labels(...a);
2074 }
2075 importMilestones(...a: Parameters<RepoImports["milestones"]>) {
2076 return this.importsModule.milestones(...a);
2077 }
2078 importIssues(...a: Parameters<RepoImports["issues"]>) {
2079 return this.importsModule.issues(...a);
2080 }
2081 importComments(...a: Parameters<RepoImports["comments"]>) {
2082 return this.importsModule.comments(...a);
2083 }
2084 importReviews(...a: Parameters<RepoImports["reviews"]>) {
2085 return this.importsModule.reviews(...a);
2086 }
2087 importSetMergedBy(...a: Parameters<RepoImports["setMergedBy"]>) {
2088 return this.importsModule.setMergedBy(...a);
2089 }
2090 importPullNumbers(...a: Parameters<RepoImports["pullNumbers"]>) {
2091 return this.importsModule.pullNumbers(...a);
2092 }
2093 importCounts() {
2094 return this.importsModule.counts();
2095 }
2096 importFindings() {
2097 return this.importsModule.findings();
2098 }
2099 /**
2100 * Point `refs/pull/N/head` at each imported pull request's head commit (the server owns
2101 * refs/pull/*; the agent pushed the commits to refs/diffinery-import/pull/N). Heads whose
2102 * commits never arrived (e.g. deleted forks) are reported, not fatal.
2103 */
2104 importPullRefs(importId?: string): { created: number; missing: number[] } {
2105 const missing: number[] = [];
2106 let created = 0;
2107 for (const p of this.importsModule.pullHeads()) {
2108 const ref = `refs/pull/${p.number}/head`;
2109 if (!/^[0-9a-f]{40}$/.test(p.headSha) || !this.store.has(p.headSha)) {
2110 missing.push(p.number);
2111 continue;
2112 }
2113 const current = this.getRef(ref);
2114 // Record provenance so a retry does not mistake refs/pull/*/head for content people adopted.
2115 if (importId) this.importsModule.recordImportRef(ref, p.headSha, importId);
2116 if (current === p.headSha) continue;
2117 if (this.casRef(ref, current, p.headSha)) created++;
2118 }
2119 return { created, missing };
2120 }
2121 /** Remove the import's own refs once refs/pull/N/head keep the pull request commits reachable. */
2122 importDropTempRefs(importId?: string): number {
2123 const refs = this.refs(IMPORT_REF_PREFIX);
2124 for (const r of refs) this.casRef(r.name, r.oid, null);
2125 if (importId) this.importsModule.dropImportRefs(importId);
2126 return refs.length;
2127 }
2128 setOrgVariables(...a: Parameters<RepoImports["setOrgVariables"]>) {
2129 return this.importsModule.setOrgVariables(...a);
2130 }
2131 issueMilestoneOf(number: number) {
2132 return this.importsModule.milestoneOf(number);
2133 }
2134 /** Check names that workflow jobs on the default branch report, keyed by job name (GitHub names checks by job). */
2135 async importCheckNames(): Promise<Record<string, string[]>> {
2136 const sha = await this.resolve("HEAD");
2137 const out: Record<string, string[]> = {};
2138 if (!sha) return out;
2139 for (const w of await this.actions.loadWorkflows(sha)) {
2140 if (!w.workflow) continue;
2141 const wf = w.workflow.name ?? w.path.split("/").pop()!;
2142 for (const [key, job] of Object.entries(w.workflow.jobs)) {
2143 const name = (job as { name?: unknown }).name;
2144 for (const n of new Set([key, typeof name === "string" ? name : key])) (out[n] ??= []).push(`${wf} / ${typeof name === "string" && !name.includes("${{") ? name : key}`);
2145 }
2146 }
2147 return out;
2148 }
2149 milestones(...a: Parameters<RepoImports["listMilestones"]>) {
2150 return this.importsModule.listMilestones(...a);
2151 }
2152 milestone(...a: Parameters<RepoImports["milestone"]>) {
2153 return this.importsModule.milestone(...a);
2154 }
2155 saveMilestone(...a: Parameters<RepoImports["saveMilestone"]>) {
2156 return this.importsModule.saveMilestone(...a);
2157 }
2158 setIssueMilestone(...a: Parameters<RepoImports["setIssueMilestone"]>) {
2159 return this.importsModule.setIssueMilestone(...a);
2160 }
2161
2162 // ---------------------------------------------------------------- live updates (WebSockets with hibernation)
2163
2164 override async fetch(request: Request): Promise<Response> {
2165 // The pack streams back through fetch, not RPC: celld can't return a stream from an RPC call
2166 // ("RPC streams cannot cross isolate boundaries yet"), and a fetch body streams on both runtimes.
2167 if (request.method === "POST" && new URL(request.url).pathname === UPLOAD_PACK_PATH) return new Response(await this.gitUploadPack(new Uint8Array(await request.arrayBuffer())));
2168 if (request.headers.get("Upgrade") !== "websocket") return new Response("expected websocket", { status: 426 });
2169 const topics = (new URL(request.url).searchParams.get("topics") ?? "repo").split(",").filter((t) => /^[a-z]+(:[A-Za-z0-9_-]+)?$/.test(t)).slice(0, 10);
2170 const pair = new WebSocketPair();
2171 this.ctx.acceptWebSocket(pair[1], topics.length ? topics : ["repo"]);
2172 // Access is checked when a page connects; reconnecting checks it again, so someone who lost access
2173 // (removed, or the repository made private) stops getting updates within LIVE_REAUTH_MS.
2174 pair[1].serializeAttachment({ until: Date.now() + LIVE_REAUTH_MS });
2175 return new Response(null, { status: 101, webSocket: pair[0] });
2176 }
2177
2178 /** Close a socket whose access check is too old; the page reconnects, and the Worker checks access again. */
2179 private expired(ws: WebSocket): boolean {
2180 const a = ws.deserializeAttachment() as { until?: number } | null;
2181 if (a?.until && a.until > Date.now()) return false;
2182 try {
2183 ws.close(LIVE_REAUTH_CODE, "reconnect");
2184 } catch {
2185 /* already closed */
2186 }
2187 return true;
2188 }
2189
2190 override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
2191 if (this.expired(ws)) return;
2192 if (message === "ping") ws.send("pong");
2193 }
2194
2195 override async webSocketClose(ws: WebSocket, code: number): Promise<void> {
2196 try {
2197 ws.close(code, "bye");
2198 } catch {
2199 /* already closed */
2200 }
2201 }
2202
2203 broadcast(topic: string, data: unknown): void {
2204 const msg = JSON.stringify({ topic, data });
2205 for (const ws of this.ctx.getWebSockets(topic)) {
2206 if (this.expired(ws)) continue;
2207 try {
2208 ws.send(msg);
2209 } catch {
2210 /* client went away */
2211 }
2212 }
2213 }
2214}
2215
2216export function toInfo(sha: string, c: Commit): CommitInfo {
2217 return { sha, tree: c.tree, parents: c.parents, author: c.author, committer: c.committer, message: c.message, signed: !!c.gpgsig };
2218}
2219
2220export { fromUtf8 };