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

Versions 32 to 318

Compare

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