Diffinery

codician/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.

1536 lines · 67.4 KBRaw History
1import { DurableObject } from "cloudflare:workers";
2import { normalizeCheckSources } from "./required.js";
3import { unsafeTreePath } from "../lib/tree-names.js";
4import {
5 EMPTY_TREE_OID,
6 ZERO_OID,
7 applyChanges,
8 diffTrees,
9 fileDiff,
10 formatUnified,
11 fromUtf8,
12 isAncestor,
13 isBinary,
14 isOid,
15 isTreeMode,
16 mergeBase,
17 parsePack,
18 peelToCommit,
19 readCommit,
20 readTree,
21 resolvePath,
22 serializeCommit,
23 walkCommits,
24 type Commit,
25 type FileChange,
26 type Signature,
27} from "@diffinery/git-core";
28import type { DiffineryEvent } from "@diffinery/shared";
29import type { Env } from "../env.js";
30import {
31 advertiseReceivePack,
32 advertiseUploadPackV2,
33 errorPacket,
34 handleUploadPackV2,
35 parseReceivePack,
36 reportStatus,
37 type RefEntry,
38 type RefResult,
39} from "../git/protocol.js";
40import { scanForSecrets, secretBypassReason } from "../git/secret-scan.js";
41import { HttpError, isValidRefName, now } from "../lib/util.js";
42import { deletePrefixes, transientPrefixes } from "../lib/storage-keys.js";
43import { Actions } from "./actions.js";
44import { AutoMerge, isPerson } from "./auto-merge.js";
45import { Collab } from "./collab.js";
46import { Deployments } from "./deployments.js";
47import { triggerWorkflows } from "./extra-triggers.js";
48import { GitData } from "./gitdata.js";
49import { IMPORT_REF_PREFIX, RepoImports } from "./imports.js";
50import { RepoObjectStore } from "./objects.js";
51import { MergeQueue, QUEUE_BRANCH_PREFIX, normalizeMergeQueue } from "./queue.js";
52import { Releases } from "./releases.js";
53import { REPO_SCHEMA, migrateRepoSchema } from "./schema.js";
54import { Runtime } from "./runtime.js";
55import { TokenPolicy } from "./token-policy.js";
56import { searchIssues } from "./search.js";
57import { repoToday } from "../agentic/today-repo.js";
58import { Social } from "./social.js";
59import { Statuses } from "./statuses.js";
60import { atLeast, globToRegExp, type Caller, type ProtectionRules, type RepoMeta } from "./types.js";
61
62const MAX_PUSH_BYTES = 100 * 1024 * 1024;
63
64export type TreeItem = {
65 name: string;
66 path: string;
67 type: "tree" | "blob" | "commit";
68 mode: string;
69 oid: string;
70 size?: number;
71};
72
73export type CommitInfo = {
74 sha: string;
75 tree: string;
76 parents: string[];
77 author: Signature;
78 committer: Signature;
79 message: string;
80 signed: boolean;
81};
82
83/**
84 * One Durable Object per repository. It is the single writer for the repo's
85 * refs, Git objects, issues, pull requests, reviews, checks and workflow runs,
86 * which gives strongly consistent ref updates and merges without locks.
87 */
88export class RepoDO extends DurableObject<Env> {
89 readonly sql: SqlStorage;
90 store!: RepoObjectStore;
91 readonly collab: Collab;
92 readonly actions: Actions;
93 readonly queue: MergeQueue;
94 readonly autoMerge: AutoMerge;
95 readonly runtime: Runtime;
96 readonly policy: TokenPolicy;
97 private metaCache: RepoMeta | null = null;
98
99 constructor(ctx: DurableObjectState, env: Env) {
100 super(ctx, env);
101 this.sql = ctx.storage.sql;
102 this.sql.exec(REPO_SCHEMA);
103 migrateRepoSchema(this.sql);
104 const meta = this.readMeta();
105 if (meta) this.store = new RepoObjectStore(this.sql, env.BUCKET, meta.repoId);
106 this.collab = new Collab(this);
107 this.actions = new Actions(this, env);
108 this.queue = new MergeQueue(this);
109 this.autoMerge = new AutoMerge(this, env);
110 this.runtime = new Runtime(this, env);
111 this.policy = new TokenPolicy(this);
112 }
113
114 // ---------------------------------------------------------------- meta
115
116 private readMeta(): RepoMeta | null {
117 const row = this.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = 'meta'").toArray()[0];
118 this.metaCache = row ? (JSON.parse(row.value) as RepoMeta) : null;
119 return this.metaCache;
120 }
121
122 get meta(): RepoMeta {
123 const m = this.metaCache ?? this.readMeta();
124 if (!m) throw new HttpError(404, "repository not initialised");
125 return m;
126 }
127
128 async init(meta: RepoMeta): Promise<void> {
129 // A repository created now (not one whose meta is updated) starts with read-only workflow tokens.
130 if (!this.readMeta()) this.policy.initNewRepo();
131 this.sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES ('meta', ?)", JSON.stringify(meta));
132 this.metaCache = meta;
133 this.store = new RepoObjectStore(this.sql, this.env.BUCKET, meta.repoId);
134 }
135
136 async updateMeta(patch: Partial<RepoMeta>): Promise<RepoMeta> {
137 const next = { ...this.meta, ...patch };
138 await this.init(next);
139 return next;
140 }
141
142 /**
143 * Whether the repository is archived (read-only). The Worker refuses writes to an archived
144 * repository, but work this object does by itself (auto-merge, the merge queue) must ask here.
145 */
146 async isArchived(): Promise<boolean> {
147 const known = this.meta.archived;
148 if (typeof known === "boolean") return known;
149 const row = await this.env.DB.prepare("SELECT archived FROM repos WHERE id = ?").bind(this.meta.repoId).first<{ archived: number }>();
150 // setArchived may have run while D1 answered; what it set wins.
151 if (typeof this.meta.archived === "boolean") return this.meta.archived;
152 const archived = !!row?.archived;
153 await this.updateMeta({ archived });
154 return archived;
155 }
156
157 /** The repository was archived or unarchived (D1 already says so). Archiving ends auto-merge and empties the merge queues. */
158 async setArchived(archived: boolean): Promise<void> {
159 await this.updateMeta({ archived });
160 if (!archived) return;
161 await this.autoMerge.repositoryArchived();
162 await this.queue.repositoryArchived();
163 }
164
165 /** Wipe all storage (repository deletion). */
166 async destroy(): Promise<void> {
167 // Caches, artifacts, logs and archives live outside repos/<id>/; with the rows gone, nothing would remove them.
168 const repoId = this.readMeta()?.repoId;
169 if (repoId) await deletePrefixes(this.env.BUCKET, transientPrefixes(repoId)).catch((e) => console.error("could not delete the repository's Actions objects", e));
170 await this.ctx.storage.deleteAll();
171 this.metaCache = null;
172 }
173
174 async stats(): Promise<{ objects: number; bytes: number; refs: number; openIssues: number; openPulls: number }> {
175 const q = (s: string) => this.sql.exec<{ n: number }>(s).one().n;
176 return {
177 objects: this.store.count(),
178 bytes: this.store.sizeBytes(),
179 refs: q("SELECT count(*) AS n FROM refs"),
180 openIssues: q("SELECT count(*) AS n FROM issues WHERE kind = 'issue' AND state = 'open'"),
181 openPulls: q("SELECT count(*) AS n FROM issues WHERE kind = 'pull' AND state = 'open'"),
182 };
183 }
184
185 /** Keep the object alive for work that finishes after the current request. */
186 background(p: Promise<unknown>): void {
187 this.ctx.waitUntil(p.catch((e) => console.error("background task failed", e)));
188 }
189
190 /** Set (or with null, clear) the object's single alarm; the merge queue uses it for check timeouts. */
191 armAlarm(at: number | null): void {
192 this.ctx.waitUntil(at === null ? this.ctx.storage.deleteAlarm() : this.ctx.storage.setAlarm(at));
193 }
194
195 override async alarm(): Promise<void> {
196 await this.queue.process();
197 }
198
199 /** 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). */
200 emit(event: DiffineryEvent, opts?: { live?: boolean }): void {
201 this.ctx.waitUntil(this.env.EVENTS.send(event).catch((e) => console.error("event send failed", e)));
202 if (opts?.live !== false) this.broadcast("repo", { kind: "event", event });
203 }
204
205 // ---------------------------------------------------------------- refs
206
207 refs(prefix = "refs/"): RefEntry[] {
208 return this.sql.exec<RefEntry>("SELECT name, oid FROM refs WHERE name >= ? AND name < ? ORDER BY name", prefix, `${prefix}￿`).toArray();
209 }
210
211 getRef(name: string): string | null {
212 return this.sql.exec<{ oid: string }>("SELECT oid FROM refs WHERE name = ?", name).toArray()[0]?.oid ?? null;
213 }
214
215 /** Compare-and-swap a ref. `expected` = ZERO_OID means "must not exist". */
216 casRef(name: string, expected: string | null, next: string | null): boolean {
217 const current = this.getRef(name);
218 if (expected !== null && (current ?? ZERO_OID) !== expected) return false;
219 if (next === null || next === ZERO_OID) this.sql.exec("DELETE FROM refs WHERE name = ?", name);
220 else this.sql.exec("INSERT OR REPLACE INTO refs (name, oid) VALUES (?, ?)", name, next);
221 return true;
222 }
223
224 get headRef(): string {
225 return `refs/heads/${this.meta.defaultBranch}`;
226 }
227
228 /** Resolve a branch, tag, full ref, HEAD or (abbreviated) SHA to a commit SHA. */
229 async resolve(rev: string | undefined | null): Promise<string | null> {
230 const r = rev && rev.length ? rev : "HEAD";
231 let oid: string | null = null;
232 if (r === "HEAD") oid = this.getRef(this.headRef);
233 else if (isOid(r)) oid = this.store.has(r) ? r : null;
234 else if (r.startsWith("refs/")) oid = this.getRef(r);
235 else oid = this.getRef(`refs/heads/${r}`) ?? this.getRef(`refs/tags/${r}`);
236 if (!oid && /^[0-9a-f]{7,39}$/.test(r)) {
237 const rows = this.sql.exec<{ oid: string }>("SELECT oid FROM objects WHERE oid >= ? AND oid < ? LIMIT 2", r, `${r}g`).toArray();
238 if (rows.length === 1) oid = rows[0]!.oid;
239 }
240 if (!oid) return null;
241 return peelToCommit(this.store, oid);
242 }
243
244 async branches(): Promise<Array<{ name: string; sha: string; protected: boolean; isDefault: boolean }>> {
245 return this.refs("refs/heads/").map((r) => {
246 const name = r.name.slice(11);
247 return { name, sha: r.oid, protected: !!this.protectionFor(name), isDefault: name === this.meta.defaultBranch };
248 });
249 }
250
251 async tags(): Promise<Array<{ name: string; sha: string; target: string }>> {
252 const out = [];
253 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) });
254 return out;
255 }
256
257 // ---------------------------------------------------------------- git smart HTTP
258
259 async gitInfoRefs(service: "git-upload-pack" | "git-receive-pack"): Promise<Uint8Array> {
260 if (service === "git-upload-pack") return advertiseUploadPackV2();
261 // Like GitHub, pull request refs are hidden from pushes (so `git push --mirror` leaves them alone).
262 return advertiseReceivePack(this.refs().filter((r) => !r.name.startsWith("refs/pull/")));
263 }
264
265 async gitUploadPack(body: Uint8Array): Promise<Uint8Array> {
266 try {
267 return await handleUploadPackV2(body, { store: this.store, refs: this.refs(), headTarget: this.headRef });
268 } catch (e) {
269 return errorPacket((e as Error).message);
270 }
271 }
272
273 /** `moved`: the push came in under an old name (a transfer or rename), so say where the repository lives now, like GitHub. */
274 async gitReceivePack(body: Uint8Array, caller: Caller, o: { moved?: boolean } = {}): Promise<Uint8Array> {
275 if (body.length > MAX_PUSH_BYTES) {
276 const req = { commands: [], capabilities: new Set<string>(), pushOptions: [], pack: null };
277 return reportStatus(req, "push exceeds 100 MB; split it into smaller pushes", []);
278 }
279 const req = parseReceivePack(body);
280 // `git push -o diffinery-import` from a GitHub import's own token: no workflows, webhooks,
281 // pull request syncs or notifications (see apps/diffinery/src/imports).
282 const importMode = !!caller.importId && req.pushOptions.some((o) => o.trim() === "diffinery-import");
283 // H2: while an import holds the repository, only that import may push. Everything else waits
284 // until the import finalises, so protection, guardrails, CI and webhooks are never bypassed.
285 const lockHolder = this.importLockHolder();
286 if (lockHolder && (!importMode || caller.importId !== lockHolder)) {
287 const denied = req.commands.map((c) => ({ ref: c.ref, ok: false as const, reason: "repository is locked by an import in progress" }));
288 return reportStatus(req, "repository is locked by an import in progress", denied);
289 }
290 const messages: string[] = o.moved ? ["This repository moved. Please use the new location:", ` ${this.env.PUBLIC_URL}/${this.meta.owner}/${this.meta.name}.git`] : [];
291 let unpackError: string | null = null;
292 // Like git's quarantine: nothing from the pack is stored until push protection passes,
293 // so a blocked push leaves no objects behind for a retry to build on.
294 let objects: Awaited<ReturnType<typeof parsePack>> = [];
295 if (req.pack && req.pack.length > 0) {
296 try {
297 objects = await parsePack(req.pack, (oid) => this.store.read(oid));
298 } catch (e) {
299 unpackError = (e as Error).message;
300 }
301 }
302 const newBlobs = objects.filter((o) => o.type === "blob").map((o) => ({ oid: o.oid, content: o.content }));
303 const results: RefResult[] = [];
304 if (unpackError) {
305 for (const c of req.commands) results.push({ ref: c.ref, ok: false, reason: "unpacker error" });
306 return reportStatus(req, unpackError, results);
307 }
308
309 const leaks = scanForSecrets(newBlobs);
310 if (leaks.length) {
311 const kinds = leaks.map((l) => l.kind);
312 const target = `${this.meta.owner}/${this.meta.name}`;
313 // Like GitHub's push protection bypass: a human repository admin may push anyway by
314 // giving a reason (`git push -o allow-secrets=<reason>`), and every bypass is audited.
315 const reason = secretBypassReason(req.pushOptions);
316 if (reason && caller.role === "admin" && caller.kind === "user") {
317 messages.push(`Push protection bypassed by ${caller.login}: ${reason}`);
318 for (const l of leaks.slice(0, 10)) messages.push(` ${l.kind} in blob ${l.oid.slice(0, 10)}`);
319 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() });
320 if (importMode) this.importsModule.recordFindings(leaks);
321 } else {
322 messages.push("Push blocked: possible secrets detected.");
323 for (const l of leaks.slice(0, 10)) messages.push(` ${l.kind} in blob ${l.oid.slice(0, 10)}`);
324 messages.push("Remove the secret from your commits, or rotate it and contact an admin.");
325 if (reason) messages.push("Only repository admins (people, not agents) can bypass push protection.");
326 for (const c of req.commands) results.push({ ref: c.ref, ok: false, reason: "secret detected (push protection)" });
327 this.emit({ type: "audit", action: "push.blocked_secret", actor: caller, target, detail: { kinds, refs: req.commands.map((c) => c.ref) }, at: now() });
328 return reportStatus(req, null, results, messages);
329 }
330 }
331
332 try {
333 for (const o of objects) await this.store.writeKnown(o.oid, o.type, o.content);
334 } catch (e) {
335 for (const c of req.commands) results.push({ ref: c.ref, ok: false, reason: "unpacker error" });
336 return reportStatus(req, (e as Error).message, results);
337 }
338
339 // Validate every command before applying any, so `atomic` is honoured.
340 const checks: Array<RefResult & { cmd: (typeof req.commands)[number] }> = [];
341 for (const cmd of req.commands) checks.push({ cmd, ...(await this.checkRefUpdate(cmd.ref, cmd.oldOid, cmd.newOid, caller, importMode)) });
342 const atomic = req.capabilities.has("atomic");
343 const anyFailed = checks.some((c) => !c.ok);
344 let imported = 0;
345 for (const c of checks) {
346 if (!c.ok) {
347 results.push({ ref: c.ref, ok: false, reason: c.reason });
348 continue;
349 }
350 if (atomic && anyFailed) {
351 results.push({ ref: c.ref, ok: false, reason: "atomic transaction failed" });
352 continue;
353 }
354 const applied = this.casRef(c.cmd.ref, c.cmd.oldOid, c.cmd.newOid);
355 results.push(applied ? { ref: c.ref, ok: true } : { ref: c.ref, ok: false, reason: "fetch first (stale info)" });
356 if (applied && importMode) {
357 imported++;
358 // Record provenance so a later push may move this ref only if the import still owns it.
359 if (c.cmd.newOid === ZERO_OID) this.sql.exec("DELETE FROM import_refs WHERE ref = ?", c.cmd.ref);
360 else this.importsModule.recordImportRef(c.cmd.ref, c.cmd.newOid, caller.importId!);
361 } else if (applied) await this.afterRefUpdate(c.cmd.ref, c.cmd.oldOid, c.cmd.newOid, caller, messages);
362 }
363 // One audit entry per import push instead of push events.
364 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() });
365 return reportStatus(req, null, results, messages);
366 }
367
368 /** As on GitHub: a rule naming the branch exactly wins; otherwise the oldest matching pattern. */
369 protectionFor(branch: string): ProtectionRules | null {
370 const rows = this.sql.exec<{ pattern: string; rules: string }>("SELECT pattern, rules FROM protections ORDER BY rowid").toArray();
371 const row = rows.find((r) => r.pattern === branch) ?? rows.find((r) => globToRegExp(r.pattern).test(branch));
372 return row ? (JSON.parse(row.rules) as ProtectionRules) : null;
373 }
374
375 /**
376 * Server-side rules for a ref update: permissions, protection, fast-forward, agent guardrails.
377 * `importMode`: a GitHub import filling the repository it created, which is the only writer
378 * until it finishes, so branch rules (copied from GitHub at its end) don't apply to it.
379 */
380 async checkRefUpdate(ref: string, oldOid: string, newOid: string, caller: Caller, importMode = false): Promise<RefResult> {
381 if (!isValidRefName(ref)) return { ref, ok: false, reason: "invalid ref name" };
382 if (!atLeast(caller.role, "write")) return { ref, ok: false, reason: "permission denied" };
383 const deleting = newOid === ZERO_OID;
384 if (ref.startsWith("refs/pull/")) return { ref, ok: false, reason: "refs/pull/ is managed by Diffinery for pull requests" };
385 if (ref.startsWith(`refs/heads/${QUEUE_BRANCH_PREFIX}`)) return { ref, ok: false, reason: "merge queue branches are read-only" };
386 if (!deleting && !this.store.has(newOid)) return { ref, ok: false, reason: "missing objects" };
387 if (ref.startsWith(IMPORT_REF_PREFIX) && !importMode) return { ref, ok: false, reason: `${IMPORT_REF_PREFIX} is reserved for GitHub imports` };
388 if (importMode) {
389 if (!/^refs\/(heads|tags|diffinery-import)\//.test(ref)) return { ref, ok: false, reason: "imports write branches and tags only" };
390 // H2: create a ref, or move one this import previously wrote — never a ref adopted since.
391 const current = this.getRef(ref);
392 if (current && !deleting) {
393 const owned = this.importsModule.importRefOid(ref, caller.importId!);
394 if (owned !== current) return { ref, ok: false, reason: "import may not overwrite a ref it did not write" };
395 }
396 return { ref, ok: true };
397 }
398 // A workflow's GITHUB_TOKEN never adds or changes workflow files (GitHub's `workflows` permission).
399 const workflowEdit = await this.policy.refuseWorkflowEdit(caller, oldOid, newOid);
400 if (workflowEdit) return { ref, ok: false, reason: workflowEdit };
401 if (!ref.startsWith("refs/heads/")) {
402 if (ref.startsWith("refs/tags/") && oldOid !== ZERO_OID && !atLeast(caller.role, "maintain")) return { ref, ok: false, reason: "only maintainers may move tags" };
403 return { ref, ok: true };
404 }
405 const branch = ref.slice(11);
406 const rules = this.protectionFor(branch);
407 const isDefault = branch === this.meta.defaultBranch;
408 if (caller.kind === "agent" && (isDefault || rules) && !rules?.agentsMayPush) {
409 return { ref, ok: false, reason: "agents may not push to protected or default branches; open a pull request" };
410 }
411 if (deleting && isDefault) return { ref, ok: false, reason: "cannot delete the default branch" };
412 if (!rules) return { ref, ok: true };
413 const bypass = caller.role === "admin" && !rules.enforceAdmins;
414 if (bypass) return { ref, ok: true };
415 if (deleting) return rules.allowDeletion ? { ref, ok: true } : { ref, ok: false, reason: "protected branch: deletion not allowed" };
416 if (rules.requirePullRequest) return { ref, ok: false, reason: "protected branch: changes must be made through a pull request" };
417 if (oldOid !== ZERO_OID && !rules.allowForcePush && !(await isAncestor(this.store, oldOid, newOid))) {
418 return { ref, ok: false, reason: "protected branch: force push not allowed" };
419 }
420 if (rules.requireLinearHistory) {
421 const fresh = await walkCommits(this.store, [newOid], { stop: new Set(oldOid === ZERO_OID ? [] : [oldOid]), limit: 1000 });
422 if (fresh.some((c) => c.commit.parents.length > 1)) return { ref, ok: false, reason: "protected branch: merge commits not allowed (linear history)" };
423 }
424 return { ref, ok: true };
425 }
426
427 /** Side effects after a ref moved: events, PR sync, workflow triggers. */
428 async afterRefUpdate(ref: string, oldOid: string, newOid: string, caller: Caller, messages: string[] = []): Promise<void> {
429 const at = now();
430 const forced = oldOid !== ZERO_OID && newOid !== ZERO_OID && !(await isAncestor(this.store, oldOid, newOid));
431 const ev: DiffineryEvent = {
432 type: "push",
433 repoId: this.meta.repoId,
434 owner: this.meta.owner,
435 repo: this.meta.name,
436 ref,
437 before: oldOid,
438 after: newOid,
439 actor: { id: caller.id, login: caller.login, kind: caller.kind, onBehalfOf: caller.onBehalfOf },
440 forced,
441 created: oldOid === ZERO_OID,
442 deleted: newOid === ZERO_OID,
443 at,
444 };
445 this.emit(ev);
446 this.policy.recordPush(ref, newOid, caller);
447 this.deploys.noteRefUpdate(ref, newOid, caller);
448 if (ref.startsWith("refs/heads/") && newOid !== ZERO_OID) {
449 const branch = ref.slice(11);
450 const synced = await this.collab.syncPullsForBranch(branch, newOid, caller);
451 for (const n of synced) messages.push(`Updated pull request #${n}: ${this.env.PUBLIC_URL}/${this.meta.owner}/${this.meta.name}/pull/${n}`);
452 if (oldOid === ZERO_OID && branch !== this.meta.defaultBranch && synced.length === 0) {
453 messages.push(`Create a pull request for '${branch}':`);
454 messages.push(` ${this.env.PUBLIC_URL}/${this.meta.owner}/${this.meta.name}/compare/${encodeURIComponent(branch)}`);
455 }
456 }
457 if (newOid !== ZERO_OID) await this.actions.onPush(ev, caller).catch((e) => messages.push(`Workflow trigger error: ${(e as Error).message}`));
458 // A base branch that moved (outside the queue, or by it) needs its merge groups checked,
459 // and pull requests into it waiting to auto-merge may now be up to date.
460 if (ref.startsWith("refs/heads/") && this.queue.hasEntries(ref.slice(11))) this.queue.schedule(ref.slice(11));
461 if (ref.startsWith("refs/heads/") && newOid !== ZERO_OID) this.autoMerge.schedule({ base: ref.slice(11) });
462 }
463
464 // ---------------------------------------------------------------- browsing
465
466 async commitInfo(sha: string): Promise<CommitInfo> {
467 const c = await readCommit(this.store, sha);
468 return toInfo(sha, c);
469 }
470
471 async tree(rev: string, path = ""): Promise<{ sha: string; items: TreeItem[] } | null> {
472 const sha = await this.resolve(rev);
473 if (!sha) return null;
474 const c = await readCommit(this.store, sha);
475 const entry = await resolvePath(this.store, c.tree, path);
476 if (!entry || !isTreeMode(entry.mode)) return null;
477 const items: TreeItem[] = [];
478 for (const e of await readTree(this.store, entry.oid)) {
479 const type = isTreeMode(e.mode) ? "tree" : e.mode === "160000" ? "commit" : "blob";
480 const raw = type === "blob" ? this.sql.exec<{ size: number }>("SELECT size FROM objects WHERE oid = ?", e.oid).toArray()[0] : undefined;
481 items.push({ name: e.name, path: path ? `${path}/${e.name}` : e.name, type, mode: e.mode, oid: e.oid, size: raw?.size });
482 }
483 items.sort((a, b) => (a.type === b.type ? a.name.localeCompare(b.name) : a.type === "tree" ? -1 : 1));
484 return { sha, items };
485 }
486
487 async blob(rev: string, path: string): Promise<{ sha: string; oid: string; mode: string; size: number; binary: boolean; content: Uint8Array } | null> {
488 const sha = await this.resolve(rev);
489 if (!sha) return null;
490 const c = await readCommit(this.store, sha);
491 const entry = await resolvePath(this.store, c.tree, path);
492 if (!entry || isTreeMode(entry.mode)) return null;
493 const o = await this.store.read(entry.oid);
494 if (!o) return null;
495 return { sha, oid: entry.oid, mode: entry.mode, size: o.content.length, binary: isBinary(o.content), content: o.content };
496 }
497
498 async log(rev: string, opts: { path?: string; limit?: number; skip?: number } = {}): Promise<CommitInfo[]> {
499 const sha = await this.resolve(rev);
500 if (!sha) return [];
501 const limit = Math.min(opts.limit ?? 30, 100);
502 const skip = opts.skip ?? 0;
503 if (!opts.path) {
504 const commits = await walkCommits(this.store, [sha], { limit: limit + skip });
505 return commits.slice(skip).map((c) => toInfo(c.oid, c.commit));
506 }
507 // Path history: commits whose tree entry at `path` differs from their first parent's.
508 const out: CommitInfo[] = [];
509 let skipped = 0;
510 for (const c of await walkCommits(this.store, [sha], { limit: 2000 })) {
511 const mine = await resolvePath(this.store, c.commit.tree, opts.path);
512 const parent = c.commit.parents[0] ? await readCommit(this.store, c.commit.parents[0]).catch(() => null) : null;
513 const theirs = parent ? await resolvePath(this.store, parent.tree, opts.path) : null;
514 if ((mine?.oid ?? null) === (theirs?.oid ?? null)) continue;
515 if (skipped++ < skip) continue;
516 out.push(toInfo(c.oid, c.commit));
517 if (out.length >= limit) break;
518 }
519 return out;
520 }
521
522 /** Diff between two commits (or a commit and its first parent). */
523 async diff(baseSha: string | null, headSha: string, opts: { patch?: boolean; maxFiles?: number } = {}) {
524 const head = await readCommit(this.store, headSha);
525 const baseTree = baseSha ? (await readCommit(this.store, baseSha)).tree : null;
526 const changes = await diffTrees(this.store, baseTree, head.tree);
527 const max = opts.maxFiles ?? 300;
528 const files = [];
529 for (const ch of changes.slice(0, max)) {
530 const d = await fileDiff(this.store, ch);
531 files.push({ ...d, patch: opts.patch === false ? undefined : formatUnified(d) });
532 }
533 return {
534 files,
535 totalFiles: changes.length,
536 additions: files.reduce((s, f) => s + f.additions, 0),
537 deletions: files.reduce((s, f) => s + f.deletions, 0),
538 truncated: changes.length > max,
539 };
540 }
541
542 async commitWithDiff(rev: string) {
543 const sha = await this.resolve(rev);
544 if (!sha) throw new HttpError(404, "commit not found");
545 const info = await this.commitInfo(sha);
546 return { ...info, ...(await this.diff(info.parents[0] ?? null, sha)) };
547 }
548
549 async compare(base: string, head: string) {
550 const b = await this.resolve(base);
551 const h = await this.resolve(head);
552 if (!b || !h) throw new HttpError(404, "unknown base or head");
553 const mb = await mergeBase(this.store, b, h);
554 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));
555 const ahead = commits.length;
556 const behind = mb ? (await walkCommits(this.store, [b], { stop: new Set([mb]), limit: 1000 })).filter((c) => c.oid !== mb).length : 0;
557 return { baseSha: b, headSha: h, mergeBase: mb, aheadBy: ahead, behindBy: behind, commits: commits.reverse(), ...(await this.diff(mb, h)) };
558 }
559
560 /**
561 * Push protection for commits made without a Git client: the same scan as `git push`, so the
562 * web editor, the contents and commits APIs and MCP cannot be used to slip a credential in.
563 */
564 private protectCommit(changes: readonly FileChange[], allowSecrets: string | undefined, caller: Caller): void {
565 const blobs = changes.filter((ch) => !ch.delete && ch.content).map((ch) => ({ oid: ch.path, content: ch.content! }));
566 const leaks = scanForSecrets(blobs);
567 if (!leaks.length) return;
568 const kinds = [...new Set(leaks.map((l) => l.kind))];
569 const paths = [...new Set(leaks.map((l) => l.oid))].slice(0, 10);
570 const target = `${this.meta.owner}/${this.meta.name}`;
571 const reason = allowSecrets?.trim().slice(0, 200);
572 if (reason && caller.role === "admin" && caller.kind === "user") {
573 this.emit({ type: "audit", action: "api.secret_bypassed", actor: caller, target, detail: { kinds, paths, reason }, at: now() });
574 return;
575 }
576 this.emit({ type: "audit", action: "api.blocked_secret", actor: caller, target, detail: { kinds, paths }, at: now() });
577 const hint = reason ? " Only repository admins (people, not agents) can bypass push protection." : "";
578 throw new HttpError(422, `push protection: possible secret detected (${kinds.join(", ")}) in ${paths.join(", ")}. Remove it, or rotate it and ask an admin.${hint}`);
579 }
580
581 /**
582 * Create a commit from file changes without a Git client (used by the web
583 * editor, the REST contents API and AI agents through MCP).
584 */
585 async commitFiles(input: {
586 branch: string;
587 message: string;
588 changes: FileChange[];
589 expectedHeadSha?: string;
590 createBranchFrom?: string;
591 author?: { name: string; email: string };
592 committer?: { name: string; email: string };
593 /** A human admin's reason for committing a detected secret anyway (like `git push -o allow-secrets=`). */
594 allowSecrets?: string;
595 }, caller: Caller): Promise<{ sha: string; branch: string }> {
596 const ref = `refs/heads/${input.branch}`;
597 let parent = this.getRef(ref);
598 if (!parent) {
599 if (input.createBranchFrom) parent = await this.resolve(input.createBranchFrom);
600 else if (this.refs("refs/heads/").length > 0) throw new HttpError(404, `branch ${input.branch} not found`);
601 }
602 if (input.expectedHeadSha && parent !== input.expectedHeadSha) throw new HttpError(409, "branch moved; refresh and retry", { currentSha: parent });
603 for (const ch of input.changes) {
604 const why = ch.delete ? null : unsafeTreePath(ch.path);
605 if (why) throw new HttpError(422, `invalid path ${JSON.stringify(ch.path)}: ${why}`);
606 }
607 this.protectCommit(input.changes, input.allowSecrets, caller);
608 const baseTree = parent ? (await readCommit(this.store, parent)).tree : null;
609 const tree = await applyChanges(this.store, baseTree, input.changes);
610 const ts = Math.floor(Date.now() / 1000);
611 const committer = input.committer
612 ? { ...input.committer, timestamp: ts, timezone: "+0000" }
613 : { name: caller.login, email: `${caller.login}@users.noreply.diffinery.com`, timestamp: ts, timezone: "+0000" };
614 const author = input.author ? { ...input.author, timestamp: ts, timezone: "+0000" } : committer;
615 const extra: [string, string][] = caller.kind === "agent" ? [["diffinery-agent", `${caller.login}${caller.onBehalfOf ? ` on-behalf-of ${caller.onBehalfOf}` : ""}`]] : [];
616 const sha = await this.store.write(
617 "commit",
618 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 }),
619 );
620 const old = parent && this.getRef(ref) ? parent : ZERO_OID;
621 const check = await this.checkRefUpdate(ref, old, sha, caller);
622 if (!check.ok) throw new HttpError(403, check.reason ?? "rejected");
623 if (!this.casRef(ref, old, sha)) throw new HttpError(409, "branch moved; refresh and retry");
624 await this.afterRefUpdate(ref, old, sha, caller);
625 return { sha, branch: input.branch };
626 }
627
628 async createRef(ref: string, sha: string, caller: Caller): Promise<void> {
629 if (!this.store.has(sha)) throw new HttpError(422, "object does not exist");
630 const check = await this.checkRefUpdate(ref, ZERO_OID, sha, caller);
631 if (!check.ok) throw new HttpError(403, check.reason ?? "rejected");
632 if (!this.casRef(ref, ZERO_OID, sha)) throw new HttpError(422, "reference already exists");
633 await this.afterRefUpdate(ref, ZERO_OID, sha, caller);
634 }
635
636 async updateRef(ref: string, sha: string, force: boolean, caller: Caller): Promise<void> {
637 const old = this.getRef(ref);
638 if (!old) throw new HttpError(404, "reference not found");
639 if (!force && !(await isAncestor(this.store, old, sha))) throw new HttpError(422, "update is not a fast-forward");
640 const check = await this.checkRefUpdate(ref, old, sha, caller);
641 if (!check.ok) throw new HttpError(403, check.reason ?? "rejected");
642 if (!this.casRef(ref, old, sha)) throw new HttpError(409, "reference moved");
643 await this.afterRefUpdate(ref, old, sha, caller);
644 }
645
646 async deleteRef(ref: string, caller: Caller): Promise<void> {
647 const old = this.getRef(ref);
648 if (!old) throw new HttpError(404, "reference not found");
649 const check = await this.checkRefUpdate(ref, old, ZERO_OID, caller);
650 if (!check.ok) throw new HttpError(403, check.reason ?? "rejected");
651 this.casRef(ref, old, null);
652 await this.afterRefUpdate(ref, old, ZERO_OID, caller);
653 }
654
655 // ---------------------------------------------------------------- protections
656
657 listProtections(): Array<{ pattern: string; rules: ProtectionRules }> {
658 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) }));
659 }
660
661 /**
662 * Create, replace or (with null) delete a rule. Only people who administer the repository change
663 * branch protection: never agents, never a workflow's token. Turning `allowAgentAutoMerge` or
664 * `agentAutoMergeWithoutApproval` on or off is audited on its own, since they let agents land changes.
665 */
666 setProtection(pattern: string, rules: ProtectionRules | null, caller: Caller): void {
667 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");
668 if (rules?.mergeQueue) {
669 const asked = typeof rules.mergeQueue === "object" ? rules.mergeQueue.method : undefined;
670 const mergeQueue = normalizeMergeQueue(rules.mergeQueue);
671 // A queue that makes merge commits could never merge into a branch that refuses them.
672 if (rules.requireLinearHistory && mergeQueue.method === "merge") {
673 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");
674 mergeQueue.method = "squash";
675 }
676 rules = { ...rules, mergeQueue };
677 }
678 if (rules?.requiredCheckSources) rules = { ...rules, requiredCheckSources: normalizeCheckSources(rules.requiredCheckSources) };
679 if (rules && rules.allowAgentAutoMerge !== undefined && typeof rules.allowAgentAutoMerge !== "boolean") throw new HttpError(422, "allowAgentAutoMerge must be a boolean");
680 if (rules && rules.agentAutoMergeWithoutApproval !== undefined && typeof rules.agentAutoMergeWithoutApproval !== "boolean") throw new HttpError(422, "agentAutoMergeWithoutApproval must be a boolean");
681 if (rules?.agentAutoMergeWithoutApproval && !rules.allowAgentAutoMerge) throw new HttpError(422, "agentAutoMergeWithoutApproval needs allowAgentAutoMerge: it only applies to what Diffinery lands for agents");
682 if (rules && !rules.allowAgentAutoMerge) {
683 const { allowAgentAutoMerge: _, agentAutoMergeWithoutApproval: _w, ...rest } = rules;
684 rules = rest;
685 }
686 if (rules && !rules.agentAutoMergeWithoutApproval) {
687 const { agentAutoMergeWithoutApproval: _, ...rest } = rules;
688 rules = rest;
689 }
690 const before = this.sql.exec<{ rules: string }>("SELECT rules FROM protections WHERE pattern = ?", pattern).toArray()[0];
691 const old = before ? (JSON.parse(before.rules) as ProtectionRules) : null;
692 const was = !!old?.allowAgentAutoMerge;
693 const waived = !!old?.agentAutoMergeWithoutApproval;
694 if (rules) this.sql.exec("INSERT INTO protections (pattern, rules) VALUES (?, ?) ON CONFLICT(pattern) DO UPDATE SET rules = excluded.rules", pattern, JSON.stringify(rules));
695 else this.sql.exec("DELETE FROM protections WHERE pattern = ?", pattern);
696 if (was !== !!rules?.allowAgentAutoMerge) {
697 const m = this.meta;
698 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() });
699 }
700 if (waived !== !!rules?.agentAutoMergeWithoutApproval) {
701 const m = this.meta;
702 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() });
703 }
704 // Turning a queue off (or changing its checks) affects what is queued, and what may auto-merge.
705 this.queue.schedule();
706 this.autoMerge.schedule();
707 }
708
709 // ---------------------------------------------------------------- RPC passthroughs (collab + actions)
710 // Workers RPC only exposes methods on the class itself, so the sub-modules are wrapped here.
711
712 issues(...a: Parameters<Collab["list"]>) {
713 return this.collab.list(...a);
714 }
715 issue(...a: Parameters<Collab["get"]>) {
716 return this.collab.get(...a);
717 }
718 createIssue(...a: Parameters<Collab["createIssue"]>) {
719 return this.collab.createIssue(...a);
720 }
721 updateIssue(...a: Parameters<Collab["update"]>) {
722 return this.collab.update(...a);
723 }
724 setPullDraft(...a: Parameters<Collab["setDraft"]>) {
725 return this.collab.setDraft(...a);
726 }
727 addComment(...a: Parameters<Collab["addComment"]>) {
728 return this.collab.addComment(...a);
729 }
730 editComment(...a: Parameters<Collab["editComment"]>) {
731 return this.collab.editComment(...a);
732 }
733 createPull(...a: Parameters<Collab["createPull"]>) {
734 return this.collab.createPull(...a);
735 }
736 pullFiles(...a: Parameters<Collab["pullFiles"]>) {
737 return this.collab.pullFiles(...a);
738 }
739 pullCommits(...a: Parameters<Collab["pullCommits"]>) {
740 return this.collab.pullCommits(...a);
741 }
742 submitReview(...a: Parameters<Collab["submitReview"]>) {
743 return this.collab.submitReview(...a);
744 }
745 resolveThread(...a: Parameters<Collab["resolveThread"]>) {
746 return this.collab.resolveThread(...a);
747 }
748 mergeability(...a: Parameters<Collab["mergeability"]>) {
749 return this.collab.mergeability(...a);
750 }
751 mergePull(...a: Parameters<Collab["merge"]>) {
752 return this.collab.merge(...a);
753 }
754 requestReviewers(...a: Parameters<Collab["requestReviewers"]>) {
755 return this.collab.requestReviewers(...a);
756 }
757 labels(...a: Parameters<Collab["labels"]>) {
758 return this.collab.labels(...a);
759 }
760 setLabel(...a: Parameters<Collab["setLabel"]>) {
761 return this.collab.setLabel(...a);
762 }
763 checks(...a: Parameters<Collab["checks"]>) {
764 return this.collab.checks(...a);
765 }
766 upsertCheck(...a: Parameters<Collab["upsertCheck"]>) {
767 return this.collab.upsertCheck(...a);
768 }
769 webhooks(...a: Parameters<Collab["webhooks"]>) {
770 return this.collab.webhooks(...a);
771 }
772 createWebhook(...a: Parameters<Collab["createWebhook"]>) {
773 return this.collab.createWebhook(...a);
774 }
775 deleteWebhook(...a: Parameters<Collab["deleteWebhook"]>) {
776 return this.collab.deleteWebhook(...a);
777 }
778 recordDelivery(...a: Parameters<Collab["recordDelivery"]>) {
779 return this.collab.recordDelivery(...a);
780 }
781
782 enqueuePull(...a: Parameters<MergeQueue["enqueue"]>) {
783 return this.queue.enqueue(...a);
784 }
785 dequeuePull(...a: Parameters<MergeQueue["dequeue"]>) {
786 return this.queue.dequeue(...a);
787 }
788 mergeQueue(...a: Parameters<MergeQueue["list"]>) {
789 return this.queue.list(...a);
790 }
791 mergeQueueSettings(...a: Parameters<MergeQueue["settings"]>) {
792 return this.queue.settings(...a);
793 }
794 enableAutoMerge(...a: Parameters<AutoMerge["enable"]>) {
795 return this.autoMerge.enable(...a);
796 }
797 disableAutoMerge(...a: Parameters<AutoMerge["disable"]>) {
798 return this.autoMerge.disable(...a);
799 }
800
801 runs(...a: Parameters<Actions["listRuns"]>) {
802 return this.actions.listRuns(...a);
803 }
804 run(...a: Parameters<Actions["getRun"]>) {
805 return this.actions.getRun(...a);
806 }
807 runJobs(...a: Parameters<Actions["jobs"]>) {
808 return this.actions.jobs(...a);
809 }
810 claimJob(...a: Parameters<Actions["claimJob"]>) {
811 return this.actions.claimJob(...a);
812 }
813 jobStatus(jobId: string): string {
814 return this.actions.getJob(jobId).status;
815 }
816 job(...a: Parameters<Actions["getJob"]>) {
817 return this.actions.getJob(...a);
818 }
819 jobLogs(...a: Parameters<Actions["logs"]>) {
820 return this.actions.logs(...a);
821 }
822 cancelRun(...a: Parameters<Actions["cancel"]>) {
823 return this.actions.cancel(...a);
824 }
825 rerun(...a: Parameters<Actions["rerun"]>) {
826 return this.actions.rerun(...a);
827 }
828 dispatchWorkflow(...a: Parameters<Actions["dispatch"]>) {
829 return this.actions.dispatch(...a);
830 }
831 scheduleTick(...a: Parameters<Actions["schedule"]>) {
832 return this.actions.schedule(...a);
833 }
834 onPullRequestEvent(...a: Parameters<Actions["onPullRequest"]>) {
835 return this.actions.onPullRequest(...a);
836 }
837 workflows(...a: Parameters<Actions["listWorkflows"]>) {
838 return this.actions.listWorkflows(...a);
839 }
840 runPlan(...a: Parameters<Actions["plan"]>) {
841 return this.actions.plan(...a);
842 }
843 startJobKey(...a: Parameters<Actions["startJobKey"]>) {
844 return this.actions.startJobKey(...a);
845 }
846 jobTimedOut(...a: Parameters<Actions["jobTimedOut"]>) {
847 return this.actions.jobTimedOut(...a);
848 }
849 finishRun(...a: Parameters<Actions["finishRun"]>) {
850 return this.actions.finishRun(...a);
851 }
852 oidcClaims(...a: Parameters<Actions["oidcClaims"]>) {
853 return this.actions.oidcClaims(...a);
854 }
855 runnerSpec(...a: Parameters<Actions["runnerSpec"]>) {
856 return this.actions.runnerSpec(...a);
857 }
858 runnerLogs(...a: Parameters<Actions["runnerLogs"]>) {
859 return this.actions.runnerLogs(...a);
860 }
861 runnerStep(...a: Parameters<Actions["runnerStep"]>) {
862 return this.actions.runnerStep(...a);
863 }
864 runnerComplete(...a: Parameters<Actions["runnerComplete"]>) {
865 return this.actions.runnerComplete(...a);
866 }
867 packagesPermission(...a: Parameters<Actions["packagesPermission"]>) {
868 return this.actions.packagesPermission(...a);
869 }
870 runnerAuth(...a: Parameters<Actions["runnerAuth"]>) {
871 return this.actions.runnerAuth(...a);
872 }
873 containerStopped(...a: Parameters<Actions["containerStopped"]>) {
874 return this.actions.containerStopped(...a);
875 }
876 setSecret(...a: Parameters<Actions["setSecret"]>) {
877 return this.actions.setSecret(...a);
878 }
879 deleteSecret(...a: Parameters<Actions["deleteSecret"]>) {
880 return this.actions.deleteSecret(...a);
881 }
882 secretNames(...a: Parameters<Actions["secretNames"]>) {
883 return this.actions.secretNames(...a);
884 }
885 setVariable(...a: Parameters<Actions["setVariable"]>) {
886 return this.actions.setVariable(...a);
887 }
888 variables(...a: Parameters<Actions["variables"]>) {
889 return this.actions.variables(...a);
890 }
891 cacheLookup(...a: Parameters<Actions["cacheLookup"]>) {
892 return this.actions.cacheLookup(...a);
893 }
894 cacheSaved(...a: Parameters<Actions["cacheSaved"]>) {
895 return this.actions.cacheSaved(...a);
896 }
897 artifactUploadKeys(...a: Parameters<Actions["artifactUploadKeys"]>) {
898 return this.actions.artifactUploadKeys(...a);
899 }
900 artifactSaved(...a: Parameters<Actions["artifactSaved"]>) {
901 return this.actions.artifactSaved(...a);
902 }
903 artifacts(...a: Parameters<Actions["artifacts"]>) {
904 return this.actions.artifacts(...a);
905 }
906 createSandbox(...a: Parameters<Actions["createSandbox"]>) {
907 return this.actions.createSandbox(...a);
908 }
909 sandbox(...a: Parameters<Actions["getSandbox"]>) {
910 return this.actions.getSandbox(...a);
911 }
912 closeSandbox(...a: Parameters<Actions["closeSandbox"]>) {
913 return this.actions.closeSandbox(...a);
914 }
915
916 plannedRunError(runId: string, message: string) {
917 return this.actions.plannedError(runId, message);
918 }
919 cacheSaveKeys(...a: Parameters<Actions["cacheSaveKeys"]>) {
920 return this.actions.cacheSaveKeys(...a);
921 }
922 cacheReadKeys(...a: Parameters<Actions["cacheReadKeys"]>) {
923 return this.actions.cacheReadKeys(...a);
924 }
925 artifactKeysFor(...a: Parameters<Actions["artifactKeysFor"]>) {
926 return this.actions.artifactKeysFor(...a);
927 }
928 artifactQuota() {
929 return this.runtime.artifactQuota;
930 }
931
932 // ---------------------------------------------------------------- RPC passthroughs (Actions runtime services)
933 // The cache and artifact services of repo/runtime.ts, called by http/actions-runtime.ts
934 // with the job named by a runtime token, and by the REST caches/artifacts routes.
935
936 rtJob(...a: Parameters<Runtime["job"]>) {
937 return this.runtime.job(...a);
938 }
939 rtGrantFor(...a: Parameters<Runtime["grantFor"]>) {
940 return this.runtime.grantFor(...a);
941 }
942 rtCacheLookup(...a: Parameters<Runtime["cacheLookup"]>) {
943 return this.runtime.cacheLookup(...a);
944 }
945 rtCacheReserve(...a: Parameters<Runtime["cacheReserve"]>) {
946 return this.runtime.cacheReserve(...a);
947 }
948 rtCacheReservation(...a: Parameters<Runtime["cacheReservation"]>) {
949 return this.runtime.cacheReservation(...a);
950 }
951 rtCacheWritable(...a: Parameters<Runtime["cacheWritable"]>) {
952 return this.runtime.cacheWritable(...a);
953 }
954 rtCacheCommit(...a: Parameters<Runtime["cacheCommit"]>) {
955 return this.runtime.cacheCommit(...a);
956 }
957 rtCacheGet(...a: Parameters<Runtime["cacheGet"]>) {
958 return this.runtime.cacheGet(...a);
959 }
960 rtListCaches(...a: Parameters<Runtime["listCaches"]>) {
961 return this.runtime.listCaches(...a);
962 }
963 rtDeleteCaches(...a: Parameters<Runtime["deleteCaches"]>) {
964 return this.runtime.deleteCaches(...a);
965 }
966 rtCacheUsage(...a: Parameters<Runtime["cacheUsage"]>) {
967 return this.runtime.cacheUsage(...a);
968 }
969 rtArtifactCreate(...a: Parameters<Runtime["artifactCreate"]>) {
970 return this.runtime.artifactCreate(...a);
971 }
972 rtArtifactUpload(...a: Parameters<Runtime["artifactUpload"]>) {
973 return this.runtime.artifactUpload(...a);
974 }
975 rtArtifactWritable(...a: Parameters<Runtime["artifactWritable"]>) {
976 return this.runtime.artifactWritable(...a);
977 }
978 rtArtifactFinalize(...a: Parameters<Runtime["artifactFinalize"]>) {
979 return this.runtime.artifactFinalize(...a);
980 }
981 rtArtifactGet(...a: Parameters<Runtime["artifactGet"]>) {
982 return this.runtime.artifactGet(...a);
983 }
984 rtJobArtifacts(...a: Parameters<Runtime["jobArtifacts"]>) {
985 return this.runtime.jobArtifacts(...a);
986 }
987 rtRunArtifacts(...a: Parameters<Runtime["runArtifacts"]>) {
988 return this.runtime.runArtifacts(...a);
989 }
990 rtRepoArtifacts(...a: Parameters<Runtime["repoArtifacts"]>) {
991 return this.runtime.repoArtifacts(...a);
992 }
993 rtArtifactDelete(...a: Parameters<Runtime["artifactDelete"]>) {
994 return this.runtime.artifactDelete(...a);
995 }
996 rtArtifactDeleteByName(...a: Parameters<Runtime["artifactDeleteByName"]>) {
997 return this.runtime.artifactDeleteByName(...a);
998 }
999 workflowSettings() {
1000 return this.policy.settings();
1001 }
1002 setWorkflowSettings(...a: Parameters<TokenPolicy["setSettings"]>) {
1003 return this.policy.setSettings(...a);
1004 }
1005 rtStage(...a: Parameters<Runtime["stage"]>) {
1006 return this.runtime.stage(...a);
1007 }
1008 rtUnstage(...a: Parameters<Runtime["unstage"]>) {
1009 return this.runtime.unstage(...a);
1010 }
1011 rtCheckCommitSize(...a: Parameters<Runtime["checkCommitSize"]>) {
1012 return this.runtime.checkCommitSize(...a);
1013 }
1014 rtCacheMissing(...a: Parameters<Runtime["cacheMissing"]>) {
1015 return this.runtime.cacheMissing(...a);
1016 }
1017 rtComposeStep(...a: Parameters<Runtime["composeStep"]>) {
1018 return this.runtime.composeStep(...a);
1019 }
1020
1021 // ---------------------------------------------------------------- RPC passthroughs (GitHub-compatible extras)
1022 // Releases, commit statuses, deployments and environments, issue sub-resources
1023 // (labels, reactions, events, locking), the Git data API, search and misc.
1024 // The modules are created on first use.
1025
1026 private extras: { releases?: Releases; statuses?: Statuses; deploys?: Deployments; social?: Social; gitdata?: GitData } = {};
1027 get releases(): Releases {
1028 return (this.extras.releases ??= new Releases(this, this.env));
1029 }
1030 get statuses(): Statuses {
1031 return (this.extras.statuses ??= new Statuses(this));
1032 }
1033 get deploys(): Deployments {
1034 return (this.extras.deploys ??= new Deployments(this, this.env));
1035 }
1036 get social(): Social {
1037 return (this.extras.social ??= new Social(this));
1038 }
1039 get gitdata(): GitData {
1040 return (this.extras.gitdata ??= new GitData(this, this.env));
1041 }
1042
1043 listReleases(...a: Parameters<Releases["list"]>) {
1044 return this.releases.list(...a);
1045 }
1046 getRelease(...a: Parameters<Releases["get"]>) {
1047 return this.releases.get(...a);
1048 }
1049 releaseByTag(...a: Parameters<Releases["byTag"]>) {
1050 return this.releases.byTag(...a);
1051 }
1052 latestRelease() {
1053 return this.releases.latest();
1054 }
1055 releaseSummary(...a: Parameters<Releases["summary"]>) {
1056 return this.releases.summary(...a);
1057 }
1058 createRelease(...a: Parameters<Releases["create"]>) {
1059 return this.releases.create(...a);
1060 }
1061 updateRelease(...a: Parameters<Releases["update"]>) {
1062 return this.releases.update(...a);
1063 }
1064 deleteRelease(...a: Parameters<Releases["remove"]>) {
1065 return this.releases.remove(...a);
1066 }
1067 generateReleaseNotes(...a: Parameters<Releases["generateNotes"]>) {
1068 return this.releases.generateNotes(...a);
1069 }
1070 releaseAssets(...a: Parameters<Releases["assets"]>) {
1071 return this.releases.assets(...a);
1072 }
1073 releaseAsset(...a: Parameters<Releases["asset"]>) {
1074 return this.releases.asset(...a);
1075 }
1076 updateReleaseAsset(...a: Parameters<Releases["updateAsset"]>) {
1077 return this.releases.updateAsset(...a);
1078 }
1079 deleteReleaseAsset(...a: Parameters<Releases["deleteAsset"]>) {
1080 return this.releases.deleteAsset(...a);
1081 }
1082 startReleaseAsset(...a: Parameters<Releases["startAsset"]>) {
1083 return this.releases.startAsset(...a);
1084 }
1085 finishReleaseAsset(...a: Parameters<Releases["finishAsset"]>) {
1086 return this.releases.finishAsset(...a);
1087 }
1088 abortReleaseAsset(...a: Parameters<Releases["abortAsset"]>) {
1089 return this.releases.abortAsset(...a);
1090 }
1091 releaseDownload(...a: Parameters<Releases["download"]>) {
1092 return this.releases.download(...a);
1093 }
1094 /** For the GitHub importer: a release with its original dates and author (no tag, events or workflows). */
1095 importRelease(...a: Parameters<Releases["importRelease"]>) {
1096 return this.releases.importRelease(...a);
1097 }
1098 /** For the GitHub importer: an asset copied from a public https URL, or from an R2 key under this repository's prefix. */
1099 importReleaseAsset(...a: Parameters<Releases["importAsset"]>) {
1100 return this.releases.importAsset(...a);
1101 }
1102
1103 createStatus(...a: Parameters<Statuses["create"]>) {
1104 return this.statuses.create(...a);
1105 }
1106 commitStatuses(...a: Parameters<Statuses["list"]>) {
1107 return this.statuses.list(...a);
1108 }
1109 combinedStatus(...a: Parameters<Statuses["combined"]>) {
1110 return this.statuses.combined(...a);
1111 }
1112 /** Check runs and commit statuses together, as pull request and commit pages show them. */
1113 checksAndStatuses(sha: string) {
1114 return [...this.collab.checks(sha), ...this.statuses.asChecks(sha)];
1115 }
1116
1117 /** This repository's part of the Today view (agentic/today.ts): open pull requests and what landed or failed since `since`. */
1118 todaySummary(since: string) {
1119 return repoToday(this.sql, (sha) => this.checksAndStatuses(sha), since);
1120 }
1121
1122 createDeployment(...a: Parameters<Deployments["create"]>) {
1123 return this.deploys.create(...a);
1124 }
1125 deployments(...a: Parameters<Deployments["list"]>) {
1126 return this.deploys.list(...a);
1127 }
1128 deployment(...a: Parameters<Deployments["get"]>) {
1129 return this.deploys.get(...a);
1130 }
1131 deleteDeployment(...a: Parameters<Deployments["remove"]>) {
1132 return this.deploys.remove(...a);
1133 }
1134 createDeploymentStatus(...a: Parameters<Deployments["createStatus"]>) {
1135 return this.deploys.createStatus(...a);
1136 }
1137 deploymentStatuses(...a: Parameters<Deployments["statuses"]>) {
1138 return this.deploys.statuses(...a);
1139 }
1140 deploymentStatus(...a: Parameters<Deployments["status"]>) {
1141 return this.deploys.status(...a);
1142 }
1143 environments() {
1144 return this.deploys.environments();
1145 }
1146 environment(...a: Parameters<Deployments["environment"]>) {
1147 return this.deploys.environment(...a);
1148 }
1149 upsertEnvironment(...a: Parameters<Deployments["upsertEnvironment"]>) {
1150 return this.deploys.upsertEnvironment(...a);
1151 }
1152 deleteEnvironment(...a: Parameters<Deployments["deleteEnvironment"]>) {
1153 return this.deploys.deleteEnvironment(...a);
1154 }
1155 addEnvironmentBranchPattern(...a: Parameters<Deployments["addBranchPattern"]>) {
1156 return this.deploys.addBranchPattern(...a);
1157 }
1158 removeEnvironmentBranchPattern(...a: Parameters<Deployments["removeBranchPattern"]>) {
1159 return this.deploys.removeBranchPattern(...a);
1160 }
1161 setEnvironmentSecret(...a: Parameters<Deployments["setSecret"]>) {
1162 return this.deploys.setSecret(...a);
1163 }
1164 deleteEnvironmentSecret(...a: Parameters<Deployments["deleteSecret"]>) {
1165 return this.deploys.deleteSecret(...a);
1166 }
1167 environmentSecretNames(...a: Parameters<Deployments["secretNames"]>) {
1168 return this.deploys.secretNames(...a);
1169 }
1170 setEnvironmentVariable(...a: Parameters<Deployments["setVariable"]>) {
1171 return this.deploys.setVariable(...a);
1172 }
1173 environmentVariables(...a: Parameters<Deployments["variables"]>) {
1174 return this.deploys.variables(...a);
1175 }
1176
1177 /** What the GitHub JSON builders need for a set of issues: label rows, reaction counts and lock reasons. */
1178 issueExtras(numbers: number[], subjects: string[] = []) {
1179 const lockReasons: Record<number, string | null> = {};
1180 for (const n of numbers) lockReasons[n] = this.social.lockReason(n);
1181 return { labels: this.social.labelRows(), reactions: this.social.reactionCounts([...numbers.map((n) => `issue:${n}`), ...subjects]), lockReasons };
1182 }
1183 issueEvents(...a: Parameters<Social["events"]>) {
1184 return this.social.events(...a);
1185 }
1186 repoIssueEvents(...a: Parameters<Social["repoEvents"]>) {
1187 return this.social.repoEvents(...a);
1188 }
1189 issueEvent(...a: Parameters<Social["event"]>) {
1190 return this.social.event(...a);
1191 }
1192 issueTimeline(...a: Parameters<Social["timeline"]>) {
1193 return this.social.timeline(...a);
1194 }
1195 labelRows() {
1196 return this.social.labelRows();
1197 }
1198 label(...a: Parameters<Social["label"]>) {
1199 return this.social.label(...a);
1200 }
1201 createLabel(...a: Parameters<Social["createLabel"]>) {
1202 return this.social.createLabel(...a);
1203 }
1204 updateLabel(...a: Parameters<Social["updateLabel"]>) {
1205 return this.social.updateLabel(...a);
1206 }
1207 deleteLabel(...a: Parameters<Social["deleteLabel"]>) {
1208 return this.social.deleteLabel(...a);
1209 }
1210 issueLabels(...a: Parameters<Social["issueLabels"]>) {
1211 return this.social.issueLabels(...a);
1212 }
1213 addIssueLabels(...a: Parameters<Social["addLabels"]>) {
1214 return this.social.addLabels(...a);
1215 }
1216 setIssueLabels(...a: Parameters<Social["setLabels"]>) {
1217 return this.social.setLabels(...a);
1218 }
1219 removeIssueLabel(...a: Parameters<Social["removeLabel"]>) {
1220 return this.social.removeLabel(...a);
1221 }
1222 assignIssue(...a: Parameters<Social["assign"]>) {
1223 return this.social.assign(...a);
1224 }
1225 lockIssue(...a: Parameters<Social["lock"]>) {
1226 return this.social.lock(...a);
1227 }
1228 unlockIssue(...a: Parameters<Social["unlock"]>) {
1229 return this.social.unlock(...a);
1230 }
1231 comment(...a: Parameters<Social["comment"]>) {
1232 return this.social.comment(...a);
1233 }
1234 deleteComment(...a: Parameters<Social["deleteComment"]>) {
1235 return this.social.deleteComment(...a);
1236 }
1237 repoComments(...a: Parameters<Social["repoComments"]>) {
1238 return this.social.repoComments(...a);
1239 }
1240 createReviewComment(...a: Parameters<Social["createReviewComment"]>) {
1241 return this.social.createReviewComment(...a);
1242 }
1243 review(...a: Parameters<Social["review"]>) {
1244 return this.social.review(...a);
1245 }
1246 dismissReview(...a: Parameters<Social["dismissReview"]>) {
1247 return this.social.dismissReview(...a);
1248 }
1249 removeReviewers(...a: Parameters<Social["removeReviewers"]>) {
1250 return this.social.removeReviewers(...a);
1251 }
1252 updatePullBranch(...a: Parameters<Social["updateBranch"]>) {
1253 return this.social.updateBranch(...a);
1254 }
1255 pullsForCommit(...a: Parameters<Social["pullsForCommit"]>) {
1256 return this.social.pullsForCommit(...a);
1257 }
1258 reactions(...a: Parameters<Social["reactions"]>) {
1259 return this.social.reactions(...a);
1260 }
1261 react(...a: Parameters<Social["react"]>) {
1262 return this.social.react(...a);
1263 }
1264 unreact(...a: Parameters<Social["unreact"]>) {
1265 return this.social.unreact(...a);
1266 }
1267 searchIssues(query: Parameters<typeof searchIssues>[1], limit: number) {
1268 return searchIssues(this, query, limit);
1269 }
1270 /** The issues for one page of search hits, in the order given (missing numbers are skipped). */
1271 issuesByNumber(numbers: number[]) {
1272 return numbers.slice(0, 100).flatMap((n) => {
1273 try {
1274 return [this.collab.get(n).issue];
1275 } catch {
1276 return [];
1277 }
1278 });
1279 }
1280
1281 objectType(...a: Parameters<GitData["objectType"]>) {
1282 return this.gitdata.objectType(...a);
1283 }
1284 refsWithTypes(...a: Parameters<GitData["refsWithTypes"]>) {
1285 return this.gitdata.refsWithTypes(...a);
1286 }
1287 createBlob(...a: Parameters<GitData["createBlob"]>) {
1288 return this.gitdata.createBlob(...a);
1289 }
1290 getBlob(...a: Parameters<GitData["getBlob"]>) {
1291 return this.gitdata.getBlob(...a);
1292 }
1293 createTree(...a: Parameters<GitData["createTree"]>) {
1294 return this.gitdata.createTree(...a);
1295 }
1296 getTree(...a: Parameters<GitData["getTree"]>) {
1297 return this.gitdata.getTree(...a);
1298 }
1299 createGitCommit(...a: Parameters<GitData["createCommit"]>) {
1300 return this.gitdata.createCommit(...a);
1301 }
1302 gitCommit(...a: Parameters<GitData["gitCommit"]>) {
1303 return this.gitdata.gitCommit(...a);
1304 }
1305 createGitTag(...a: Parameters<GitData["createTag"]>) {
1306 return this.gitdata.createTag(...a);
1307 }
1308 gitTag(...a: Parameters<GitData["getTag"]>) {
1309 return this.gitdata.getTag(...a);
1310 }
1311 putContents(...a: Parameters<GitData["putContents"]>) {
1312 return this.gitdata.putContents(...a);
1313 }
1314 deleteContents(...a: Parameters<GitData["deleteContents"]>) {
1315 return this.gitdata.deleteContents(...a);
1316 }
1317 readme(...a: Parameters<GitData["readme"]>) {
1318 return this.gitdata.readme(...a);
1319 }
1320 mergeBranches(...a: Parameters<GitData["merge"]>) {
1321 return this.gitdata.merge(...a);
1322 }
1323 languages() {
1324 return this.gitdata.languages();
1325 }
1326 archiveKey(...a: Parameters<GitData["archiveKey"]>) {
1327 return this.gitdata.archiveKey(...a);
1328 }
1329 buildArchive(...a: Parameters<GitData["buildArchive"]>) {
1330 return this.gitdata.buildArchive(...a);
1331 }
1332 runLogsZip(...a: Parameters<GitData["runLogsZip"]>) {
1333 return this.gitdata.runLogsZip(...a);
1334 }
1335 runAttemptId(...a: Parameters<GitData["runAttemptId"]>) {
1336 return this.gitdata.runAttemptId(...a);
1337 }
1338 checkRun(...a: Parameters<GitData["check"]>) {
1339 return this.gitdata.check(...a);
1340 }
1341 updateCheckRun(...a: Parameters<GitData["updateCheck"]>) {
1342 return this.gitdata.updateCheck(...a);
1343 }
1344 checkSuites(...a: Parameters<GitData["checkSuites"]>) {
1345 return this.gitdata.checkSuites(...a);
1346 }
1347 checkSuite(...a: Parameters<GitData["checkSuite"]>) {
1348 return this.gitdata.checkSuite(...a);
1349 }
1350
1351 /** repository_dispatch: an external event that starts workflows listening for its `event_type`. */
1352 async repositoryDispatch(eventType: string, clientPayload: Record<string, unknown>, caller: Caller): Promise<void> {
1353 if (!atLeast(caller.role, "write")) throw new HttpError(403, "write access is required to dispatch events");
1354 const sha = this.getRef(this.headRef);
1355 if (!sha) throw new HttpError(422, "the repository is empty");
1356 const m = this.meta;
1357 const payload = { action: eventType, branch: m.defaultBranch, client_payload: clientPayload };
1358 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() });
1359 await triggerWorkflows(this, { name: "repository_dispatch", action: eventType, ref: this.headRef, sha, payload, title: eventType }, caller);
1360 }
1361
1362 // ---------------------------------------------------------------- RPC passthroughs: GitHub imports and milestones (repo/imports.ts)
1363
1364 private importsCache?: RepoImports;
1365 private get importsModule(): RepoImports {
1366 return (this.importsCache ??= new RepoImports(this.sql));
1367 }
1368
1369 /** The import that currently holds this repository, or null. Other writes are refused meanwhile (loadRepo, gitReceivePack). */
1370 importLockHolder(): string | null {
1371 return this.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = 'import_lock'").toArray()[0]?.value ?? null;
1372 }
1373
1374 /**
1375 * Claim the repository for an import. Refuses if another import holds it, or if the repo
1376 * already holds any ref, issue, comment, milestone, protection or release this import did not write
1377 * (so a retry never adopts content people added in the meantime — H2).
1378 */
1379 importBegin(importId: string): void {
1380 const holder = this.importLockHolder();
1381 if (holder && holder !== importId) throw new HttpError(409, "another import is in progress for this repository");
1382 // A ref not written by this import, or any foreign row, means the repo was adopted since.
1383 for (const r of this.refs()) {
1384 if (r.name.startsWith("refs/diffinery-import/")) continue;
1385 if (this.importsModule.importRefOid(r.name, importId) === null) {
1386 if (holder !== importId) throw new HttpError(409, "repository already holds content not written by this import; start a new import");
1387 }
1388 }
1389 if (this.importsModule.hasForeignContent(importId)) throw new HttpError(409, "repository already holds content not written by this import; start a new import");
1390 this.sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES ('import_lock', ?)", importId);
1391 }
1392
1393 /** Release the import lock (on finalize, fail or cancel). */
1394 importEnd(importId: string): void {
1395 if (this.importLockHolder() === importId) this.sql.exec("DELETE FROM meta WHERE key = 'import_lock'");
1396 }
1397
1398 importProtection(pattern: string, rules: ProtectionRules | null, importId: string) {
1399 // What agents may do is a person's decision here, never something an import brings in.
1400 if (rules) {
1401 const { allowAgentAutoMerge: _a, agentAutoMergeWithoutApproval: _w, agentsMayPush: _p, agentsMayMerge: _m, ...rest } = rules;
1402 rules = rest;
1403 }
1404 if (rules?.mergeQueue) rules = { ...rules, mergeQueue: normalizeMergeQueue(rules.mergeQueue) };
1405 if (rules?.requiredCheckSources) rules = { ...rules, requiredCheckSources: normalizeCheckSources(rules.requiredCheckSources) };
1406 if (rules) this.importsModule.protection(pattern, JSON.stringify(rules), importId);
1407 }
1408 importLabels(...a: Parameters<RepoImports["labels"]>) {
1409 return this.importsModule.labels(...a);
1410 }
1411 importMilestones(...a: Parameters<RepoImports["milestones"]>) {
1412 return this.importsModule.milestones(...a);
1413 }
1414 importIssues(...a: Parameters<RepoImports["issues"]>) {
1415 return this.importsModule.issues(...a);
1416 }
1417 importComments(...a: Parameters<RepoImports["comments"]>) {
1418 return this.importsModule.comments(...a);
1419 }
1420 importReviews(...a: Parameters<RepoImports["reviews"]>) {
1421 return this.importsModule.reviews(...a);
1422 }
1423 importSetMergedBy(...a: Parameters<RepoImports["setMergedBy"]>) {
1424 return this.importsModule.setMergedBy(...a);
1425 }
1426 importPullNumbers(...a: Parameters<RepoImports["pullNumbers"]>) {
1427 return this.importsModule.pullNumbers(...a);
1428 }
1429 importCounts() {
1430 return this.importsModule.counts();
1431 }
1432 importFindings() {
1433 return this.importsModule.findings();
1434 }
1435 /**
1436 * Point `refs/pull/N/head` at each imported pull request's head commit (the server owns
1437 * refs/pull/*; the agent pushed the commits to refs/diffinery-import/pull/N). Heads whose
1438 * commits never arrived (e.g. deleted forks) are reported, not fatal.
1439 */
1440 importPullRefs(importId?: string): { created: number; missing: number[] } {
1441 const missing: number[] = [];
1442 let created = 0;
1443 for (const p of this.importsModule.pullHeads()) {
1444 const ref = `refs/pull/${p.number}/head`;
1445 if (!/^[0-9a-f]{40}$/.test(p.headSha) || !this.store.has(p.headSha)) {
1446 missing.push(p.number);
1447 continue;
1448 }
1449 const current = this.getRef(ref);
1450 // Record provenance so a retry does not mistake refs/pull/*/head for content people adopted.
1451 if (importId) this.importsModule.recordImportRef(ref, p.headSha, importId);
1452 if (current === p.headSha) continue;
1453 if (this.casRef(ref, current, p.headSha)) created++;
1454 }
1455 return { created, missing };
1456 }
1457 /** Remove the import's own refs once refs/pull/N/head keep the pull request commits reachable. */
1458 importDropTempRefs(importId?: string): number {
1459 const refs = this.refs(IMPORT_REF_PREFIX);
1460 for (const r of refs) this.casRef(r.name, r.oid, null);
1461 if (importId) this.importsModule.dropImportRefs(importId);
1462 return refs.length;
1463 }
1464 setOrgVariables(...a: Parameters<RepoImports["setOrgVariables"]>) {
1465 return this.importsModule.setOrgVariables(...a);
1466 }
1467 issueMilestoneOf(number: number) {
1468 return this.importsModule.milestoneOf(number);
1469 }
1470 /** Check names that workflow jobs on the default branch report, keyed by job name (GitHub names checks by job). */
1471 async importCheckNames(): Promise<Record<string, string[]>> {
1472 const sha = await this.resolve("HEAD");
1473 const out: Record<string, string[]> = {};
1474 if (!sha) return out;
1475 for (const w of await this.actions.loadWorkflows(sha)) {
1476 if (!w.workflow) continue;
1477 const wf = w.workflow.name ?? w.path.split("/").pop()!;
1478 for (const [key, job] of Object.entries(w.workflow.jobs)) {
1479 const name = (job as { name?: unknown }).name;
1480 for (const n of new Set([key, typeof name === "string" ? name : key])) (out[n] ??= []).push(`${wf} / ${typeof name === "string" && !name.includes("${{") ? name : key}`);
1481 }
1482 }
1483 return out;
1484 }
1485 milestones(...a: Parameters<RepoImports["listMilestones"]>) {
1486 return this.importsModule.listMilestones(...a);
1487 }
1488 milestone(...a: Parameters<RepoImports["milestone"]>) {
1489 return this.importsModule.milestone(...a);
1490 }
1491 saveMilestone(...a: Parameters<RepoImports["saveMilestone"]>) {
1492 return this.importsModule.saveMilestone(...a);
1493 }
1494 setIssueMilestone(...a: Parameters<RepoImports["setIssueMilestone"]>) {
1495 return this.importsModule.setIssueMilestone(...a);
1496 }
1497
1498 // ---------------------------------------------------------------- live updates (WebSockets with hibernation)
1499
1500 override async fetch(request: Request): Promise<Response> {
1501 if (request.headers.get("Upgrade") !== "websocket") return new Response("expected websocket", { status: 426 });
1502 const topics = (new URL(request.url).searchParams.get("topics") ?? "repo").split(",").filter((t) => /^[a-z]+(:[A-Za-z0-9_-]+)?$/.test(t)).slice(0, 10);
1503 const pair = new WebSocketPair();
1504 this.ctx.acceptWebSocket(pair[1], topics.length ? topics : ["repo"]);
1505 return new Response(null, { status: 101, webSocket: pair[0] });
1506 }
1507
1508 override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
1509 if (message === "ping") ws.send("pong");
1510 }
1511
1512 override async webSocketClose(ws: WebSocket, code: number): Promise<void> {
1513 try {
1514 ws.close(code, "bye");
1515 } catch {
1516 /* already closed */
1517 }
1518 }
1519
1520 broadcast(topic: string, data: unknown): void {
1521 const msg = JSON.stringify({ topic, data });
1522 for (const ws of this.ctx.getWebSockets(topic)) {
1523 try {
1524 ws.send(msg);
1525 } catch {
1526 /* client went away */
1527 }
1528 }
1529 }
1530}
1531
1532export function toInfo(sha: string, c: Commit): CommitInfo {
1533 return { sha, tree: c.tree, parents: c.parents, author: c.author, committer: c.committer, message: c.message, signed: !!c.gpgsig };
1534}
1535
1536export { fromUtf8 };