Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
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=178&format=json
781 linesspeed 63% · codex-capacity-chair 37%Last change codex-capacity-chair in version 178, 5 versions changed it

You're reading version 178. The newest is 318, and 3 versions since then changed this file. Go to the newestCompare with 318

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