11 files, 672 lines added, 30 removed.
--- a/client/hooks/register.ts
+++ b/client/hooks/register.ts
@@ -182,6 +182,9 @@
182182 for (let job = jobs.shift(); job !== undefined; job = jobs.shift()) await run($, job); 185+/** A local project's folder (abso init --local): its config names no server. */ 186+const LOCAL_FOLDER = /"server"\s*:\s*"local"/; 185188async function run($: Engine, job: Job): Promise<void> { 186189 const started = await $.clock.now().catch(() => job.queuedAt); 187190 let outcome: string; @@ -191,6 +194,9 @@
191194 outcome = "skipped: recording is paused (abso resume)"; 192195 } else if (/"reader"\s*:\s*true/.test((await readOr($, `${await stateOf($, job.root)}/config.json`)) ?? "")) { 193196 outcome = "skipped: this folder is a reader"; 197+ } else if (LOCAL_FOLDER.test((await readOr($, `${await stateOf($, job.root)}/config.json`)) ?? "")) { 198+ // A local project's history is in a store on this machine, which only the abso command opens. 199+ outcome = "skipped: a local project; abso record sends its edits"; 194200 } else if (await ignored($, job.root, job.rel)) { 195201 outcome = "skipped: ignored path"; 196202 } else if (await isLink($, job.root, job.rel)) { @@ -242,6 +248,7 @@
251+ if (config.server === "local") return; 245252 const bearer = await token($, config.server); 246253 const r = await $.http.fetch( 247254 `${config.server.replace(/\/+$/, "")}/p/${encodeURIComponent(config.project)}/a/${encodeURIComponent(config.agent)}/news`, --- a/client/src/api.ts
+++ b/client/src/api.ts
@@ -20,6 +20,7 @@
2121} from "./api-answers.ts"; 2222import { ApiError, errorSentence, neverSent } from "./api-error.ts"; 23+import { UsageError } from "./args.ts"; 2324import type { AutosettleAnswer, AutosettleMode } from "./autosettle-commands.ts"; @@ -68,6 +69,7 @@
7071} from "./issues-wire.ts"; 72+import { isLocal, LOCAL_BASE, localFetch, NO_STORE } from "./local-store.ts"; 7173import type { Modes } from "./modes.ts"; 7375export * from "./api-answers.ts"; @@ -191,9 +193,13 @@
191193 caller: string | undefined; 193195 url(path: string, server = this.config.server): string { 194− return `${server.replace(/\/+$/, "")}/p/${encodeURIComponent(this.config.project)}${path}`;
196+ const base = isLocal(server) ? LOCAL_BASE : server; 197+ return `${base.replace(/\/+$/, "")}/p/${encodeURIComponent(this.config.project)}${path}`; 200+ /** A local project's calls: answered in this process (local-store.ts). */ 201+ private local: ((input: string, init?: RequestInit) => Promise<Response>) | undefined; 197203 agentPath(action: string): string { 198204 return `/a/${encodeURIComponent(this.config.agent)}/${action}`; @@ -214,6 +220,12 @@
214220 * and follows no redirect, so nothing it sends goes anywhere it didn't name (headers() adds no sign-in). 216222 send(url: string, init: RequestInit = {}): Promise<Response> { 223+ if (isLocal(this.config.server)) { 224+ const dir = this.config.localStore; 225+ if (dir === undefined) return Promise.reject(new UsageError(NO_STORE)); 226+ this.local ??= localFetch(dir); 227+ return this.local(url, init); 217229 if (!this.config.visitor) return fetch(url, init); 218230 if ((init.method ?? "GET") !== "GET") 219231 return Promise.reject(new ApiError("a folder that reads signed out sends only reads")); @@ -248,6 +260,8 @@
248260 signal: AbortSignal.timeout(timeoutMs), 263+ // A local project's refusal (no store, a Node without SQLite) says itself. 264+ if (err instanceof UsageError) throw err; 251265 const e = err as Error; 253267 e.name === "TimeoutError" --- a/client/src/config.ts
+++ b/client/src/config.ts
@@ -11,6 +11,7 @@
1111import { UsageError } from "./args.ts"; 1212import { type MachineServers, machineServers, TOKEN_SERVERS, tokenGoesTo, trustedList } from "./core.ts"; 1313import { fromEnv } from "./env-names.ts"; 14+import { isLocal, storeDir } from "./local-store.ts"; 1415import { homeFile, stateDir } from "./state-dir.ts"; 1617/** What .avcs/config.json holds. */ @@ -27,10 +28,14 @@
2728 * routes anyone can read and sends no credential. It has no agent; its config holds server, project and this. 2930 readonly visitor?: boolean; 31+ /** A local project's store (abso init --local --store), when it isn't the machine's own: ABSO_STORE or the OS data folder. */ 32+ readonly store?: string; 3235export interface Config extends Settings { 3336 readonly token?: string; 37+ /** For a local project (server "local"): the store folder its history is in, or undefined when there's none to use. */ 38+ readonly localStore?: string; 3641export function configPath(root: string): string { @@ -64,11 +69,15 @@
6469 for (const key of ["server", "project", "agent"] as const) { 6570 if (typeof raw[key] !== "string" || raw[key] === "") throw new Error(`${configPath(root)} has no "${key}"`); 67− const token = tokenFor(raw.server!, env, root, tokenFileOk);
72+ // A local project's calls never leave this process, so no credential goes with them. 73+ const local = isLocal(raw.server); 74+ const token = local ? undefined : tokenFor(raw.server!, env, root, tokenFileOk); 6976 server: raw.server!, 7077 project: raw.project!, 79+ ...(typeof raw.store === "string" && raw.store !== "" ? { store: raw.store } : {}), 80+ ...(local ? { localStore: storeDir(env, raw.store, root) } : {}), 7281 ...(typeof raw.follow === "string" && raw.follow !== "" ? { follow: raw.follow } : {}), 7382 ...(raw.reader === true ? { reader: true } : {}), 7483 ...(token ? { token } : {}), @@ -275,10 +284,17 @@
276285export function writeConfig(root: string, settings: Settings): void { 277286 mkdirSync(stateDir(root), { recursive: true }); 278− const { server, project, agent, follow, reader, visitor } = settings;
287+ const { server, project, agent, follow, reader, visitor, store } = settings; 279288 const written = visitor 280289 ? { server, project, visitor: true } 281− : { server, project, agent, ...(follow ? { follow } : {}), ...(reader ? { reader: true } : {}) };
294+ ...(follow ? { follow } : {}), 295+ ...(reader ? { reader: true } : {}), 296+ ...(store ? { store } : {}), 282298 writeFileSync(configPath(root), `${JSON.stringify(written, null, 2)}\n`); 283299 excludeFromGit(root); --- /dev/null
+++ b/client/src/durable-object-stand-in.ts
@@ -0,0 +1,13 @@
1+// What `import { DurableObject } from "cloudflare:workers"` gives the open server's code when it runs inside the client 2+// for a local project (local-store.ts): a base class that keeps the object's state and settings, which is all the 3+// project object takes from it. The build points that import here (scripts/build-client.mjs); run as .ts files, a 4+// module hook does (local-store.ts). 6+export class DurableObject<Env = unknown> { 9+ constructor(ctx: unknown, env: Env) { --- a/client/src/join-commands.ts
+++ b/client/src/join-commands.ts
@@ -2,7 +2,7 @@
33import { randomUUID } from "node:crypto"; 44import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; 5−import { join, relative, resolve } from "node:path";
5+import { isAbsolute, join, relative, resolve, sep } from "node:path"; 66import { Api, ApiError, type SyncAnswer } from "./api.ts"; 77import { bool, type Parsed, str, UsageError } from "./args.ts"; 88import { writeKnownBlobs } from "./blobs.ts"; @@ -33,6 +33,7 @@
3333import { fromEnv } from "./env-names.ts"; 3434import { clearKnown, loadIgnore, readFolder, writeKnown } from "./folder.ts"; 3535import { installerCommand, modInstalled } from "./install.ts"; 36+import { LOCAL, NO_STORE, storeDir } from "./local-store.ts"; 3637import { type FullMode, foldModes, writeKnownModes } from "./modes.ts"; 3738import { initInOrg, siteOf } from "./orgs.ts"; 3839import { projectFileName, readProjectFile, startingProjectFileText, writeStartingProjectFile } from "./project-file.ts"; @@ -101,6 +102,48 @@
106+ * --local (abso init, abso join): the project's history is in a store on this machine, not on a server. The store is 107+ * --store, else ABSO_STORE, else the OS's data folder; one given with --store is kept in the folder's config. 109+function localFrom(args: Parsed, env: Env, command: string): { dir: string; settings: { store?: string } } | undefined { 110+ const store = str(args, "store"); 111+ if (!bool(args, "local")) { 112+ if (store !== undefined) 113+ throw new UsageError("--store goes with --local: it says where a local project's history is"); 116+ if (str(args, "server") !== undefined) 117+ throw new UsageError("--local or --server, not both: a local project has no server"); 118+ if (str(args, "org") !== undefined || bool(args, "public") || bool(args, "private") || bool(args, "reader")) 119+ throw new UsageError( 120+ `abso ${command} --local takes --project, --agent, --store and --as-is; a local project has no server to share it`, 122+ const dir = storeDir(env.env, store, env.cwd); 123+ if (dir === undefined) throw new UsageError(NO_STORE); 124+ return { dir, settings: store === undefined ? {} : { store: dir } }; 127+/** A store inside the project folder is left out of its files: a line in .absoignore. Its relative path, if so. */ 128+function ignoreStoreInside(root: string, dir: string): string | undefined { 129+ const rel = relative(root, dir); 130+ if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) return undefined; 131+ const line = `/${rel.split(sep).join("/")}/`; 132+ const file = join(root, ".absoignore"); 133+ const had = existsSync(file) ? readFileSync(file, "utf8") : ""; 134+ const lines = had.split(/\r?\n/); 135+ if (!lines.includes(line)) { 136+ const gap = had === "" || had.endsWith("\n") ? "" : "\n"; 137+ writeFileSync(file, `${had}${gap}${line}\n`); 142+/** What init and join say about a local project's store. */ 143+function localText(dir: string, project: string, ignored?: string): string { 144+ return `It's a local project: its history is in ${join(dir, project)}, on this machine, and no server is needed.${ignored === undefined ? "" : ` .absoignore leaves the store, ${ignored}, out of the project's files.`}`; 104147/** Why a token file is no fallback: said when one is here and nothing else signs in. */ 105148const TOKEN_FILE_ASKED = "~/.abso/token is used only with --token-file."; @@ -112,35 +155,41 @@
112155 const project = str(args, "project"); 113156 if (!project) throw new UsageError("give the project a name with --project <name>"); 114157 if (bool(args, "public") && bool(args, "private")) throw new UsageError("--public or --private, not both"); 158+ const local = localFrom(args, env, "init"); 115159 // A box signed in here, and no other credential asked for: the project is made as the person who approved the box, 116160 // the way the website makes one (abso 663). The token file only with --token-file, never by itself. 117− const server = serverFrom(args, env);
118− const box = readBox(server);
119− const credential = tokenCredential(args, env.env, server, root);
161+ const server = local ? LOCAL : serverFrom(args, env); 162+ const box = local ? undefined : readBox(server); 163+ const credential = local ? undefined : tokenCredential(args, env.env, server, root); 120164 const say = env.writeErr ?? env.write; 121165 if (box && credential === undefined) { 122166 say(`Signing in with this box's sign-in, ${box.id}. 124168 return initFromBox(args, env, root, project, server, box); 126− if (credential === undefined && tokenFile() !== undefined)
170+ if (!local && credential === undefined && tokenFile() !== undefined) 127171 throw new UsageError( 128172 `abso init signs in with this box's sign-in, and this box isn't signed in to ${server}: abso login signs it in. ${TOKEN_FILE_ASKED}`, 130174 const org = str(args, "org"); 131175 if (org !== undefined) return initInOrg(org, server); 132− const config = makeSettings(args, env, project);
176+ const config: Settings = local 177+ ? { server: LOCAL, project, agent: agentFrom(args, str(args, "agent") ?? defaultAgentName()), ...local.settings } 178+ : makeSettings(args, env, project); 133179 const asIs = bool(args, "as-is"); 134180 const absoignore = join(root, ".absoignore"); 135181 const wroteIgnore = !asIs && !existsSync(absoignore) && !existsSync(join(root, ".avcsignore")); 136182 if (wroteIgnore) writeFileSync(absoignore, STARTING_ABSOIGNORE); 183+ // A store kept inside the project folder, like a virtual environment, isn't the project's files. 184+ const ignoredStore = local ? ignoreStoreInside(root, local.dir) : undefined; 137185 // What the server runs on each new version (#39), guessed from package.json; recorded with the rest. 138186 const wroteProject = asIs ? "exists" : writeStartingProjectFile(root); 139187 const { files, blobs, modes, leftOut } = readFolder(root, loadIgnore(root)); 140188 const token = credential?.token; 141− say(`Signing in with ${credential?.words ?? `no credential: nothing here signs in to ${server}`}.
190+ say(`Signing in with ${credential?.words ?? `no credential: nothing here signs in to ${server}`}. 143− const api = new Api({ ...config, ...(token ? { token } : {}) });
192+ const api = new Api({ ...config, ...(token ? { token } : {}), ...(local ? { localStore: local.dir } : {}) }); 144193 let answer: Awaited<ReturnType<Api["init"]>>; 146195 await uploadBlobs(api, blobs); @@ -170,12 +219,14 @@
171220 ? ["Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore."] 173− ...startingProjectFileText(wroteProject),
222+ // A local project has no CI to run abso.json, so no word about one that isn't there. 223+ ...(local && wroteProject === "nothing" ? [] : startingProjectFileText(wroteProject)), 174224 ...(answer.skipped && answer.skipped.length > 0 ? [`The server skipped: ${answer.skipped.join(", ")}.`] : []), 225+ ...(local ? [localText(local.dir, project, ignoredStore)] : []), 175226 `This folder is agent ${config.agent}. Settings are in .abso/config.json.`, 176227 ...refusedText(synced.refused), 177228 ...(synced.kept.length > 0 ? [`Kept your copy of ${synced.kept.join(", ")}.`] : []), 178− hookHint(env.env),
229+ hookHint(env.env, local !== undefined), @@ -186,6 +237,7 @@
186237 wroteAbsoignore: wroteIgnore, 187238 wroteProjectFile: typeof wroteProject === "string" ? null : wroteProject, 240+ ...(local ? { store: local.dir } : {}), @@ -380,14 +432,17 @@
380432 mkdirSync(root, { recursive: true }); 381433 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`); 382434 const reader = bool(args, "reader"); 383− const server = serverFrom(args, env);
384− const box = readBox(server);
385− const hasKey = existsSync(join(stateDir(root), "key"));
386− const credential = tokenCredential(args, env.env, server, root);
435+ // A local project: no box, key or credential, and the agent is --agent or this computer's name. 436+ const local = localFrom(args, env, "join"); 437+ const server = local ? LOCAL : serverFrom(args, env); 438+ const box = local ? undefined : readBox(server); 439+ const hasKey = !local && existsSync(join(stateDir(root), "key")); 440+ const credential = local ? undefined : tokenCredential(args, env.env, server, root); 387441 const tokenFileAsked = bool(args, "token-file"); 388442 let agent: string; 389443 let minted: { key: string; id: string } | undefined; 390− if (str(args, "agent") !== undefined) {
444+ if (local) agent = agentFrom(args, str(args, "agent") ?? defaultAgentName()); 445+ else if (str(args, "agent") !== undefined) { 391446 agent = agentFrom(args); 393448 box && !hasKey && !fromEnv(env.env, "KEY_FILE") && !tokenFileAsked @@ -412,7 +467,7 @@
412467 agent = free.agent; 413468 minted = { key: free.key, id: free.id }; 415− const config = { server, project, agent, ...(reader ? { reader: true } : {}) };
470+ const config = { server, project, agent, ...(reader ? { reader: true } : {}), ...local?.settings }; 416471 writeConfig(root, config); 418473 if (minted) installKey(root, JSON.stringify(minted)); @@ -425,10 +480,11 @@
427482 const settings = tokenFileAsked ? { ...read, token: credential?.token } : read; 428− (env.writeErr ?? env.write)(
429− `Signing in with ${minted && box ? `a new key from this box's sign-in, ${box.id}` : hasKey ? "this folder's key" : (credential?.words ?? `no credential: nothing here signs in to ${server}`)}.
484+ (env.writeErr ?? env.write)( 485+ `Signing in with ${minted && box ? `a new key from this box's sign-in, ${box.id}` : hasKey ? "this folder's key" : (credential?.words ?? `no credential: nothing here signs in to ${server}`)}. 431− );
432488 const api = new Api(settings); 433489 let answer: SyncAnswer; @@ -454,9 +510,10 @@
454510 `These files were already here and differ from shared, so they were left alone: ${synced.kept.join(", ")}. abso record sends them as your changes.`, 513+ ...(local ? [localText(local.dir, project)] : []), 457514 ...emptyHint(synced.version, synced.written.length, synced.kept.length, reader), 458515 ...setupHint(root), 459− hookHint(env.env),
516+ hookHint(env.env, local !== undefined), 460517 ...(root === resolve(env.cwd) ? [] : [`cd ${relative(env.cwd, root) || root}`]), @@ -480,7 +537,9 @@
480537 : [`Nothing is installed yet. Before building or testing here, run ${projectFileName(root)}'s setup: ${setup}`]; 483−function hookHint(env: Readonly<Record<string, string | undefined>>): string {
540+function hookHint(env: Readonly<Record<string, string | undefined>>, local = false): string { 541+ // The mod sends each edit to the folder's server itself, and a local project has none. 542+ if (local) return "abso record sends the edits made here: the abso mod doesn't record local projects yet."; 484543 if (modInstalled(env)) 485544 return "Edits made by Claude Code here are recorded by the abso mod on this machine, signed in as this folder. Anything else: abso record."; 486545 // A built copy (the npm package) has no installer to point at (abso-core 18). --- /dev/null
+++ b/client/src/local-server.d.mts
@@ -0,0 +1,3 @@
1+// The types of local-server.mjs: as much of the open server as the client calls. 2+export declare function handle(request: Request, env: unknown, ctx: unknown, issues: unknown): Promise<Response>; 3+export declare const ProjectObject: new (ctx: unknown, env: unknown) => object; --- /dev/null
+++ b/client/src/local-server.mjs
@@ -0,0 +1,6 @@
1+// The open server's router and project object, for local projects (local-store.ts). Plain JS, with its types in 2+// local-server.d.mts, so the client's typecheck stops here: server/src is typechecked with the Workers' types 3+// (server/tsconfig.json). The build and Node follow these imports as usual. 5+export { ProjectObject } from "../../server/src/project-object.ts"; 6+export { handle } from "../../server/src/router.ts"; --- /dev/null
+++ b/client/src/local-store.ts
@@ -0,0 +1,360 @@
1+// Local projects (abso init --local): the open server's own router and project object (server/src) run in this 2+// process, over Node's SQLite, so a project needs no server, account or network. Each project is one SQLite file in a 3+// store folder. Every call runs in one SQLite write transaction, which is the store's lock: another process's call 4+// waits for it, and a process that dies mid-call leaves nothing half-written. 6+import { existsSync, mkdirSync } from "node:fs"; 7+import { homedir } from "node:os"; 8+import { join, resolve } from "node:path"; 9+import { deserialize, serialize } from "node:v8"; 10+import { UsageError } from "./args.ts"; 11+import { fromEnv } from "./env-names.ts"; 13+/** The server a local folder's config names. */ 14+export const LOCAL = "local"; 15+/** The address the client's calls use for a local project; they never leave this process. */ 16+export const LOCAL_BASE = "http://local.abso.invalid"; 17+/** The shared token the in-process server is given, and that its calls carry. Not a secret: nothing listens. */ 18+const LOCAL_TOKEN = "local-store"; 20+export const isLocal = (server: string | undefined): boolean => server === LOCAL; 22+type EnvMap = Readonly<Record<string, string | undefined>>; 25+ * Where local projects live: the folder's own store (--store, kept in its config), else ABSO_STORE, else the OS's 26+ * per-user data folder. Undefined when there is none to use (no data folder and nothing named), so nothing assumes a 27+ * writable home folder. 29+export function storeDir(env: EnvMap, configured?: string, cwd = process.cwd()): string | undefined { 30+ if (configured) return resolve(cwd, configured); 31+ const named = fromEnv(env, "STORE"); 32+ if (named) return resolve(cwd, named); 34+ process.platform === "win32" 36+ : process.platform === "darwin" 37+ ? env.HOME && join(env.HOME, "Library", "Application Support") 38+ : env.XDG_DATA_HOME || (env.HOME ? join(env.HOME, ".local", "share") : undefined); 39+ if (data) return join(data, "abso", "store"); 41+ const home = homedir(); 42+ return home ? join(home, ".local", "share", "abso", "store") : undefined; 48+export const NO_STORE = 49+ "there's no folder for local projects here: set ABSO_STORE to one, or give abso init --local a --store <folder>"; 51+// --- The Workers runtime's parts the server uses, over node:sqlite ----------------------------------------------- 54+ exec(sql: string): void; 55+ prepare(sql: string): { 56+ all(...args: unknown[]): unknown[]; 57+ run(...args: unknown[]): unknown; 58+ get(...args: unknown[]): unknown; 59+ columns(): unknown[]; 64+/** A Durable Object's storage: SQL, synchronous transactions, the key-value calls and the alarm, on one database. */ 65+function storageOver(db: Db) { 67+ "CREATE TABLE IF NOT EXISTS _local_kv (key TEXT PRIMARY KEY, value BLOB NOT NULL); CREATE TABLE IF NOT EXISTS _local_alarm (id INTEGER PRIMARY KEY CHECK (id = 0), at INTEGER)", 69+ const statements = new Map<string, ReturnType<Db["prepare"]>>(); 70+ const prepared = (query: string) => { 71+ let s = statements.get(query); 73+ s = db.prepare(query); 74+ statements.set(query, s); 78+ // Workers takes and gives BLOB columns as ArrayBuffers; node:sqlite as Uint8Arrays. 79+ const bind = (v: unknown) => (v instanceof ArrayBuffer ? new Uint8Array(v) : v); 80+ const out = (v: unknown) => (v instanceof Uint8Array ? v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength) : v); 82+ const kvGet = (key: string) => { 83+ const row = prepared("SELECT value FROM _local_kv WHERE key = ?").get(key) as { value: Uint8Array } | undefined; 84+ return row ? deserialize(row.value) : undefined; 86+ const kvPut = (key: string, value: unknown) => 88+ "INSERT INTO _local_kv (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", 89+ ).run(key, serialize(value)); 90+ const kvDelete = (key: string) => 91+ (prepared("DELETE FROM _local_kv WHERE key = ?").run(key) as { changes: number | bigint }).changes > 0; 94+ exec(query: string, ...bindings: unknown[]) { 95+ const statement = prepared(query); 96+ const args = bindings.map(bind); 97+ const rows = statement.columns().length > 0 ? statement.all(...args) : (statement.run(...args), []); 100+ (rows as Record<string, unknown>[]).map((r) => 101+ Object.fromEntries(Object.entries(r).map(([k, v]) => [k, out(v)])), 106+ transactionSync<T>(fn: () => T): T { 107+ const name = `local_t${depth++}`; 108+ db.exec(`SAVEPOINT ${name}`); 111+ db.exec(`RELEASE ${name}`); 114+ db.exec(`ROLLBACK TO ${name}; RELEASE ${name}`); 120+ async transaction<T>(fn: (txn: unknown) => Promise<T>): Promise<T> { 123+ async get(key: string | string[]) { 124+ if (typeof key === "string") return kvGet(key); 125+ return new Map(key.flatMap((k) => (kvGet(k) === undefined ? [] : [[k, kvGet(k)] as const]))); 127+ async put(key: string | Record<string, unknown>, value?: unknown) { 128+ if (typeof key === "string") kvPut(key, value); 129+ else for (const [k, v] of Object.entries(key)) kvPut(k, v); 131+ async delete(key: string | string[]) { 132+ if (typeof key === "string") return kvDelete(key); 133+ return key.filter(kvDelete).length; 135+ async list(options: { prefix?: string } = {}) { 136+ const rows = prepared("SELECT key, value FROM _local_kv WHERE key >= ? ORDER BY key").all( 137+ options.prefix ?? "", 138+ ) as { key: string; value: Uint8Array }[]; 140+ rows.filter((r) => r.key.startsWith(options.prefix ?? "")).map((r) => [r.key, deserialize(r.value)]), 143+ // The alarm is kept, but nothing in a local project needs it: it pushes out to Artifacts, which is off here. 145+ const row = prepared("SELECT at FROM _local_alarm WHERE id = 0").get() as { at: number | null } | undefined; 146+ return row?.at ?? null; 148+ async setAlarm(at: number | Date) { 149+ prepared("INSERT INTO _local_alarm (id, at) VALUES (0, ?) ON CONFLICT (id) DO UPDATE SET at = excluded.at").run( 153+ async deleteAlarm() { 154+ prepared("DELETE FROM _local_alarm WHERE id = 0").run(); 160+/** Workers' crypto.DigestStream, which the blob store hashes uploads with. */ 161+async function installDigestStream(): Promise<void> { 162+ const c = globalThis.crypto as unknown as { DigestStream?: unknown }; 163+ if (c.DigestStream) return; 164+ const { createHash } = await import("node:crypto"); 165+ class DigestStream extends WritableStream<Uint8Array> { 166+ readonly digest: Promise<ArrayBuffer>; 167+ constructor(algorithm: string) { 168+ const hash = createHash(algorithm.replace("-", "").toLowerCase()); 169+ let done!: (b: ArrayBuffer) => void; 170+ const digest = new Promise<ArrayBuffer>((ok) => { 174+ write: (chunk) => void hash.update(chunk), 176+ const b = hash.digest(); 177+ done(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer); 180+ this.digest = digest; 183+ c.DigestStream = DigestStream; 186+// --- Loading the server's code ------------------------------------------------------------------------------------ 189+ DatabaseSync: new (path: string) => Db; 190+ handle: (request: Request, env: unknown, ctx: unknown, issues: unknown) => Promise<Response>; 191+ ProjectObject: new (ctx: unknown, env: unknown) => object; 193+let server: Promise<Server> | undefined; 195+/** Node's SQLite says it's experimental on every start; that line would land in every local command's output. */ 196+function quietSqliteWarning(): void { 197+ const emit = process.emitWarning; 198+ if ((emit as { quiet?: boolean }).quiet) return; 199+ const quiet = ((warning: string | Error, ...rest: unknown[]) => { 200+ const text = typeof warning === "string" ? warning : warning.message; 201+ if (text.startsWith("SQLite is an experimental feature")) return; 202+ return (emit as (...a: unknown[]) => void).call(process, warning, ...rest); 203+ }) as typeof process.emitWarning; 204+ (quiet as unknown as { quiet: boolean }).quiet = true; 205+ process.emitWarning = quiet; 208+export const NODE_TOO_OLD = `local projects need Node 22.13 or later, for its built-in SQLite; this is Node ${process.versions.node}`; 210+function loadServer(): Promise<Server> { 211+ server ??= (async () => { 212+ quietSqliteWarning(); 213+ let sqlite: { DatabaseSync: Server["DatabaseSync"] }; 215+ sqlite = (await import("node:sqlite")) as unknown as typeof sqlite; 217+ throw new LocalError(NODE_TOO_OLD); 219+ await installDigestStream(); 220+ // Run as .ts files, the server's `import { DurableObject } from "cloudflare:workers"` needs a stand-in. A built 221+ // copy has it already: the build points the import at the same file (scripts/build-client.mjs). 222+ const standIn = new URL("./durable-object-stand-in.ts", import.meta.url).href; 223+ const mod = (await import("node:module")) as unknown as { 224+ registerHooks?: (hooks: unknown) => { deregister(): void }; 226+ const hooks = mod.registerHooks?.({ 227+ resolve(specifier: string, context: unknown, next: (s: string, c: unknown) => unknown) { 228+ if (specifier === "cloudflare:workers") return { url: standIn, shortCircuit: true }; 229+ return next(specifier, context); 233+ const { handle, ProjectObject } = await import("./local-server.mjs"); 235+ DatabaseSync: sqlite.DatabaseSync, 240+ hooks?.deregister(); 246+/** What stops a local project from opening at all: said plainly, like a usage error. */ 247+export class LocalError extends UsageError {} 249+// --- One store, as a fetch ----------------------------------------------------------------------------------------- 253+ storage: ReturnType<typeof storageOver>; 254+ object: object | undefined; 255+ /** PRAGMA data_version when this process last used the project: it changes when another process writes. */ 256+ seen: number | undefined; 259+/** Every store file this process has open: closed when its command ends (closeLocalStores). */ 260+const opened = new Set<Db>(); 262+/** Closes every local project this process opened. Its next call opens them again. */ 263+export function closeLocalStores(): void { 264+ for (const db of opened) { 272+const PROJECT_PATH = /^\/p\/([^/]+)\//; 273+const NAME = /^[A-Za-z0-9._-]{1,100}$/; 274+const json = (status: number, body: unknown) => Response.json(body, { status }); 277+ * The fetch a local folder's calls go through: each call is answered by the open server's router, in this process, 278+ * against the project's SQLite file in `dir`. Only init makes a project's file. 280+export function localFetch(dir: string): (input: string, init?: RequestInit) => Promise<Response> { 281+ const open = new Map<string, Open>(); 282+ let opening: Server | undefined; 283+ const openProject = (name: string, create: boolean): Open | undefined => { 284+ const existing = open.get(name); 285+ if (existing && opened.has(existing.db)) return existing; 286+ const folder = join(dir, name); 287+ const file = join(folder, "project.sqlite"); 288+ if (create) mkdirSync(folder, { recursive: true }); 289+ else if (!existsSync(file)) return undefined; 290+ const db = new opening!.DatabaseSync(file); 292+ db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 120000; PRAGMA synchronous = NORMAL"); 293+ const project = { db, storage: storageOver(db), object: undefined, seen: undefined }; 294+ open.set(name, project); 297+ const env = (name: string) => ({ 298+ ABSO_TOKEN: LOCAL_TOKEN, 299+ ABSO_ARTIFACTS: "off", 300+ ABSO_DISK_FIRST: "off", 302+ idFromName: (n: string) => n, 303+ get: (n: string) => { 304+ const p = open.get(n); 305+ if (!p || n !== name) throw new LocalError(`no local project ${n}`); 306+ p.object ??= new opening!.ProjectObject( 307+ { id: { toString: () => n, name: n }, storage: p.storage, waitUntil: () => {} }, 313+ // Issues, asks and news aren't in local projects yet: a start note's issue hooks find nothing to call. 314+ ISSUES_DO: { idFromName: (n: string) => n, get: () => ({}) }, 316+ return async (input, init = {}) => { 317+ const s = await loadServer(); 319+ const url = new URL(input); 320+ const match = PROJECT_PATH.exec(url.pathname); 321+ if (!match) return json(404, { error: "a local store answers only project calls" }); 322+ const name = decodeURIComponent(match[1]!); 323+ if (!NAME.test(name)) return json(400, { error: "project names use letters, digits, '.', '_' and '-'" }); 324+ const p = openProject(name, url.pathname === `/p/${match[1]}/init`); 325+ if (!p) return json(404, { error: `no local project ${name} in ${dir}` }); 326+ const headers = new Headers(init.headers); 327+ headers.set("authorization", `Bearer ${LOCAL_TOKEN}`); 328+ const request = new Request(url, { ...init, headers }); 329+ const waits: Promise<unknown>[] = []; 330+ p.db.exec("BEGIN IMMEDIATE"); 332+ const version = (p.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version; 333+ if (p.seen !== undefined && version !== p.seen) p.object = undefined; 334+ const response = await s.handle( 337+ { waitUntil: (w: Promise<unknown>) => waits.push(w) }, 340+ await Promise.allSettled(waits); 341+ // The answer is read whole before the write is kept, so a body that fails to arrive keeps nothing either. 342+ const body = await response.arrayBuffer(); 343+ p.db.exec("COMMIT"); 344+ p.seen = (p.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version; 345+ return new Response(body, { status: response.status, headers: response.headers }); 348+ p.db.exec("ROLLBACK"); 350+ // What the object held in memory may be from the rolled-back call. 351+ p.object = undefined; 353+ if (e instanceof LocalError) throw e; 354+ // Where the Workers runtime answers a throw with a 500, so does this. 355+ return json(500, { error: e instanceof Error ? e.message : String(e) }); 360+const issuesNone = async () => json(404, { error: "issues, asks and news aren't in local projects yet" }); --- a/client/src/main.ts
+++ b/client/src/main.ts
@@ -59,6 +59,7 @@
6060} from "./issues.ts"; 6161import { adminToken, adminTokenWords, issuedPublic, keyList, keyListText, keyNew, keyRevoke } from "./key-admin.ts"; 62+import { closeLocalStores } from "./local-store.ts"; 6263import { browserSkip, openInBrowser } from "./open-browser.ts"; 6364import { runOrg, runOrgs } from "./orgs.ts"; 6465import { runUnqueue } from "./queue.ts"; @@ -121,11 +122,13 @@
121122 public: "boolean", 122123 private: "boolean", 123124 "token-file": "boolean", 126− "abso init [folder] --project <name> [--agent <name>] [--as-is] [--org <org>] [--public|--private] [--token-file]",
129+ "abso init [folder] --project <name> [--agent <name>] [--as-is] [--org <org>] [--public|--private] [--token-file] | abso init [folder] --local --project <name> [--agent <name>] [--store <folder>] [--as-is]", 128− "Create a project on the server from a folder's text files. The folder becomes that agent's folder. It writes a starting .absoignore, and, when the folder has no abso.json and package.json gives a check or a build to guess, an abso.json (setup, check, build and out): what the server's CI runs on each new version of shared. Without one, CI runs what it can guess itself, or nothing. --as-is writes neither: the folder goes up exactly as it is (an import). On a server this box is signed in to (abso login, approving all your projects), the project is made as you, the way the website's New project makes it: you own it, it's private unless you say --public, and the folder joins it at once with its own key (--agent names it; else the box's name). --org <org> makes it that organization's project. Elsewhere it needs --agent and a token: ABSO_TOKEN, or with --token-file this machine's ~/.abso/token, which is never used unasked. Before it makes anything, it says what it signs in with.",
131+ "Create a project on the server from a folder's text files. The folder becomes that agent's folder. It writes a starting .absoignore, and, when the folder has no abso.json and package.json gives a check or a build to guess, an abso.json (setup, check, build and out): what the server's CI runs on each new version of shared. Without one, CI runs what it can guess itself, or nothing. --as-is writes neither: the folder goes up exactly as it is (an import). On a server this box is signed in to (abso login, approving all your projects), the project is made as you, the way the website's New project makes it: you own it, it's private unless you say --public, and the folder joins it at once with its own key (--agent names it; else the box's name). --org <org> makes it that organization's project. Elsewhere it needs --agent and a token: ABSO_TOKEN, or with --token-file this machine's ~/.abso/token, which is never used unasked. Before it makes anything, it says what it signs in with. --local makes a local project instead: its history is kept on this machine, in a store folder, and no server, sign-in or network is needed (Node 22.13 or later). The store is --store <folder> (kept in the folder's settings; inside the folder, .absoignore leaves it out), else ABSO_STORE, else this user's data folder (%LOCALAPPDATA%\\abso\\store, ~/Library/Application Support/abso/store, or $XDG_DATA_HOME/abso/store). The agent is --agent, else this computer's name.", 129132 run: (args, env) => runInit(args, env), @@ -327,10 +330,19 @@
330− flags: { server: "string", agent: "string", dir: "string", reader: "boolean", "token-file": "boolean" },
331− usage: "abso join <project> [--agent <name>] [--dir <folder>] [--reader] [--token-file]",
338+ "token-file": "boolean", 343+ "abso join <project> [--agent <name>] [--dir <folder>] [--reader] [--token-file] | abso join <project> --local [--agent <name>] [--store <folder>] [--dir <folder>]", 333− "Join a project as a new agent and write its shared files into a folder: --dir, else here when this folder is empty, else ./<project> (which has to be new or empty). Without --agent the agent is named after this box (the name abso login gave it, lower-cased), or the next free <name>-2, <name>-3; that needs the box signed in with abso login. --reader joins as a reader: it reads everything and records nothing, and the server refuses its edits, records and pushes. With --reader and no sign-in, a public project is joined to read signed out: the folder holds only its settings, sends no sign-in, and runs status, log, show, files, blame, why, where, issues, issue and search; every other command is refused. It says what it signs in with: a new key from this box's sign-in, the folder's key, or ABSO_TOKEN; this machine's ~/.abso/token only with --token-file, never unasked.",
345+ "Join a project as a new agent and write its shared files into a folder: --dir, else here when this folder is empty, else ./<project> (which has to be new or empty). Without --agent the agent is named after this box (the name abso login gave it, lower-cased), or the next free <name>-2, <name>-3; that needs the box signed in with abso login. --reader joins as a reader: it reads everything and records nothing, and the server refuses its edits, records and pushes. With --reader and no sign-in, a public project is joined to read signed out: the folder holds only its settings, sends no sign-in, and runs status, log, show, files, blame, why, where, issues, issue and search; every other command is refused. It says what it signs in with: a new key from this box's sign-in, the folder's key, or ABSO_TOKEN; this machine's ~/.abso/token only with --token-file, never unasked. --local joins a local project (abso init --local) from the same store: --store, else ABSO_STORE, else this user's data folder; the agent is --agent, else this computer's name.", @@ -989,6 +1001,15 @@
9911003export async function main(argv: readonly string[], env: Env): Promise<MainResult> { 1005+ return await runMain(argv, env); 1007+ // A local project's store stays open only while its command runs. 1008+ closeLocalStores(); 1012+async function runMain(argv: readonly string[], env: Env): Promise<MainResult> { 9921013 const command = argv[0]; 9931014 const json = argv.includes("--json") && command !== "run" && command !== "logs"; 9941015 const asked = argv.includes("--token-file"); --- /dev/null
+++ b/client/test/local.test.ts
@@ -0,0 +1,140 @@
1+// Local projects (abso init --local): a project whose history is in a store on this machine, answered by the open 2+// server's own code in the client's process. Every test here runs with fetch replaced by one that throws, so any 3+// call that would leave the machine fails the test. 5+import assert from "node:assert/strict"; 6+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; 7+import { tmpdir } from "node:os"; 8+import { join } from "node:path"; 9+import { after, before, describe, it } from "node:test"; 10+import { main } from "../src/main.ts"; 11+import { stateDir } from "../src/state-dir.ts"; 13+const dirs: string[] = []; 14+const temp = (label: string) => { 15+ const d = mkdtempSync(join(tmpdir(), `abso-local-${label}-`)); 20+const outside: string[] = []; 21+const realFetch = globalThis.fetch; 23+ globalThis.fetch = (async (input: unknown) => { 24+ outside.push(String(input instanceof Request ? input.url : input)); 25+ throw new TypeError("network is off in this test"); 29+ globalThis.fetch = realFetch; 30+ for (const d of dirs) rmSync(d, { recursive: true, force: true, maxRetries: 5 }); 31+ assert.deepEqual(outside, [], "nothing reached for the network"); 35+const env = () => ({ ABSO_STORE: store, ABSO_SERVERS_FILE: "no-servers.json", ABSO_HOOK_FORCE: "1" }); 36+async function run(cwd: string, ...argv: string[]): Promise<{ exit: number; out: string; err: string }> { 37+ const r = await main(argv, { cwd, env: env(), write: () => {} }); 38+ return { exit: r.exit, out: r.stdout, err: r.stderr }; 40+const text = (dir: string, rel: string) => readFileSync(join(dir, rel), "utf8"); 42+describe("a local project, with the network off", () => { 46+ store = temp("store"); 49+ it("init --local makes the project in the store, with no sign-in", async () => { 50+ alice = temp("alice"); 51+ writeFileSync(join(alice, "a.txt"), "one\ntwo\nthree\n"); 52+ const r = await run(alice, "init", "--local", "--project", "demo", "--agent", "alice"); 53+ assert.equal(r.exit, 0, r.out + r.err); 54+ assert.match(r.out, /Created project demo at version 0 from 2 text files/, "a.txt and the starting .absoignore"); 55+ assert.doesNotMatch(r.out, /CI has nothing to run/); 56+ assert.match(r.out, /It's a local project: its history is in .*demo, on this machine/); 57+ assert.doesNotMatch(r.out + r.err, /Signing in/); 58+ assert.ok(existsSync(join(store, "demo", "project.sqlite"))); 59+ const config = JSON.parse(readFileSync(join(stateDir(alice), "config.json"), "utf8")); 60+ assert.equal(config.server, "local"); 61+ assert.equal(config.store, undefined, "the store came from ABSO_STORE, so the folder doesn't name it"); 64+ it("record and push make version 1, and log says so", async () => { 65+ writeFileSync(join(alice, "a.txt"), "one\nTWO\nthree\n"); 66+ writeFileSync(join(alice, "b.txt"), "new\n"); 67+ assert.equal((await run(alice, "record")).exit, 0); 68+ const pushed = await run(alice, "push", "-m", "Change two, add b"); 69+ assert.equal(pushed.exit, 0, pushed.out + pushed.err); 70+ assert.match(pushed.out, /Pushed version 1/); 71+ const log = await run(alice, "log"); 72+ assert.equal(log.exit, 0, log.err); 73+ assert.match(log.out, /Change two, add b/); 76+ it("a second folder joins, and pulls what the first pushes", async () => { 78+ const joined = await run(bob, "join", "demo", "--local", "--agent", "bob", "--dir", bob); 79+ assert.equal(joined.exit, 0, joined.out + joined.err); 80+ assert.equal(text(bob, "a.txt"), "one\nTWO\nthree\n"); 81+ assert.equal(text(bob, "b.txt"), "new\n"); 82+ writeFileSync(join(alice, "b.txt"), "new\nmore\n"); 83+ assert.equal((await run(alice, "push", "-m", "More in b")).exit, 0); 84+ const pulled = await run(bob, "pull"); 85+ assert.equal(pulled.exit, 0, pulled.out + pulled.err); 86+ assert.equal(text(bob, "b.txt"), "new\nmore\n"); 89+ it("blame names who wrote each line", async () => { 90+ const r = await run(bob, "blame", "a.txt"); 91+ assert.equal(r.exit, 0, r.err); 92+ assert.match(r.out, /alice/); 93+ assert.match(r.out, /TWO/); 96+ it("a push that collides with work pushed since is held", async () => { 97+ assert.equal((await run(bob, "pull")).exit, 0); 98+ writeFileSync(join(alice, "a.txt"), "one\nalice's\nthree\n"); 99+ assert.equal((await run(alice, "push", "-m", "Alice's two")).exit, 0); 100+ writeFileSync(join(bob, "a.txt"), "one\nbob's\nthree\n"); 101+ const held = await run(bob, "push", "-m", "Bob's two"); 102+ assert.notEqual(held.exit, 0); 103+ assert.match(held.out + held.err, /collision/); 107+describe("where a local project's store is", () => { 108+ it("--store inside the folder is kept in its settings and left out of its files", async () => { 109+ store = temp("unused"); 110+ const dir = temp("venv"); 111+ writeFileSync(join(dir, "a.txt"), "x\n"); 112+ const r = await run(dir, "init", "--local", "--project", "beside", "--agent", "a", "--store", ".abso-store"); 113+ assert.equal(r.exit, 0, r.out + r.err); 114+ assert.ok(existsSync(join(dir, ".abso-store", "beside", "project.sqlite"))); 115+ assert.equal(JSON.parse(readFileSync(join(stateDir(dir), "config.json"), "utf8")).store, join(dir, ".abso-store")); 116+ assert.match(text(dir, ".absoignore"), /^\/\.abso-store\/$/m); 117+ assert.match(r.out, /from 2 text files/, "a.txt and .absoignore, not the store"); 118+ // Every later command finds the store from the folder's settings, whatever ABSO_STORE says. 119+ writeFileSync(join(dir, "a.txt"), "y\n"); 120+ assert.equal((await run(dir, "push", "-m", "y")).exit, 0); 123+ it("--local refuses --server, and --store needs --local", async () => { 124+ const dir = temp("refuse"); 125+ mkdirSync(join(dir, "x")); 126+ const both = await run(dir, "init", "--local", "--server", "https://abso.test", "--project", "p"); 127+ assert.match(both.out + both.err, /--local or --server, not both/); 128+ const alone = await run(dir, "init", "--store", "s", "--project", "p"); 129+ assert.match(alone.out + alone.err, /--store goes with --local/); 132+ it("joining a project the store doesn't have leaves nothing behind", async () => { 133+ store = temp("empty"); 134+ const dir = temp("nojoin"); 135+ const r = await run(dir, "join", "nothing", "--local", "--agent", "a", "--dir", dir); 136+ assert.notEqual(r.exit, 0); 137+ assert.match(r.out + r.err, /no local project nothing/); 138+ assert.equal(existsSync(join(dir, ".abso")) || existsSync(join(dir, ".avcs")), false); --- a/scripts/build-client.mjs
+++ b/scripts/build-client.mjs
@@ -31,6 +31,9 @@
3333 logLevel: "warning", 34+ // Local projects run the open server's code in the client (client/src/local-store.ts); its Durable Object 35+ // base class comes from the Workers runtime, so the bundle gets the client's stand-in. 36+ alias: { "cloudflare:workers": "./client/src/durable-object-stand-in.ts" }, 3437 // A bundled CommonJS package (yaml) calls require("process") lazily, which an ES module bundle 3538 // can't do without a real require.