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
show on this site's /mcp
CLI
abso show 150 --json
JSON
/christopher/abso-core/versions/150?format=json

Open server: the project Worker, Durable Object and Artifacts (issue 17)

of shared·speed··Not checked

Version 149 · Files at version 150

25 files, 3455 lines added, 4 removed.

--- a/.absoignore
+++ b/.absoignore
@@ -6,7 +6,9 @@
66# Each session's own Claude Code state
77.claude/
88
9−# Local config and secrets
9+# Local config and secrets (the open server's server/.dev.vars and server/.wrangler/ are named too)
10+server/.dev.vars
11+server/.wrangler/
1012.env
1113.env.*
1214.dev.vars*
--- a/biome.json
+++ b/biome.json
@@ -6,6 +6,7 @@
66 "src/**",
77 "worker/project/**",
88 "scripts/**",
9+ "server/**",
910 "*.json",
1011 "!**/node_modules",
1112 "!**/.abso",
Binary file package-lock.json changed: b10521cd9bad -> 2e1381de46c1
--- a/package.json
+++ b/package.json
@@ -9,15 +9,17 @@
99 "node": ">=24"
1010 },
1111 "scripts": {
12− "test": "node --import ./client/test/setup.ts --test \"src/**/*.test.ts\" \"worker/project/**/*.test.ts\" \"client/test/**/*.test.ts\" \"scripts/**/*.test.ts\"",
12+ "test": "node --import ./client/test/setup.ts --test \"src/**/*.test.ts\" \"worker/project/**/*.test.ts\" \"client/test/**/*.test.ts\" \"scripts/**/*.test.ts\" \"server/test/**/*.test.ts\"",
1313 "typecheck": "tsc --noEmit -p tsconfig.json",
14− "check": "npm run typecheck && npm test",
14+ "check": "npm run typecheck && npm run typecheck:server && npm test",
1515 "check:changed": "node scripts/check-changed.mjs",
1616 "format": "biome check --write .",
17− "lint": "biome ci ."
17+ "lint": "biome ci .",
18+ "typecheck:server": "tsc --noEmit -p server/tsconfig.json"
1819 },
1920 "devDependencies": {
2021 "@biomejs/biome": "2.5.15",
22+ "@cloudflare/workers-types": "^5.20261013.1",
2123 "@types/node": "^24.19.1",
2224 "typescript": "^5.9.3"
2325 },
Binary file server/package-lock.json changed: none -> f5cebad6e233
--- /dev/null
+++ b/server/package.json
@@ -0,0 +1,22 @@
1+{
2+ "name": "abso-server",
3+ "version": "0.0.1",
4+ "private": true,
5+ "type": "module",
6+ "description": "abso's open server: one Worker with a Durable Object per project, on your own Cloudflare account.",
7+ "license": "MIT",
8+ "scripts": {
9+ "dev": "wrangler dev --local",
10+ "deploy": "wrangler deploy",
11+ "typecheck": "tsc --noEmit -p tsconfig.json"
12+ },
13+ "dependencies": {
14+ "isomorphic-git": "^1.43.0"
15+ },
16+ "devDependencies": {
17+ "@cloudflare/workers-types": "^5.20261001.1",
18+ "@types/node": "^24.19.1",
19+ "typescript": "^5.9.3",
20+ "wrangler": "^4.147.0"
21+ }
22+}
--- /dev/null
+++ b/server/src/blobs.ts
@@ -0,0 +1,237 @@
1+// Binary files' bytes (#27), content-addressed by SHA-256, kept in the
2+// project's own Durable Object SQLite: 1 MB rows, so a blob is never larger
3+// than a row allows, and hasBlob is a synchronous lookup the engine can call.
4+// Uploads stream in (a Durable Object RPC message stops at 32 MiB) and are
5+// hashed as they arrive; a blob whose bytes don't match its name isn't kept.
6+import { createHash } from "node:crypto";
7+import type { SqliteStorage } from "./engine-project.ts";
8+
9+/** Per file. The push out to Artifacts holds a tree in memory, and a Durable Object has 128 MB. */
10+export const BLOB_MAX = 20 * 1024 * 1024;
11+const PART = 1024 * 1024;
12+const SHA = /^[0-9a-f]{64}$/;
13+const SCHEMA =
14+ "CREATE TABLE blobs (sha TEXT NOT NULL, part INTEGER NOT NULL, data BLOB NOT NULL, PRIMARY KEY (sha, part))";
16+const normalizedSchema = (sql: string) => sql.replace(/\s+/g, " ").trim().toUpperCase();
18+export type PutBlob =
19+ | { status: 200; body: { sha256: string; size: number; stored: boolean } }
20+ | { status: 400 | 413; body: { error: string } };
22+export class BlobStore {
23+ private storage: SqliteStorage;
25+ constructor(storage: SqliteStorage) {
26+ this.storage = storage;
27+ }
29+ /** Reads must not create storage, including when a cold object has no blobs. */
30+ private hasSchema(): boolean {
31+ const rows = this.storage.sql.exec("SELECT type, sql FROM sqlite_master WHERE name = 'blobs'").toArray() as {
32+ type: string;
33+ sql: string | null;
34+ }[];
35+ if (rows.length === 0) return false;
36+ if (
37+ rows.length !== 1 ||
38+ rows[0]?.type !== "table" ||
39+ typeof rows[0].sql !== "string" ||
40+ normalizedSchema(rows[0].sql) !== normalizedSchema(SCHEMA)
41+ )
42+ throw new Error("unsupported blob storage schema");
43+ return true;
44+ }
46+ /** Only mutation paths may initialize the exact supported table. Never repair a mismatch. */
47+ private ensureSchema(): void {
48+ if (!this.hasSchema()) this.storage.sql.exec(SCHEMA);
49+ }
51+ /** Blobs in sha order after `after`, with their sizes (temporary uploads left out). */
52+ list(after: string, limit: number): { blobs: { sha: string; size: number }[]; next: string | null } {
53+ if (!this.hasSchema()) return { blobs: [], next: null };
54+ const rows = this.storage.sql
55+ .exec(
56+ "SELECT sha, SUM(LENGTH(data)) AS size FROM blobs WHERE sha > ? AND sha NOT LIKE 'tmp-%' GROUP BY sha ORDER BY sha LIMIT ?",
57+ after,
58+ limit + 1,
59+ )
60+ .toArray() as { sha: string; size: number }[];
61+ const more = rows.length > limit;
62+ const blobs = rows.slice(0, limit);
63+ return { blobs, next: more ? blobs.at(-1)!.sha : null };
64+ }
66+ has(sha: string): boolean {
67+ return (
68+ this.hasSchema() &&
69+ SHA.test(sha) &&
70+ this.storage.sql.exec("SELECT 1 FROM blobs WHERE sha = ? LIMIT 1", sha).toArray().length > 0
71+ );
72+ }
74+ /** Every byte, for the push out. Blobs are at most BLOB_MAX. */
75+ read(sha: string): Uint8Array | null {
76+ if (!this.hasSchema()) return null;
77+ const rows = this.storage.sql.exec("SELECT data FROM blobs WHERE sha = ? ORDER BY part", sha).toArray() as {
78+ data: ArrayBuffer;
79+ }[];
80+ if (rows.length === 0) return null;
81+ const out = new Uint8Array(rows.reduce((n, r) => n + r.data.byteLength, 0));
82+ let at = 0;
83+ for (const r of rows) {
84+ out.set(new Uint8Array(r.data), at);
85+ at += r.data.byteLength;
86+ }
87+ return out;
88+ }
90+ /** The bytes as a stream, one row at a time, or null. */
91+ stream(sha: string): ReadableStream<Uint8Array> | null {
92+ if (!this.has(sha)) return null;
93+ const parts = (
94+ this.storage.sql.exec("SELECT part FROM blobs WHERE sha = ? ORDER BY part", sha).toArray() as { part: number }[]
95+ ).map((r) => r.part);
96+ let i = 0;
97+ return new ReadableStream<Uint8Array>({
98+ pull: (c) => {
99+ if (i >= parts.length) return c.close();
100+ const [row] = this.storage.sql
101+ .exec("SELECT data FROM blobs WHERE sha = ? AND part = ?", sha, parts[i++]!)
102+ .toArray() as { data: ArrayBuffer }[];
103+ c.enqueue(new Uint8Array(row!.data));
104+ },
105+ });
106+ }
108+ /**
109+ * A whole file's text (#46), stored as UTF-8 under its SHA-256. Synchronous,
110+ * so the engine can call it while it records.
111+ */
112+ putText(text: string): string {
113+ const bytes = new TextEncoder().encode(text);
114+ const sha = createHash("sha256").update(bytes).digest("hex");
115+ if (!this.has(sha)) this.write(sha, bytes, 0);
116+ return sha;
117+ }
119+ /** A whole file's text back, or null. */
120+ textOf(sha: string): string | null {
121+ const bytes = this.read(sha);
122+ return bytes ? new TextDecoder().decode(bytes) : null;
123+ }
125+ /** Stores bytes already in memory (plain-git intake), under their own hash. */
126+ async putBytes(bytes: Uint8Array): Promise<string> {
127+ const sha = hex(await crypto.subtle.digest("SHA-256", bytes));
128+ if (!this.has(sha)) this.write(sha, bytes, 0);
129+ return sha;
130+ }
132+ /** Streams an upload in, checking its size and that its SHA-256 is `sha`. */
133+ /** `max` lowers BLOB_MAX for this put (a capped project's file cap, abso issue 249). */
134+ async put(sha: string, body: ReadableStream<Uint8Array>, max: number = BLOB_MAX): Promise<PutBlob> {
135+ if (!SHA.test(sha)) return { status: 400, body: { error: "a blob's name is its SHA-256 in lowercase hex" } };
136+ if (this.has(sha)) {
137+ await body.cancel().catch(() => {});
138+ return { status: 200, body: { sha256: sha, size: this.size(sha), stored: false } };
139+ }
140+ const temp = `tmp-${crypto.randomUUID()}`;
141+ const digest = new crypto.DigestStream("SHA-256");
142+ const hashing = digest.getWriter();
143+ let size = 0;
144+ let part = 0;
145+ let pending: Uint8Array[] = [];
146+ let pendingSize = 0;
147+ const flush = () => {
148+ if (pendingSize === 0) return;
149+ part = this.write(temp, concat(pending, pendingSize), part);
150+ pending = [];
151+ pendingSize = 0;
152+ };
153+ try {
154+ for await (const chunk of body) {
155+ size += chunk.byteLength;
156+ if (size > max) {
157+ this.drop(temp);
158+ return { status: 413, body: { error: `blobs are at most ${max / 1024 / 1024} MB` } };
159+ }
160+ await hashing.write(chunk);
161+ pending.push(chunk);
162+ pendingSize += chunk.byteLength;
163+ if (pendingSize >= PART) flush();
164+ }
165+ flush();
166+ if (part === 0) part = this.write(temp, new Uint8Array(), 0); // an empty file is a blob too
167+ await hashing.close();
168+ const got = hex(await digest.digest);
169+ if (got !== sha) {
170+ this.drop(temp);
171+ return { status: 400, body: { error: `the bytes hash to ${got}, not ${sha}` } };
172+ }
173+ // Another upload of the same bytes may have finished meanwhile.
174+ if (this.has(sha)) this.drop(temp);
175+ else {
176+ this.ensureSchema();
177+ this.storage.sql.exec("UPDATE blobs SET sha = ? WHERE sha = ?", sha, temp);
178+ }
179+ return { status: 200, body: { sha256: sha, size, stored: true } };
180+ } catch (e) {
181+ this.drop(temp);
182+ throw e;
183+ }
184+ }
186+ /** Every blob's bytes together, referenced or not (a capped project's total, 249). Uploads in progress don't count. */
187+ total(): number {
188+ if (!this.hasSchema()) return 0;
189+ const [row] = this.storage.sql
190+ .exec("SELECT COALESCE(SUM(LENGTH(data)), 0) AS n FROM blobs WHERE sha NOT LIKE 'tmp-%'")
191+ .toArray() as { n: number }[];
192+ return row?.n ?? 0;
193+ }
195+ /** A blob's size in bytes: 0 when the project doesn't hold it. */
196+ size(sha: string): number {
197+ if (!this.hasSchema()) return 0;
198+ const [row] = this.storage.sql
199+ .exec("SELECT COALESCE(SUM(LENGTH(data)), 0) AS n FROM blobs WHERE sha = ?", sha)
200+ .toArray() as { n: number }[];
201+ return row?.n ?? 0;
202+ }
204+ /** Writes bytes as rows of at most PART from part `first` on; answers the next part. An empty blob is one empty row. */
205+ private write(sha: string, bytes: Uint8Array, first: number): number {
206+ this.ensureSchema();
207+ let part = first;
208+ for (let at = 0; at < bytes.byteLength || (at === 0 && part === 0); at += PART) {
209+ this.storage.sql.exec(
210+ "INSERT INTO blobs (sha, part, data) VALUES (?, ?, ?)",
211+ sha,
212+ part++,
213+ bytes.slice(at, at + PART),
214+ );
215+ if (bytes.byteLength === 0) break;
216+ }
217+ return part;
218+ }
220+ private drop(sha: string) {
221+ this.ensureSchema();
222+ this.storage.sql.exec("DELETE FROM blobs WHERE sha = ?", sha);
223+ }
224+}
226+function concat(chunks: Uint8Array[], size: number): Uint8Array {
227+ if (chunks.length === 1) return chunks[0]!;
228+ const out = new Uint8Array(size);
229+ let at = 0;
230+ for (const c of chunks) {
231+ out.set(c, at);
232+ at += c.byteLength;
233+ }
234+ return out;
235+}
237+const hex = (buf: ArrayBuffer) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
--- /dev/null
+++ b/server/src/engine-project.ts
@@ -0,0 +1,724 @@
1+// The engine's Project (worker/project/project.ts) behind the server's calls, with its append-only log kept in the
2+// Durable Object's SQLite. An entry longer than one row allows (init holds every starting file; SQLite rows stop at
3+// 2 MB) is split across rows and joined on load. Ported from the platform's worker/src/engine-project.ts; the
4+// writer-adoption and R2 version parts are left out.
5+
6+import { blame, folderBlame, why } from "../../worker/project/blame.ts";
7+import { feedEvents } from "../../worker/project/feed.ts";
8+import { type Entry, type ProjectStore as LogStore, MemoryStore, Project } from "../../worker/project/project.ts";
9+import type { EditBody, ProjectCalls, ProjectHistory } from "../../worker/project/project-api.ts";
10+import { where } from "../../worker/project/where.ts";
12+/** The parts of a Durable Object's storage the log and blob store use, declared structurally so tests can stand in. */
13+export interface SqliteStorage {
14+ sql: { exec(query: string, ...bindings: unknown[]): { toArray(): unknown[] } };
15+ transactionSync<T>(fn: () => T): T;
16+}
18+// Characters per row. SQLite's 2 MB cap is in bytes, and a character is at
19+// most 3 bytes of UTF-8 (an emoji is 2 characters and 4 bytes), so 600,000 stays under it.
20+const PART = 600_000;
22+/** An entry's JSON in rows of at most PART characters, never cutting an emoji's two halves apart. */
23+export function logParts(text: string): string[] {
24+ const parts: string[] = [];
25+ let at = 0;
26+ do {
27+ let end = Math.min(at + PART, text.length);
28+ const c = text.charCodeAt(end - 1);
29+ if (end < text.length && c >= 0xd800 && c <= 0xdbff) end--;
30+ parts.push(text.slice(at, end));
31+ at = end;
32+ } while (at < text.length);
33+ return parts;
34+}
36+/** The lines an entry's atoms write: what a loaded project's size grows with (#46, #56). */
37+function linesIn(entry: Entry): number {
38+ let n = 0;
39+ for (const a of [
40+ (entry as { atom?: { inserts?: { lines: unknown[] }[] } }).atom,
41+ (entry as { tie?: { inserts?: { lines: unknown[] }[] } }).tie,
42+ ]) {
43+ for (const r of a?.inserts ?? []) n += r.lines.length;
44+ }
45+ return n;
46+}
48+/** The version of shared an entry makes, or undefined (abso issue 78: the access check reads it without loading). */
49+function sharedVersionOf(entry: Entry): number | undefined {
50+ if (entry.type === "init") return 0;
51+ if (entry.type === "land" || entry.type === "drop") return entry.version;
52+ if (entry.type === "publish" && (entry.space ?? "") === "") return entry.version;
53+ return undefined;
54+}
56+/** Who made that version of shared, and when. Init is not a publish (abso issue 86). */
57+function lastPublishOf(entry: Entry): { agent: string; time: number } | undefined {
58+ if (entry.type === "land" || entry.type === "drop") return { agent: entry.agent, time: entry.time };
59+ if (entry.type === "publish" && (entry.space ?? "") === "") return { agent: entry.agent, time: entry.time };
60+ return undefined;
61+}
63+/** An entry's claim keys and deletes (#46): with entries and lines, what the load guard estimates memory by. */
64+function keysIn(entry: Entry): number {
65+ let n = 0;
66+ for (const a of [
67+ (entry as { atom?: Partial<Record<"writes" | "reads" | "holds" | "deletes", unknown[]>> }).atom,
68+ (entry as { tie?: Partial<Record<"writes" | "reads" | "holds" | "deletes", unknown[]>> }).tie,
69+ ]) {
70+ if (a) n += (a.writes?.length ?? 0) + (a.reads?.length ?? 0) + (a.holds?.length ?? 0) + (a.deletes?.length ?? 0);
71+ }
72+ return n;
73+}
75+export class SqliteLog implements LogStore {
76+ private storage: SqliteStorage;
77+ private next: number;
79+ constructor(storage: SqliteStorage) {
80+ this.storage = storage;
81+ storage.sql.exec(
82+ "CREATE TABLE IF NOT EXISTS log (seq INTEGER, part INTEGER, text TEXT NOT NULL, PRIMARY KEY (seq, part))",
83+ );
84+ storage.sql.exec(
85+ "CREATE TABLE IF NOT EXISTS shapes (space TEXT NOT NULL, version INTEGER NOT NULL, value TEXT NOT NULL, PRIMARY KEY (space, version))",
86+ );
87+ storage.sql.exec("CREATE TABLE IF NOT EXISTS counts (name TEXT PRIMARY KEY, value INTEGER NOT NULL)");
88+ storage.sql.exec("CREATE TABLE IF NOT EXISTS marks (name TEXT PRIMARY KEY, value TEXT NOT NULL)");
89+ const rows = storage.sql.exec("SELECT COALESCE(MAX(seq), -1) AS last FROM log").toArray() as { last: number }[];
90+ this.next = (rows[0]?.last ?? -1) + 1;
91+ }
93+ /** The seq the next entry would take. A copy's next page must start here. */
94+ seq(): number {
95+ return this.next;
96+ }
98+ /** Monotonic cache invalidation epoch for every canonical log mutation. */
99+ generation(): number {
100+ const rows = this.storage.sql.exec("SELECT value FROM marks WHERE name = ?", "generation").toArray() as {
101+ value: string;
102+ }[];
103+ const generation = Number(rows[0]?.value ?? 0);
104+ if (!Number.isSafeInteger(generation) || generation < 0) throw new Error("canonical log generation is invalid");
105+ return generation;
106+ }
108+ /**
109+ * Lines ever recorded (#46, #56): what loading the project costs grows with
110+ * this, not with the log's size, so a guard can read it without loading.
111+ * Kept with each append; undefined for a log written before the count,
112+ * until it next loads.
113+ */
114+ lineCount(): number | undefined {
115+ const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'lines'").toArray() as {
116+ value: number;
117+ }[];
118+ return rows[0]?.value;
119+ }
121+ /**
122+ * The newest version of shared, without loading the project (abso issue 78: the website's access check asked
123+ * every project's engine for it). Kept with each append; a log from before the count is read once by streaming.
124+ */
125+ sharedVersion(): number {
126+ const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'shared'").toArray() as {
127+ value: number;
128+ }[];
129+ if (rows[0] !== undefined) return rows[0].value;
130+ let version = -1;
131+ for (const e of this.#entries()) version = sharedVersionOf(e) ?? version;
132+ if (version >= 0)
133+ this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('shared', ?)", version);
134+ return version;
135+ }
137+ /**
138+ * Who published shared's newest version, and when, without loading the project (abso issue 86).
139+ * Null when shared has no publish yet. A log from before the mark is read once by streaming.
140+ */
141+ lastPublish(): { agent: string; time: number } | null {
142+ const rows = this.storage.sql.exec("SELECT value FROM marks WHERE name = ?", "last").toArray() as {
143+ value: string;
144+ }[];
145+ if (rows[0] !== undefined) return JSON.parse(rows[0].value) as { agent: string; time: number };
146+ let last: { agent: string; time: number } | null = null;
147+ for (const e of this.#entries()) {
148+ const found = lastPublishOf(e);
149+ if (found) last = found;
150+ }
151+ if (last)
152+ this.storage.sql.exec("INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)", "last", JSON.stringify(last));
153+ return last;
154+ }
156+ /**
157+ * How big the log is, without loading the project or scanning it twice (ask 160).
158+ * Entries are the next seq. Chars are kept like lines; a log from before the
159+ * count is summed once, then kept. GET /projects' 2-second wait needs this
160+ * to stay a storage read: SUM(LENGTH(text)) over abso's log misses it.
161+ */
162+ logSize(): { chars: number; entries: number } {
163+ const entries = this.next;
164+ const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'chars'").toArray() as {
165+ value: number;
166+ }[];
167+ if (rows[0] !== undefined) return { chars: rows[0].value, entries };
168+ if (entries === 0) return { chars: 0, entries: 0 };
169+ const summed = this.storage.sql.exec("SELECT COALESCE(SUM(LENGTH(text)), 0) AS chars FROM log").toArray()[0] as
170+ | { chars: number }
171+ | undefined;
172+ const chars = summed?.chars ?? 0;
173+ this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('chars', ?)", chars);
174+ return { chars, entries };
175+ }
177+ /** Claim keys and deletes ever recorded (#46), kept like the line count; undefined before they were counted. */
178+ keyCount(): number | undefined {
179+ const rows = this.storage.sql.exec("SELECT value FROM counts WHERE name = 'keys'").toArray() as { value: number }[];
180+ return rows[0]?.value;
181+ }
183+ /**
184+ * The lines and keys ever recorded, counting a log from before either count without loading the project
185+ * (#46): one entry parsed at a time, so a log the load guard would refuse can still be measured. Kept once counted.
186+ */
187+ countSizes(): { lines: number; keys: number } {
188+ const lines = this.lineCount();
189+ const keys = this.keyCount();
190+ if (lines !== undefined && keys !== undefined) return { lines, keys };
191+ let l = 0;
192+ let k = 0;
193+ for (const e of this.#entries()) {
194+ l += linesIn(e);
195+ k += keysIn(e);
196+ }
197+ this.#keep(lines === undefined ? l : undefined, keys === undefined ? k : undefined);
198+ return { lines: lines ?? l, keys: keys ?? k };
199+ }
201+ /** Stores the counts given. */
202+ #keep(lines: number | undefined, keys: number | undefined): void {
203+ if (lines !== undefined)
204+ this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('lines', ?)", lines);
205+ if (keys !== undefined)
206+ this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('keys', ?)", keys);
207+ }
209+ /** Every stored entry, in order. Rows are read one at a time, so loading never holds the whole log's text at once (#43). */
210+ *entries(): Iterable<Entry> {
211+ // A log from before the counts: counted as it loads, and kept.
212+ const countLines = this.lineCount() === undefined;
213+ const countKeys = this.keyCount() === undefined;
214+ let lines = 0;
215+ let keys = 0;
216+ for (const e of this.#entries()) {
217+ if (countLines) lines += linesIn(e);
218+ if (countKeys) keys += keysIn(e);
219+ yield e;
220+ }
221+ this.#keep(countLines ? lines : undefined, countKeys ? keys : undefined);
222+ }
224+ *#entries(from = 0): Iterable<Entry> {
225+ // A Workers cursor is iterable; a test's stand-in may only have toArray.
226+ const cursor = this.storage.sql.exec("SELECT seq, text FROM log WHERE seq >= ? ORDER BY seq, part", from) as {
227+ toArray(): unknown[];
228+ } & Partial<Iterable<unknown>>;
229+ const rows = (cursor[Symbol.iterator] ? cursor : cursor.toArray()) as Iterable<{ seq: number; text: string }>;
230+ let seq = -1;
231+ let text = "";
232+ for (const r of rows) {
233+ if (r.seq !== seq && seq >= 0) yield JSON.parse(text) as Entry;
234+ if (r.seq !== seq) text = "";
235+ seq = r.seq;
236+ text += r.text;
237+ }
238+ if (seq >= 0) yield JSON.parse(text) as Entry;
239+ }
241+ /**
242+ * For backups (#29): the entries from seq `from` on as their stored JSON
243+ * text (not parsed, so an export holds the project up as little as it
244+ * can), at most `limit` of them and about 8 MB (always at least one), and
245+ * the seq to ask for next, or null at the end.
246+ */
247+ page(from: number, limit: number): { texts: string[]; next: number | null } {
248+ const rows = this.storage.sql
249+ .exec("SELECT seq, text FROM log WHERE seq >= ? AND seq < ? ORDER BY seq, part", from, from + limit)
250+ .toArray() as { seq: number; text: string }[];
251+ const texts: string[] = [];
252+ let seq = -1;
253+ let text = "";
254+ let size = 0;
255+ let next: number | null = null;
256+ for (const r of rows) {
257+ if (r.seq < from || r.seq >= from + limit) continue;
258+ if (r.seq !== seq && seq >= 0) {
259+ texts.push(text);
260+ size += text.length;
261+ if (size > 8_000_000) {
262+ next = r.seq;
263+ break;
264+ }
265+ }
266+ if (r.seq !== seq) text = "";
267+ seq = r.seq;
268+ text += r.text;
269+ }
270+ if (next === null && seq >= 0) texts.push(text);
271+ if (next === null && from + limit < this.next) next = from + limit;
272+ return { texts, next };
273+ }
275+ /** Up to `limit` entries from position `from`, parsed (#41: the feed and replay). */
276+ since(from: number, limit: number): Entry[] {
277+ const out: Entry[] = [];
278+ for (let at = from; out.length < limit; ) {
279+ const { texts, next } = this.page(at, limit - out.length);
280+ for (const t of texts) out.push(JSON.parse(t) as Entry);
281+ if (next === null || texts.length === 0) break;
282+ at = next;
283+ }
284+ return out;
285+ }
287+ /** Removes every entry: only for a restore whose log didn't load (#29). */
288+ clear(): void {
289+ const generation = this.generation() + 1;
290+ this.storage.transactionSync(() => {
291+ this.storage.sql.exec("DELETE FROM log");
292+ this.storage.sql.exec("DELETE FROM shapes");
293+ this.storage.sql.exec("DELETE FROM counts");
294+ this.storage.sql.exec("DELETE FROM marks WHERE name != ?", "generation");
295+ this.storage.sql.exec(
296+ "INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)",
297+ "generation",
298+ String(generation),
299+ );
300+ });
301+ this.next = 0;
302+ }
304+ /**
305+ * Each version's changed files, kept between loads (#41, the Files pages):
306+ * worked out from the log, never part of it, so an older Worker ignores
307+ * the table and nothing about the project depends on it.
308+ */
309+ shapes(): {
310+ get(space: string, version: number): string | undefined;
311+ put(space: string, version: number, value: string): void;
312+ } {
313+ const sql = this.storage.sql;
314+ return {
315+ get: (space, version) =>
316+ (
317+ sql.exec("SELECT value FROM shapes WHERE space = ? AND version = ?", space, version).toArray() as {
318+ value: string;
319+ }[]
320+ )[0]?.value,
321+ put: (space, version, value) =>
322+ void sql.exec("INSERT OR REPLACE INTO shapes (space, version, value) VALUES (?, ?, ?)", space, version, value),
323+ };
324+ }
326+ append(entries: readonly Entry[]): void {
327+ if (!entries.length) return;
328+ let next = this.next;
329+ this.storage.transactionSync(() => {
330+ const lines = entries.reduce((n, e) => n + linesIn(e), 0);
331+ if (lines > 0)
332+ this.storage.sql.exec(
333+ "INSERT INTO counts (name, value) VALUES ('lines', ?) ON CONFLICT(name) DO UPDATE SET value = value + ?",
334+ lines,
335+ lines,
336+ );
337+ // The newest version of shared: appended entries are the newest, so the last one that makes a version wins.
338+ for (const e of entries) {
339+ const v = sharedVersionOf(e);
340+ if (v !== undefined)
341+ this.storage.sql.exec("INSERT OR REPLACE INTO counts (name, value) VALUES ('shared', ?)", v);
342+ const last = lastPublishOf(e);
343+ if (last)
344+ this.storage.sql.exec(
345+ "INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)",
346+ "last",
347+ JSON.stringify(last),
348+ );
349+ }
350+ // Keys are only added to once counted: a log from before the key count is counted whole first (countSizes).
351+ const keys = entries.reduce((n, e) => n + keysIn(e), 0);
352+ if (keys > 0) this.storage.sql.exec("UPDATE counts SET value = value + ? WHERE name = 'keys'", keys);
353+ let chars = 0;
354+ for (const entry of entries) {
355+ const json = JSON.stringify(entry);
356+ logParts(json).forEach((text, part) => {
357+ chars += text.length;
358+ this.storage.sql.exec("INSERT INTO log (seq, part, text) VALUES (?, ?, ?)", next, part, text);
359+ });
360+ next++;
361+ }
362+ // Chars are only added to once counted: a log from before the count is summed whole first (logSize).
363+ if (chars > 0) this.storage.sql.exec("UPDATE counts SET value = value + ? WHERE name = 'chars'", chars);
364+ const generation = this.generation() + 1;
365+ this.storage.sql.exec(
366+ "INSERT OR REPLACE INTO marks (name, value) VALUES (?, ?)",
367+ "generation",
368+ String(generation),
369+ );
370+ });
371+ this.next = next;
372+ }
373+}
375+/** The engine's Project as the Worker's ProjectCalls; the clock comes from here. */
376+export class EngineProject implements ProjectCalls, ProjectHistory {
377+ blame(file: string, from?: number, to?: number, version?: number, draft?: string, agent?: string) {
378+ return blame(this.project, file, from, to, version, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) });
379+ }
380+ folderBlame(folder: string, version?: number, draft?: string, agent?: string) {
381+ return folderBlame(this.project, folder, version, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) });
382+ }
383+ tree(folder: string, version?: number, draft?: string | null, agent?: string, authors?: boolean) {
384+ return this.project.tree(folder, {
385+ ...(version !== undefined ? { version } : {}),
386+ draft: draft ?? null,
387+ ...(agent !== undefined ? { agent } : {}),
388+ ...(authors ? { authors } : {}),
389+ });
390+ }
391+ pathLife(path: string, version?: number, draft?: string | null) {
392+ return this.project.pathLife(path, { ...(version !== undefined ? { version } : {}), draft: draft ?? null });
393+ }
394+ follow(path: string, version: number, from: number, to: number, at?: number, draft?: string | null) {
395+ return this.project.follow(path, version, from, to, { ...(at !== undefined ? { at } : {}), draft: draft ?? null });
396+ }
397+ pathsOf(agent: string) {
398+ return this.project.pathsOf(agent);
399+ }
400+ draftState(name: string) {
401+ return this.project.draftState(name);
402+ }
403+ collisions(file?: string, folder?: string) {
404+ return this.project.collisions({
405+ ...(file !== undefined ? { file } : {}),
406+ ...(folder !== undefined ? { folder } : {}),
407+ });
408+ }
409+ why(file: string, line: number, draft?: string, agent?: string) {
410+ return why(this.project, file, line, { ...(draft ? { draft } : {}), ...(agent ? { agent } : {}) });
411+ }
412+ where() {
413+ return where(this.project);
414+ }
415+ refusals(agent?: string, limit?: number) {
416+ return this.project.refusals({ ...(agent ? { agent } : {}), ...(limit !== undefined ? { limit } : {}) });
417+ }
419+ log(draft: string | null, limit?: number, path?: string, agent?: string, before?: number, follow?: boolean) {
420+ return this.project.log({
421+ draft,
422+ ...(limit !== undefined ? { limit } : {}),
423+ ...(path !== undefined ? { path } : {}),
424+ ...(agent ? { agent } : {}),
425+ ...(before !== undefined ? { before } : {}),
426+ ...(follow ? { follow } : {}),
427+ });
428+ }
429+ fileAt(path: string, version: number, draft: string | null, agent?: string) {
430+ return this.project.fileAt(path, version, { draft, ...(agent ? { agent } : {}) });
431+ }
432+ compare(from: number, to: number, draft: string | null, agent?: string) {
433+ return this.project.compare(from, to, { draft, ...(agent ? { agent } : {}) });
434+ }
435+ show(version: number, draft: string | null, agent?: string) {
436+ return this.project.show(version, { draft, ...(agent ? { agent } : {}) });
437+ }
438+ diff(agent: string) {
439+ return this.project.diff(agent);
440+ }
441+ syncFull(agent: string, label?: string) {
442+ return this.project.sync(agent, { full: true, ...(label !== undefined ? { label } : {}) });
443+ }
444+ agentPaths(agent: string) {
445+ return this.project.agentPaths(agent);
446+ }
447+ pathsAt(version?: number, draft?: string | null) {
448+ return this.project.pathsAt(version, draft ?? null);
449+ }
450+ syncTo(agent: string, label: string) {
451+ return this.project.sync(agent, { label });
452+ }
453+ label(agent: string, name: string, version?: number, remove?: boolean) {
454+ return this.project.label(agent, name, version, Date.now(), { remove: remove === true });
455+ }
456+ labels() {
457+ return this.project.labels();
458+ }
459+ amend(agent: string, message: string) {
460+ return this.project.amend(agent, message, Date.now());
461+ }
462+ pluck(agent: string, draft: string, versions: number[], message: string, withDependencies?: boolean) {
463+ return this.project.pluck(agent, draft, versions, message, Date.now(), {
464+ withDependencies: withDependencies === true,
465+ });
466+ }
467+ drop(agent: string, versions: number[], message: string, withDependents?: boolean) {
468+ return this.project.drop(agent, versions, message, Date.now(), { withDependents: withDependents === true });
469+ }
470+ announce(agent: string, text: string, to?: string[], how?: string) {
471+ return this.project.announce(agent, text, to, Date.now(), how);
472+ }
474+ announcePerson(person: { id: string; name: string }, text: string, to?: string[]) {
475+ return this.project.announcePerson(person, text, to, Date.now());
476+ }
477+ starting(agent: string, text: string | null, files?: string[], options: { issue?: unknown; done?: unknown } = {}) {
478+ return this.project.starting(agent, text, files, Date.now(), options);
479+ }
480+ news(agent: string) {
481+ return this.project.news(agent);
482+ }
483+ restore(agent: string, files: string[] | null) {
484+ return this.project.restore(agent, files, Date.now());
485+ }
487+ private project: Project;
489+ /** Reads stored entries by log position, for the feed and replay (#41); absent, those answer 501. */
490+ private readonly read: ((from: number, limit: number) => Entry[]) | undefined;
491+ private readonly store: SqliteLog | undefined;
493+ constructor(project: Project, read?: (from: number, limit: number) => Entry[], store?: SqliteLog) {
494+ this.project = project;
495+ this.read = read;
496+ this.store = store;
497+ }
499+ /** The project's events from log position `from` (#41): reading consumes nothing. */
500+ feed(from: number, limit = 500) {
501+ if (!this.read) throw Object.assign(new Error("the feed needs the log"), { code: "not-implemented" });
502+ const end = this.project.logLength;
503+ const start = Math.max(0, Math.min(from, end));
504+ const entries = start < end ? this.read(start, Math.min(limit, end - start)) : [];
505+ // A drop event names the files it took out (#41), so a timeline needs no read per drop.
506+ const events = feedEvents(entries, start).map((e) => {
507+ if (e.type !== "drop" || e.version === undefined) return e;
508+ const v = this.project.log({ limit: 1, before: e.version + 1 }).versions[0];
509+ return v && v.version === e.version ? { ...e, dropped: v.files } : e;
510+ });
511+ return { next: start + entries.length, end, events };
512+ }
514+ /** The log position for a time (ms since 1970) or a version of shared (#41). */
515+ position(q: { time?: number; version?: number }) {
516+ return this.project.position(q);
517+ }
518+ /** Whether the Worker runs the queue's check; until it does, "queue": true does nothing. */
519+ setCheckerReady(ready: boolean): void {
520+ this.project.checkerReady = ready;
521+ }
522+ /** An agent withdraws what it has queued (#39). */
523+ unqueue(agent: string) {
524+ return this.project.unqueue(agent, Date.now());
525+ }
526+ /** The log length now: what a long-poll waits to see grow. */
527+ logLength() {
528+ return this.project.logLength;
529+ }
530+ /** An agent's draft diff for a reader: never creates the agent (#41). */
531+ diffOf(agent: string) {
532+ return this.project.diffOf(agent);
533+ }
534+ /** Every agent with unpublished changes: its files and how many changes (#41). */
535+ change(id: number) {
536+ return this.project.change(id);
537+ }
539+ changes(since: number, limit: number, before?: number, issue?: number) {
540+ return this.project.changes(since, limit, before, issue);
541+ }
543+ move(agent: string, from: string, to: string) {
544+ return this.project.move(agent, from, to, Date.now());
545+ }
547+ note(agent: string, body: Record<string, unknown>) {
548+ return this.project.note(agent, body, Date.now());
549+ }
551+ notePerson(person: { id: string; name: string }, body: Record<string, unknown>) {
552+ return this.project.notePerson(person, body, Date.now());
553+ }
555+ closeNotePerson(person: { id: string; name: string }, id: number, how: unknown) {
556+ return this.project.closeNotePerson(person, id, how, Date.now());
557+ }
559+ closeNote(agent: string, id: number, how: unknown) {
560+ return this.project.closeNote(agent, id, how, Date.now());
561+ }
563+ notes(options: { file?: string; change?: number; open?: boolean }) {
564+ return this.project.notes(options);
565+ }
567+ ribbon() {
568+ return this.project.ribbon();
569+ }
571+ drafts() {
572+ const s = this.project.status();
573+ return {
574+ version: s.version,
575+ drafts: s.agents
576+ .filter((a) => a.draftChanges > 0)
577+ .map((a) => ({ agent: a.agent, draft: a.draft, base: a.base, draftChanges: a.draftChanges, files: a.files })),
578+ };
579+ }
580+ /** The last copy replay loaded: scrubbing forward from it applies only the entries after it. */
581+ private replica: Project | undefined;
583+ /** The project as it stood with the first `at` log entries (#41, replay). */
584+ private at(at: number): Project {
585+ if (!this.read) throw Object.assign(new Error("replay needs the log"), { code: "not-implemented" });
586+ const n = Math.max(0, Math.min(at, this.project.logLength));
587+ const r = this.replica;
588+ if (r && r.logLength === n) return r;
589+ if (r && r.logLength < n) {
590+ r.catchUp(this.read(r.logLength, n - r.logLength));
591+ return r;
592+ }
593+ this.replica = Project.load(this.read(0, n), new MemoryStore());
594+ return this.replica;
595+ }
596+ statusAt(at: number) {
597+ const p = this.at(at);
598+ const answer = {
599+ at: Math.min(at, this.project.logLength),
600+ ...(p.initialized ? p.status() : { version: -1, agents: [] }),
601+ };
602+ this.release();
603+ return answer;
604+ }
605+ whereAt(at: number) {
606+ const p = this.at(at);
607+ const answer = {
608+ at: Math.min(at, this.project.logLength),
609+ ...(p.initialized ? where(p) : { version: -1, files: {} }),
610+ };
611+ this.release();
612+ return answer;
613+ }
615+ /**
616+ * Drop the replay copy after each read (#46): a second copy of a large
617+ * project's history doubles its memory, past a Durable Object's 128 MB.
618+ * Each scrub replays from the start instead (about 0.2 s on game).
619+ */
620+ private release(): void {
621+ this.replica = undefined;
622+ }
624+ /** hasBlob says whether the project holds a blob's bytes (#27); without it, every blob is refused. */
625+ /** whole stores and reads files kept whole (#46); without it every text file is tracked by line. */
626+ static open(
627+ storage: SqliteStorage,
628+ hasBlob?: (sha256: string) => boolean,
629+ whole?: { keep(text: string): string; read(sha: string): string | null },
630+ ): EngineProject {
631+ const log = new SqliteLog(storage);
632+ return new EngineProject(
633+ Project.load(log.entries(), log, {
634+ ...(hasBlob ? { hasBlob } : {}),
635+ ...(whole ? { whole } : {}),
636+ now: () => Date.now(),
637+ shapes: log.shapes(),
638+ entryAt: (at) => log.since(at, 1)[0]!,
639+ }),
640+ (from, limit) => log.since(from, limit),
641+ log,
642+ );
643+ }
645+ exists() {
646+ return this.project.initialized;
647+ }
648+ /** Committed log epoch for host-side cache invalidation; it does not dispatch work. */
649+ committedGeneration(): number {
650+ return this.store?.generation() ?? 0;
651+ }
652+ init(
653+ files: Record<string, string>,
654+ modes?: Record<string, { exec?: boolean; link?: string | null }>,
655+ blobs?: Record<string, string>,
656+ ) {
657+ return this.project.init(files, Date.now(), modes ?? {}, blobs ?? {});
658+ }
659+ edit(agent: string, body: EditBody) {
660+ return this.project.edit(agent, body as Parameters<Project["edit"]>[1], Date.now());
661+ }
662+ record(
663+ agent: string,
664+ files: Record<string, string | null>,
665+ modes?: Record<string, { exec?: boolean; link?: string | null }>,
666+ blobs?: Record<string, string>,
667+ meta?: { session?: string; subagent?: string; client?: string },
668+ ) {
669+ return this.project.record(agent, files, Date.now(), modes ?? {}, blobs ?? {}, meta ?? {});
670+ }
671+ publish(agent: string, message: string, asIs?: boolean) {
672+ return this.project.publish(agent, message, Date.now(), { asIs: asIs === true });
673+ }
674+ sync(agent: string) {
675+ return this.project.sync(agent);
676+ }
677+ status() {
678+ return this.project.status();
679+ }
680+ switchTo(agent: string, name: string | null, carry = false) {
681+ return this.project.switchTo(agent, name, Date.now(), { carry });
682+ }
683+ land(agent: string, message: string) {
684+ return this.project.land(agent, message, Date.now());
685+ }
686+ ingest(input: Parameters<Project["ingest"]>[0], time: number) {
687+ return this.project.ingest(input, time);
688+ }
689+ syncDraft(agent: string) {
690+ return this.project.syncDraft(agent, Date.now());
691+ }
692+ filesAt(version: number) {
693+ return this.project.viewAt(version).files();
694+ }
695+ blobsAt(version: number) {
696+ return this.project.viewAt(version).blobs();
697+ }
698+ /**
699+ * Shared's newest version. Its files and modes are laid out on first read: every call reads shared().version
700+ * before and after its op, and laying out the files reads each file's text from the log, about 0.5 s on abso
701+ * (abso 299).
702+ */
703+ shared() {
704+ const version = this.project.version;
705+ const by = version > 0 ? this.project.published(version) : undefined;
706+ const blobs = this.project.blobs();
707+ const project = this.project;
708+ let files: Record<string, string> | undefined;
709+ let modes: ReturnType<Project["modes"]> | undefined;
710+ return {
711+ version,
712+ get files() {
713+ files ??= project.files();
714+ return files;
715+ },
716+ get modes() {
717+ modes ??= project.modes();
718+ return modes;
719+ },
720+ ...(Object.keys(blobs).length > 0 ? { blobs } : {}),
721+ ...(by ? { last: { agent: by.agent, message: by.message } } : {}),
722+ };
723+ }
724+}
--- /dev/null
+++ b/server/src/env.ts
@@ -0,0 +1,36 @@
1+// What the open server's Worker is given: wrangler.jsonc's bindings and the secrets set with `wrangler secret put`.
2+
3+import type { IssueProject } from "./issues-entry.ts";
4+import type { ProjectObject } from "./project-object.ts";
5+
6+export interface Env {
7+ /** One Durable Object per project, named by the project's name. */
8+ PROJECT: DurableObjectNamespace<ProjectObject>;
9+ /** Issues, asks and news: one Durable Object per project, named by the project's name. */
10+ ISSUES_DO: DurableObjectNamespace<IssueProject>;
11+ /** Each project's shared, pushed out as a git repo abso-<project>. Unbound under local `wrangler dev`: skipped. */
12+ ARTIFACTS?: Artifacts;
13+ /** "off" leaves Artifacts alone even where it is bound: local `wrangler dev --local` binds it but cannot reach it. */
14+ ABSO_ARTIFACTS?: string;
15+ CF_VERSION_METADATA?: WorkerVersionMetadata;
16+ /** The shared token every agent signs in with. AVCS_TOKEN is its old name. With neither set, every call is refused. */
17+ ABSO_TOKEN?: string;
18+ AVCS_TOKEN?: string;
19+ /** For /admin/agent-keys, sent as the x-abso-admin header beside the shared token. */
20+ ABSO_ADMIN_TOKEN?: string;
21+ AVCS_ADMIN_TOKEN?: string;
22+ /** Per-agent keys: "on" with KEY_HMAC_SECRET set. */
23+ AGENT_KEYS?: string;
24+ KEY_HMAC_SECRET?: string;
25+}
27+/** A secret by its abso name, or its avcs name from before the rename. Empty counts as unset. */
28+export function secret(env: Env, name: "TOKEN" | "ADMIN_TOKEN"): string | undefined {
29+ for (const v of [env[`ABSO_${name}`], env[`AVCS_${name}`]]) if (typeof v === "string" && v !== "") return v;
30+ return undefined;
31+}
33+/** The Artifacts binding, unless it is unbound or ABSO_ARTIFACTS is "off": then nothing is pushed out or taken in. */
34+export function artifactsOf(env: Env): Artifacts | undefined {
35+ return env.ABSO_ARTIFACTS === "off" ? undefined : env.ARTIFACTS;
36+}
--- /dev/null
+++ b/server/src/index.ts
@@ -0,0 +1,12 @@
1+// The Worker's entry: the router (router.ts) and the Durable Object classes wrangler.jsonc binds.
2+
3+import type { Env } from "./env.ts";
4+import { issuesFetch } from "./issues-entry.ts";
5+import { handle } from "./router.ts";
6+
7+export { IssueProject } from "./issues-entry.ts";
8+export { ProjectObject } from "./project-object.ts";
9+
10+export default {
11+ fetch: (request, env, ctx) => handle(request, env, ctx, issuesFetch),
12+} satisfies ExportedHandler<Env>;
--- /dev/null
+++ b/server/src/ingest.ts
@@ -0,0 +1,174 @@
1+// In from plain git (#8, demo moment 5): commits a person pushed to the
2+// project's Artifacts repo, read back for project.ingest. Every commit the
3+// Worker pushes ends "abso-version: N" ("avcs-version: N" before the rename); the commits above the newest such
4+// commit that haven't been taken in yet are the person's, and N is their base.
5+import git from "isomorphic-git";
6+import http from "isomorphic-git/http/web";
7+import type { FileModes } from "../../worker/project/project-api.ts";
8+import { MemoryFS } from "./memory-fs.ts";
9+import { repoName } from "./push.ts";
11+const EXEC = 0o100755;
12+const LINK = 0o120000;
14+/** How far back to look for the Worker's last commit. */
15+const DEPTH = 50;
16+const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false });
18+export interface PushedCommits {
19+ /** main's head when read. */
20+ head: string;
21+ author: string;
22+ base: number;
23+ /** Oldest first, each with its whole tree as text and every file's mode. Binary files are left out. */
24+ commits: {
25+ sha: string;
26+ message: string;
27+ files: Record<string, string>;
28+ modes: FileModes;
29+ blobs: Record<string, string>;
30+ }[];
31+ /** Binary files over the blob limit, left out of the commits. */
32+ tooBig: string[];
33+}
35+export function absoVersion(message: string): number | undefined {
36+ const m = /^(?:abso|avcs)-version: (\d+)\s*$/m.exec(message);
37+ return m ? Number(m[1]) : undefined;
38+}
40+async function readAccess(
41+ artifacts: Artifacts,
42+ project: string,
43+): Promise<{ url: string; onAuth: () => { username: string; password: string } } | null> {
44+ let repo: Awaited<ReturnType<Artifacts["get"]>>;
45+ try {
46+ repo = await artifacts.get(repoName(project));
47+ } catch {
48+ return null;
49+ }
50+ using r = repo;
51+ const [info, token] = await Promise.all([r.info(), r.createToken("read", 600)]);
52+ const password = token.plaintext.split("?expires=")[0]!;
53+ return { url: info!.remote, onAuth: () => ({ username: "x", password }) };
54+}
56+/** main's head on the project's repo, or null when there's no repo or no main yet. Cheap: one ref listing. */
57+export async function remoteHead(artifacts: Artifacts, project: string): Promise<string | null> {
58+ const access = await readAccess(artifacts, project);
59+ if (!access) return null;
60+ const refs = await git.listServerRefs({ http, url: access.url, onAuth: access.onAuth, prefix: "refs/heads/main" });
61+ return refs.find((r) => r.ref === "refs/heads/main")?.oid ?? null;
62+}
64+/**
65+ * The commits pushed since `seen` (the last head this project handled), or
66+ * none when every commit above the Worker's last one has been seen.
67+ */
68+/** Stores a binary file's bytes and answers their SHA-256, or null when they're over the limit. */
69+export type StoreBlob = (bytes: Uint8Array) => Promise<string | null>;
71+/**
72+ * `oldBlob` gives shared's blob for a path: a binary file over the limit
73+ * keeps it, since a path missing from a commit would mean the file was deleted.
74+ */
75+export async function pushedSince(
76+ artifacts: Artifacts,
77+ project: string,
78+ seen: string | undefined,
79+ storeBlob?: StoreBlob,
80+ oldBlob: (path: string) => string | undefined = () => undefined,
81+): Promise<PushedCommits | null> {
82+ const access = await readAccess(artifacts, project);
83+ if (!access) return null;
84+ const fs = new MemoryFS();
85+ const dir = "/repo";
86+ await git.clone({
87+ fs,
88+ http,
89+ dir,
90+ url: access.url,
91+ onAuth: access.onAuth,
92+ ref: "main",
93+ singleBranch: true,
94+ depth: DEPTH,
95+ noCheckout: true,
96+ });
97+ const log = await git.log({ fs, dir, ref: "main", depth: DEPTH });
98+ if (log.length === 0) return null;
99+ const head = log[0]!.oid;
100+ const fresh: typeof log = [];
101+ let base: number | undefined;
102+ let past = false;
103+ for (const c of log) {
104+ if (c.oid === seen) past = true;
105+ base = absoVersion(c.commit.message);
106+ if (base !== undefined) break;
107+ if (!past) fresh.unshift(c);
108+ }
109+ if (base === undefined) throw new Error(`no abso-version commit in main's last ${DEPTH} commits`);
110+ const commits = [];
111+ const tooBig = new Set<string>();
112+ for (const c of fresh)
113+ commits.push({
114+ sha: c.oid,
115+ message: c.commit.message.trim(),
116+ ...(await treeText(fs, dir, c.oid, storeBlob, tooBig, oldBlob)),
117+ });
118+ return { head, author: fresh.at(-1)?.commit.author.name ?? "git", base, commits, tooBig: [...tooBig] };
119+}
121+/**
122+ * A commit's whole tree as text, and every file's mode: 100755 is exec, and
123+ * a link (120000) is "" with its target in modes. Files that aren't UTF-8
124+ * are left out.
125+ */
126+async function treeText(
127+ fs: MemoryFS,
128+ dir: string,
129+ oid: string,
130+ storeBlob: StoreBlob | undefined,
131+ tooBig: Set<string>,
132+ oldBlob: (path: string) => string | undefined,
133+): Promise<{ files: Record<string, string>; modes: FileModes; blobs: Record<string, string> }> {
134+ const files: Record<string, string> = {};
135+ const modes: FileModes = {};
136+ const blobs: Record<string, string> = {};
137+ await git.walk({
138+ fs,
139+ dir,
140+ trees: [git.TREE({ ref: oid })],
141+ map: async (path, [entry]) => {
142+ if (!entry || path === ".") return true;
143+ if ((await entry.type()) !== "blob") return true;
144+ const bytes = await entry.content();
145+ if (!bytes) return true;
146+ let body: string;
147+ try {
148+ body = text.decode(bytes);
149+ } catch {
150+ // Binary (#27): the bytes go to the blob store, and the file is a pointer to them.
151+ const sha = storeBlob ? await storeBlob(bytes) : null;
152+ if (sha) {
153+ blobs[path] = sha;
154+ modes[path] = { exec: (await entry.mode()) === EXEC, link: null };
155+ } else if (storeBlob) {
156+ tooBig.add(path);
157+ const kept = oldBlob(path);
158+ if (kept) blobs[path] = kept;
159+ }
160+ return true;
161+ }
162+ const mode = await entry.mode();
163+ if (mode === LINK) {
164+ files[path] = "";
165+ modes[path] = { exec: false, link: body };
166+ } else {
167+ files[path] = body;
168+ modes[path] = { exec: mode === EXEC, link: null };
169+ }
170+ return true;
171+ },
172+ });
173+ return { files, modes, blobs };
174+}
--- /dev/null
+++ b/server/src/issues-entry.ts
@@ -0,0 +1,27 @@
1+// Where the router meets issues, asks and news (server/src/issues/, built alongside this file). Until that folder
2+// lands, this is a stand-in with the same exports, so the Worker builds and its tests run. When it lands, this file
3+// becomes one line:
4+//
5+// export { IssueProject, issuesFetch } from "./issues/index.ts";
6+//
7+// The agreed interface: issuesFetch(request, env, ctx, {project, rest, auth}), where rest is the path after
8+// /issues/p/<project> and auth is {kind: "token"} or {kind: "key", agent, role}. The router has checked auth before it
9+// calls. The issues code reaches the project through env.PROJECT and its RPC methods agents(project) and
10+// news(project, items) on ProjectObject.
12+import { DurableObject } from "cloudflare:workers";
13+import type { Env } from "./env.ts";
14+import type { KeyRole } from "./keys.ts";
16+export type IssuesAuth = { kind: "token" } | { kind: "key"; agent: string; role: KeyRole };
18+export class IssueProject extends DurableObject<Env> {}
20+export async function issuesFetch(
21+ _request: Request,
22+ _env: Env,
23+ _ctx: ExecutionContext,
24+ _where: { project: string; rest: string; auth: IssuesAuth },
25+): Promise<Response> {
26+ return Response.json({ error: "issues aren't on this server yet" }, { status: 404 });
27+}
--- /dev/null
+++ b/server/src/keys.ts
@@ -0,0 +1,253 @@
1+// Per-agent keys, ported from the platform's worker/src/keys.ts. They run when AGENT_KEYS is "on" and
2+// KEY_HMAC_SECRET is set. Each key belongs to one agent of one project; the project's Durable Object keeps only the
3+// key's HMAC, never the key. Without keys, the shared token (ABSO_TOKEN) is the only way in.
4+
5+export const KEY_PREFIX = "abso_sk_";
6+const FAIL_LIMIT = 8;
7+const FAIL_WINDOW_MS = 10 * 60 * 1000;
8+const AUDIT_CAP = 200;
9+const DAY_MS = 24 * 60 * 60 * 1000;
11+export interface KeyEnv {
12+ AGENT_KEYS?: string;
13+ KEY_HMAC_SECRET?: string;
14+}
16+/** What a key may do in its project: the admin's choice when it was issued. */
17+export type KeyRole = "owner" | "writer" | "reader";
19+export interface KeyRow {
20+ id: string;
21+ hmac: string;
22+ agent: string;
23+ issuedBy: string;
24+ at: number;
25+ lastUsed: number | null;
26+ revokedAt: number | null;
27+ expiresAt?: number | null;
28+ /** Absent on a key issued before roles existed: it counts as reader, so it fails closed. */
29+ role?: KeyRole;
30+}
32+export interface FailRow {
33+ n: number;
34+ at: number;
35+}
37+export interface AuditRow {
38+ t: number;
39+ kind: "issue" | "revoke" | "use" | "fail";
40+ id: string | null;
41+ addr: string;
42+}
44+export interface KeyState {
45+ rows: KeyRow[];
46+ fails: Record<string, FailRow>;
47+ seen: Record<string, string>;
48+ audit: AuditRow[];
49+}
51+export function emptyKeyState(): KeyState {
52+ return { rows: [], fails: {}, seen: {}, audit: [] };
53+}
55+/** Keys run when the switch and the secret are both set. */
56+export function keysEnabled(env: KeyEnv): boolean {
57+ return env.AGENT_KEYS === "on" && !!env.KEY_HMAC_SECRET;
58+}
60+/** 90 days when omitted. 1d to 365d otherwise. */
61+export function expiresAt(now: number, raw: string | null): number | { error: string } {
62+ if (raw === null || raw === "") return now + 90 * DAY_MS;
63+ const match = /^(\d+)d$/.exec(raw);
64+ if (!match) return { error: "expires is a number of days, like 7d, from 1d to 365d" };
65+ const days = Number(match[1]);
66+ if (days < 1 || days > 365) return { error: "expires is from 1d to 365d" };
67+ return now + days * DAY_MS;
68+}
70+export function isAgentKey(presented: string | undefined): boolean {
71+ return typeof presented === "string" && presented.startsWith(KEY_PREFIX) && presented.length > KEY_PREFIX.length;
72+}
74+export async function hmac(secret: string, message: string): Promise<string> {
75+ const key = await crypto.subtle.importKey(
76+ "raw",
77+ new TextEncoder().encode(secret),
78+ { name: "HMAC", hash: "SHA-256" },
79+ false,
80+ ["sign"],
81+ );
82+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(message)));
83+ return [...mac].map((b) => b.toString(16).padStart(2, "0")).join("");
84+}
86+/** Whether two strings are equal, taking the same time wherever they differ. */
87+export function timingSame(a: string, b: string): boolean {
88+ if (a.length !== b.length) return false;
89+ let diff = 0;
90+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
91+ return diff === 0;
92+}
94+function randomHex(bytes: number): string {
95+ const b = new Uint8Array(bytes);
96+ crypto.getRandomValues(b);
97+ return [...b].map((n) => n.toString(16).padStart(2, "0")).join("");
98+}
100+export function newKey(): { id: string; key: string } {
101+ const raw = new Uint8Array(32);
102+ crypto.getRandomValues(raw);
103+ const body = btoa(String.fromCharCode(...raw))
104+ .replaceAll("+", "-")
105+ .replaceAll("/", "_")
106+ .replace(/=+$/, "");
107+ return { id: `k_${randomHex(4)}`, key: `${KEY_PREFIX}${body}` };
108+}
110+function note(state: KeyState, row: AuditRow): void {
111+ state.audit.push(row);
112+ if (state.audit.length > AUDIT_CAP) state.audit.splice(0, state.audit.length - AUDIT_CAP);
113+}
115+export interface Issued {
116+ id: string;
117+ key: string;
118+ agent: string;
119+}
121+/** Issues a key. The returned value is the only copy; the state keeps the HMAC. */
122+export async function issueKey(
123+ state: KeyState,
124+ secret: string,
125+ agent: string,
126+ by: string,
127+ now: number,
128+ address: string,
129+ expires: number,
130+ role: KeyRole,
131+): Promise<Issued> {
132+ const made = newKey();
133+ const addr = await hmac(secret, address);
134+ state.rows.push({
135+ id: made.id,
136+ hmac: await hmac(secret, made.key),
137+ agent,
138+ issuedBy: by,
139+ at: now,
140+ lastUsed: null,
141+ revokedAt: null,
142+ expiresAt: expires,
143+ role,
144+ });
145+ note(state, { t: now, kind: "issue", id: made.id, addr });
146+ return { id: made.id, key: made.key, agent };
147+}
149+export function revokeKey(state: KeyState, id: string, now: number, addr: string): boolean {
150+ const row = state.rows.find((r) => r.id === id);
151+ if (!row || row.revokedAt !== null) return false;
152+ row.revokedAt = now;
153+ note(state, { t: now, kind: "revoke", id, addr });
154+ return true;
155+}
157+export function listKeys(state: KeyState, agent?: string) {
158+ return state.rows
159+ .filter((r) => agent === undefined || r.agent === agent)
160+ .map(({ id, agent: a, issuedBy, at, lastUsed, revokedAt, expiresAt: exp, role }) => ({
161+ id,
162+ agent: a,
163+ role: role ?? "reader",
164+ issuedBy,
165+ at,
166+ lastUsed,
167+ revokedAt,
168+ expiresAt: exp ?? null,
169+ }));
170+}
172+export type KeyDecision =
173+ | { ok: true; id: string; as: string; role: KeyRole; dirty: boolean }
174+ | { ok: false; status: number; error: string; dirty: boolean };
176+/**
177+ * Checks a presented key against one project. The URL's agent must match the key's agent: a mismatch is a 403, and
178+ * the agent is not rewritten. A missing secret is a 503 that names no key. Failures are counted per address and
179+ * slowed after a few. Nothing returned or recorded contains the key.
180+ */
181+export async function checkKey(
182+ state: KeyState,
183+ secret: string | undefined,
184+ presented: string,
185+ agent: string | undefined,
186+ now: number,
187+ address: string,
188+): Promise<KeyDecision> {
189+ if (!secret) return { ok: false, status: 503, error: "the key secret (KEY_HMAC_SECRET) is not set", dirty: false };
190+ const addr = await hmac(secret, address);
191+ const fail = state.fails[addr];
192+ if (fail && now - fail.at < FAIL_WINDOW_MS && fail.n >= FAIL_LIMIT) {
193+ return { ok: false, status: 429, error: "too many failed keys; try again shortly", dirty: false };
194+ }
195+ const mac = await hmac(secret, presented);
196+ const row = state.rows.find((r) => timingSame(r.hmac, mac));
197+ const bump = () => {
198+ const cur = state.fails[addr];
199+ state.fails[addr] = !cur || now - cur.at >= FAIL_WINDOW_MS ? { n: 1, at: now } : { n: cur.n + 1, at: cur.at };
200+ note(state, { t: now, kind: "fail", id: row?.id ?? null, addr });
201+ };
202+ if (!row || row.revokedAt !== null || (row.expiresAt != null && now >= row.expiresAt)) {
203+ bump();
204+ const error = !row
205+ ? "that key is not for this project"
206+ : row.revokedAt !== null
207+ ? "that key was revoked"
208+ : "that key has expired";
209+ return { ok: false, status: 403, error, dirty: true };
210+ }
211+ if (agent !== undefined && row.agent !== agent) {
212+ bump();
213+ return { ok: false, status: 403, error: "that key is not for this agent", dirty: true };
214+ }
215+ let dirty = false;
216+ if (state.fails[addr]) {
217+ delete state.fails[addr];
218+ dirty = true;
219+ }
220+ if (state.seen[row.id] !== addr) {
221+ state.seen[row.id] = addr;
222+ note(state, { t: now, kind: "use", id: row.id, addr });
223+ dirty = true;
224+ }
225+ if (row.lastUsed === null || now - row.lastUsed >= 60_000) {
226+ row.lastUsed = now;
227+ dirty = true;
228+ }
229+ return { ok: true, id: row.id, as: `key ${row.id}`, role: row.role ?? "reader", dirty };
230+}
232+/** Project routes only an owner's key may use, whatever the method. */
233+const OWNER_ONLY = new Set(["git-remote", "git-sync", "export"]);
235+/**
236+ * Whether a key's role allows a request. A reader only reads. A writer also writes, but only on its own agent's
237+ * routes (/a/:agent/..., where checkKey has matched the agent), and blob uploads, which a record needs. Owner-only
238+ * routes need an owner's key.
239+ */
240+export function keyAllows(
241+ role: KeyRole,
242+ request: { write: boolean; agent: string | undefined; route: string | undefined; method?: string },
243+): { ok: true } | { ok: false; status: number; error: string } {
244+ if (role === "owner") return { ok: true };
245+ if (request.route !== undefined && OWNER_ONLY.has(request.route))
246+ return { ok: false, status: 403, error: `${request.route} needs an owner's key` };
247+ if (!request.write) return { ok: true };
248+ if (role === "reader") return { ok: false, status: 403, error: "this key only reads" };
249+ if (request.method === "PUT" && /^blobs\/[0-9a-f]{64}$/.test(request.route ?? "")) return { ok: true };
250+ if (request.agent === undefined)
251+ return { ok: false, status: 403, error: "a writer's key writes only on its own agent's routes" };
252+ return { ok: true };
253+}
--- /dev/null
+++ b/server/src/memory-fs.ts
@@ -0,0 +1,235 @@
1+// From Cloudflare's isomorphic-git example, with fixes isomorphic-git 1.43
2+// needs: errors carry .code (isomorphic-git checks err.code === "ENOENT"),
3+// stats are plain fields it can normalize in place, and the executable bit
4+// and symbolic links are kept (#27), so a checkout of a repo with either works.
5+
6+function fsError(code: string, path: string): Error {
7+ return Object.assign(new Error(`${code}: ${path}`), { code });
8+}
9+
10+type Entry =
11+ | { kind: "dir"; children: Set<string>; mtimeMs: number }
12+ | { kind: "file"; data: Uint8Array; exec: boolean; mtimeMs: number }
13+ | { kind: "link"; target: string; mtimeMs: number };
15+const enc = new TextEncoder();
17+/** Plain fields, not getters: isomorphic-git writes to them when it normalizes stats. */
18+class MemoryStats {
19+ size: number;
20+ mtimeMs: number;
21+ ctimeMs: number;
22+ mode: number;
23+ private kind: Entry["kind"];
25+ constructor(entry: Entry) {
26+ this.kind = entry.kind;
27+ this.size =
28+ entry.kind === "file" ? entry.data.byteLength : entry.kind === "link" ? enc.encode(entry.target).byteLength : 0;
29+ this.mtimeMs = entry.mtimeMs;
30+ this.ctimeMs = entry.mtimeMs;
31+ this.mode = entry.kind === "dir" ? 0o040000 : entry.kind === "link" ? 0o120000 : entry.exec ? 0o100755 : 0o100644;
32+ }
34+ isFile() {
35+ return this.kind === "file";
36+ }
38+ isDirectory() {
39+ return this.kind === "dir";
40+ }
42+ isSymbolicLink() {
43+ return this.kind === "link";
44+ }
45+}
47+export class MemoryFS {
48+ encoder = new TextEncoder();
49+ decoder = new TextDecoder();
50+ entries = new Map<string, Entry>([["/", { kind: "dir", children: new Set(), mtimeMs: Date.now() }]]);
52+ promises = {
53+ readFile: this.readFile.bind(this),
54+ writeFile: this.writeFile.bind(this),
55+ unlink: this.unlink.bind(this),
56+ readdir: this.readdir.bind(this),
57+ mkdir: this.mkdir.bind(this),
58+ rmdir: this.rmdir.bind(this),
59+ stat: this.stat.bind(this),
60+ lstat: this.lstat.bind(this),
61+ readlink: this.readlink.bind(this),
62+ symlink: this.symlink.bind(this),
63+ chmod: this.chmod.bind(this),
64+ };
66+ normalize(input: string) {
67+ const segments: string[] = [];
69+ for (const part of input.split("/")) {
70+ if (!part || part === ".") {
71+ continue;
72+ }
74+ if (part === "..") {
75+ segments.pop();
76+ continue;
77+ }
79+ segments.push(part);
80+ }
82+ return `/${segments.join("/")}` || "/";
83+ }
85+ parent(path: string) {
86+ const normalized = this.normalize(path);
87+ if (normalized === "/") {
88+ return "/";
89+ }
91+ const parts = normalized.split("/").filter(Boolean);
92+ parts.pop();
93+ return parts.length ? `/${parts.join("/")}` : "/";
94+ }
96+ basename(path: string) {
97+ return this.normalize(path).split("/").filter(Boolean).pop() ?? "";
98+ }
100+ getEntry(path: string) {
101+ return this.entries.get(this.normalize(path));
102+ }
104+ requireEntry(path: string) {
105+ const entry = this.getEntry(path);
106+ if (!entry) {
107+ throw fsError("ENOENT", path);
108+ }
110+ return entry;
111+ }
113+ requireDir(path: string) {
114+ const entry = this.requireEntry(path);
115+ if (entry.kind !== "dir") {
116+ throw fsError("ENOTDIR", path);
117+ }
119+ return entry;
120+ }
122+ async mkdir(path: string, options?: { recursive?: boolean } | number) {
123+ const target = this.normalize(path);
124+ if (target === "/") {
125+ return;
126+ }
128+ const recursive = typeof options === "object" && options !== null && options.recursive;
129+ const parent = this.parent(target);
131+ if (!this.entries.has(parent)) {
132+ if (!recursive) {
133+ throw fsError("ENOENT", parent);
134+ }
136+ await this.mkdir(parent, { recursive: true });
137+ }
139+ if (this.entries.has(target)) {
140+ return;
141+ }
143+ this.entries.set(target, {
144+ kind: "dir",
145+ children: new Set(),
146+ mtimeMs: Date.now(),
147+ });
149+ this.requireDir(parent).children.add(this.basename(target));
150+ }
152+ /** options.mode with any execute bit (isomorphic-git passes 0o777 for 100755) makes the file executable. */
153+ async writeFile(path: string, data: string | Uint8Array | ArrayBuffer, options?: string | { mode?: number }) {
154+ const target = this.normalize(path);
155+ await this.mkdir(this.parent(target), { recursive: true });
157+ const bytes =
158+ typeof data === "string" ? this.encoder.encode(data) : data instanceof Uint8Array ? data : new Uint8Array(data);
159+ const mode = typeof options === "object" && options !== null ? options.mode : undefined;
161+ this.entries.set(target, {
162+ kind: "file",
163+ data: bytes,
164+ exec: mode !== undefined && (mode & 0o111) !== 0,
165+ mtimeMs: Date.now(),
166+ });
168+ this.requireDir(this.parent(target)).children.add(this.basename(target));
169+ }
171+ async readFile(path: string, options?: string | { encoding?: string }) {
172+ const entry = this.requireEntry(path);
173+ if (entry.kind === "dir") {
174+ throw fsError("EISDIR", path);
175+ }
177+ const data = entry.kind === "link" ? this.encoder.encode(entry.target) : entry.data;
178+ const encoding = typeof options === "string" ? options : options?.encoding;
179+ return encoding ? this.decoder.decode(data) : data;
180+ }
182+ async readdir(path: string) {
183+ return [...this.requireDir(path).children].sort();
184+ }
186+ async unlink(path: string) {
187+ const target = this.normalize(path);
188+ const entry = this.requireEntry(target);
189+ if (entry.kind === "dir") {
190+ throw fsError("EISDIR", path);
191+ }
193+ this.entries.delete(target);
194+ this.requireDir(this.parent(target)).children.delete(this.basename(target));
195+ }
197+ async rmdir(path: string) {
198+ const target = this.normalize(path);
199+ const entry = this.requireDir(target);
200+ if (entry.children.size > 0) {
201+ throw fsError("ENOTEMPTY", path);
202+ }
204+ this.entries.delete(target);
205+ this.requireDir(this.parent(target)).children.delete(this.basename(target));
206+ }
208+ async stat(path: string) {
209+ return new MemoryStats(this.requireEntry(path));
210+ }
212+ /** Links aren't followed anywhere here, so lstat and stat agree. */
213+ async lstat(path: string) {
214+ return this.stat(path);
215+ }
217+ async readlink(path: string): Promise<string> {
218+ const entry = this.requireEntry(path);
219+ if (entry.kind !== "link") throw fsError("EINVAL", path);
220+ return entry.target;
221+ }
223+ async symlink(target: string, path: string): Promise<void> {
224+ const at = this.normalize(path);
225+ if (this.entries.has(at)) throw fsError("EEXIST", path);
226+ await this.mkdir(this.parent(at), { recursive: true });
227+ this.entries.set(at, { kind: "link", target, mtimeMs: Date.now() });
228+ this.requireDir(this.parent(at)).children.add(this.basename(at));
229+ }
231+ async chmod(path: string, mode: number): Promise<void> {
232+ const entry = this.requireEntry(path);
233+ if (entry.kind === "file") entry.exec = (mode & 0o111) !== 0;
234+ }
235+}
--- /dev/null
+++ b/server/src/project-object.ts
@@ -0,0 +1,534 @@
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 { type Answer, answer, type Readers } from "../../worker/project/http.ts";
8+import type { ProjectCalls, ProjectHistory } from "../../worker/project/project-api.ts";
9+import { BLOB_MAX, BlobStore } from "./blobs.ts";
10+import { EngineProject, SqliteLog } from "./engine-project.ts";
11+import { artifactsOf, type Env } from "./env.ts";
12+import { pushedSince, remoteHead } from "./ingest.ts";
13+import {
14+ checkKey,
15+ emptyKeyState,
16+ expiresAt,
17+ hmac,
18+ issueKey,
19+ type KeyRole,
20+ type KeyState,
21+ keyAllows,
22+ listKeys,
23+ revokeKey,
24+} from "./keys.ts";
25+import { type PushResult, pushShared, repoName } from "./push.ts";
27+/** At most one push out a minute: each one clones the repo, so publishes in a burst share one. */
28+export const PUSH_EVERY_MS = 60_000;
29+/** While agents are working, how often a call looks for plain-git pushes to the repo. */
30+const GIT_CHECK_MS = 15_000;
32+/**
33+ * The load guard (platform issue 46): an estimate of a loaded project's memory from its log entries, lines and claim
34+ * keys, all read from SQLite without loading. A Durable Object has 128 MB. Past the hard cap a project refuses to
35+ * load (export still reads it); past the soft cap, new work is held so the hard cap is never reached.
36+ */
37+const LOAD_BYTES_PER_ENTRY = 1_200;
38+const LOAD_BYTES_PER_LINE = 20;
39+const LOAD_BYTES_PER_KEY = 20;
40+const LOAD_BASE_BYTES = 10_000_000;
41+const LOAD_MAX_BYTES = 114_000_000;
42+const LOAD_SOFT_BYTES = 94_800_000;
43+/** Before its lines are counted, a log over this many characters refuses to load. */
44+const LOG_LOAD_MAX_CHARS = 12_000_000;
45+/** The ops the soft cap holds: the ones that bring new work into the history. */
46+const SOFT_HELD_OPS: ReadonlySet<string> = new Set(["record", "edit", "publish", "land", "amend", "pluck", "drop"]);
48+export function loadEstimate(entries: number, lines: number, keys: number): number {
49+ return entries * LOAD_BYTES_PER_ENTRY + lines * LOAD_BYTES_PER_LINE + keys * LOAD_BYTES_PER_KEY + LOAD_BASE_BYTES;
50+}
52+/** A presented agent key, checked inside the call so the check and the call are one trip. */
53+export interface KeyForCall {
54+ presented: string;
55+ address: string;
56+ write: boolean;
57+ route: string | undefined;
58+}
60+/** A news item from the issues code: delivered as an announcement from its writer. */
61+export interface IssueNews {
62+ from: string;
63+ issue: number | null;
64+ text: string;
65+ to?: string[];
66+}
68+/** What the issues Durable Object hears when a start note naming an issue begins and ends. Each is optional. */
69+interface IssueHooks {
70+ claim?(agent: string, issue: number, change: number): Promise<unknown>;
71+ unclaim?(agent: string, issue: number): Promise<unknown>;
72+ done?(agent: string, issue: number, version: number): Promise<unknown>;
73+}
75+export class ProjectObject extends DurableObject<Env> {
76+ private blobs: BlobStore;
77+ private loaded: ProjectCalls | undefined;
78+ /** Why the log didn't load, if it didn't. */
79+ private loadError: unknown;
80+ private tried = false;
81+ /** Feed long-polls waiting for the log to grow; woken after every call that wrote. */
82+ private waiting: (() => void)[] = [];
83+ /** When this object last asked the repo for pushes made with plain git. */
84+ private gitCheckedAt = 0;
85+ private gitSyncing: Promise<{ head: string; commits: number; answer: unknown } | null> | undefined;
87+ constructor(ctx: DurableObjectState, env: Env) {
88+ super(ctx, env);
89+ this.blobs = new BlobStore(ctx.storage);
90+ }
92+ /** Where files kept whole go: the project's blob store. */
93+ private wholeFiles() {
94+ return { keep: (text: string) => this.blobs.putText(text), read: (sha: string) => this.blobs.textOf(sha) };
95+ }
97+ /** The project, loaded from its log on first use. A log too big for memory is refused, not loaded. */
98+ private ensure(): ProjectCalls | undefined {
99+ if (this.loaded || this.tried) return this.loaded;
100+ this.tried = true;
101+ try {
102+ const why = this.tooBigToLoad();
103+ if (why) throw new Error(`${why}, too big to load in a Durable Object's memory; GET export still reads it`);
104+ this.loaded = EngineProject.open(this.ctx.storage, (sha) => this.blobs.has(sha), this.wholeFiles());
105+ } catch (e) {
106+ this.loadError = e;
107+ }
108+ return this.loaded;
109+ }
111+ private get project(): ProjectCalls {
112+ const p = this.ensure();
113+ if (!p) throw this.loadError;
114+ return p;
115+ }
117+ private logChars(): { chars: number; entries: number } {
118+ const tables = this.ctx.storage.sql
119+ .exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'log'")
120+ .toArray();
121+ return tables.length === 0 ? { chars: 0, entries: 0 } : new SqliteLog(this.ctx.storage).logSize();
122+ }
124+ private sizes(): { lines: number; keys: number } | undefined {
125+ if (this.logChars().entries === 0) return undefined;
126+ try {
127+ return new SqliteLog(this.ctx.storage).countSizes();
128+ } catch {
129+ return undefined;
130+ }
131+ }
133+ /** Why recording new work is held: the estimate is past the soft cap; else null. */
134+ private softHeld(): string | null {
135+ const counted = this.sizes();
136+ if (counted === undefined) return null;
137+ const bytes = loadEstimate(this.logChars().entries, counted.lines, counted.keys);
138+ return bytes > LOAD_SOFT_BYTES
139+ ? `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`
140+ : null;
141+ }
143+ /** Why this project mustn't load: its estimated memory, or before its lines are counted, its log's size; else null. */
144+ private tooBigToLoad(): string | null {
145+ const counted = this.sizes();
146+ if (counted !== undefined) {
147+ const bytes = loadEstimate(this.logChars().entries, counted.lines, counted.keys);
148+ return bytes > LOAD_MAX_BYTES
149+ ? `this project holds ${counted.lines} lines and ${this.logChars().entries} entries, an estimated ${(bytes / 1e6).toFixed(0)} MB once loaded`
150+ : null;
151+ }
152+ const { chars } = this.logChars();
153+ return chars > LOG_LOAD_MAX_CHARS ? `this project's log is ${(chars / 1e6).toFixed(1)} MB` : null;
154+ }
156+ // Blobs: binary files' bytes, named by their SHA-256.
158+ async putBlob(sha: string, body: ReadableStream<Uint8Array>): Promise<Answer> {
159+ const a = await this.blobs.put(sha, body);
160+ // A push out waiting on missing blobs goes again now.
161+ if (a.status === 200 && (await this.ctx.storage.get("pushError"))) await this.ctx.storage.setAlarm(Date.now());
162+ return a;
163+ }
165+ async getBlob(sha: string): Promise<ReadableStream<Uint8Array> | null> {
166+ return this.blobs.stream(sha);
167+ }
169+ /** Shared's newest version, from storage alone, never loading the project. Null when there's no project. */
170+ async head(): Promise<{ version: number; at: string } | null> {
171+ if (this.logChars().entries === 0) return null;
172+ return { version: new SqliteLog(this.ctx.storage).sharedVersion(), at: new Date().toISOString() };
173+ }
175+ /** Backups: one page of the log as JSON lines. It works even when the log won't load. */
176+ async exportLog(from: number, limit: number): Promise<{ lines: string; next: number | null } | null> {
177+ if (this.logChars().entries === 0) return null;
178+ const { texts, next } = new SqliteLog(this.ctx.storage).page(from, limit);
179+ return { lines: texts.map((t) => `${t}\n`).join(""), next };
180+ }
182+ private wake(): void {
183+ const all = this.waiting;
184+ this.waiting = [];
185+ for (const w of all) w();
186+ }
188+ /**
189+ * GET feed?from=&wait=<seconds, up to 25>: when nothing is new, hold the call until an entry is written or the wait
190+ * ends, then answer as usual.
191+ */
192+ private async feed(name: string, body: unknown): Promise<Answer> {
193+ const q = (body ?? {}) as Record<string, string | undefined>;
194+ const wait = Math.min(25, Math.max(0, Number(q.wait) || 0));
195+ const first = await this.call(name, "feed", undefined, body, true);
196+ const from = Number(q.from) || 0;
197+ const empty = first.status === 200 && (first.body as { next: number }).next <= from;
198+ if (!empty || wait === 0) return first;
199+ await new Promise<void>((resolve) => {
200+ const timer = setTimeout(resolve, wait * 1000);
201+ this.waiting.push(() => {
202+ clearTimeout(timer);
203+ resolve();
204+ });
205+ });
206+ return this.call(name, "feed", undefined, body, true);
207+ }
209+ /** One project call: the agent key (if any), the size caps, then answer() from worker/project/http.ts. */
210+ async call(
211+ name: string,
212+ op: string,
213+ agent: string | undefined,
214+ body: unknown,
215+ inFeed = false,
216+ how?: string,
217+ key?: KeyForCall,
218+ ): Promise<Answer> {
219+ if (key) {
220+ const decided = await this.checkAgentKey(key.presented, agent, key.address);
221+ if (!decided.ok) return { status: decided.status, body: { error: decided.error } };
222+ const allowed = keyAllows(decided.role, { write: key.write, agent, route: key.route });
223+ if (!allowed.ok) return { status: allowed.status, body: { error: allowed.error } };
224+ how = decided.as;
225+ }
226+ if (op === "feed" && !inFeed) return this.feed(name, body);
227+ if (SOFT_HELD_OPS.has(op)) {
228+ const held = this.softHeld();
229+ if (held) return { status: 507, body: { error: held } };
230+ }
231+ const loaded = this.ensure();
232+ if (!loaded) {
233+ const why = this.loadError instanceof Error ? this.loadError.message : String(this.loadError);
234+ return { status: 507, body: { error: `the project's log did not load: ${why}` } };
235+ }
236+ // Readers live in storage, not the log: a refused call writes nothing, so replay never needs them.
237+ const list = new Set((await this.ctx.storage.get<string[]>("readers")) ?? []);
238+ let changed = false;
239+ const readers: Readers = {
240+ has: (a) => list.has(a),
241+ set: (a, on) => {
242+ if (on === list.has(a)) return;
243+ if (on) list.add(a);
244+ else list.delete(a);
245+ changed = true;
246+ },
247+ list: () => [...list].sort(),
248+ };
249+ const before = loaded.exists() ? loaded.shared().version : -1;
250+ const logLength = () => (this.loaded as { logLength?: () => number } | undefined)?.logLength?.() ?? 0;
251+ const entriesBefore = logLength();
252+ const a = answer(loaded, op, agent, body, readers, how);
253+ if (changed) await this.ctx.storage.put("readers", readers.list());
254+ if (logLength() !== entriesBefore) this.wake();
255+ if (a.status === 200 && op === "starting") a.body = await this.startingHooks(name, a.body);
256+ if (a.status === 200) a.body = this.withBlobSizes(op, a.body);
257+ const after = loaded.exists() ? loaded.shared().version : -1;
258+ if (a.status === 200 && after >= 0 && (op === "init" || after > before)) {
259+ // A new version of shared: push it out to Artifacts in the background. The alarm retries; the call never waits.
260+ await this.ctx.storage.put("name", name);
261+ if (artifactsOf(this.env)) await this.ctx.storage.setAlarm(Date.now());
262+ } else if (
263+ a.status === 200 &&
264+ artifactsOf(this.env) &&
265+ Date.now() - this.gitCheckedAt > GIT_CHECK_MS &&
266+ (await this.ctx.storage.get("name")) !== undefined &&
267+ (await this.ctx.storage.getAlarm()) === null
268+ ) {
269+ // While agents are working, the alarm also looks for plain-git pushes.
270+ await this.ctx.storage.setAlarm(Date.now());
271+ }
272+ return a;
273+ }
275+ /**
276+ * The engine's starting answer carries hooks for the issues code (a start note naming an issue began or ended). They
277+ * go to the project's IssueProject, and never to the client. A failed hook is logged and never fails the call.
278+ */
279+ private async startingHooks(name: string, body: unknown): Promise<unknown> {
280+ const { hooks, ...rest } = body as {
281+ hooks?: {
282+ claim?: { issue: number; agent: string; change: number };
283+ unclaim?: { issue: number; agent: string; change: number; done?: boolean; version?: number };
284+ };
285+ };
286+ if (!hooks) return body;
287+ const issues = this.env.ISSUES_DO.get(this.env.ISSUES_DO.idFromName(name)) as unknown as IssueHooks;
288+ const tell = async (what: string, call: () => Promise<unknown> | undefined) => {
289+ try {
290+ await call();
291+ } catch (e) {
292+ console.log(JSON.stringify({ event: "issues-hook", what, project: name, error: String(e).slice(0, 200) }));
293+ }
294+ };
295+ const end = hooks.unclaim;
296+ if (end?.done && end.version !== undefined) {
297+ const version = end.version;
298+ await tell("done", () => issues.done?.(end.agent, end.issue, version));
299+ } else if (end) await tell("unclaim", () => issues.unclaim?.(end.agent, end.issue));
300+ const claim = hooks.claim;
301+ if (claim) await tell("claim", () => issues.claim?.(claim.agent, claim.issue, claim.change));
302+ return rest;
303+ }
305+ /** A folder's binary files count by their bytes, and a binary file says its size: the blob store knows both. */
306+ private withBlobSizes(op: string, body: unknown): unknown {
307+ if (op === "tree" && Array.isArray((body as { entries?: unknown }).entries)) {
308+ const b = body as { entries: { bytes?: number; blobs?: string[] }[] };
309+ return {
310+ ...b,
311+ entries: b.entries.map(({ blobs, ...e }) =>
312+ blobs ? { ...e, bytes: (e.bytes ?? 0) + blobs.reduce((n, sha) => n + this.blobs.size(sha), 0) } : e,
313+ ),
314+ };
315+ }
316+ if (op === "file" && typeof (body as { blob?: unknown }).blob === "string")
317+ return { ...(body as object), size: this.blobs.size((body as { blob: string }).blob) };
318+ return body;
319+ }
321+ // The push out to Artifacts, and plain-git pushes back in.
323+ /**
324+ * Takes in commits pushed to the project's repo with plain git: the ones above the server's last commit that
325+ * haven't been taken in yet. One run at a time; a call while a run is going gets that run's answer.
326+ */
327+ gitSync(): Promise<{ head: string; commits: number; answer: unknown } | null> {
328+ this.gitSyncing ??= this.gitSyncOnce().finally(() => {
329+ this.gitSyncing = undefined;
330+ });
331+ return this.gitSyncing;
332+ }
334+ private async gitSyncOnce(): Promise<{ head: string; commits: number; answer: unknown } | null> {
335+ const artifacts = artifactsOf(this.env);
336+ if (!artifacts) return null;
337+ this.gitCheckedAt = Date.now();
338+ const name = await this.ctx.storage.get<string>("name");
339+ if (!name || !this.project.exists()) return null;
340+ const seen = await this.ctx.storage.get<string>("git:head");
341+ const pushed = await this.ctx.storage.get<PushResult>("pushed");
342+ const head = await remoteHead(artifacts, name);
343+ if (!head || head === seen || head === pushed?.commit) return null;
344+ const sharedBlobs = this.project.shared().blobs ?? {};
345+ const found = await pushedSince(
346+ artifacts,
347+ name,
348+ seen,
349+ async (bytes) => (bytes.byteLength > BLOB_MAX ? null : this.blobs.putBytes(bytes)),
350+ (path) => sharedBlobs[path],
351+ );
352+ if (!found || found.commits.length === 0) {
353+ if (found) await this.ctx.storage.put("git:head", found.head);
354+ return null;
355+ }
356+ let result: unknown;
357+ try {
358+ result = this.project.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now());
359+ } catch (e) {
360+ result = { error: e instanceof Error ? e.message : String(e) };
361+ }
362+ const taken = {
363+ at: new Date().toISOString(),
364+ head: found.head,
365+ commits: found.commits.length,
366+ answer: result,
367+ ...(found.tooBig.length ? { tooBig: found.tooBig } : {}),
368+ };
369+ await this.ctx.storage.put({ "git:head": found.head, "git:last": taken });
370+ this.wake();
371+ if ((result as { landed?: boolean }).landed) await this.ctx.storage.setAlarm(Date.now());
372+ return taken;
373+ }
375+ /** Sets the alarm for `at` unless one is due sooner. */
376+ private async soon(at: number): Promise<void> {
377+ const now = await this.ctx.storage.getAlarm();
378+ if (now === null || now > at) await this.ctx.storage.setAlarm(at);
379+ }
381+ /**
382+ * Plain-git pushes in first, so the push out builds on them; then shared out to the project's Artifacts repo, at
383+ * most once a minute, backing off on failure. Without an ARTIFACTS binding (local dev) it does nothing.
384+ */
385+ async alarm(): Promise<void> {
386+ const artifacts = artifactsOf(this.env);
387+ if (!artifacts) return;
388+ const name = await this.ctx.storage.get<string>("name");
389+ if (!name || !this.ensure()?.exists()) return;
390+ await this.gitSync().then(
391+ () => this.ctx.storage.delete("git:error"),
392+ (e) =>
393+ this.ctx.storage.put("git:error", {
394+ at: new Date().toISOString(),
395+ error: e instanceof Error ? e.message : String(e),
396+ }),
397+ );
398+ const shared = this.project.shared();
399+ const done = await this.ctx.storage.get<PushResult>("pushed");
400+ if (done && done.version >= shared.version) return;
401+ const pushedAt = (await this.ctx.storage.get<number>("pushedAt")) ?? 0;
402+ if (Date.now() - pushedAt < PUSH_EVERY_MS) {
403+ await this.soon(pushedAt + PUSH_EVERY_MS);
404+ return;
405+ }
406+ let result: PushResult;
407+ try {
408+ result = await pushShared(artifacts, name, shared, (sha) => this.blobs.read(sha));
409+ } catch (e) {
410+ // Kept for /out, and tried again with a backoff of our own (a thrown alarm is retried only six times).
411+ const was = await this.ctx.storage.get<{ attempts?: number }>("pushError");
412+ const attempts = (was?.attempts ?? 0) + 1;
413+ await this.ctx.storage.put("pushError", {
414+ version: shared.version,
415+ at: new Date().toISOString(),
416+ attempts,
417+ error: e instanceof Error ? e.message : String(e),
418+ });
419+ await this.soon(Date.now() + Math.min(10 * 60_000, 15_000 * 2 ** Math.min(attempts - 1, 6)));
420+ return;
421+ }
422+ await this.ctx.storage.put({ pushed: result, "git:head": result.commit, pushedAt: Date.now() });
423+ await this.ctx.storage.delete("pushError");
424+ // Another publish may have landed while this push ran.
425+ if (this.project.shared().version > result.version) await this.soon(Date.now() + PUSH_EVERY_MS);
426+ }
428+ /** The push out: the repo, the last version pushed, and plain-git intake. */
429+ async out() {
430+ const name = await this.ctx.storage.get<string>("name");
431+ const p = this.ensure();
432+ return {
433+ repo: name ? repoName(name) : null,
434+ artifacts: artifactsOf(this.env) ? "bound" : "unbound",
435+ version: p?.exists() ? p.shared().version : null,
436+ pushed: (await this.ctx.storage.get<PushResult>("pushed")) ?? null,
437+ error: (await this.ctx.storage.get("pushError")) ?? null,
438+ git: {
439+ head: (await this.ctx.storage.get<string>("git:head")) ?? null,
440+ last: (await this.ctx.storage.get("git:last")) ?? null,
441+ error: (await this.ctx.storage.get("git:error")) ?? null,
442+ },
443+ };
444+ }
446+ // Per-agent keys: the HMACs live here, one project's keys per object.
448+ private async keyState(): Promise<KeyState> {
449+ return (await this.ctx.storage.get<KeyState>("agent-keys")) ?? emptyKeyState();
450+ }
452+ async checkAgentKey(presented: string, agent: string | undefined, address: string) {
453+ const state = await this.keyState();
454+ const decided = await checkKey(state, this.env.KEY_HMAC_SECRET, presented, agent, Date.now(), address);
455+ if (decided.dirty) await this.ctx.storage.put("agent-keys", state);
456+ if (!decided.ok) return decided;
457+ const row = state.rows.find((r) => r.id === decided.id);
458+ return { ...decided, agent: row?.agent ?? "" };
459+ }
461+ /** Issues a key. The returned key is the only copy. */
462+ async issueAgentKey(
463+ agent: string,
464+ address: string,
465+ expiresRaw: string | null,
466+ role: KeyRole,
467+ ): Promise<{ id: string; key: string; agent: string } | { error: string }> {
468+ const secret = this.env.KEY_HMAC_SECRET;
469+ if (!secret) return { error: "the key secret (KEY_HMAC_SECRET) is not set" };
470+ const when = expiresAt(Date.now(), expiresRaw);
471+ if (typeof when !== "number") return { error: when.error };
472+ const state = await this.keyState();
473+ const issued = await issueKey(state, secret, agent, "admin", Date.now(), address, when, role);
474+ await this.ctx.storage.put("agent-keys", state);
475+ return issued;
476+ }
478+ async revokeAgentKey(id: string, address: string): Promise<{ revoked: boolean }> {
479+ const secret = this.env.KEY_HMAC_SECRET;
480+ if (!secret) return { revoked: false };
481+ const state = await this.keyState();
482+ const revoked = revokeKey(state, id, Date.now(), await hmac(secret, address));
483+ await this.ctx.storage.put("agent-keys", state);
484+ return { revoked };
485+ }
487+ async listAgentKeys(agent?: string) {
488+ return listKeys(await this.keyState(), agent);
489+ }
491+ // For the issues code (server/src/issues/).
493+ /** The project's agent names, for the ask seat check. None when there's no project. */
494+ async agents(_project: string): Promise<string[]> {
495+ const p = this.ensure();
496+ if (!p?.exists()) return [];
497+ return p.status().agents.map((a) => a.agent);
498+ }
500+ /**
501+ * Issues news, delivered through the engine's announce path: each item goes to the agents whose start note names
502+ * its issue and to the known agents in `to`, never back to its writer.
503+ */
504+ async news(_project: string, items: IssueNews[]): Promise<{ to: string[] }[]> {
505+ const p = this.ensure();
506+ if (!p?.exists()) return items.map(() => ({ to: [] }));
507+ const engine = p as ProjectCalls & ProjectHistory;
508+ const out: { to: string[] }[] = [];
509+ for (const item of items) {
510+ const status = p.status() as { agents: { agent: string; starting?: { issue?: number } }[] };
511+ const known = new Set(status.agents.map((a) => a.agent));
512+ const to = new Set([
513+ ...(item.issue !== null
514+ ? status.agents.filter((a) => a.starting?.issue === item.issue).map((a) => a.agent)
515+ : []),
516+ ...(item.to ?? []).filter((t) => known.has(t)),
517+ ]);
518+ to.delete(item.from);
519+ if (to.size === 0) {
520+ out.push({ to: [] });
521+ continue;
522+ }
523+ try {
524+ engine.announce(item.from, item.text, [...to]);
525+ out.push({ to: [...to] });
526+ } catch (e) {
527+ console.log(JSON.stringify({ event: "issues-news", error: String(e).slice(0, 200) }));
528+ out.push({ to: [] });
529+ }
530+ }
531+ this.wake();
532+ return out;
533+ }
534+}
--- /dev/null
+++ b/server/src/push.ts
@@ -0,0 +1,256 @@
1+// Out to Artifacts (#8): shared's files as one git commit on main of the
2+// project's repo, with the publish message and the agent as author. The repo
3+// is created on first use. isomorphic-git works in an in-memory filesystem:
4+// a depth-1 clone of main with nothing checked out, then a new tree from
5+// shared's files that compresses and writes only what changed (abso issue 293).
6+import git from "isomorphic-git";
7+import http from "isomorphic-git/http/web";
8+import type { FileModes } from "../../worker/project/project-api.ts";
9+import { MemoryFS } from "./memory-fs.ts";
11+export interface PushResult {
12+ repo: string;
13+ remote: string;
14+ commit: string;
15+ version: number;
16+ ms: number;
17+}
19+/** New blob bytes per push before the push out splits into parts: Artifacts refuses a push much over 20 MB. */
20+const PUSH_BATCH = 16 * 1024 * 1024;
22+/** A file as a tree entry holds it: its blob and its mode ("100644", "100755", "120000"). */
23+export interface TreeFile {
24+ oid: string;
25+ mode: string;
26+}
28+/** Every file in a tree, and every folder's tree oid ("" is the root), read from tree objects only. */
29+export async function readTreeFiles(
30+ fs: MemoryFS,
31+ dir: string,
32+ oid: string,
33+ prefix = "",
34+ files = new Map<string, TreeFile>(),
35+ trees = new Map<string, string>(),
36+): Promise<{ files: Map<string, TreeFile>; trees: Map<string, string> }> {
37+ trees.set(prefix, oid);
38+ const { tree } = await git.readTree({ fs, dir, oid });
39+ for (const e of tree) {
40+ const path = prefix === "" ? e.path : `${prefix}/${e.path}`;
41+ if (e.type === "tree") await readTreeFiles(fs, dir, e.oid, path, files, trees);
42+ else if (e.type === "blob") files.set(path, { oid: e.oid, mode: e.mode });
43+ }
44+ return { files, trees };
45+}
47+/**
48+ * A blob's git oid, with the platform's SHA-1 (abso issue 293): native and awaited, so hashing every file of a big
49+ * project neither burns the object's CPU in JavaScript nor holds its other requests back for long.
50+ */
51+export async function blobOid(bytes: Uint8Array): Promise<string> {
52+ const head = new TextEncoder().encode(`blob ${bytes.byteLength}\0`);
53+ const all = new Uint8Array(head.byteLength + bytes.byteLength);
54+ all.set(head);
55+ all.set(bytes, head.byteLength);
56+ const d = new Uint8Array(await crypto.subtle.digest("SHA-1", all));
57+ return [...d].map((b) => b.toString(16).padStart(2, "0")).join("");
58+}
60+const parentOf = (path: string) => {
61+ const cut = path.lastIndexOf("/");
62+ return cut < 0 ? "" : path.slice(0, cut);
63+};
65+/**
66+ * The tree for `files`, written bottom up. A folder with nothing changed under it keeps its old tree oid (`before`),
67+ * so only the folders on a changed path are written again.
68+ */
69+export async function writeTrees(
70+ fs: MemoryFS,
71+ dir: string,
72+ files: Map<string, TreeFile>,
73+ before: Map<string, string>,
74+ changed: Set<string>,
75+): Promise<string> {
76+ const dirty = new Set<string>([""]);
77+ for (const path of changed) for (let d = parentOf(path); d !== ""; d = parentOf(d)) dirty.add(d);
78+ type Entry = { mode: string; oid: string; type: "blob" | "tree" };
79+ const kids = new Map<string, Map<string, Entry>>([["", new Map()]]);
80+ const folder = (d: string) => {
81+ let k = kids.get(d);
82+ if (!k) {
83+ kids.set(d, (k = new Map()));
84+ if (d !== "") folder(parentOf(d));
85+ }
86+ return k;
87+ };
88+ for (const [path, f] of files)
89+ folder(parentOf(path)).set(path.slice(path.lastIndexOf("/") + 1), { ...f, type: "blob" });
90+ // Deepest first, so a folder's subfolders have their oids before it is written.
91+ const depth = (d: string) => (d === "" ? 0 : d.split("/").length);
92+ const order = [...kids.keys()].sort((a, b) => depth(b) - depth(a));
93+ let root = "";
94+ for (const d of order) {
95+ const old = before.get(d);
96+ const oid =
97+ old !== undefined && !dirty.has(d)
98+ ? old
99+ : await git.writeTree({ fs, dir, tree: [...kids.get(d)!].map(([path, e]) => ({ path, ...e })) });
100+ if (d === "") root = oid;
101+ else folder(parentOf(d)).set(d.slice(d.lastIndexOf("/") + 1), { mode: "040000", oid, type: "tree" });
102+ }
103+ return root;
104+}
106+/**
107+ * A project's Artifacts repo: abso-<project>. Project names are letters, digits, ".", "_" and "-" (validName), which
108+ * repo names take as they are.
109+ */
110+export function repoName(project: string): string {
111+ return `abso-${project}`;
112+}
114+/** The project one of our repos holds, or null for a repo that isn't ours. */
115+export function projectOfRepo(repo: string): string | null {
116+ return repo.startsWith("abso-") && repo.length > "abso-".length ? repo.slice("abso-".length) : null;
117+}
119+/** The repo's remote and a write token good for `seconds`, creating the repo if it's new. */
120+export async function writeAccess(
121+ artifacts: Artifacts,
122+ name: string,
123+ seconds = 600,
124+): Promise<{ remote: string; secret: string }> {
125+ try {
126+ using repo = await artifacts.get(name);
127+ const [info, token] = await Promise.all([repo.info(), repo.createToken("write", seconds)]);
128+ return { remote: info!.remote, secret: token.plaintext.split("?expires=")[0]! };
129+ } catch {
130+ const created = await artifacts.create(name, { description: `abso project ${name}`, setDefaultBranch: "main" });
131+ return { remote: created.remote, secret: created.token.split("?expires=")[0]! };
132+ }
133+}
135+export interface SharedFiles {
136+ version: number;
137+ files: Record<string, string>;
138+ modes?: FileModes;
139+ blobs?: Record<string, string>;
140+ last?: { agent: string; message: string };
141+}
143+/**
144+ * Shared's files as commits on top of `head` (null: a repo with no main yet), in the repo at `dir`. `part` is called
145+ * with each earlier part's commit when the new blobs are too big for one push. Answers the last commit and how many
146+ * paths changed.
147+ */
148+export async function commitShared(
149+ fs: MemoryFS,
150+ dir: string,
151+ head: string | null,
152+ shared: SharedFiles,
153+ readBlob: (sha256: string) => Uint8Array | null,
154+ part: (commit: string) => Promise<void> = async () => {},
155+): Promise<{ commit: string; changed: number }> {
156+ const old = head
157+ ? await readTreeFiles(fs, dir, (await git.readCommit({ fs, dir, oid: head })).commit.tree)
158+ : { files: new Map<string, TreeFile>(), trees: new Map<string, string>() };
159+ const blobs = shared.blobs ?? {};
160+ const now = new Map<string, TreeFile>();
161+ const changed = new Set<string>();
162+ for (const path of old.files.keys()) if (!(path in shared.files) && !(path in blobs)) changed.add(path);
163+ // A file whose blob and mode match the last push keeps its entry; only a new blob is compressed and written.
164+ const put = async (path: string, bytes: Uint8Array, mode: string, oid: string) => {
165+ const was = old.files.get(path);
166+ if (was?.oid !== oid) await git.writeBlob({ fs, dir, blob: bytes });
167+ if (was?.oid !== oid || was.mode !== mode) changed.add(path);
168+ now.set(path, { oid, mode });
169+ };
170+ // Each file goes into the tree as a blob with its mode (#27): 100755 for exec, 120000 for a link, whose blob is
171+ // its target.
172+ const enc = new TextEncoder();
173+ for (const [path, text] of Object.entries(shared.files)) {
174+ const mode = shared.modes?.[path];
175+ const link = typeof mode?.link === "string" ? mode.link : null;
176+ const bytes = enc.encode(link ?? text);
177+ await put(path, bytes, link !== null ? "120000" : mode?.exec ? "100755" : "100644", await blobOid(bytes));
178+ }
179+ const agent = shared.last?.agent ?? "abso";
180+ const author = { name: agent, email: `${agent}@abso.invalid` };
181+ const committer = { name: "abso", email: "abso@abso.invalid" };
182+ const say = (p: string) => `${shared.last?.message ?? "Start the project"}${p}\n\nabso-version: ${shared.version}\n`;
183+ let parent = head;
184+ // A part holds what's written so far, and the last push's entries for the binary files not reached yet.
185+ const commitNow = async (message: string) => {
186+ const files = new Map(now);
187+ for (const [path, f] of old.files) if (!files.has(path) && path in blobs) files.set(path, f);
188+ const tree = await writeTrees(fs, dir, files, old.trees, changed);
189+ parent = await git.commit({
190+ fs,
191+ dir,
192+ message,
193+ author,
194+ committer,
195+ tree,
196+ parent: parent ? [parent] : [],
197+ ref: "main",
198+ });
199+ return parent;
200+ };
201+ // Binary files (#27) aren't in files: their bytes come from the blob store.
202+ // Artifacts refuses a push much over 20 MB, so when the new blobs add up
203+ // to more than PUSH_BATCH, the earlier ones go in commits of their own
204+ // first. Every part carries abso-version, so intake never takes them in.
205+ let pending = 0;
206+ let parts = 0;
207+ for (const [path, sha] of Object.entries(blobs)) {
208+ const bytes = readBlob(sha);
209+ if (!bytes) throw new Error(`${path}: blob ${sha} is missing from the project's store`);
210+ const oid = await blobOid(bytes);
211+ const fresh = old.files.get(path)?.oid !== oid;
212+ if (fresh && pending > 0 && pending + bytes.byteLength > PUSH_BATCH) {
213+ await part(await commitNow(say(` (part ${++parts})`)));
214+ pending = 0;
215+ }
216+ if (fresh) pending += bytes.byteLength;
217+ await put(path, bytes, shared.modes?.[path]?.exec ? "100755" : "100644", oid);
218+ }
219+ const commit = await commitNow(say(parts > 0 ? ` (part ${parts + 1}, last)` : ""));
220+ return { commit, changed: changed.size };
221+}
223+export async function pushShared(
224+ artifacts: Artifacts,
225+ project: string,
226+ shared: SharedFiles,
227+ /** A binary file's bytes by SHA-256 (#27), from the project's blob store. */
228+ readBlob: (sha256: string) => Uint8Array | null = () => null,
229+): Promise<PushResult> {
230+ const t0 = Date.now();
231+ const name = repoName(project);
232+ const { remote, secret } = await writeAccess(artifacts, name);
233+ const onAuth = () => ({ username: "x", password: secret });
234+ let fs = new MemoryFS();
235+ const dir = "/repo";
236+ // A new repo has no main yet. isomorphic-git "clones" an empty repo without
237+ // an error but leaves HEAD on master, so check for main and start clean.
238+ // Nothing is checked out: the new tree is built from tree objects (293).
239+ const head = await git
240+ .clone({ fs, http, dir, url: remote, ref: "main", singleBranch: true, depth: 1, noCheckout: true, onAuth })
241+ .then(() => git.resolveRef({ fs, dir, ref: "main" }))
242+ .catch(() => null);
243+ if (head === null) {
244+ fs = new MemoryFS();
245+ await git.init({ fs, dir, defaultBranch: "main" });
246+ }
247+ const t1 = Date.now();
248+ const push = () => git.push({ fs, http, dir, url: remote, ref: "main", remoteRef: "main", onAuth });
249+ const { commit, changed } = await commitShared(fs, dir, head, shared, readBlob, async () => void (await push()));
250+ const t2 = Date.now();
251+ await push();
252+ console.log(
253+ `push ${project} v${shared.version}: clone ${t1 - t0} ms, files ${t2 - t1} ms (${changed} changed), push ${Date.now() - t2} ms`,
254+ );
255+ return { repo: name, remote, commit, version: shared.version, ms: Date.now() - t0 };
256+}
--- /dev/null
+++ b/server/src/router.ts
@@ -0,0 +1,299 @@
1+// The open server's router (index.ts is the Worker's entry). abso's open server: one Worker that anyone deploys to their own Cloudflare account (`cd server && npx wrangler
2+// deploy`). Every project is a Durable Object named by the project's name; its shared is pushed out to an Artifacts
3+// repo abso-<project>. The routes are the platform's core routes, so the stock client works against it:
4+//
5+// GET /version the deployed version's tag; no token needed
6+// /p/<project>/<read or init> init, status, log, show, file, blame, feed and the other reads (http.ts)
7+// /p/<project>/a/<agent>/<op> an agent's calls: record, publish, sync, draft, land, announce, ...
8+// GET /p/<project>/head shared's newest version, read from storage without loading the project
9+// PUT|GET /p/<project>/blobs/<sha256> a binary file's bytes; a PUT whose bytes don't hash to the name is refused
10+// GET /p/<project>/out the push out to Artifacts: repo, last version pushed, plain-git intake
11+// POST /p/<project>/git-remote the repo's remote and a write token good for an hour, for plain git
12+// POST /p/<project>/git-sync takes in commits pushed with plain git now (the alarm also does)
13+// GET /p/<project>/export?from=&limit= the log as JSON lines, for backups
14+// /issues/p/<project>/... issues, asks and news (issues-entry.ts)
15+// GET|POST /admin/agent-keys?project= per-agent keys: list, or issue (?agent=&role=&expires=); POST .../revoke?id=
16+//
17+// Every route but /version needs Authorization: Bearer <ABSO_TOKEN>, or an agent's key when AGENT_KEYS is on. With no
18+// ABSO_TOKEN set, the server refuses every call.
20+import { type Answer, validName } from "../../worker/project/http.ts";
21+import { artifactsOf, type Env, secret } from "./env.ts";
22+import type { IssuesAuth, issuesFetch } from "./issues-entry.ts";
23+import { isAgentKey, type KeyRole, keyAllows, keysEnabled, timingSame } from "./keys.ts";
24+import type { KeyForCall } from "./project-object.ts";
25+import { repoName, writeAccess } from "./push.ts";
27+const AGENT_OPS =
28+ "edit|record|publish|sync|draft|draft-sync|land|pluck|amend|diff|restore|drop|label|announce|news|note|note-close|move|starting|reader|files|status|unqueue";
29+const TOP_ROUTES =
30+ "init|status|head|out|export|blobs/[^/]+|git-sync|git-remote|blame|why|tree|path|follow|collisions|draft-state|where|feed|drafts|diff|ribbon|position|changes|notes|change/[0-9]{1,12}|refusals|labels|files|announce|log|show|file|compare|visibility|ci|queue";
32+/** A project's routes: the project, the top-level route, and an agent's name and op under /a/. */
33+export const PROJECT_ROUTE = new RegExp(`^/p/([^/]+)/(${TOP_ROUTES}|a/([^/]+)/(${AGENT_OPS}))$`);
34+/** Issues, asks and news: the project and the rest of the path, handed to the issues code. */
35+export const ISSUES_ROUTE = /^\/issues\/p\/([^/]+)(\/.*)?$/;
37+/** Routes answered here or by a direct object method, not through the project call. */
38+const DIRECT = new Set(["head", "out", "export", "git-remote", "git-sync", "ci", "queue", "visibility"]);
39+/** Reads whose query string is the call's body. */
40+const QUERY_READS = new Set([
41+ "status",
42+ "blame",
43+ "why",
44+ "tree",
45+ "path",
46+ "follow",
47+ "collisions",
48+ "draft-state",
49+ "refusals",
50+ "labels",
51+ "log",
52+ "show",
53+ "file",
54+ "files",
55+ "compare",
56+ "where",
57+ "feed",
58+ "drafts",
59+ "diff",
60+ "ribbon",
61+ "position",
62+ "changes",
63+ "notes",
64+]);
65+const SHA = /^[0-9a-f]{64}$/;
67+const json = (status: number, body: unknown) =>
68+ Response.json(body, { status, headers: { "cache-control": "no-store" } });
70+/** Whether two secrets match, in constant time whatever their lengths: their SHA-256 digests are compared. */
71+export async function sameSecret(a: string, b: string): Promise<boolean> {
72+ const digest = async (s: string) =>
73+ [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)))]
74+ .map((n) => n.toString(16).padStart(2, "0"))
75+ .join("");
76+ return timingSame(await digest(a), await digest(b));
77+}
79+export type Caller = { kind: "token" } | { kind: "key"; presented: string };
81+/**
82+ * Who is calling: the shared token, or an agent key to be checked by its project. A Response is a refusal. With no
83+ * shared token set, everything is refused.
84+ */
85+export async function authorize(request: Request, env: Env): Promise<Caller | Response> {
86+ const shared = secret(env, "TOKEN");
87+ if (!shared)
88+ return json(503, {
89+ error:
90+ "this server has no ABSO_TOKEN set, so it refuses every call; set one with npx wrangler secret put ABSO_TOKEN",
91+ });
92+ const presented = (request.headers.get("authorization") ?? "").replace(/^Bearer /, "");
93+ if (presented && isAgentKey(presented) && keysEnabled(env)) return { kind: "key", presented };
94+ if (presented && (await sameSecret(presented, shared))) return { kind: "token" };
95+ return json(401, { error: "missing or wrong token" });
96+}
98+/** The x-abso-admin header against ABSO_ADMIN_TOKEN, in constant time. */
99+async function isAdmin(request: Request, env: Env): Promise<boolean> {
100+ const token = secret(env, "ADMIN_TOKEN");
101+ const sent = request.headers.get("x-abso-admin") ?? request.headers.get("x-avcs-admin");
102+ return !!token && !!sent && (await sameSecret(sent, token));
103+}
105+const addressOf = (request: Request) => request.headers.get("cf-connecting-ip") ?? "unknown";
106+const projectObject = (env: Env, project: string) => env.PROJECT.get(env.PROJECT.idFromName(project));
108+/** Per-agent keys for one project: list (GET), issue (POST ?agent=&role=&expires=), revoke (POST .../revoke?id=). */
109+async function agentKeys(request: Request, env: Env, url: URL, caller: Caller): Promise<Response> {
110+ if (!keysEnabled(env))
111+ return json(404, { error: "agent keys are off here: AGENT_KEYS=on and KEY_HMAC_SECRET turn them on" });
112+ if (caller.kind !== "token") return json(401, { error: "missing or wrong token" });
113+ if (!(await isAdmin(request, env))) return json(403, { error: "agent keys need x-abso-admin: <the admin token>" });
114+ const project = url.searchParams.get("project") ?? "";
115+ if (!validName(project)) return json(400, { error: "agent keys need ?project=<name>" });
116+ const obj = projectObject(env, project);
117+ if (url.pathname === "/admin/agent-keys/revoke") {
118+ if (request.method !== "POST") return json(405, { error: "revoking a key is a POST" });
119+ return json(200, await obj.revokeAgentKey(url.searchParams.get("id") ?? "", addressOf(request)));
120+ }
121+ if (request.method === "GET")
122+ return json(200, { keys: await obj.listAgentKeys(url.searchParams.get("agent") ?? undefined) });
123+ if (request.method !== "POST") return json(405, { error: "agent keys take GET or POST" });
124+ const agent = url.searchParams.get("agent") ?? "";
125+ if (!validName(agent)) return json(400, { error: "issuing a key needs ?agent=<name>" });
126+ const role = url.searchParams.get("role") ?? "writer";
127+ if (role !== "owner" && role !== "writer" && role !== "reader")
128+ return json(400, { error: "role is owner, writer or reader" });
129+ const issued = await obj.issueAgentKey(agent, addressOf(request), url.searchParams.get("expires"), role);
130+ return "error" in issued ? json(400, issued) : json(200, issued);
131+}
133+/** The engine's ci and queue reads, for a server with neither: empty, so status and log say nothing about them. */
134+const NO_CI = { latest: null, checked: null, running: null, red: null, behind: null };
135+const NO_QUEUE = { items: [], paused: null };
137+async function projectRoute(
138+ request: Request,
139+ env: Env,
140+ url: URL,
141+ caller: Caller,
142+ match: RegExpExecArray,
143+): Promise<Response> {
144+ const [, project, top, agent, op] = match as unknown as [
145+ string,
146+ string,
147+ string,
148+ string | undefined,
149+ string | undefined,
150+ ];
151+ if (!validName(project)) return json(400, { error: "project names use letters, digits, '.', '_' and '-'" });
152+ const obj = projectObject(env, project);
153+ const route = agent === undefined ? top : op;
154+ const write = request.method !== "GET" && request.method !== "HEAD";
155+ const blob = top.startsWith("blobs/");
156+ let keyForCall: KeyForCall | undefined;
157+ let how: string | undefined;
158+ if (caller.kind === "key") {
159+ if (DIRECT.has(top) || blob) {
160+ const decided = await obj.checkAgentKey(caller.presented, agent, addressOf(request));
161+ if (!decided.ok) return json(decided.status, { error: decided.error });
162+ const allowed = keyAllows(decided.role, { write, agent, route, method: request.method });
163+ if (!allowed.ok) return json(allowed.status, { error: allowed.error });
164+ how = decided.as;
165+ } else keyForCall = { presented: caller.presented, address: addressOf(request), write, route };
166+ }
168+ if (top === "head") {
169+ if (request.method !== "GET") return json(405, { error: "head is a GET" });
170+ const head = await obj.head();
171+ return head ? json(200, head) : json(404, { error: "no such project; run init first" });
172+ }
173+ if (top === "out") return json(200, await obj.out());
174+ if (top === "ci") return json(200, NO_CI);
175+ if (top === "queue") return json(200, NO_QUEUE);
176+ if (top === "visibility") {
177+ if (request.method !== "GET")
178+ return json(400, { error: "every project on this server is private: it answers only its token and keys" });
179+ return json(200, { project, visibility: "private" });
180+ }
181+ if (blob) {
182+ const sha = top.slice("blobs/".length);
183+ if (!SHA.test(sha)) return json(400, { error: "a blob's name is its SHA-256 in lowercase hex" });
184+ if (request.method === "PUT") {
185+ if (!request.body) return json(400, { error: "PUT the blob's bytes as the body" });
186+ const a = (await obj.putBlob(sha, request.body)) as unknown as Answer;
187+ return json(a.status, a.body);
188+ }
189+ if (request.method !== "GET") return json(405, { error: "blobs take GET or PUT" });
190+ const bytes = await obj.getBlob(sha);
191+ if (!bytes) return json(404, { error: `no blob ${sha} in this project` });
192+ return new Response(bytes, {
193+ headers: { "content-type": "application/octet-stream", "cache-control": "private, max-age=31536000, immutable" },
194+ });
195+ }
196+ if (top === "export") {
197+ const from = Number(url.searchParams.get("from") ?? "0");
198+ const limit = Number(url.searchParams.get("limit") ?? "500");
199+ if (!Number.isInteger(from) || from < 0 || !Number.isInteger(limit) || limit < 1 || limit > 5000)
200+ return json(400, { error: "export takes ?from=<seq>&limit=<1-5000>" });
201+ const page = await obj.exportLog(from, limit);
202+ if (page === null) return json(404, { error: "no such project; run init first" });
203+ return new Response(page.lines, {
204+ headers: {
205+ "content-type": "application/x-ndjson",
206+ "x-abso-next": page.next === null ? "" : String(page.next),
207+ "cache-control": "no-store",
208+ },
209+ });
210+ }
211+ if (top === "git-remote") {
212+ // For a person who works with plain git: clone, commit, push; the project takes the commits in.
213+ if (request.method !== "POST") return json(405, { error: "git-remote is a POST" });
214+ const artifacts = artifactsOf(env);
215+ if (!artifacts) return json(501, { error: "this server has no Artifacts binding, so no git remote" });
216+ if ((await obj.head()) === null) return json(404, { error: "no such project; run init first" });
217+ const { remote, secret: token } = await writeAccess(artifacts, repoName(project), 3600);
218+ // The token goes in a header for each git call, never in the remote URL or a credential store.
219+ const header = `Authorization: Basic ${btoa(`x:${token}`)}`;
220+ const git = `git -c credential.helper= -c http.extraHeader="${header}"`;
221+ return json(200, {
222+ remote,
223+ token,
224+ expiresIn: 3600,
225+ header,
226+ clone: `${git} clone ${remote}`,
227+ fetch: `${git} fetch`,
228+ push: `${git} push`,
229+ });
230+ }
231+ if (top === "git-sync") {
232+ if (request.method !== "POST") return json(405, { error: "git-sync is a POST" });
233+ try {
234+ return json(200, { taken: await obj.gitSync() });
235+ } catch (e) {
236+ return json(502, { error: `could not read the project's repo: ${e instanceof Error ? e.message : String(e)}` });
237+ }
238+ }
240+ let body: unknown;
241+ if (request.method === "POST") {
242+ const text = await request.text();
243+ if (text) {
244+ try {
245+ body = JSON.parse(text);
246+ } catch {
247+ return json(400, { error: "the body must be JSON" });
248+ }
249+ }
250+ } else if (request.method === "GET" && (QUERY_READS.has(route ?? "") || top.startsWith("change/"))) {
251+ body = Object.fromEntries(url.searchParams);
252+ } else return json(405, { error: `${route} is a POST` });
253+ // Which client sent a recording goes in the log with it.
254+ if ((op === "edit" || op === "record") && body && typeof body === "object") {
255+ const client = request.headers.get("x-abso-client") ?? request.headers.get("x-avcs-client") ?? "";
256+ const { client: _, ...rest } = body as Record<string, unknown>;
257+ body = { ...rest, ...(/^[\w.+-]{1,20}\/[\w.+-]{1,40}$/.test(client) ? { client } : {}) };
258+ }
259+ try {
260+ const a = (await obj.call(project, (op ?? top)!, agent, body, false, how, keyForCall)) as unknown as Answer;
261+ return json(a.status, a.body);
262+ } catch (e) {
263+ const error = `the project object failed: ${e instanceof Error ? e.message : String(e)}`;
264+ console.error(`${project} ${op ?? top}: ${error}`);
265+ return json(500, { error });
266+ }
267+}
269+/** One request. The issues code comes in as an argument, so this file loads without the Workers runtime (tests). */
270+export async function handle(
271+ request: Request,
272+ env: Env,
273+ ctx: ExecutionContext,
274+ issues: typeof issuesFetch,
275+): Promise<Response> {
276+ const url = new URL(request.url);
277+ if (url.pathname === "/version") return json(200, { commit: env.CF_VERSION_METADATA?.tag || null });
278+ const caller = await authorize(request, env);
279+ if (caller instanceof Response) return caller;
280+ if (url.pathname === "/")
281+ return new Response("abso: agent-first version control. The API lives under /p/<project>.\n");
282+ if (url.pathname === "/admin/agent-keys" || url.pathname === "/admin/agent-keys/revoke")
283+ return agentKeys(request, env, url, caller);
284+ const onIssues = ISSUES_ROUTE.exec(url.pathname);
285+ if (onIssues) {
286+ const project = decodeURIComponent(onIssues[1]!);
287+ if (!validName(project)) return json(400, { error: "project names use letters, digits, '.', '_' and '-'" });
288+ let auth: IssuesAuth = { kind: "token" };
289+ if (caller.kind === "key") {
290+ const decided = await projectObject(env, project).checkAgentKey(caller.presented, undefined, addressOf(request));
291+ if (!decided.ok) return json(decided.status, { error: decided.error });
292+ auth = { kind: "key", agent: decided.agent, role: decided.role as KeyRole };
293+ }
294+ return issues(request, env, ctx, { project, rest: onIssues[2] ?? "", auth });
295+ }
296+ const m = PROJECT_ROUTE.exec(url.pathname);
297+ if (!m) return json(404, { error: "no such route" });
298+ return projectRoute(request, env, url, caller, m);
299+}
--- /dev/null
+++ b/server/test/blobs.test.ts
@@ -0,0 +1,44 @@
1+import assert from "node:assert/strict";
2+import { createHash } from "node:crypto";
3+import { before, describe, it } from "node:test";
4+import { BlobStore } from "../src/blobs.ts";
5+import { installDigestStream, memoryStorage, streamOf } from "./helpers.ts";
6+
7+const sha = (text: string) => createHash("sha256").update(text).digest("hex");
8+
9+describe("the blob store", () => {
10+ before(installDigestStream);
12+ it("keeps bytes whose SHA-256 is their name", async () => {
13+ const store = new BlobStore(memoryStorage());
14+ const a = await store.put(sha("hello"), streamOf("hello"));
15+ assert.deepEqual(a, { status: 200, body: { sha256: sha("hello"), size: 5, stored: true } });
16+ assert.equal(store.has(sha("hello")), true);
17+ assert.equal(new TextDecoder().decode(store.read(sha("hello"))!), "hello");
18+ const again = await store.put(sha("hello"), streamOf("hello"));
19+ assert.equal((again.body as { stored: boolean }).stored, false);
20+ });
22+ it("refuses bytes that hash to something else, and keeps nothing", async () => {
23+ const store = new BlobStore(memoryStorage());
24+ const a = await store.put(sha("hello"), streamOf("goodbye"));
25+ assert.equal(a.status, 400);
26+ assert.match((a.body as { error: string }).error, new RegExp(`hash to ${sha("goodbye")}`));
27+ assert.equal(store.has(sha("hello")), false);
28+ assert.equal(store.has(sha("goodbye")), false);
29+ assert.deepEqual(store.list("", 10), { blobs: [], next: null });
30+ });
32+ it("refuses a name that isn't a lowercase SHA-256", async () => {
33+ const store = new BlobStore(memoryStorage());
34+ assert.equal((await store.put("abc", streamOf("x"))).status, 400);
35+ assert.equal((await store.put(sha("x").toUpperCase(), streamOf("x"))).status, 400);
36+ });
38+ it("refuses a blob over the size cap", async () => {
39+ const store = new BlobStore(memoryStorage());
40+ const a = await store.put(sha("too big"), streamOf("too big"), 3);
41+ assert.equal(a.status, 413);
42+ assert.equal(store.total(), 0);
43+ });
44+});
--- /dev/null
+++ b/server/test/e2e-transcript.md
@@ -0,0 +1,132 @@
1+# End to end: the stock client against `wrangler dev --local`
2+
3+Server: `http://127.0.0.1:8799` (server/ in abso-core, run with `npx wrangler dev --local`, Artifacts off).
4+Token: an invented local test token in `server/.dev.vars`, given to the client as `ABSO_TOKEN`.
5+Project: `e2e-1791907434`. Folders are temporary, outside abso-core. Run 2026-10-13T16:03Z.
6+
7+## Init and join
8+
9+```
10+(starter) $ abso init . --server http://127.0.0.1:8799 --project e2e-1791907434 --agent starter
11+Created project e2e-1791907434 at version 0 from 3 text files in <temp>\starter.
12+Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore.
13+No abso.json written: package.json gives no check or build to guess, so CI has nothing to run on each new version. To give it a check, push an abso.json like {"check": "npm test"} (abso ci --help says what it runs).
14+This folder is agent starter. Settings are in .abso/config.json.
15+Edits made by Claude Code reach the server through the abso mod, which isn't on this machine yet: node <abso-core>\client\install-mod.ts installs it, and new chats load it. Anything else: abso record.
16+[exit 0]
17+```
19+```
20+(alice) $ abso join e2e-1791907434 --agent alice --dir . --server http://127.0.0.1:8799
21+Joined e2e-1791907434 as alice at version 0: wrote 3 files into <temp>\alice.
22+Edits made by Claude Code reach the server through the abso mod, which isn't on this machine yet: node <abso-core>\client\install-mod.ts installs it, and new chats load it. Anything else: abso record.
23+[exit 0]
24+```
26+```
27+(bob) $ abso join e2e-1791907434 --agent bob --dir . --server http://127.0.0.1:8799
28+Joined e2e-1791907434 as bob at version 0: wrote 3 files into <temp>\bob.
29+Edits made by Claude Code reach the server through the abso mod, which isn't on this machine yet: node <abso-core>\client\install-mod.ts installs it, and new chats load it. Anything else: abso record.
30+[exit 0]
31+```
33+## Both agents edit and push (different files)
35+```
36+(alice) $ abso push -m Alice edits line two
37+Recorded first: 1 changed (hello.txt).
38+Pushed version 1.
39+[exit 0]
40+```
42+```
43+(bob) $ abso push -m Bob writes the notes
44+Recorded first: 1 changed (notes.md).
45+Pushed version 2. It went on top of version 1 (alice: "Alice edits line two"), which your folder doesn't have yet. Nothing of theirs was overwritten; run abso pull to see both.
46+[exit 0]
47+```
49+## A collision: both change line four
51+```
52+(alice) $ abso pull
53+Pulled to version 2: 1 file updated, 0 deleted.
54+ updated: notes.md
55+[exit 0]
56+```
58+```
59+(bob) $ abso pull
60+Pulled to version 2: 1 file updated, 0 deleted.
61+ updated: hello.txt
62+[exit 0]
63+```
65+```
66+(alice) $ abso push -m Alice rewrites line four
67+Recorded first: 1 changed (hello.txt).
68+Pushed version 3.
69+[exit 0]
70+```
72+```
73+(bob) $ abso push -m Bob rewrites line four
74+Recorded first: 1 changed (hello.txt).
75+Not pushed: 1 collision with work pushed since your last pull.
76+ hello.txt:
77+ yours (line 4):
78+ line four, as bob wants it
79+ theirs, by alice in version 3 ("Alice rewrites line four") (line 4):
80+ line four, as alice wants it
81+Run abso pull: each of those files comes back holding both sides' lines, with no markers. Edit it to what it should be, then push again.
82+News:
83+ alice pushed "Alice rewrites line four" (version 3), which changes hello.txt lines 4-4, where your draft also changes lines; run abso pull to see both versions.
84+[exit 2]
85+```
87+## Log and status
89+```
90+(bob) $ abso log
91+shared is at version 3.
92+version 3 by alice, 2026-10-13 16:03 UTC: Alice rewrites line four
93+ 1 file: hello.txt
94+version 2 by bob, 2026-10-13 16:03 UTC: Bob writes the notes
95+ 1 file: notes.md
96+version 1 by alice, 2026-10-13 16:03 UTC: Alice edits line two
97+ 1 file: hello.txt
98+version 0 by init, 2026-10-13 16:03 UTC: Start the project
99+ 3 files: .absoignore, hello.txt, notes.md
100+[exit 0]
101+```
103+```
104+(bob) $ abso status
105+Project e2e-1791907434: shared is at version 3. This folder is bob, working in shared. Signed in with shared token.
106+Everything in this folder is recorded.
107+Agents:
108+ alice, base 3, 0 draft changes
109+ * bob, base 2, 1 draft change: hello.txt
110+ starter, base 0, 0 draft changes
111+[exit 0]
112+```
114+```
115+(alice) $ abso status
116+Project e2e-1791907434: shared is at version 3. This folder is alice, working in shared. Signed in with shared token.
117+Everything in this folder is recorded.
118+Agents:
119+ * alice, base 3, 0 draft changes
120+ bob, base 2, 1 draft change: hello.txt
121+ starter, base 0, 0 draft changes
122+[exit 0]
123+```
125+## Other checks against the same server, with curl
127+- No token, or a wrong one: 401 `missing or wrong token`. `GET /version` answers without one.
128+- Per-agent keys (`AGENT_KEYS=on`, a local `KEY_HMAC_SECRET`): `POST /admin/agent-keys` without `x-abso-admin` is 403; with it, a writer key for `carol` is issued and listed. Carol's key syncs as carol; as `dave` it is 403 `that key is not for this agent`; on another project, 403 `that key is not for this project`.
129+- Blobs: a PUT whose bytes don't hash to the name is 400 `the bytes hash to …, not …`; the right hash is stored and read back; a name that isn't a SHA-256 is 400.
130+- `GET head` answers `{version, at}` from storage. `GET feed?from=<end>&wait=3` holds for 3 seconds, then answers with no events.
131+- `/issues/p/<project>/...` reaches the issues stand-in (404 `issues aren't on this server yet`) after auth.
132+- `POST git-remote` with Artifacts off: 501 `this server has no Artifacts binding, so no git remote`.
--- /dev/null
+++ b/server/test/engine-project.test.ts
@@ -0,0 +1,37 @@
1+import assert from "node:assert/strict";
2+import { describe, it } from "node:test";
3+import { answer } from "../../worker/project/http.ts";
4+import { EngineProject, SqliteLog } from "../src/engine-project.ts";
5+import { memoryStorage } from "./helpers.ts";
6+
7+describe("the engine over the object's SQLite log", () => {
8+ it("serves init, records and pushes through answer(), and holds a collision", () => {
9+ const storage = memoryStorage();
10+ const p = EngineProject.open(storage);
11+ assert.equal(answer(p, "init", undefined, { files: { "a.txt": "one\ntwo\nthree\n" } }).status, 200);
12+ for (const agent of ["alice", "bob"]) assert.equal(answer(p, "sync", agent, {}).status, 200);
13+ answer(p, "record", "alice", { files: { "a.txt": "one\nTWO by alice\nthree\n" } });
14+ answer(p, "record", "bob", { files: { "a.txt": "one\ntwo by bob\nthree\n" } });
15+ const first = answer(p, "publish", "alice", { message: "Alice's two" });
16+ assert.deepEqual(first, { status: 200, body: { ok: true, version: 1, changes: 1 } });
17+ const second = answer(p, "publish", "bob", { message: "Bob's two" }).body as { ok: boolean; collisions: unknown[] };
18+ assert.equal(second.ok, false);
19+ assert.equal(second.collisions.length, 1);
20+ });
22+ it("loads the same project back from the log", () => {
23+ const storage = memoryStorage();
24+ const p = EngineProject.open(storage);
25+ answer(p, "init", undefined, { files: { "a.txt": "one\n" } });
26+ answer(p, "sync", "alice", {});
27+ answer(p, "record", "alice", { files: { "a.txt": "one\ntwo\n" } });
28+ answer(p, "publish", "alice", { message: "Add two" });
29+ const again = EngineProject.open(storage);
30+ assert.equal(again.shared().version, 1);
31+ assert.equal(again.shared().files["a.txt"], "one\ntwo\n");
32+ const log = new SqliteLog(storage);
33+ assert.equal(log.sharedVersion(), 1);
34+ assert.deepEqual(log.lastPublish()?.agent, "alice");
35+ assert.equal(log.logSize().entries, log.seq());
36+ });
37+});
--- /dev/null
+++ b/server/test/helpers.ts
@@ -0,0 +1,82 @@
1+// Stand-ins for the Workers runtime in Node tests: a Durable Object's SQLite storage over node:sqlite, and the
2+// DigestStream the blob store hashes uploads with.
3+
4+import { createHash } from "node:crypto";
5+import { DatabaseSync } from "node:sqlite";
6+import type { SqliteStorage } from "../src/engine-project.ts";
7+
8+export function memoryStorage(): SqliteStorage & { db: DatabaseSync } {
9+ const db = new DatabaseSync(":memory:");
10+ let depth = 0;
11+ return {
12+ db,
13+ sql: {
14+ exec(query: string, ...bindings: unknown[]) {
15+ const statement = db.prepare(query);
16+ const args = bindings as never[];
17+ const rows = statement.columns().length > 0 ? statement.all(...args) : (statement.run(...args), []);
18+ // Workers hands BLOB columns back as ArrayBuffers.
19+ return {
20+ toArray: () =>
21+ rows.map((r) =>
22+ Object.fromEntries(
23+ Object.entries(r as Record<string, unknown>).map(([k, v]) => [
24+ k,
25+ v instanceof Uint8Array ? v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength) : v,
26+ ]),
27+ ),
28+ ),
29+ };
30+ },
31+ },
32+ transactionSync<T>(fn: () => T): T {
33+ const name = `t${depth++}`;
34+ db.exec(`SAVEPOINT ${name}`);
35+ try {
36+ const value = fn();
37+ db.exec(`RELEASE ${name}`);
38+ return value;
39+ } catch (e) {
40+ db.exec(`ROLLBACK TO ${name}; RELEASE ${name}`);
41+ throw e;
42+ } finally {
43+ depth--;
44+ }
45+ },
46+ };
47+}
49+/** Workers' crypto.DigestStream, for the blob store's streaming hash. */
50+export function installDigestStream(): void {
51+ const c = (globalThis as unknown as { crypto: { DigestStream?: unknown } }).crypto;
52+ if (c.DigestStream) return;
53+ class DigestStream extends WritableStream<Uint8Array> {
54+ readonly digest: Promise<ArrayBuffer>;
55+ constructor(algorithm: string) {
56+ const hash = createHash(algorithm.replace("-", "").toLowerCase());
57+ let done!: (b: ArrayBuffer) => void;
58+ const digest = new Promise<ArrayBuffer>((ok) => {
59+ done = ok;
60+ });
61+ super({
62+ write: (chunk) => void hash.update(chunk),
63+ close: () => {
64+ const b = hash.digest();
65+ done(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength));
66+ },
67+ });
68+ this.digest = digest;
69+ }
70+ }
71+ c.DigestStream = DigestStream;
72+}
74+export function streamOf(text: string): ReadableStream<Uint8Array> {
75+ const bytes = new TextEncoder().encode(text);
76+ return new ReadableStream({
77+ start(c) {
78+ c.enqueue(bytes);
79+ c.close();
80+ },
81+ });
82+}
--- /dev/null
+++ b/server/test/push.test.ts
@@ -0,0 +1,68 @@
1+import assert from "node:assert/strict";
2+import { describe, it } from "node:test";
3+import git from "isomorphic-git";
4+import { absoVersion } from "../src/ingest.ts";
5+import { MemoryFS } from "../src/memory-fs.ts";
6+import { commitShared, projectOfRepo, readTreeFiles, repoName } from "../src/push.ts";
7+
8+describe("repo names", () => {
9+ it("names a project's Artifacts repo abso-<project>, and back", () => {
10+ assert.equal(repoName("game"), "abso-game");
11+ assert.equal(repoName("my.site_2"), "abso-my.site_2");
12+ assert.equal(projectOfRepo("abso-game"), "game");
13+ assert.equal(projectOfRepo("avcs-game"), null);
14+ assert.equal(projectOfRepo("abso-"), null);
15+ });
17+ it("reads the version a pushed commit carries, under either name", () => {
18+ assert.equal(absoVersion("Fix it\n\nabso-version: 12\n"), 12);
19+ assert.equal(absoVersion("Fix it\n\navcs-version: 7\n"), 7);
20+ assert.equal(absoVersion("a person's own commit"), undefined);
21+ });
22+});
24+describe("commitShared", () => {
25+ it("writes shared as a commit with its modes, then only what changed", async () => {
26+ const fs = new MemoryFS();
27+ const dir = "/repo";
28+ await git.init({ fs, dir, defaultBranch: "main" });
29+ const noBlobs = () => null;
30+ const first = await commitShared(
31+ fs,
32+ dir,
33+ null,
34+ {
35+ version: 0,
36+ files: { "a.txt": "one\n", "run.sh": "echo hi\n", link: "" },
37+ modes: { "run.sh": { exec: true }, link: { link: "a.txt" } },
38+ },
39+ noBlobs,
40+ );
41+ assert.equal(first.changed, 3);
42+ const commit = (await git.readCommit({ fs, dir, oid: first.commit })).commit;
43+ assert.match(commit.message, /^Start the project\n\nabso-version: 0\n$/);
44+ const { files } = await readTreeFiles(fs, dir, commit.tree);
45+ assert.deepEqual(Object.fromEntries([...files].map(([p, f]) => [p, f.mode])), {
46+ "a.txt": "100644",
47+ link: "120000",
48+ "run.sh": "100755",
49+ });
50+ const second = await commitShared(
51+ fs,
52+ dir,
53+ first.commit,
54+ {
55+ version: 1,
56+ files: { "a.txt": "one\ntwo\n", "run.sh": "echo hi\n", link: "" },
57+ modes: { "run.sh": { exec: true }, link: { link: "a.txt" } },
58+ last: { agent: "alice", message: "Add two" },
59+ },
60+ noBlobs,
61+ );
62+ assert.equal(second.changed, 1);
63+ const next = (await git.readCommit({ fs, dir, oid: second.commit })).commit;
64+ assert.equal(next.author.name, "alice");
65+ assert.deepEqual(next.parent, [first.commit]);
66+ assert.equal(absoVersion(next.message), 1);
67+ });
68+});
--- /dev/null
+++ b/server/test/router.test.ts
@@ -0,0 +1,224 @@
1+import assert from "node:assert/strict";
2+import { describe, it } from "node:test";
3+import type { Env } from "../src/env.ts";
4+import { authorize, handle, ISSUES_ROUTE, PROJECT_ROUTE, sameSecret } from "../src/router.ts";
5+
6+const TOKEN = "test-token-for-the-router";
7+
8+/** A project namespace whose objects record every call and answer what each test needs. */
9+function fakeEnv(extra: Partial<Env> = {}) {
10+ const calls: { project: string; method: string; args: unknown[] }[] = [];
11+ const object = (project: string) =>
12+ new Proxy(
13+ {},
14+ {
15+ get:
16+ (_t, method: string) =>
17+ async (...args: unknown[]) => {
18+ calls.push({ project, method, args });
19+ if (method === "call") return { status: 200, body: { op: args[1], agent: args[2], body: args[3] } };
20+ if (method === "putBlob") return { status: 200, body: { stored: true } };
21+ if (method === "head") return { version: 3, at: "now" };
22+ if (method === "checkAgentKey")
23+ return { ok: true, id: "k_1", as: "key k_1", role: "writer", agent: "carol", dirty: false };
24+ if (method === "issueAgentKey") return { id: "k_2", key: "abso_sk_new", agent: args[0] };
25+ return null;
26+ },
27+ },
28+ );
29+ const env = {
30+ PROJECT: { idFromName: (n: string) => n, get: (id: string) => object(id) },
31+ ISSUES_DO: { idFromName: (n: string) => n, get: () => ({}) },
32+ ABSO_TOKEN: TOKEN,
33+ ...extra,
34+ } as unknown as Env;
35+ return { env, calls };
36+}
38+const ctx = {} as ExecutionContext;
39+const noIssues = async () => new Response("issues", { status: 299 });
40+const request = (path: string, init: RequestInit & { token?: string | null } = {}) => {
41+ const { token = TOKEN, ...rest } = init;
42+ const headers = new Headers(rest.headers);
43+ if (token) headers.set("authorization", `Bearer ${token}`);
44+ return new Request(`http://abso.test${path}`, { ...rest, headers });
45+};
47+describe("routes", () => {
48+ it("matches the project's top routes and an agent's ops", () => {
49+ assert.deepEqual(PROJECT_ROUTE.exec("/p/game/status")?.slice(1, 3), ["game", "status"]);
50+ assert.deepEqual(PROJECT_ROUTE.exec("/p/game/a/alice/publish")?.slice(1), [
51+ "game",
52+ "a/alice/publish",
53+ "alice",
54+ "publish",
55+ ]);
56+ assert.equal(PROJECT_ROUTE.exec("/p/game/change/12")?.[2], "change/12");
57+ assert.equal(PROJECT_ROUTE.exec("/p/game/a/alice/run"), null, "boxes are not on the open server");
58+ assert.equal(PROJECT_ROUTE.exec("/p/game/ci/log"), null, "nor CI's output");
59+ assert.equal(PROJECT_ROUTE.exec("/p/game/members"), null);
60+ assert.deepEqual(ISSUES_ROUTE.exec("/issues/p/game/issues/4")?.slice(1), ["game", "/issues/4"]);
61+ assert.deepEqual(ISSUES_ROUTE.exec("/issues/p/game")?.slice(1), ["game", undefined]);
62+ });
64+ it("sends an agent's op to the project's object, with the JSON body", async () => {
65+ const { env, calls } = fakeEnv();
66+ const res = await handle(
67+ request("/p/game/a/alice/publish", { method: "POST", body: JSON.stringify({ message: "why" }) }),
68+ env,
69+ ctx,
70+ noIssues,
71+ );
72+ assert.equal(res.status, 200);
73+ assert.deepEqual(await res.json(), { op: "publish", agent: "alice", body: { message: "why" } });
74+ assert.equal(calls[0]?.project, "game");
75+ });
77+ it("reads take their query as the body, and a read refuses a POST-only op as a GET", async () => {
78+ const { env } = fakeEnv();
79+ const log = await handle(request("/p/game/log?limit=5"), env, ctx, noIssues);
80+ assert.deepEqual(await log.json(), { op: "log", body: { limit: "5" } });
81+ const publish = await handle(request("/p/game/a/alice/publish"), env, ctx, noIssues);
82+ assert.equal(publish.status, 405);
83+ });
85+ it("refuses a project name the engine wouldn't take", async () => {
86+ const { env, calls } = fakeEnv();
87+ const res = await handle(request("/p/..bad/status"), env, ctx, noIssues);
88+ assert.equal(res.status, 400);
89+ assert.equal(calls.length, 0);
90+ });
92+ it("answers head from the object, and ci and queue as empty", async () => {
93+ const { env } = fakeEnv();
94+ assert.deepEqual(await (await handle(request("/p/game/head"), env, ctx, noIssues)).json(), {
95+ version: 3,
96+ at: "now",
97+ });
98+ const ci = (await (await handle(request("/p/game/ci"), env, ctx, noIssues)).json()) as Record<string, unknown>;
99+ assert.equal(ci.red, null);
100+ assert.deepEqual(await (await handle(request("/p/game/queue"), env, ctx, noIssues)).json(), {
101+ items: [],
102+ paused: null,
103+ });
104+ });
106+ it("checks a blob's name before its bytes go anywhere", async () => {
107+ const { env, calls } = fakeEnv();
108+ const bad = await handle(request("/p/game/blobs/not-a-hash", { method: "PUT", body: "x" }), env, ctx, noIssues);
109+ assert.equal(bad.status, 400);
110+ const upper = await handle(
111+ request(`/p/game/blobs/${"A".repeat(64)}`, { method: "PUT", body: "x" }),
112+ env,
113+ ctx,
114+ noIssues,
115+ );
116+ assert.equal(upper.status, 400);
117+ assert.equal(calls.length, 0);
118+ const good = await handle(
119+ request(`/p/game/blobs/${"a".repeat(64)}`, { method: "PUT", body: "x" }),
120+ env,
121+ ctx,
122+ noIssues,
123+ );
124+ assert.equal(good.status, 200);
125+ assert.equal(calls[0]?.method, "putBlob");
126+ });
128+ it("hands /issues to the issues code with the rest of the path and who is calling", async () => {
129+ const { env } = fakeEnv();
130+ let seen: unknown;
131+ const res = await handle(request("/issues/p/game/issues?open=1"), env, ctx, async (_r, _e, _c, where) => {
132+ seen = where;
133+ return new Response("ok");
134+ });
135+ assert.equal(await res.text(), "ok");
136+ assert.deepEqual(seen, { project: "game", rest: "/issues", auth: { kind: "token" } });
137+ });
139+ it("gives the issues code a key's agent and role", async () => {
140+ const { env } = fakeEnv({ AGENT_KEYS: "on", KEY_HMAC_SECRET: "s" });
141+ let seen: unknown;
142+ await handle(request("/issues/p/game/issues", { token: "abso_sk_abc" }), env, ctx, async (_r, _e, _c, where) => {
143+ seen = where;
144+ return new Response("ok");
145+ });
146+ assert.deepEqual(seen, { project: "game", rest: "/issues", auth: { kind: "key", agent: "carol", role: "writer" } });
147+ });
149+ it("answers /version without a token", async () => {
150+ const { env } = fakeEnv({ ABSO_TOKEN: undefined });
151+ const res = await handle(request("/version", { token: null }), env, ctx, noIssues);
152+ assert.equal(res.status, 200);
153+ });
154+});
156+describe("auth", () => {
157+ it("refuses everything when no shared token is set", async () => {
158+ const { env, calls } = fakeEnv({ ABSO_TOKEN: undefined });
159+ const res = await handle(request("/p/game/status", { token: "anything" }), env, ctx, noIssues);
160+ assert.equal(res.status, 503);
161+ assert.match(((await res.json()) as { error: string }).error, /no ABSO_TOKEN/);
162+ const empty = await authorize(request("/p/game/status", { token: null }), { ...env, ABSO_TOKEN: "" });
163+ assert.ok(empty instanceof Response && empty.status === 503);
164+ assert.equal(calls.length, 0);
165+ });
167+ it("refuses a missing or wrong token, and takes the right one", async () => {
168+ const { env, calls } = fakeEnv();
169+ assert.equal((await handle(request("/p/game/status", { token: null }), env, ctx, noIssues)).status, 401);
170+ assert.equal((await handle(request("/p/game/status", { token: "wrong" }), env, ctx, noIssues)).status, 401);
171+ assert.equal((await handle(request("/p/game/status", { token: `${TOKEN}x` }), env, ctx, noIssues)).status, 401);
172+ assert.equal((await handle(request("/", { token: "wrong" }), env, ctx, noIssues)).status, 401);
173+ assert.equal(calls.length, 0);
174+ assert.equal((await handle(request("/p/game/status"), env, ctx, noIssues)).status, 200);
175+ });
177+ it("takes the token under its old name, AVCS_TOKEN", async () => {
178+ const { env } = fakeEnv({ ABSO_TOKEN: undefined, AVCS_TOKEN: TOKEN });
179+ assert.deepEqual(await authorize(request("/p/game/status"), env), { kind: "token" });
180+ });
182+ it("treats an agent key as a key only when keys are on", async () => {
183+ const off = fakeEnv();
184+ const refused = await authorize(request("/p/game/status", { token: "abso_sk_abc" }), off.env);
185+ assert.ok(refused instanceof Response && refused.status === 401);
186+ const on = fakeEnv({ AGENT_KEYS: "on", KEY_HMAC_SECRET: "s" });
187+ assert.deepEqual(await authorize(request("/p/game/status", { token: "abso_sk_abc" }), on.env), {
188+ kind: "key",
189+ presented: "abso_sk_abc",
190+ });
191+ });
193+ it("compares secrets whatever their lengths", async () => {
194+ assert.equal(await sameSecret("abc", "abc"), true);
195+ assert.equal(await sameSecret("abc", "abcd"), false);
196+ assert.equal(await sameSecret("", "abc"), false);
197+ });
199+ it("issues agent keys only with the admin token beside the shared one", async () => {
200+ const { env, calls } = fakeEnv({ AGENT_KEYS: "on", KEY_HMAC_SECRET: "s", ABSO_ADMIN_TOKEN: "admin-secret" });
201+ const path = "/admin/agent-keys?project=game&agent=carol";
202+ assert.equal((await handle(request(path, { method: "POST" }), env, ctx, noIssues)).status, 403);
203+ const wrong = request(path, { method: "POST", headers: { "x-abso-admin": "nope" } });
204+ assert.equal((await handle(wrong, env, ctx, noIssues)).status, 403);
205+ const key = request(path, { method: "POST", token: "abso_sk_abc", headers: { "x-abso-admin": "admin-secret" } });
206+ assert.equal((await handle(key, env, ctx, noIssues)).status, 401);
207+ assert.equal(calls.length, 0);
208+ const ok = request(path, { method: "POST", headers: { "x-abso-admin": "admin-secret" } });
209+ const res = await handle(ok, env, ctx, noIssues);
210+ assert.equal(res.status, 200);
211+ assert.deepEqual(await res.json(), { id: "k_2", key: "abso_sk_new", agent: "carol" });
212+ });
214+ it("has no agent keys routes while keys are off", async () => {
215+ const { env } = fakeEnv({ ABSO_ADMIN_TOKEN: "admin-secret" });
216+ const res = await handle(
217+ request("/admin/agent-keys?project=game", { headers: { "x-abso-admin": "admin-secret" } }),
218+ env,
219+ ctx,
220+ noIssues,
221+ );
222+ assert.equal(res.status, 404);
223+ });
224+});
--- /dev/null
+++ b/server/tsconfig.json
@@ -0,0 +1,17 @@
1+{
2+ "compilerOptions": {
3+ "target": "es2023",
4+ "module": "es2022",
5+ "moduleResolution": "bundler",
6+ "lib": ["es2023"],
7+ "strict": true,
8+ "noEmit": true,
9+ "allowImportingTsExtensions": true,
10+ "verbatimModuleSyntax": true,
11+ "erasableSyntaxOnly": true,
12+ "noUncheckedIndexedAccess": true,
13+ "skipLibCheck": true,
14+ "types": ["@cloudflare/workers-types", "node"]
15+ },
16+ "include": ["src/**/*.ts", "test/**/*.ts"]
17+}
--- /dev/null
+++ b/server/wrangler.jsonc
@@ -0,0 +1,33 @@
1+// abso's open server: deploy it to your own Cloudflare account with `npx wrangler deploy` from this folder, after
2+// `npx wrangler secret put ABSO_TOKEN`. Without that secret the server refuses every call. Local development:
3+// `npx wrangler dev --local` (or `npm run dev`), with ABSO_TOKEN=<anything> in .dev.vars (never recorded: .absoignore
4+// leaves it out). Keep --local: Artifacts is a remote binding, and without it wrangler dev connects to your account.
5+// Put ABSO_ARTIFACTS=off in .dev.vars too: --local still binds Artifacts, but nothing local can reach it.
6+{
7+ "$schema": "./node_modules/wrangler/config-schema.json",
8+ "name": "abso",
9+ "main": "src/index.ts",
10+ "compatibility_date": "2026-10-01",
11+ "compatibility_flags": ["nodejs_compat"],
12+ "workers_dev": true,
13+ "observability": { "enabled": true },
14+ // CPU per request: 2 minutes, not the default 30 seconds, so a heavy push finishes instead of resetting the
15+ // project's object. Billed only for CPU used.
16+ "limits": { "cpu_ms": 120000 },
17+ // GET /version answers with the deployed version's tag.
18+ "version_metadata": { "binding": "CF_VERSION_METADATA" },
19+ "vars": {
20+ // Per-agent keys: on once KEY_HMAC_SECRET is set (npx wrangler secret put KEY_HMAC_SECRET). Until then, only
21+ // the shared token signs in.
22+ "AGENT_KEYS": "on"
23+ },
24+ // Each project's shared is pushed out to its own repo, abso-<project>, in this namespace.
25+ "artifacts": [{ "binding": "ARTIFACTS", "namespace": "abso" }],
26+ "durable_objects": {
27+ "bindings": [
28+ { "name": "PROJECT", "class_name": "ProjectObject" },
29+ { "name": "ISSUES_DO", "class_name": "IssueProject" }
30+ ]
31+ },
32+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ProjectObject", "IssueProject"] }]
33+}