- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/server/src/project-object.ts?version=181&format=json
837 linesspeed 58% · codex-capacity-chair 42%Last change codex-capacity-chair in version 180, 6 versions changed it
You're reading version 181. The newest is 318, and 2 versions since then changed this file.
1// One project: its append-only log and blobs in the Durable Object's SQLite, the engine loaded from them, and the push
2// out to the project's Artifacts repo after each new version of shared. Ported from the platform's ProjectObject
3// (worker/src/index.ts), trimmed to the core path: no CI, merge queue checker, boxes, pipelines, members, visibility,
4// R2 copies, edge cache, probes or disk-first writer.
6import { DurableObject } from "cloudflare:workers";
7import { createHash } from "node:crypto";
8import { type Answer, answer, type Readers, readerAnswer } from "../../worker/project/http.ts";
9import type { ProjectCalls, ProjectHistory } from "../../worker/project/project-api.ts";
10import { ProjectError } from "../../worker/project/project-error.ts";
11import { BLOB_MAX, BlobStore } from "./blobs.ts";
12import { DiskFirstRuntime } from "./disk-first-runtime.ts";
13import { EngineProject, SqliteLog } from "./engine-project.ts";
14import { artifactsOf, type Env } from "./env.ts";
15import { GitDiskIntake } from "./git-disk-intake.ts";
16import { GitFileContents } from "./git-file-contents.ts";
17import { GitIntakeLimitError } from "./git-intake-limit.ts";
18import { GitIntakeTrees } from "./git-intake-trees.ts";
19import { pushedSince, remoteHead } from "./ingest.ts";
20import {
21 checkKey,
22 emptyKeyState,
23 expiresAt,
24 hmac,
25 issueKey,
26 type KeyRole,
27 type KeyState,
28 keyAllows,
29 listKeys,
30 revokeKey,
31} from "./keys.ts";
32import { type PushResult, pushShared, repoName } from "./push.ts";
33import { pushSnapshot } from "./push-snapshot.ts";
34import { SqliteWriterState } from "./writer-host.ts";
36const READ_OPS = new Set([
37 "status",
38 "blame",
39 "why",
40 "tree",
41 "path",
42 "follow",
43 "collisions",
44 "draft-state",
45 "refusals",
46 "labels",
47 "log",
48 "show",
49 "file",
50 "files",
51 "compare",
52 "where",
53 "feed",
54 "drafts",
55 "diff",
56 "ribbon",
57 "position",
58 "changes",
59 "notes",
60]);
62/** At most one push out a minute: each one clones the repo, so publishes in a burst share one. */
63export const PUSH_EVERY_MS = 60_000;
64/** While agents are working, how often a call looks for plain-git pushes to the repo. */
65const GIT_CHECK_MS = 15_000;
66// Disk scratch admission limits, independent of the Worker's resident memory.
67const GIT_PACK_MAX_BYTES = 128 * 1024 * 1024;
68const GIT_OBJECT_MAX_BYTES = 64 * 1024 * 1024;
69const GIT_DECODED_MAX_BYTES = 256 * 1024 * 1024;
70const GIT_LIMIT_POLICY = `expanded-v2:${GIT_PACK_MAX_BYTES}:${GIT_OBJECT_MAX_BYTES}:${GIT_DECODED_MAX_BYTES}`;
72/**
73 * The load guard (platform issue 46): an estimate of a loaded project's memory from its log entries, lines and claim
74 * keys, all read from SQLite without loading. A Durable Object has 128 MB. Past the hard cap a project refuses to
75 * load (export still reads it); past the soft cap, new work is held so the hard cap is never reached.
76 */
77const LOAD_BYTES_PER_ENTRY = 1_200;
78const LOAD_BYTES_PER_LINE = 20;
79const LOAD_BYTES_PER_KEY = 20;
80const LOAD_BASE_BYTES = 10_000_000;
81const LOAD_MAX_BYTES = 114_000_000;
82const LOAD_SOFT_BYTES = 94_800_000;
83/** Before its lines are counted, a log over this many characters refuses to load. */
84const LOG_LOAD_MAX_CHARS = 12_000_000;
85/** The ops the soft cap holds: the ones that bring new work into the history. */
86const SOFT_HELD_OPS: ReadonlySet<string> = new Set(["record", "edit", "publish", "land", "amend", "pluck", "drop"]);
88export function loadEstimate(entries: number, lines: number, keys: number): number {
89 return entries * LOAD_BYTES_PER_ENTRY + lines * LOAD_BYTES_PER_LINE + keys * LOAD_BYTES_PER_KEY + LOAD_BASE_BYTES;
90}
92/** A presented agent key, checked inside the call so the check and the call are one trip. */
93export interface KeyForCall {
94 presented: string;
95 address: string;
96 write: boolean;
97 route: string | undefined;
98}
100/** A news item from the issues code: delivered as an announcement from its writer. */
101export interface IssueNews {
102 from: string;
103 issue: number | null;
104 text: string;
105 to?: string[];
106}
108/** What the issues Durable Object hears when a start note naming an issue begins and ends. Each is optional. */
109interface IssueHooks {
110 claim?(agent: string, issue: number, change: number): Promise<unknown>;
111 unclaim?(agent: string, issue: number): Promise<unknown>;
112 done?(agent: string, issue: number, version: number): Promise<unknown>;
113}
115export class ProjectObject extends DurableObject<Env> {
116 private blobs: BlobStore;
117 private loaded: ProjectCalls | undefined;
118 /** Why the log didn't load, if it didn't. */
119 private loadError: unknown;
120 private tried = false;
121 private authorityRevision = 0;
122 /** Feed long-polls waiting for the log to grow; woken after every call that wrote. */
123 private waiting: (() => void)[] = [];
124 /** When this object last asked the repo for pushes made with plain git. */
125 private gitCheckedAt = 0;
126 private gitSyncing: Promise<{ head: string; commits: number; answer: unknown } | null> | undefined;
128 constructor(ctx: DurableObjectState, env: Env) {
129 super(ctx, env);
130 this.blobs = new BlobStore(ctx.storage);
131 if (env.ABSO_DISK_FIRST === "on") {
132 GitDiskIntake.recover(ctx.storage);
133 GitFileContents.recover(ctx.storage);
134 GitIntakeTrees.recover(ctx.storage);
135 }
136 }
138 /** Where files kept whole go: the project's blob store. */
139 private wholeFiles() {
140 return { keep: (text: string) => this.blobs.putText(text), read: (sha: string) => this.blobs.textOf(sha) };
141 }
143 private diskRuntime(): DiskFirstRuntime | undefined {
144 return this.env.ABSO_DISK_FIRST === "on"
145 ? new DiskFirstRuntime(this.ctx.storage, this.ctx.id.toString(), "server-disk-v1", {
146 hasBlob: (sha) => this.blobs.has(sha),
147 whole: this.wholeFiles(),
148 })
149 : undefined;
150 }
151 private async prepareDisk(validate: () => void = () => {}) {
152 const runtime = this.diskRuntime();
153 if (!runtime) return undefined;
154 const progress = runtime.preparePage(validate);
155 if (!progress.ready && progress.phase !== "empty") await this.soon(Date.now() + 100);
156 return progress;
157 }
158 /** Once indexing starts, legacy writes would invalidate the persistent root. */
159 private legacyWritesHeld(): boolean {
160 if (this.env.ABSO_DISK_FIRST === "on") return false;
161 const tables = this.ctx.storage.sql
162 .exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'writer_state'")
163 .toArray();
164 return (
165 tables.length > 0 &&
166 new SqliteWriterState(this.ctx.storage, "server-disk-v1").read("runtime", "format") !== undefined
167 );
168 }
169 private useProject<T>(operation: (calls: EngineProject) => T, write = false): T {
170 const runtime = this.diskRuntime();
171 if (runtime) return write ? runtime.write(operation, () => {}) : runtime.read(operation, () => {});
172 if (write && this.legacyWritesHeld())
173 throw Error("disk-first indexes exist; enable ABSO_DISK_FIRST before writing");
174 return operation(this.project as EngineProject);
175 }
176 private async diskCall(
177 name: string,
178 op: string,
179 agent: string | undefined,
180 body: unknown,
181 how: string | undefined,
182 revision: number,
183 request?: { id: string; principal: string },
184 ): Promise<Answer> {
185 const runtime = this.diskRuntime()!;
186 const validate = () => {
187 if (revision !== this.authorityRevision)
188 throw Object.assign(Error("project authorization changed during call setup"), { code: "authority-changed" });
189 };
190 const progress = await this.prepareDisk(validate);
191 const legacyReaders = (await this.ctx.storage.get<string[]>("readers")) ?? [];
192 const storedReaders = progress?.ready
193 ? (new SqliteWriterState(this.ctx.storage, "server-disk-v1").read("runtime", "readers") as string[] | undefined)
194 : undefined;
195 const known = new Set(storedReaders ?? legacyReaders);
196 validate();
197 let readersChanged = false;
198 const readers: Readers = {
199 has: (a) => known.has(a),
200 list: () => [...known].sort(),
201 set: (a, on) => {
202 if (on === known.has(a)) return;
203 if (on) known.add(a);
204 else known.delete(a);
205 readersChanged = true;
206 },
207 };
208 if (progress?.phase === "empty" && op !== "init")
209 return { status: 404, body: { error: "no such project; run init first" } };
210 if (!progress?.ready && !(progress?.phase === "empty" && op === "init"))
211 return { status: 503, body: { error: "project indexes are being prepared", retryAfter: 1, progress } };
212 if (agent && op !== "reader") {
213 const refused = readerAnswer({ status: () => undefined }, op, agent, body, readers);
214 if (refused) return refused;
215 }
216 const before = new SqliteLog(this.ctx.storage).seq();
217 const action = (calls: EngineProject) => {
218 const result = answer(calls, op, agent, body, readers, how);
219 if (result.status >= 500) throw Error(`project operation failed: ${JSON.stringify(result.body)}`);
220 if (readersChanged)
221 new SqliteWriterState(this.ctx.storage, "server-disk-v1").write("runtime", "readers", readers.list());
222 return result;
223 };
225 const receipt = request
226 ? {
227 id: `http:${createHash("sha256").update(request.principal).digest("hex")}:${request.id}`,
228 identity: {
229 project: name,
230 principal: request.principal,
231 agent: agent ?? null,
232 operation: op,
233 body: body ?? null,
234 how: how ?? null,
235 },
236 }
237 : undefined;
238 const result =
239 progress.phase === "empty"
240 ? runtime.initialize(action, validate, receipt)
241 : READ_OPS.has(op) || op.startsWith("change/")
242 ? runtime.read(action, validate)
243 : runtime.write(action, validate, receipt);
245 if (readersChanged) {
246 this.authorityRevision++;
247 }
248 const log = new SqliteLog(this.ctx.storage);
249 if (log.seq() !== before || (request && !READ_OPS.has(op))) {
250 this.wake();
251 await this.ctx.storage.put("name", name);
252 await this.soon(Date.now() + 100);
253 }
254 if (
255 result.status === 200 &&
256 artifactsOf(this.env) &&
257 Date.now() - this.gitCheckedAt > GIT_CHECK_MS &&
258 (await this.ctx.storage.get("name")) !== undefined &&
259 (await this.ctx.storage.getAlarm()) === null
260 )
261 await this.ctx.storage.setAlarm(Date.now());
262 if (result.status === 200 && op === "starting") result.body = await this.startingHooks(name, result.body);
263 if (result.status === 200) result.body = this.withBlobSizes(op, result.body);
264 return result;
265 }
267 /** The project, loaded from its log on first use. A log too big for memory is refused, not loaded. */
268 private ensure(): ProjectCalls | undefined {
269 if (this.diskRuntime()) throw Error("legacy project load forbidden in disk-first mode");
270 if (this.loaded || this.tried) return this.loaded;
271 this.tried = true;
272 try {
273 const why = this.tooBigToLoad();
274 if (why) throw new Error(`${why}, too big to load in a Durable Object's memory; GET export still reads it`);
275 this.loaded = EngineProject.open(this.ctx.storage, (sha) => this.blobs.has(sha), this.wholeFiles());
276 } catch (e) {
277 this.loadError = e;
278 }
279 return this.loaded;
280 }
282 private get project(): ProjectCalls {
283 const p = this.ensure();
284 if (!p) throw this.loadError;
285 return p;
286 }
288 private logChars(): { chars: number; entries: number } {
289 const tables = this.ctx.storage.sql
290 .exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'log'")
291 .toArray();
292 return tables.length === 0 ? { chars: 0, entries: 0 } : new SqliteLog(this.ctx.storage).logSize();
293 }
295 private sizes(): { lines: number; keys: number } | undefined {
296 if (this.logChars().entries === 0) return undefined;
297 try {
298 return new SqliteLog(this.ctx.storage).countSizes();
299 } catch {
300 return undefined;
301 }
302 }
304 /** Why recording new work is held: the estimate is past the soft cap; else null. */
305 private softHeld(): string | null {
306 const counted = this.sizes();
307 if (counted === undefined) return null;
308 const bytes = loadEstimate(this.logChars().entries, counted.lines, counted.keys);
309 return bytes > LOAD_SOFT_BYTES
310 ? `this project is near the most a project can hold (an estimated ${(bytes / 1e6).toFixed(0)} MB of ${LOAD_MAX_BYTES / 1e6} MB), so recording and publishing are held; status and reads keep working`
311 : null;
312 }
314 /** Why this project mustn't load: its estimated memory, or before its lines are counted, its log's size; else null. */
315 private tooBigToLoad(): string | null {
316 const counted = this.sizes();
317 if (counted !== undefined) {
318 const bytes = loadEstimate(this.logChars().entries, counted.lines, counted.keys);
319 return bytes > LOAD_MAX_BYTES
320 ? `this project holds ${counted.lines} lines and ${this.logChars().entries} entries, an estimated ${(bytes / 1e6).toFixed(0)} MB once loaded`
321 : null;
322 }
323 const { chars } = this.logChars();
324 return chars > LOG_LOAD_MAX_CHARS ? `this project's log is ${(chars / 1e6).toFixed(1)} MB` : null;
325 }
327 // Blobs: binary files' bytes, named by their SHA-256.
329 async putBlob(sha: string, body: ReadableStream<Uint8Array>): Promise<Answer> {
330 const a = await this.blobs.put(sha, body);
331 // A push out waiting on missing blobs goes again now.
332 if (a.status === 200 && (await this.ctx.storage.get("pushError"))) await this.ctx.storage.setAlarm(Date.now());
333 return a;
334 }
336 async getBlob(sha: string): Promise<ReadableStream<Uint8Array> | null> {
337 return this.blobs.stream(sha);
338 }
340 /** Shared's newest version, from storage alone, never loading the project. Null when there's no project. */
341 async head(): Promise<{ version: number; at: string } | null> {
342 if (this.logChars().entries === 0) return null;
343 return { version: new SqliteLog(this.ctx.storage).sharedVersion(), at: new Date().toISOString() };
344 }
346 /** Backups: one page of the log as JSON lines. It works even when the log won't load. */
347 async exportLog(from: number, limit: number): Promise<{ lines: string; next: number | null } | null> {
348 if (this.logChars().entries === 0) return null;
349 const { texts, next } = new SqliteLog(this.ctx.storage).page(from, limit);
350 return { lines: texts.map((t) => `${t}\n`).join(""), next };
351 }
353 private wake(): void {
354 const all = this.waiting;
355 this.waiting = [];
356 for (const w of all) w();
357 }
359 /**
360 * GET feed?from=&wait=<seconds, up to 25>: when nothing is new, hold the call until an entry is written or the wait
361 * ends, then answer as usual.
362 */
363 private async feed(name: string, body: unknown): Promise<Answer> {
364 const q = (body ?? {}) as Record<string, string | undefined>;
365 const wait = Math.min(25, Math.max(0, Number(q.wait) || 0));
366 const first = await this.call(name, "feed", undefined, body, true);
367 const from = Number(q.from) || 0;
368 const empty = first.status === 200 && (first.body as { next: number }).next <= from;
369 if (!empty || wait === 0) return first;
370 await new Promise<void>((resolve) => {
371 const timer = setTimeout(resolve, wait * 1000);
372 this.waiting.push(() => {
373 clearTimeout(timer);
374 resolve();
375 });
376 });
377 return this.call(name, "feed", undefined, body, true);
378 }
380 /** One project call: the agent key (if any), the size caps, then answer() from worker/project/http.ts. */
381 async call(
382 name: string,
383 op: string,
384 agent: string | undefined,
385 body: unknown,
386 inFeed = false,
387 how?: string,
388 key?: KeyForCall,
389 requestId?: string,
390 ): Promise<Answer> {
391 const revision = this.authorityRevision;
392 let principal = "shared-token";
393 if (
394 requestId !== undefined &&
395 !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(requestId)
396 )
397 return { status: 400, body: { error: "Idempotency-Key must be a UUID" } };
398 if (key) {
399 const decided = await this.checkAgentKey(key.presented, agent, key.address);
400 if (!decided.ok) return { status: decided.status, body: { error: decided.error } };
401 const allowed = keyAllows(decided.role, { write: key.write, agent, route: key.route });
402 if (!allowed.ok) return { status: allowed.status, body: { error: allowed.error } };
403 how = decided.as;
404 principal = `key:${decided.id}`;
405 }
406 if (op === "feed" && !inFeed) return this.feed(name, body);
407 if (this.diskRuntime()) {
408 try {
409 return await this.diskCall(
410 name,
411 op,
412 agent,
413 body,
414 how,
415 revision,
416 requestId ? { id: requestId, principal } : undefined,
417 );
418 } catch (error) {
419 if ((error as { code?: string })?.code === "request-reused")
420 return { status: 409, body: { error: "Idempotency-Key was reused for a different request" } };
421 if ((error as { code?: string })?.code === "authority-changed")
422 return { status: 409, body: { error: "project authorization changed; retry the request", retryable: true } };
423 throw error;
424 }
425 }
426 if (this.legacyWritesHeld() && !READ_OPS.has(op) && !op.startsWith("change/"))
427 return { status: 409, body: { error: "disk-first indexes exist; enable ABSO_DISK_FIRST before writing" } };
428 if (SOFT_HELD_OPS.has(op)) {
429 const held = this.softHeld();
430 if (held) return { status: 507, body: { error: held } };
431 }
432 const loaded = this.ensure();
433 if (!loaded) {
434 const why = this.loadError instanceof Error ? this.loadError.message : String(this.loadError);
435 return { status: 507, body: { error: `the project's log did not load: ${why}` } };
436 }
437 // Readers live in storage, not the log: a refused call writes nothing, so replay never needs them.
438 const list = new Set((await this.ctx.storage.get<string[]>("readers")) ?? []);
439 let changed = false;
440 const readers: Readers = {
441 has: (a) => list.has(a),
442 set: (a, on) => {
443 if (on === list.has(a)) return;
444 if (on) list.add(a);
445 else list.delete(a);
446 changed = true;
447 },
448 list: () => [...list].sort(),
449 };
450 const before = loaded.exists() ? loaded.shared().version : -1;
451 const logLength = () => (this.loaded as { logLength?: () => number } | undefined)?.logLength?.() ?? 0;
452 const entriesBefore = logLength();
453 const a = answer(loaded, op, agent, body, readers, how);
454 if (changed) await this.ctx.storage.put("readers", readers.list());
455 if (logLength() !== entriesBefore) this.wake();
456 if (a.status === 200 && op === "starting") a.body = await this.startingHooks(name, a.body);
457 if (a.status === 200) a.body = this.withBlobSizes(op, a.body);
458 const after = loaded.exists() ? loaded.shared().version : -1;
459 if (a.status === 200 && after >= 0 && (op === "init" || after > before)) {
460 // A new version of shared: push it out to Artifacts in the background. The alarm retries; the call never waits.
461 await this.ctx.storage.put("name", name);
462 if (artifactsOf(this.env)) await this.ctx.storage.setAlarm(Date.now());
463 } else if (
464 a.status === 200 &&
465 artifactsOf(this.env) &&
466 Date.now() - this.gitCheckedAt > GIT_CHECK_MS &&
467 (await this.ctx.storage.get("name")) !== undefined &&
468 (await this.ctx.storage.getAlarm()) === null
469 ) {
470 // While agents are working, the alarm also looks for plain-git pushes.
471 await this.ctx.storage.setAlarm(Date.now());
472 }
473 return a;
474 }
476 /**
477 * The engine's starting answer carries hooks for the issues code (a start note naming an issue began or ended). They
478 * go to the project's IssueProject, and never to the client. A failed hook is logged and never fails the call.
479 */
480 private async startingHooks(name: string, body: unknown): Promise<unknown> {
481 const { hooks, ...rest } = body as {
482 hooks?: {
483 claim?: { issue: number; agent: string; change: number };
484 unclaim?: { issue: number; agent: string; change: number; done?: boolean; version?: number };
485 };
486 };
487 if (!hooks) return body;
488 const issues = this.env.ISSUES_DO.get(this.env.ISSUES_DO.idFromName(name)) as unknown as IssueHooks;
489 const tell = async (what: string, call: () => Promise<unknown> | undefined) => {
490 try {
491 await call();
492 } catch (e) {
493 console.log(JSON.stringify({ event: "issues-hook", what, project: name, error: String(e).slice(0, 200) }));
494 }
495 };
496 const end = hooks.unclaim;
497 if (end?.done && end.version !== undefined) {
498 const version = end.version;
499 await tell("done", () => issues.done?.(end.agent, end.issue, version));
500 } else if (end) await tell("unclaim", () => issues.unclaim?.(end.agent, end.issue));
501 const claim = hooks.claim;
502 if (claim) await tell("claim", () => issues.claim?.(claim.agent, claim.issue, claim.change));
503 return rest;
504 }
506 /** A folder's binary files count by their bytes, and a binary file says its size: the blob store knows both. */
507 private withBlobSizes(op: string, body: unknown): unknown {
508 if (op === "tree" && Array.isArray((body as { entries?: unknown }).entries)) {
509 const b = body as { entries: { bytes?: number; blobs?: string[] }[] };
510 return {
511 ...b,
512 entries: b.entries.map(({ blobs, ...e }) =>
513 blobs ? { ...e, bytes: (e.bytes ?? 0) + blobs.reduce((n, sha) => n + this.blobs.size(sha), 0) } : e,
514 ),
515 };
516 }
517 if (op === "file" && typeof (body as { blob?: unknown }).blob === "string")
518 return { ...(body as object), size: this.blobs.size((body as { blob: string }).blob) };
519 return body;
520 }
522 // The push out to Artifacts, and plain-git pushes back in.
524 /**
525 * Takes in commits pushed to the project's repo with plain git: the ones above the server's last commit that
526 * haven't been taken in yet. One run at a time; a call while a run is going gets that run's answer.
527 */
528 gitSync(): Promise<{ head: string; commits: number; answer: unknown } | null> {
529 this.gitSyncing ??= this.gitSyncOnce().finally(() => {
530 this.gitSyncing = undefined;
531 });
532 return this.gitSyncing;
533 }
535 private async gitSyncOnce(): Promise<{ head: string; commits: number; answer: unknown } | null> {
536 if (this.legacyWritesHeld()) return null;
537 const artifacts = artifactsOf(this.env);
538 if (!artifacts) return null;
539 this.gitCheckedAt = Date.now();
540 const name = await this.ctx.storage.get<string>("name");
541 if (!name) return null;
542 const progress = await this.prepareDisk();
543 if (progress && !progress.ready) return null;
544 if (!this.useProject((p) => p.exists())) return null;
545 const seen = await this.ctx.storage.get<string>("git:head");
546 const pushed = await this.ctx.storage.get<PushResult>("pushed");
547 const head = await remoteHead(artifacts, name);
548 const refusal = this.diskRuntime()
549 ? await this.ctx.storage.get<{ head: string; policy: string; kind: GitIntakeLimitError["kind"]; error: string }>(
550 "git:size-refusal",
551 )
552 : undefined;
553 if (refusal) {
554 if (
555 head &&
556 head !== seen &&
557 head !== pushed?.commit &&
558 refusal.head === head &&
559 refusal.policy === GIT_LIMIT_POLICY
560 )
561 throw new GitIntakeLimitError(refusal.kind, refusal.error);
562 await this.ctx.storage.delete("git:size-refusal");
563 }
564 if (!head || head === seen || head === pushed?.commit) return null;
565 const sharedBlobs = this.useProject((p) => p.shared().blobs ?? {});
566 using trees = this.diskRuntime() ? new GitIntakeTrees(this.ctx.storage) : undefined;
567 const found = await pushedSince(
568 artifacts,
569 name,
570 seen,
571 async (bytes) => (bytes.byteLength > BLOB_MAX ? null : this.blobs.putBytes(bytes)),
572 (path) => sharedBlobs[path],
573 trees ? (files, path, body, oid) => trees.retainFile(files, path, body, oid) : undefined,
574 trees
575 ? {
576 storage: this.ctx.storage,
577 maxPackBytes: GIT_PACK_MAX_BYTES,
578 maxObjectBytes: GIT_OBJECT_MAX_BYTES,
579 maxDecodedBytes: GIT_DECODED_MAX_BYTES,
580 retainFileChunks: (files, path, chunks, oid) => trees.retainChunks(files, path, chunks, oid),
581 }
582 : undefined,
583 ).catch(async (error: unknown) => {
584 if (trees && error instanceof GitIntakeLimitError) {
585 const refusal = {
586 head,
587 policy: GIT_LIMIT_POLICY,
588 kind: error.kind,
589 error: error.message,
590 at: new Date().toISOString(),
591 };
592 await this.ctx.storage.put({ "git:size-refusal": refusal, "git:error": refusal });
593 }
594 throw error;
595 });
596 if (!found || found.commits.length === 0) {
597 if (found) await this.ctx.storage.put("git:head", found.head);
598 return null;
599 }
600 // Unexpected failures leave the cursor unacknowledged for retry. Engine
601 // refusals are recorded and acknowledged so a later fixing commit can advance.
602 const ingest = (p: EngineProject) =>
603 p.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now());
604 const runtime = this.diskRuntime();
605 let result: unknown;
606 try {
607 result = runtime
608 ? runtime.write(ingest, () => {}, {
609 id: `git:${found.head}`,
610 identity: {
611 project: name,
612 head: found.head,
613 base: found.base,
614 commits: found.commits.map((commit) => commit.sha),
615 },
616 })
617 : this.useProject(ingest, true);
618 } catch (error) {
619 if (!(error instanceof ProjectError)) throw error;
620 result = { error: error.message };
621 }
622 const taken = {
623 at: new Date().toISOString(),
624 head: found.head,
625 commits: found.commits.length,
626 answer: result,
627 ...(found.tooBig.length ? { tooBig: found.tooBig } : {}),
628 };
629 await this.ctx.storage.put({ "git:head": found.head, "git:last": taken });
630 this.wake();
631 if ((result as { landed?: boolean }).landed) await this.ctx.storage.setAlarm(Date.now());
632 return taken;
633 }
635 /** Sets the alarm for `at` unless one is due sooner. */
636 private async soon(at: number): Promise<void> {
637 const now = await this.ctx.storage.getAlarm();
638 if (now === null || now > at) await this.ctx.storage.setAlarm(at);
639 }
641 /**
642 * Plain-git pushes in first, so the push out builds on them; then shared out to the project's Artifacts repo, at
643 * most once a minute, backing off on failure. Without an ARTIFACTS binding (local dev) it does nothing.
644 */
645 async alarm(): Promise<void> {
646 if (!this.diskRuntime() && !artifactsOf(this.env)) return;
647 if (!this.diskRuntime() && !this.ensure()) return;
648 const progress = await this.prepareDisk();
649 if (progress && !progress.ready) return;
650 const artifacts = artifactsOf(this.env);
651 if (!artifacts) return;
652 const name = await this.ctx.storage.get<string>("name");
653 if (!name || !this.useProject((p) => p.exists())) return;
654 let intakeFailed = false;
655 await this.gitSync().then(
656 async () => {
657 await this.ctx.storage.delete("git:error");
658 await this.ctx.storage.delete("git:retry-attempts");
659 },
660 async (e) => {
661 intakeFailed = true;
662 const attempts = ((await this.ctx.storage.get<number>("git:retry-attempts")) ?? 0) + 1;
663 await this.ctx.storage.put("git:retry-attempts", attempts);
664 await this.ctx.storage.put("git:error", {
665 at: new Date().toISOString(),
666 error: e instanceof Error ? e.message : String(e),
667 });
668 await this.soon(Date.now() + (attempts === 1 ? 1 : attempts === 2 ? 5 : 15) * 60_000);
669 },
670 );
671 // Never export over a remote head whose changes could not be taken in.
672 if (intakeFailed) return;
673 const shared = pushSnapshot(
674 this.useProject((p) => p.sharedPushMetadata()),
675 (version, path) => this.useProject((current) => current.fileTextAt(version, path)),
676 (version, paths) => this.useProject((current) => current.fileTextsAt(version, paths)),
677 );
678 const done = await this.ctx.storage.get<PushResult>("pushed");
679 if (done && done.version >= shared.version) return;
680 const pushedAt = (await this.ctx.storage.get<number>("pushedAt")) ?? 0;
681 if (Date.now() - pushedAt < PUSH_EVERY_MS) {
682 await this.soon(pushedAt + PUSH_EVERY_MS);
683 return;
684 }
685 let result: PushResult;
686 try {
687 result = await pushShared(
688 artifacts,
689 name,
690 shared,
691 (sha) => this.blobs.read(sha),
692 this.env.ABSO_DISK_FIRST === "on"
693 ? {
694 storage: this.ctx.storage,
695 maxPackBytes: GIT_PACK_MAX_BYTES,
696 maxObjectBytes: GIT_OBJECT_MAX_BYTES,
697 maxDecodedBytes: GIT_DECODED_MAX_BYTES,
698 }
699 : undefined,
700 );
701 } catch (e) {
702 // Kept for /out, and tried again with a backoff of our own (a thrown alarm is retried only six times).
703 const was = await this.ctx.storage.get<{ attempts?: number }>("pushError");
704 const attempts = (was?.attempts ?? 0) + 1;
705 await this.ctx.storage.put("pushError", {
706 version: shared.version,
707 at: new Date().toISOString(),
708 attempts,
709 error: e instanceof Error ? e.message : String(e),
710 });
711 await this.soon(Date.now() + Math.min(10 * 60_000, 15_000 * 2 ** Math.min(attempts - 1, 6)));
712 return;
713 }
714 await this.ctx.storage.put({ pushed: result, "git:head": result.commit, pushedAt: Date.now() });
715 await this.ctx.storage.delete("pushError");
716 // Another publish may have landed while this push ran.
717 if (this.useProject((p) => p.shared().version) > result.version) await this.soon(Date.now() + PUSH_EVERY_MS);
718 }
720 /** The push out: the repo, the last version pushed, and plain-git intake. */
721 async out() {
722 const name = await this.ctx.storage.get<string>("name");
723 return {
724 repo: name ? repoName(name) : null,
725 artifacts: artifactsOf(this.env) ? "bound" : "unbound",
726 version: this.logChars().entries ? new SqliteLog(this.ctx.storage).sharedVersion() : null,
727 pushed: (await this.ctx.storage.get<PushResult>("pushed")) ?? null,
728 error: (await this.ctx.storage.get("pushError")) ?? null,
729 git: {
730 head: (await this.ctx.storage.get<string>("git:head")) ?? null,
731 last: (await this.ctx.storage.get("git:last")) ?? null,
732 error: (await this.ctx.storage.get("git:error")) ?? null,
733 },
734 };
735 }
737 // Per-agent keys: the HMACs live here, one project's keys per object.
739 private async keyState(): Promise<KeyState> {
740 return (await this.ctx.storage.get<KeyState>("agent-keys")) ?? emptyKeyState();
741 }
743 async checkAgentKey(presented: string, agent: string | undefined, address: string) {
744 const state = await this.keyState();
745 const decided = await checkKey(state, this.env.KEY_HMAC_SECRET, presented, agent, Date.now(), address);
746 if (decided.dirty) await this.ctx.storage.put("agent-keys", state);
747 if (!decided.ok) return decided;
748 const row = state.rows.find((r) => r.id === decided.id);
749 return { ...decided, agent: row?.agent ?? "" };
750 }
752 /** Issues a key. The returned key is the only copy. */
753 async issueAgentKey(
754 agent: string,
755 address: string,
756 expiresRaw: string | null,
757 role: KeyRole,
758 ): Promise<{ id: string; key: string; agent: string } | { error: string }> {
759 const secret = this.env.KEY_HMAC_SECRET;
760 if (!secret) return { error: "the key secret (KEY_HMAC_SECRET) is not set" };
761 const when = expiresAt(Date.now(), expiresRaw);
762 if (typeof when !== "number") return { error: when.error };
763 const state = await this.keyState();
764 const issued = await issueKey(state, secret, agent, "admin", Date.now(), address, when, role);
765 this.authorityRevision++;
766 await this.ctx.storage.put("agent-keys", state);
767 return issued;
768 }
770 async revokeAgentKey(id: string, address: string): Promise<{ revoked: boolean }> {
771 const secret = this.env.KEY_HMAC_SECRET;
772 if (!secret) return { revoked: false };
773 const state = await this.keyState();
774 const revoked = revokeKey(state, id, Date.now(), await hmac(secret, address));
775 this.authorityRevision++;
776 await this.ctx.storage.put("agent-keys", state);
777 return { revoked };
778 }
780 async listAgentKeys(agent?: string) {
781 return listKeys(await this.keyState(), agent);
782 }
784 // For the issues code (server/src/issues/).
786 /** The project's agent names, for the ask seat check. None when there's no project. */
787 async agents(_project: string): Promise<string[]> {
788 if (!this.diskRuntime() && !this.ensure()) return [];
789 const progress = await this.prepareDisk();
790 if (progress?.phase === "empty") return [];
791 if (progress && !progress.ready) throw Error("project indexes are being prepared");
792 return this.useProject((p) => (p.exists() ? p.status().agents.map((a) => a.agent) : []));
793 }
795 /**
796 * Issues news, delivered through the engine's announce path: each item goes to the agents whose start note names
797 * its issue and to the known agents in `to`, never back to its writer.
798 */
799 async news(_project: string, items: IssueNews[]): Promise<{ to: string[] }[]> {
800 if (!this.diskRuntime() && !this.ensure()) return items.map(() => ({ to: [] }));
801 const progress = await this.prepareDisk();
802 if (progress?.phase === "empty") return items.map(() => ({ to: [] }));
803 if (progress && !progress.ready) throw Error("project indexes are being prepared");
804 return this.useProject((p) => {
805 if (!p.exists()) return items.map(() => ({ to: [] }));
806 const engine = p as ProjectCalls & ProjectHistory;
807 const out: { to: string[] }[] = [];
808 for (const item of items) {
809 const status = p.status() as { agents: { agent: string; starting?: { issue?: number } }[] };
810 const known = new Set(status.agents.map((a) => a.agent));
811 const to = new Set([
812 ...(item.issue !== null
813 ? status.agents.filter((a) => a.starting?.issue === item.issue).map((a) => a.agent)
814 : []),
815 ...(item.to ?? []).filter((t) => known.has(t)),
816 ]);
817 to.delete(item.from);
818 if (to.size === 0) {
819 out.push({ to: [] });
820 continue;
821 }
822 try {
823 engine.announce(item.from, item.text, [...to]);
824 out.push({ to: [...to] });
825 } catch (e) {
826 // Persistent writer state may already have changed. Let the outer
827 // transaction undo the whole batch before reporting a failure.
828 if (this.env.ABSO_DISK_FIRST === "on") throw e;
829 console.log(JSON.stringify({ event: "issues-news", error: String(e).slice(0, 200) }));
830 out.push({ to: [] });
831 }
832 }
833 this.wake();
834 return out;
835 }, true);
836 }
837}