Lines 3–35 at 318 (were 3–17 at 277)
33// `abso help` lists the commands. `abso hook` is the Claude Code hook; it 44// loads only what it needs, since every edit pays for its start-up. 6+import { readFileSync } from "node:fs"; 67import * as nodeModule from "node:module"; 8+import { dirname, join } from "node:path"; 10+const argv = process.argv.slice(2); 13+ * Whether this command opens a local project (abso init --local): --local, or a folder whose config names the server 14+ * "local". Those load the open server's code through a module hook, and with the compile cache on Node 24 crashes. 16+function opensLocal(): boolean { 17+ if (argv.includes("--local")) return true; 18+ for (let dir = process.cwd(); ; dir = dirname(dir)) { 19+ for (const state of [".abso", ".avcs"]) { 21+ return /"server"\s*:\s*"local"/.test(readFileSync(join(dir, state, "config.json"), "utf8")); 24+ if (dirname(dir) === dir) return false; 828// Node keeps the compiled modules (TypeScript already stripped) in a cache in 929// the temp folder. Loading the hook's modules drops from about 55 ms to 11 ms. 1030// Node 20 has no compile cache, and the built client runs there without one. 11−(nodeModule as { enableCompileCache?: () => unknown }).enableCompileCache?.();
31+if (!opensLocal()) (nodeModule as { enableCompileCache?: () => unknown }).enableCompileCache?.(); 13−const argv = process.argv.slice(2);
14−
1533if (argv[0] === "hook") { 1634 const { runHook } = await import("./src/hook.ts"); 1735 const chunks: Buffer[] = []; Lines 3–12 at 318 (were 3–11 at 277)
44import type { On } from "claude-code"; 55import { expect, mock, test } from "claude-code/testing"; 6+import { HOOK_COMMAND } from "./stamp.ts"; 78/** The world beneath the mod: a chat in /w/p, an abso folder when `inFolder`, and a server with `news` waiting. */ 8−function world(on: On, inFolder: boolean, news: string[][]) {
9+function world(on: On, inFolder: boolean, news: string[][], server = "https://avcs.test") { 910 mock.env(on, { AVCS_TOKEN: "test-token" }); 1011 const clock = mock.clock(on, { now: 1_000_000 }); 1112 const asked: string[] = []; Lines 22–28 at 318 (were 21–27 at 277)
2122 on("fs.read", (_$, e) => { 2223 const path = norm(e.path); 2324 if (inFolder && path === "/w/p/.abso/config.json") 24− return { value: JSON.stringify({ server: "https://avcs.test", project: "p", agent: "bob" }) };
25+ return { value: JSON.stringify({ server, project: "p", agent: "bob" }) }; 2526 if (written.has(path)) return { value: written.get(path)! }; 2627 return { deny: `ENOENT: ${path}` }; Lines 115–152 at 318 (were 114–116 at 277)
114115 expect(w.written.get("/w/p/.abso/hook.log") ?? "").toContain("not sent: a NUL byte at line 3"); 115116 expect(w.asked.filter((u) => !u.endsWith("/news"))).toEqual([]); 119+test("a local project's edit goes to abso hook as Claude Code's command hook would get it, and its news to the chat", async ($, on) => { 120+ const w = world(on, true, [], "local"); 121+ w.written.set("/w/p/notes.md", "hello\n"); 122+ on("fs.stat", () => ({ value: { realPath: "/w/p/notes.md" } }) as never); 123+ on("session.id", () => ({ value: "sess" })); 124+ const ran: { argv: readonly string[]; stdin?: string; env?: Record<string, string> }[] = []; 125+ const context = "abso: Announcement from lead: hold pushes"; 126+ on("process.run", (_$, e) => { 127+ ran.push({ argv: e.argv, stdin: e.init?.stdin, env: e.init?.env }); 128+ const stdout = JSON.stringify({ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: context } }); 129+ return { value: { exitCode: 0, stdout, stderr: "" } } as never; 131+ await $.session.start({ cwd: "/w/p" }); 132+ await $.tool.call({ tool: "Write", tool_use_id: "t1", file_path: "/w/p/notes.md", content: "hello\n" } as never); 133+ await w.clock.advance(1_000); 134+ // A local project has no server to call: nothing goes over the network. 135+ expect(w.asked.filter((u) => !u.endsWith("/news"))).toEqual([]); 136+ const log = w.written.get("/w/p/.abso/hook.log") ?? ""; 137+ if (HOOK_COMMAND === undefined) { 138+ // Loaded from a checkout, the mod has no client to hand it to. 139+ expect(ran).toEqual([]); 140+ expect(log).toContain("skipped: a local project"); 143+ expect(ran).toHaveLength(1); 144+ expect(ran[0]!.argv).toEqual(HOOK_COMMAND); 145+ expect(ran[0]!.env).toEqual({ ABSO_HOOK_FORCE: "1" }); 146+ const input = JSON.parse(ran[0]!.stdin ?? "{}") as Record<string, unknown>; 147+ expect(input.session_id).toBe("sess"); 148+ expect(input.tool_name).toBe("Write"); 149+ expect((input.tool_input as Record<string, unknown>).file_path).toBe("/w/p/notes.md"); 150+ expect(log).toContain("handed to abso hook"); 151+ expect(w.appended).toEqual([context]); Lines 33–39 at 318 (were 33–39 at 277)
3535} from "../src/core.ts"; 36−import { STAMP } from "./stamp.ts";
36+import { HOOK_COMMAND, STAMP } from "./stamp.ts"; 3838const TOOLS = ["Edit", "MultiEdit", "Write", "NotebookEdit"]; 3939/** A known copy holding a NUL byte reads as no known copy (the client treats it as binary). */ Lines 182–205 at 318 (were 182–196 at 277)
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"/; 187+/** How long abso hook may take on a local project's edit: it waits up to two minutes for the store's lock. */ 188+const LOCAL_HOOK_MS = 150_000; 185190async function run($: Engine, job: Job): Promise<void> { 186191 const started = await $.clock.now().catch(() => job.queuedAt); 187192 let outcome: string; 188193 let news: readonly string[] = []; 194+ /** What abso hook handed back for the agent, on a local project's edit (it keeps the news log itself). */ 195+ let handed: string | undefined; 190197 if ((await readOr($, `${await stateOf($, job.root)}/paused`)) !== undefined) { 191198 outcome = "skipped: recording is paused (abso resume)"; 192199 } else if (/"reader"\s*:\s*true/.test((await readOr($, `${await stateOf($, job.root)}/config.json`)) ?? "")) { 193200 outcome = "skipped: this folder is a reader"; 201+ } else if (LOCAL_FOLDER.test((await readOr($, `${await stateOf($, job.root)}/config.json`)) ?? "")) { 202+ ({ outcome, context: handed } = await handToClient($, job)); 194203 } else if (await ignored($, job.root, job.rel)) { 195204 outcome = "skipped: ignored path"; 196205 } else if (await isLink($, job.root, job.rel)) { Lines 220–230 at 318 (were 211–221 at 277)
212221 `${new Date(job.queuedAt).toISOString()}\t${job.tool}\t${job.rel}\t${outcome}\t${done - started}ms sending, ${started - job.queuedAt}ms queued (in process, async)\t${CLIENT}`, 214− const context = newsContext(news);
223+ const context = handed ?? newsContext(news); 215224 if (context === undefined) return; 216225 // For anything that shows news later (the avcs-view mod reads it). 217226 const at = new Date(done).toISOString(); 218− await log($, job.root, news.map((n) => `${at}\t${n}`).join("\n"), "news.log");
227+ if (news.length > 0) await log($, job.root, news.map((n) => `${at}\t${n}`).join("\n"), "news.log"); 220229 await $.session.append({ 221230 message: { type: "user", content: [{ type: "text", text: context }] }, Lines 237–279 at 318 (were 228–233 at 277)
241+ * A local project's history is in a store on this machine that only the abso command opens, so its edits go to 242+ * `abso hook` from the checkout this mod was installed from, as Claude Code's command hook would run it. 244+async function handToClient($: Engine, job: Job): Promise<{ outcome: string; context?: string }> { 245+ if (HOOK_COMMAND === undefined || HOOK_COMMAND.length === 0) 248+ "skipped: a local project, and this mod has no abso to hand it to (install-mod.ts adds one); abso record sends it", 251+ session_id: await $.session.id(), 252+ cwd: slash(await $.session.cwd()), 253+ tool_name: job.tool, 254+ tool_input: job.input, 255+ ...(job.agentId ? { agent_id: job.agentId } : {}), 257+ const ran = await $.process.run(HOOK_COMMAND, { 259+ env: { ABSO_HOOK_FORCE: "1" }, 260+ stdin: JSON.stringify(hookInput), 261+ timeoutMs: LOCAL_HOOK_MS, 263+ if (ran.exitCode !== 0) throw new Error(`abso hook exited ${ran.exitCode}: ${ran.stderr.trim().split("\n").at(-1)}`); 264+ // It prints Claude Code's JSON when it has news for the agent, and nothing otherwise. 265+ const out = ran.stdout.trim(); 269+ : (JSON.parse(out) as { hookSpecificOutput?: { additionalContext?: unknown } }).hookSpecificOutput 270+ ?.additionalContext; 272+ outcome: "handed to abso hook (a local project; its own line is just above)", 273+ ...(typeof context === "string" ? { context } : {}), 231277/** Ask for the news waiting for this agent (announcements, collisions) and hand it to the model. */ 232278async function pollNews($: Engine, root: string): Promise<void> { Lines 288–294 at 318 (were 242–247 at 277)
291+ if (config.server === "local") return; 245292 const bearer = await token($, config.server); 246293 const r = await $.http.fetch( 247294 `${config.server.replace(/\/+$/, "")}/p/${encodeURIComponent(config.project)}/a/${encodeURIComponent(config.agent)}/news`, Lines 3–11 at 318 (were 3–5 at 277)
33// this file with the version it installs: plugin.json's, plus the commit 44// (0.1.0+702c616). Loaded straight from a checkout, it stays undefined. 55export const STAMP: string | undefined = undefined; 7+// The command that runs `abso hook` from the checkout the mod was installed 8+// from, as [node, client/abso.ts, "hook"]; the installer writes it too. A 9+// local project's history is in a store on this machine that only the abso 10+// command opens, so the mod hands those edits to it. 11+export const HOOK_COMMAND: readonly string[] | undefined = undefined; Lines 107–114 at 318 (were 107–112 at 277)
108108 const ended = await follow({ 109109 mint: () => api.newsTicket(), 110+ // A frame is a wake: read the news, which marks it heard, and print that (news-stream.ts). 111+ take: async () => newsLines((await api.news()).news), 110112 connect: (url, protocols) => new WebSocket(url, [...protocols]) as unknown as Socket, 111113 write: (line) => { 112114 logNews(root, [line]); Lines 20–26 at 318 (were 20–25 at 277)
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"; Lines 69–75 at 318 (were 68–73 at 277)
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"; Lines 193–205 at 318 (were 191–199 at 277)
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}`; Lines 220–231 at 318 (were 214–219 at 277)
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")); Lines 260–267 at 318 (were 248–253 at 277)
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" Lines 1017–1023 at 318 (were 1003–1009 at 277)
10051019 /** A ticket that opens this agent's news stream once, within a minute (abso 690; news-stream.ts). */ 1006− newsTicket(): Promise<{ url: string; protocols: string[]; expiresAt: number }> {
1020+ newsTicket(): Promise<{ url: string; protocols: string[]; expiresAt: number | string }> { 10071021 return this.json("POST", this.agentPath("news/ticket"), {}); Lines 2–8 at 318 (were 2–8 at 277)
22// passes a native command's argument badly, so a multi-line --comment, 33// --description or answer reached the server cut to its first line, and nobody 44// knew. Any text flag also takes --<flag>-file <path>, and the commands whose 5−// text is their words (ask, answer, announce) take --file <path>. A path of -
5+// text is their words (ask, answer, reply, announce) take --file <path>. A path of - 66// reads stdin. The file's text arrives whole on any shell. 88import { readFileSync } from "node:fs"; Lines 12–18 at 318 (were 12–18 at 277)
1212/** The text flags a command may take from a file instead. */ 1313const BODY_FLAGS = ["message", "comment", "object", "description", "note"] as const; 1414/** Commands whose text is their last words: --file gives those words. */ 15−const WORDS_FROM_FILE = new Set(["ask", "answer", "announce"]);
15+const WORDS_FROM_FILE = new Set(["ask", "answer", "reply", "announce"]); 1717/** The command's flags, plus a -file twin for each text flag it takes, and --file where its words are its text. */ 1818export function withBodyFiles(command: string, spec: FlagSpec): FlagSpec { Lines 75–81 at 318 (were 75–81 at 277)
7676 const path = flags.get("file"); 7777 if (WORDS_FROM_FILE.has(command) && typeof path === "string") { 78− // ask <who> and answer <ask> keep their first word; announce's words are all text.
78+ // ask <who>, answer <ask> and reply <ask> keep their first word; announce's words are all text. 7979 const keep = command === "announce" ? 0 : 1; 8080 if (positionals.length > keep) 8181 throw new UsageError(`--file gives ${command}'s text, so leave the words off the command line`); Lines 80–122 at 318 (were 80–85 at 277)
83+/** A stored pipeline run as runRuns lists it: what the CI lines need of it. */ 86+ readonly version: number; 87+ readonly state: string; 88+ readonly file: string; 91+/** The stored pipeline runs, newest first, from the server's `pipelines` read; empty for anything else. */ 92+export function storedRuns(raw: unknown): StoredRun[] { 93+ const runs = (raw as { runs?: unknown } | null)?.runs; 94+ if (!Array.isArray(runs)) return []; 96+ (r): r is StoredRun => 97+ typeof r === "object" && 99+ Number.isInteger((r as StoredRun).id) && 100+ Number.isInteger((r as StoredRun).version) && 101+ typeof (r as StoredRun).state === "string" && 102+ typeof (r as StoredRun).file === "string", 106+/** One stored run in a line, with where its jobs are. */ 107+export function runLine(run: StoredRun): string { 108+ const how = run.state === "planned" ? "was planned, not run," : run.state === "running" ? "is running" : run.state; 109+ return `Pipeline run ${run.id} (${run.file}) ${how} on version ${run.version}. abso pipeline runs ${run.id} shows its jobs.`; 113+ * Whether the built-in check (abso.json's setup, build and check) had nothing of its own to run. With stored runs, that is 114+ * about the built-in check, not the project's CI, so it isn't said as the project's (abso 719). 116+export function builtInHasNothing(ci: CiStatus): boolean { 117+ return ci.red === null && ci.skipped?.reason.startsWith("nothing to run") === true; 83120/** A shared version's mark in abso log; "not checked" says nothing, since most versions in a busy hour are covered by a newer one's job. */ 84121export function ciMarkText(mark: CiMark | undefined): string { Lines 180–199 at 318 (were 143–153 at 277)
144181 if (typed !== undefined) { 145182 if (!/^\d+$/.test(typed)) throw new UsageError(`a version is a number (got ${JSON.stringify(typed)})`); 146− const job = await api.ci(Number(typed));
147− return { text: jobText(job).join("\n"), json: { ...job } };
183+ const [job, raw] = await Promise.all([api.ci(Number(typed)), api.pipelineRuns().catch(() => null)]); 184+ const run = storedRuns(raw).find((r) => r.version === job.version); 185+ // A version the built-in check never ran, with a pipeline run of its own: the run is its CI (abso 719). 186+ const text = run !== undefined && job.result === "none" ? [runLine(run)] : jobText(job); 187+ return { text: text.join("\n"), json: { ...job } }; 149− const [ci, status] = await Promise.all([api.ci(), api.status()]);
150− const lines = ciText(ci, status.version);
189+ const [ci, status, raw] = await Promise.all([api.ci(), api.status(), api.pipelineRuns().catch(() => null)]); 190+ const newest = storedRuns(raw)[0]; 192+ newest === undefined 193+ ? ciText(ci, status.version) 194+ : builtInHasNothing(ci) 196+ : [...ciText(ci, status.version), runLine(newest)]; 153199 `shared is at version ${status.version}.`, Lines 1–6 at 318 (were 1–5 at 277)
11// What every abso command shares: its output, its environment, the folder it opens, and the news it took. 3+import { createHash } from "node:crypto"; 34import { hostname } from "node:os"; 45import { callerHeader } from "../../src/caller.ts"; 56import { Api, type News, newsLines, type RunKind, takeSeatNotices } from "./api.ts"; Lines 49–74 at 318 (were 48–58 at 277)
4950 const config = readConfig(root, env.env, env.tokenFile === true); 5051 const api = new Api(config); 51− api.caller = callerHeader({ session: env.env.CLAUDE_CODE_SESSION_ID, machine: hostname(), folder: root });
52+ api.caller = callerFor(env.env.CLAUDE_CODE_SESSION_ID, hostname(), root); 5253 return { root, config, api }; 57+ * The caller header for this chat, computer and folder. The chat's session id goes as a short SHA-256 of it and the 58+ * folder as its last part, so neither the raw id nor the path (which names the person) leaves the machine. 60+export function callerFor(session: string | undefined, machine: string, root: string): string | undefined { 61+ const hashed = session ? createHash("sha256").update(session).digest("hex").slice(0, 16) : undefined; 62+ // The last part on either separator, so a Windows path names its folder on any machine. 66+ .filter((p) => p !== "") 68+ return callerHeader({ session: hashed, machine, folder }); 5672 * News a command took from the server while recording first. main() prints it 5773 * after whatever the command says, so every command that takes news shows it 5874 * (#37, News Report: sync, run and diff took it, wrote it to .avcs/news.log and Lines 7–13 at 318 (were 7–12 at 277)
77// The engine's own key, so both sides match spellings the same way (#49). Not in core.ts: the edit mod installs core.ts alone. Lines 432–485 at 318 (were 431–439 at 277)
433434export async function syncFolder(root: string, api: Api, full = false): Promise<Applied> { 434− return applyAnswer(root, api, await api.sync({ full }));
435+ const applied = await applyAnswer(root, api, await pullAnswer(root, api, full)); 440+const PULLING_FILE = "pulling.json"; 443+ * Whether a pull here asked the server and never wrote its answer (abso-core 26): it timed out, or stopped 444+ * partway. The server moved the agent's base when it answered, and later pulls send only what changed since 445+ * that base, so the files it would have written stay behind until a pull asks for every file. 447+export function pullUnfinished(root: string): boolean { 448+ return existsSync(join(stateDir(root), PULLING_FILE)); 452+ * Ask the server for a pull, noting first that one is under way, so a pull whose answer never gets written 453+ * leaves the note behind. With that note, or `full`, it asks for every file in the agent's view, which the 454+ * folder's own checks then write only where the folder differs. pullWritten takes the note away. 456+export async function pullAnswer(root: string, api: Api, full = false): Promise<SyncAnswer> { 457+ const unfinished = pullUnfinished(root); 458+ writeFileAtomic(join(stateDir(root), PULLING_FILE), `${JSON.stringify({ at: new Date().toISOString() })}\n`); 459+ if (!full && !unfinished) return api.sync(); 461+ return await api.sync({ full: true }); 463+ // A server from before full pulls (501): the plain pull is still better than none. 464+ if (unfinished && !full && err instanceof ApiError && err.status === 501) return api.sync(); 469+/** The pull's answer is written into the folder: take away pullAnswer's note. */ 470+export function pullWritten(root: string): void { 471+ rmSync(join(stateDir(root), PULLING_FILE), { force: true }); 474+/** Status's line, and pull's when it caught up. */ 475+export function pullUnfinishedText(root: string): string[] { 476+ return pullUnfinished(root) 478+ "A pull here didn't finish (its answer never arrived or wasn't written), so files may be behind this folder's base. abso pull fetches every file and writes the ones that differ.", 437483/** What writing a sync or switch answer into the folder did. */ 438484export interface Applied { 439485 readonly version: number; Lines 11–17 at 318 (were 11–16 at 277)
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. */ Lines 28–41 at 318 (were 27–36 at 277)
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 { Lines 69–83 at 318 (were 64–74 at 277)
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 } : {}), Lines 284–300 at 318 (were 275–284 at 277)
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); Lines 327–339 at 318 (were 327–339 at 277)
329329 * The commonest failures in plain words, with the next step: no credential, a credential the server refuses, and a 330− * server that can't be reached. Anything else is left as it was. `signedIn` is whether the call carried a key or token.
330+ * server that can't be reached. Anything else is left as it was. `sent` names the key or token the call carried, if any. 332−export function plainError(err: unknown, signedIn: boolean, tokenFileUnasked = false): string | undefined {
332+export function plainError(err: unknown, sent: string | undefined, tokenFileUnasked = false): string | undefined { 333333 if (!(err instanceof ApiError)) return undefined; 334334 if (err.status === 401) 335− return signedIn
336− ? `The server didn't accept this folder's key: it may be revoked or expired. abso doctor checks it. (${err.message})`
335+ return sent !== undefined 336+ ? `The server didn't accept ${sent}: it may be revoked or expired. abso doctor checks it. (${err.message})` 337337 : `You're not signed in. Run abso login, then abso join <project>.${tokenFileUnasked ? " ~/.abso/token is used only with --token-file." : ""}`; 338338 if (err.status === undefined && err.message.startsWith("could not reach ")) { 339339 const said = err.message.replace(/^could not reach /, "Can't reach "); Lines 19–26 at 318 (were 19–24 at 277)
2426} from "./commands.ts"; Lines 59–68 at 318 (were 57–65 at 277)
5860 const switched = await applyAnswer(root, api, answer); 5961 // The switch brings back the space as it was when parked; sync straight away so the folder shows it as it is now (#22). 60− const syncAnswer = await api.sync();
62+ const syncAnswer = await pullAnswer(root, api); 6163 note(syncAnswer.files); 6264 const synced = await applyAnswer(root, api, syncAnswer); 6366 const touched = new Set([...switched.written, ...switched.deleted, ...synced.written, ...synced.deleted]); 6467 const written: string[] = []; 6568 const deleted: string[] = []; Lines 151–158 at 318 (were 148–154 at 277)
148151 const moved = await api.draftSync(); 149152 // Bring the moved draft's new view into this folder straight away. 150153 const recorded = await recordFolder(root, api); 151− const applied = await applyAnswer(root, api, await api.sync());
154+ const applied = await applyAnswer(root, api, await pullAnswer(root, api)); 153157 `Moved draft ${moved.draft} onto shared version ${moved.sharedBase} (the draft is at version ${moved.version}).`, 154158 ...recordedFirst(recorded), new file, 13 lines
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) { Lines 94–101 at 318 (were 94–99 at 277)
9494 /** For tests: the rename that moves each file into place. */ 9595 readonly rename?: (from: string, to: string) => void; 9696 readonly now?: Date; 97+ /** For tests: the command stamped as HOOK_COMMAND, instead of this client's own `abso hook`. */ 98+ readonly hookCommand?: readonly string[]; 99101const RECORD = ".avcs-install.json"; Lines 134–148 at 318 (were 132–137 at 277)
132134 existsSync(at(skillsFolder(AVCS_MOD.name, env), MANIFEST)) || 133135 existsSync(at(skillsFolder(OLD_MOD_NAMES[AVCS_MOD.name]!, env), MANIFEST)); 137+/** Whether the installed abso mod hands a local project's edits to abso hook: it was installed with a HOOK_COMMAND. */ 138+export function modHandsLocal(env: Readonly<Record<string, string | undefined>> = process.env): boolean { 140+ return /HOOK_COMMAND[^=\n]*=\s*\[/.test(readFileSync(at(skillsFolder(AVCS_MOD.name, env), STAMP_FILE), "utf8")); 136147 * After the new mod is in, the folder it replaces (skills/avcs, skills/avcs-view) would load beside it, so it 137148 * is moved, not deleted, to ~/.abso/retired-mods/<name>-<stamp>. Returns where it went, or undefined when there was none. Lines 237–247 at 318 (were 226–233 at 277)
229−/** The files to install, stamped with `version`, in install order. */
230−function filesFor(spec: ModSpec, version: string): Map<string, Buffer> {
240+/** The command that runs this checkout's `abso hook`: what the mod hands a local project's edits to. */ 241+export const hookCommand = (): readonly string[] => [process.execPath, join(CLIENT_DIR, "abso.ts"), "hook"]; 243+/** The files to install, stamped with `version` (and HOOK_COMMAND, where a stamp.ts has it), in install order. */ 244+function filesFor(spec: ModSpec, version: string, hook: readonly string[] = hookCommand()): Map<string, Buffer> { 231245 if (!/^[\w.+-]+$/.test(version)) throw new Error(`can't stamp the version ${JSON.stringify(version)}`); 232246 const out = new Map<string, Buffer>(); 233247 for (const rel of spec.files) { Lines 253–261 at 318 (were 239–245 at 277)
239253 const text = data.toString("utf8"); 240254 const stamped = text.replace(/(STAMP[^=\n]*=\s*)undefined/, `$1'${version}'`); 241255 if (stamped === text) throw new Error(`${rel} has no "STAMP ... = undefined" line to stamp`); 242− data = Buffer.from(stamped);
257+ stamped.replace(/(HOOK_COMMAND[^=\n]*=\s*)undefined/, (_, head: string) => head + JSON.stringify(hook)), 244260 out.set(rel, data); Lines 402–408 at 318 (were 386–392 at 277)
386402export function installMod(spec: ModSpec, options: InstallOptions): Installed { 387403 const target = resolve(options.target); 388404 const version = versionFor(spec, options.commit); 389− const next = filesFor(spec, version);
405+ const next = filesFor(spec, version, options.hookCommand); 390406 const existed = existsSync(target); 391407 mkdirSync(target, { recursive: true }); Lines 533–550 at 318 (were 517–523 at 277)
517533 readonly current: string; 520−/** `avcs --version`: this client, and the mods installed on this machine, compared with this client's. */
537+ * The command that runs one of this client's installers (client/install-mod.ts or install-view.ts), by its full 538+ * path. They are .ts files, which Node runs itself from 22.18, so on an older Node it says which one it needs. 540+export function installerCommand(installer: string): string { 541+ const command = `node ${join(CLIENT_DIR, installer)}`; 542+ return (process.features as { typescript?: unknown }).typescript 544+ : `${command} (with Node 22.18 or later, which runs .ts files; this is Node ${process.versions.node})`; 547+/** `abso --version`: this client, and the mods installed on this machine, compared with this client's. */ 521548export function versionReport(env: Readonly<Record<string, string | undefined>>): { 523550 json: Record<string, unknown>; Lines 581–594 at 318 (were 554–567 at 277)
555582 // A built copy has no mod files to compare with or install from: it reports what is installed. 556583 if (m.version === undefined) { 557− lines.push(`the ${m.name} mod: not installed${builtCopy() ? "" : ` (node client/${installer})`}`);
584+ lines.push(`the ${m.name} mod: not installed${builtCopy() ? "" : ` (${installerCommand(installer)})`}`); 560587 const when = m.at ? `, installed ${m.at.slice(0, 16).replace("T", " ")} UTC` : ""; 562589 builtCopy() || m.version === m.current 564− : `; this client has ${m.current}: node client/${installer} installs it`;
591+ : `; this client has ${m.current}: ${installerCommand(installer)} installs it`; 565592 lines.push(`the ${m.name} mod: ${m.version} in ${m.folder}${when}${behind}`); 567594 return { text: lines.join("\n"), json: { client, folder: CLIENT_DIR, mods } }; Lines 606–611 at 318 (were 579–584 at 277)
579606 .filter((m) => m.version?.includes("+") && /\+[0-9a-f]{7}$/.test(m.current) && m.version !== m.current) 582− `The ${m.name} mod installed on this machine is ${m.version}, and this client has ${m.current}: node client/${installers[m.name]} installs it (new chats load it).`,
609+ `The ${m.name} mod installed on this machine is ${m.version}, and this client has ${m.current}: ${installerCommand(installers[m.name]!)} installs it (new chats load it).`, Lines 28–34 at 318 (were 28–33 at 277)
2828import { ignoredHere } from "./fetch.ts"; 2929import { loadIgnore, relativeTo } from "./folder.ts"; 3030import type { AskReply } from "./issues-wire.ts"; 31+import { isLocal, LOCAL_BASE } from "./local-store.ts"; 3132import { queuedLines, standing } from "./queue.ts"; 3233import { seenText, shortWhen } from "./times.ts"; Lines 37–47 at 318 (were 36–41 at 277)
3637/** The folder, with its Api pointed at the Issues Worker: the token goes only where tokenGoesTo allows, as for the avcs server. */ 3738export function openIssues(env: Env): { root: string; config: Config; api: Api } { 3839 const { root, config, api } = open(env); 40+ // A local project's issues are in its store, where the open server keeps them: at /issues. 41+ if (isLocal(config.server)) { 42+ api.issuesServer = `${LOCAL_BASE}/issues`; 43+ return { root, config, api }; 3945 // An explicit --server goes to that server's own Issues Worker: ABSO_ISSUES_SERVER doesn't redirect it. 4147 (env.server === undefined ? fromEnv(env.env, "ISSUES_SERVER") : undefined) || Lines 2–9 at 318 (were 2–9 at 277)
33import { randomUUID } from "node:crypto"; 44import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; 5−import { join, relative, resolve } from "node:path";
6−import { Api, ApiError } from "./api.ts";
5+import { isAbsolute, join, relative, resolve, sep } from "node:path"; 6+import { Api, ApiError, type SyncAnswer } from "./api.ts"; 77import { bool, type Parsed, str, UsageError } from "./args.ts"; 88import { writeKnownBlobs } from "./blobs.ts"; Lines 16–24 at 318 (were 16–24 at 277)
1818import { STARTING_ABSOIGNORE } from "./check-ignore.ts"; 19−import { CLIENT_DIR } from "./client-version.ts";
19+import { builtCopy } from "./client-version.ts"; 2020import { type Env, type Output, plural } from "./command-env.ts"; 21−import { leftOutText, syncFolder, uploadBlobs } from "./commands.ts";
21+import { applyAnswer, leftOutText, pullAnswer, pullWritten, syncFolder, uploadBlobs } from "./commands.ts"; Lines 32–39 at 318 (were 32–38 at 277)
3232import { elsewhereText } from "./doctor.ts"; 3333import { fromEnv } from "./env-names.ts"; 3434import { clearKnown, loadIgnore, readFolder, writeKnown } from "./folder.ts"; 35−import { modInstalled } from "./install.ts";
35+import { installerCommand, modHandsLocal, 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"; Lines 102–149 at 318 (were 101–106 at 277)
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."; Lines 154–214 at 318 (were 111–152 at 277)
111154 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`); 112155 const project = str(args, "project"); 113156 if (!project) throw new UsageError("give the project a name with --project <name>"); 157+ // Checked before any call: a name like ".." would otherwise go out as part of the request's path. 158+ if (!NAME.test(project)) 159+ throw new UsageError( 160+ `project names are letters, digits, dot, dash and underscore (got ${JSON.stringify(project)})`, 114162 if (bool(args, "public") && bool(args, "private")) throw new UsageError("--public or --private, not both"); 163+ const local = localFrom(args, env, "init"); 115164 // A box signed in here, and no other credential asked for: the project is made as the person who approved the box, 116165 // 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);
166+ const server = local ? LOCAL : serverFrom(args, env); 167+ const box = local ? undefined : readBox(server); 168+ const credential = local ? undefined : tokenCredential(args, env.env, server, root); 120169 const say = env.writeErr ?? env.write; 121170 if (box && credential === undefined) { 122171 say(`Signing in with this box's sign-in, ${box.id}. 124173 return initFromBox(args, env, root, project, server, box); 126− if (credential === undefined && tokenFile() !== undefined)
175+ if (!local && credential === undefined && tokenFile() !== undefined) 127176 throw new UsageError( 128177 `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}`, 130179 const org = str(args, "org"); 131180 if (org !== undefined) return initInOrg(org, server); 132− const config = makeSettings(args, env, project);
181+ const config: Settings = local 182+ ? { server: LOCAL, project, agent: agentFrom(args, str(args, "agent") ?? defaultAgentName()), ...local.settings } 183+ : makeSettings(args, env, project); 133184 const asIs = bool(args, "as-is"); 134185 const absoignore = join(root, ".absoignore"); 135186 const wroteIgnore = !asIs && !existsSync(absoignore) && !existsSync(join(root, ".avcsignore")); 136187 if (wroteIgnore) writeFileSync(absoignore, STARTING_ABSOIGNORE); 188+ // A store kept inside the project folder, like a virtual environment, isn't the project's files. 189+ const ignoredStore = local ? ignoreStoreInside(root, local.dir) : undefined; 137190 // What the server runs on each new version (#39), guessed from package.json; recorded with the rest. 138191 const wroteProject = asIs ? "exists" : writeStartingProjectFile(root); 139192 const { files, blobs, modes, leftOut } = readFolder(root, loadIgnore(root)); 140193 const token = credential?.token; 141− say(`Signing in with ${credential?.words ?? `no credential: nothing here signs in to ${server}`}.
195+ say(`Signing in with ${credential?.words ?? `no credential: nothing here signs in to ${server}`}. 143− const api = new Api({ ...config, ...(token ? { token } : {}) });
144− await uploadBlobs(api, blobs);
145− const answer = await api.init(
146− Object.fromEntries(files),
147− modes,
148− Object.fromEntries([...blobs].map(([rel, b]) => [rel, b.sha])),
149− );
197+ const api = new Api({ ...config, ...(token ? { token } : {}), ...(local ? { localStore: local.dir } : {}) }); 198+ let answer: Awaited<ReturnType<Api["init"]>>; 200+ await uploadBlobs(api, blobs); 201+ answer = await api.init( 202+ Object.fromEntries(files), 204+ Object.fromEntries([...blobs].map(([rel, b]) => [rel, b.sha])), 207+ // No project was made: the starting files init wrote go too, so the folder is as it was. 208+ if (wroteIgnore) rmSync(absoignore, { force: true }); 209+ if (typeof wroteProject !== "string") rmSync(join(root, projectFileName(root)), { force: true }); 150212 writeConfig(root, config); 152214 for (const [rel, text] of files) writeKnown(root, rel, text); Lines 224–237 at 318 (were 162–173 at 277)
163225 ? ["Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore."] 165− ...startingProjectFileText(wroteProject),
227+ // A local project has no CI to run abso.json, so no word about one that isn't there. 228+ ...(local && wroteProject === "nothing" ? [] : startingProjectFileText(wroteProject)), 166229 ...(answer.skipped && answer.skipped.length > 0 ? [`The server skipped: ${answer.skipped.join(", ")}.`] : []), 230+ ...(local ? [localText(local.dir, project, ignoredStore)] : []), 167231 `This folder is agent ${config.agent}. Settings are in .abso/config.json.`, 168232 ...refusedText(synced.refused), 169233 ...(synced.kept.length > 0 ? [`Kept your copy of ${synced.kept.join(", ")}.`] : []), 170− hookHint(env.env),
234+ hookHint(env.env, local !== undefined), Lines 242–248 at 318 (were 178–183 at 277)
178242 wroteAbsoignore: wroteIgnore, 179243 wroteProjectFile: typeof wroteProject === "string" ? null : wroteProject, 245+ ...(local ? { store: local.dir } : {}), Lines 416–431 at 318 (were 351–356 at 277)
419+/** A join that failed before writing files: its state goes, but a key (already here, or made for it) stays for the next try. */ 420+function takeBackJoin(root: string): void { 421+ const dir = stateDir(root); 422+ if (!existsSync(join(dir, "key"))) { 423+ rmSync(dir, { recursive: true, force: true }); 426+ for (const entry of readdirSync(dir)) if (entry !== "key") rmSync(join(dir, entry), { recursive: true, force: true }); 354429export async function runJoin(args: Parsed, env: Env): Promise<Output> { 355430 if (args.positionals.length !== 1) throw new UsageError("join takes the project name: abso join <project>"); 356431 const project = args.positionals[0]!; Lines 437–453 at 318 (were 362–375 at 277)
362437 mkdirSync(root, { recursive: true }); 363438 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`); 364439 const reader = bool(args, "reader"); 365− const server = serverFrom(args, env);
366− const box = readBox(server);
367− const hasKey = existsSync(join(stateDir(root), "key"));
368− const credential = tokenCredential(args, env.env, server, root);
440+ // A local project: no box, key or credential, and the agent is --agent or this computer's name. 441+ const local = localFrom(args, env, "join"); 442+ const server = local ? LOCAL : serverFrom(args, env); 443+ const box = local ? undefined : readBox(server); 444+ const hasKey = !local && existsSync(join(stateDir(root), "key")); 445+ const credential = local ? undefined : tokenCredential(args, env.env, server, root); 369446 const tokenFileAsked = bool(args, "token-file"); 370447 let agent: string; 371448 let minted: { key: string; id: string } | undefined; 372− if (str(args, "agent") !== undefined) {
449+ if (local) agent = agentFrom(args, str(args, "agent") ?? defaultAgentName()); 450+ else if (str(args, "agent") !== undefined) { 373451 agent = agentFrom(args); 375453 box && !hasKey && !fromEnv(env.env, "KEY_FILE") && !tokenFileAsked Lines 472–511 at 318 (were 394–423 at 277)
394472 agent = free.agent; 395473 minted = { key: free.key, id: free.id }; 397− const config = { server, project, agent, ...(reader ? { reader: true } : {}) };
475+ const config = { server, project, agent, ...(reader ? { reader: true } : {}), ...local?.settings }; 398476 writeConfig(root, config); 400478 if (minted) installKey(root, JSON.stringify(minted)); 401479 // The token file only with --token-file: readConfig reads it otherwise. 402− const read = readConfig(root, env.env, false);
480+ let read: ReturnType<typeof readConfig>; 482+ read = readConfig(root, env.env, false); 403487 const settings = tokenFileAsked ? { ...read, token: credential?.token } : read; 404− (env.writeErr ?? env.write)(
405− `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}`)}.
489+ (env.writeErr ?? env.write)( 490+ `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}`)}. 407− );
408493 const api = new Api(settings); 409− let synced: Awaited<ReturnType<typeof syncFolder>>;
494+ let answer: SyncAnswer; 411496 // Before the sync, so the server never takes a record from this folder. 412497 if (reader) await api.reader(true); 413498 // Every file, even when the server has seen this agent sync before: its plain sync answer would hold only what changed since (#37). 414− synced = await syncFolder(root, api, true);
499+ answer = await pullAnswer(root, api, true); 501+ // Nothing is written yet: take back what join wrote so it can run again here. 416503 if (!(error instanceof ApiError && error.status === 401 && !box && !settings.token)) throw error; 417− rmSync(stateDir(root), { recursive: true, force: true });
418504 const why = await signedOut(config.server, project); 419505 throw new UsageError(!tokenFileAsked && tokenFile() !== undefined ? `${why} ${TOKEN_FILE_ASKED}` : why); 507+ const synced = await applyAnswer(root, api, answer); 423511 `Joined ${project} as ${config.agent} at version ${synced.version}: wrote ${plural(synced.written.length, "file")} into ${root}.${reader ? " It is a reader: status, pull, log, show, files and export work, and nothing it does is recorded or pushed." : ""}${minted ? ` It signs in with its own key, ${minted.id}, made from this box's sign-in.` : ""}`, Lines 515–524 at 318 (were 427–435 at 277)
427515 `These files were already here and differ from shared, so they were left alone: ${synced.kept.join(", ")}. abso record sends them as your changes.`, 518+ ...(local ? [localText(local.dir, project)] : []), 430519 ...emptyHint(synced.version, synced.written.length, synced.kept.length, reader), 431520 ...setupHint(root), 432− hookHint(env.env),
521+ hookHint(env.env, local !== undefined), 433522 ...(root === resolve(env.cwd) ? [] : [`cd ${relative(env.cwd, root) || root}`]), Lines 542–559 at 318 (were 453–460 at 277)
453542 : [`Nothing is installed yet. Before building or testing here, run ${projectFileName(root)}'s setup: ${setup}`]; 456−function hookHint(env: Readonly<Record<string, string | undefined>>): string {
457− return modInstalled(env)
458− ? "Edits made by Claude Code here are recorded by the abso mod on this machine, signed in as this folder. Anything else: abso record."
459− : `Edits made by Claude Code reach the server through the abso mod, which isn't on this machine yet: node ${join(CLIENT_DIR, "install-mod.ts")} installs it, and new chats load it. Anything else: abso record.`;
545+function hookHint(env: Readonly<Record<string, string | undefined>>, local = false): string { 546+ // A local project has no server: the mod hands its edits to abso hook, when it was installed with one to hand them to. 548+ if (modHandsLocal(env)) 549+ return "Edits made by Claude Code here are recorded by the abso mod on this machine, through abso hook. Anything else: abso record."; 550+ if (modInstalled(env) && !builtCopy()) 551+ return `abso record sends the edits made here: the abso mod on this machine is older than local projects. ${installerCommand("install-mod.ts")} updates it, and new chats load it.`; 552+ return "abso record sends the edits made here, whoever made them."; 554+ if (modInstalled(env)) 555+ 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."; 556+ // A built copy (the npm package) has no installer to point at (abso-core 18). 557+ if (builtCopy()) return "abso record sends the edits made here, whoever made them."; 558+ return `Edits made by Claude Code reach the server through the abso mod, which isn't on this machine yet: ${installerCommand("install-mod.ts")} installs it, and new chats load it. Anything else: abso record.`; new file, 5 lines
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; 4+export declare const IssueProject: new (ctx: unknown, env: unknown) => object; 5+export declare function issuesFetch(request: Request, env: unknown, ctx: unknown, route: unknown): Promise<Response>; new file, 7 lines
1+// The open server's router, project object and issues, for local projects (local-store.ts). Plain JS, with its types 2+// in 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 { IssueProject, issuesFetch } from "../../server/src/issues-entry.ts"; 6+export { ProjectObject } from "../../server/src/project-object.ts"; 7+export { handle } from "../../server/src/router.ts"; new file, 407 lines
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+ // Through a cast: abso's worker compiles this file too (tool.lock.json), and its types have no globalThis.crypto. 163+ const c = (globalThis as unknown as { crypto: { DigestStream?: unknown } }).crypto; 164+ if (c.DigestStream) return; 165+ const { createHash } = await import("node:crypto"); 166+ class DigestStream extends WritableStream<Uint8Array> { 167+ readonly digest: Promise<ArrayBuffer>; 168+ constructor(algorithm: string) { 169+ const hash = createHash(algorithm.replace("-", "").toLowerCase()); 170+ let done!: (b: ArrayBuffer) => void; 171+ const digest = new Promise<ArrayBuffer>((ok) => { 175+ write: (chunk) => void hash.update(chunk), 177+ const b = hash.digest(); 178+ done(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer); 181+ this.digest = digest; 184+ c.DigestStream = DigestStream; 187+// --- Loading the server's code ------------------------------------------------------------------------------------ 190+ DatabaseSync: new (path: string) => Db; 191+ handle: (request: Request, env: unknown, ctx: unknown, issues: unknown) => Promise<Response>; 192+ ProjectObject: new (ctx: unknown, env: unknown) => object; 193+ IssueProject: new (ctx: unknown, env: unknown) => object; 194+ issuesFetch: (request: Request, env: unknown, ctx: unknown, route: unknown) => Promise<Response>; 196+let server: Promise<Server> | undefined; 198+/** Node's SQLite says it's experimental on every start; that line would land in every local command's output. */ 199+function quietSqliteWarning(): void { 200+ const emit = process.emitWarning; 201+ if ((emit as { quiet?: boolean }).quiet) return; 202+ const quiet = ((warning: string | Error, ...rest: unknown[]) => { 203+ const text = typeof warning === "string" ? warning : warning.message; 204+ if (text.startsWith("SQLite is an experimental feature")) return; 205+ return (emit as (...a: unknown[]) => void).call(process, warning, ...rest); 206+ }) as typeof process.emitWarning; 207+ (quiet as unknown as { quiet: boolean }).quiet = true; 208+ process.emitWarning = quiet; 211+export const NODE_TOO_OLD = `local projects need Node 22.13 or later, for its built-in SQLite; this is Node ${process.versions.node}`; 213+function loadServer(): Promise<Server> { 214+ server ??= (async () => { 215+ quietSqliteWarning(); 216+ let sqlite: { DatabaseSync: Server["DatabaseSync"] }; 218+ sqlite = (await import("node:sqlite")) as unknown as typeof sqlite; 220+ throw new LocalError(NODE_TOO_OLD); 222+ await installDigestStream(); 223+ // Run as .ts files, the server's `import { DurableObject } from "cloudflare:workers"` needs a stand-in. A built 224+ // copy has it already: the build points the import at the same file (scripts/build-client.mjs). 225+ const standIn = new URL("./durable-object-stand-in.ts", import.meta.url).href; 226+ const mod = (await import("node:module")) as unknown as { 227+ registerHooks?: (hooks: unknown) => unknown; 229+ // The hook stays for the rest of the process: deregistering it crashes Node 24 at exit when the compile cache 230+ // is on (client/avcs.ts turns it on). It answers only cloudflare:workers. 231+ mod.registerHooks?.({ 232+ resolve(specifier: string, context: unknown, next: (s: string, c: unknown) => unknown) { 233+ if (specifier === "cloudflare:workers") return { url: standIn, shortCircuit: true }; 234+ return next(specifier, context); 237+ let loaded: typeof import("./local-server.mjs"); 239+ loaded = await import("./local-server.mjs"); 241+ // Nothing is reached for here: a part of the client is missing (its packages not installed, say). 242+ throw new LocalError( 243+ `local projects couldn't load the server's code: ${e instanceof Error ? e.message : String(e)}`, 247+ DatabaseSync: sqlite.DatabaseSync, 248+ handle: loaded.handle, 249+ ProjectObject: loaded.ProjectObject, 250+ IssueProject: loaded.IssueProject, 251+ issuesFetch: loaded.issuesFetch, 257+/** What stops a local project from opening at all: said plainly, like a usage error. */ 258+export class LocalError extends UsageError {} 260+// --- One store, as a fetch ----------------------------------------------------------------------------------------- 264+ storage: ReturnType<typeof storageOver>; 265+ object: object | undefined; 266+ /** PRAGMA data_version when this process last used the project: it changes when another process writes. */ 267+ seen: number | undefined; 268+ /** The project's issues, asks and news: issues.sqlite beside it, opened when a call first reaches them. */ 269+ issues?: { db: Db; storage: ReturnType<typeof storageOver> }; 270+ /** The issues object for the call under way: made again for each call, as another process may have written. */ 271+ issueObject?: object; 274+/** Every store file this process has open: closed when its command ends (closeLocalStores). */ 275+const opened = new Set<Db>(); 277+/** Closes every local project this process opened. Its next call opens them again. */ 278+export function closeLocalStores(): void { 279+ for (const db of opened) { 287+/** A project's calls, and its issues, asks and news, which the open server keeps at /issues/p/<project>/. */ 288+const PROJECT_PATH = /^(?:\/issues)?\/p\/([^/]+)\//; 289+/** A project's name is also its folder in the store, so it never starts with a dot ("." and ".." would leave it). */ 290+const NAME = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,99}$/; 291+const json = (status: number, body: unknown) => Response.json(body, { status }); 294+ * The fetch a local folder's calls go through: each call is answered by the open server's router, in this process, 295+ * against the project's SQLite file in `dir`. Only init makes a project's file. 297+export function localFetch(dir: string): (input: string, init?: RequestInit) => Promise<Response> { 298+ const open = new Map<string, Open>(); 299+ let opening: Server | undefined; 300+ const openProject = (name: string, create: boolean): Open | undefined => { 301+ const existing = open.get(name); 302+ if (existing && opened.has(existing.db)) return existing; 303+ const folder = join(dir, name); 304+ const file = join(folder, "project.sqlite"); 305+ if (create) mkdirSync(folder, { recursive: true }); 306+ else if (!existsSync(file)) return undefined; 307+ const db = new opening!.DatabaseSync(file); 309+ db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 120000; PRAGMA synchronous = NORMAL"); 310+ const project = { db, storage: storageOver(db), object: undefined, seen: undefined }; 311+ open.set(name, project); 314+ const env = (name: string) => ({ 315+ ABSO_TOKEN: LOCAL_TOKEN, 316+ ABSO_ARTIFACTS: "off", 317+ ABSO_DISK_FIRST: "off", 319+ idFromName: (n: string) => n, 320+ get: (n: string) => { 321+ const p = open.get(n); 322+ if (!p || n !== name) throw new LocalError(`no local project ${n}`); 323+ p.object ??= new opening!.ProjectObject( 324+ { id: { toString: () => n, name: n }, storage: p.storage, waitUntil: () => {} }, 331+ idFromName: (n: string) => n, 332+ get: (n: string) => { 333+ const p = open.get(n); 334+ if (!p || n !== name) throw new LocalError(`no local project ${n}`); 335+ if (p.issues === undefined || !opened.has(p.issues.db)) { 336+ const db = new opening!.DatabaseSync(join(dir, name, "issues.sqlite")); 338+ db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 120000; PRAGMA synchronous = NORMAL"); 339+ p.issues = { db, storage: storageOver(db) }; 341+ // Its writes need no lock of their own: every call holds the project file's (see below). 342+ p.issueObject ??= new opening!.IssueProject( 343+ { id: { toString: () => n, name: n }, storage: p.issues.storage }, 346+ return p.issueObject; 350+ // One call at a time, as a Durable Object takes them: a call holds its project's write transaction across awaits, 351+ // and the connection can't start a second (two calls at once come from Promise.all in ci and waiting --mine). 352+ let last: Promise<unknown> = Promise.resolve(); 353+ return (input, init) => { 354+ const next = last.then( 355+ () => call(input, init), 356+ () => call(input, init), 358+ last = next.catch(() => {}); 362+ async function call(input: string, init: RequestInit = {}): Promise<Response> { 363+ const s = await loadServer(); 365+ const url = new URL(input); 366+ const match = PROJECT_PATH.exec(url.pathname); 367+ if (!match) return json(404, { error: "a local store answers only project calls" }); 368+ const name = decodeURIComponent(match[1]!); 369+ if (!NAME.test(name)) return json(400, { error: "project names use letters, digits, '.', '_' and '-'" }); 370+ const p = openProject(name, url.pathname === `/p/${match[1]}/init`); 371+ if (!p) return json(404, { error: `no local project ${name} in ${dir}` }); 372+ const headers = new Headers(init.headers); 373+ headers.set("authorization", `Bearer ${LOCAL_TOKEN}`); 374+ const request = new Request(url, { ...init, headers }); 375+ const waits: Promise<unknown>[] = []; 376+ // Every call, issues ones too, holds the project file's lock, so local writers of the project and of its 377+ // issues take one lock in one order. 378+ p.db.exec("BEGIN IMMEDIATE"); 379+ p.issueObject = undefined; 381+ const version = (p.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version; 382+ if (p.seen !== undefined && version !== p.seen) p.object = undefined; 383+ const response = await s.handle( 386+ { waitUntil: (w: Promise<unknown>) => waits.push(w) }, 389+ await Promise.allSettled(waits); 390+ // The answer is read whole before the write is kept, so a body that fails to arrive keeps nothing either. 391+ const body = await response.arrayBuffer(); 392+ p.db.exec("COMMIT"); 393+ p.seen = (p.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version; 394+ return new Response(body, { status: response.status, headers: response.headers }); 397+ p.db.exec("ROLLBACK"); 399+ // What the object held in memory may be from the rolled-back call. 400+ p.object = undefined; 402+ if (e instanceof LocalError) throw e; 403+ // Where the Workers runtime answers a throw with a 500, so does this. 404+ return json(500, { error: e instanceof Error ? e.message : String(e) }); Lines 1–8 at 318 (were 1–8 at 277)
11// The command table and the dispatcher. main() returns what to print and the 22// exit code instead of printing, so tests can call it directly. 4−import { readFileSync } from "node:fs";
5−import { resolve } from "node:path";
4+import { existsSync, readFileSync } from "node:fs"; 5+import { join, resolve } from "node:path"; 66import { runAnnounce, runNews, runStart } from "./announce.ts"; 77import { ApiError } from "./api.ts"; 88import { bool, type FlagSpec, type Parsed, parseArgs, str, UsageError } from "./args.ts"; Lines 38–44 at 318 (were 38–44 at 277)
4040} from "./commands.ts"; 41−import { configPath, findRoot, installKey, isVisitor, readConfig, tokenFile } from "./config.ts";
41+import { configPath, findRoot, installKey, isVisitor, readConfig, runKey, tokenFile } from "./config.ts"; 4242import { newsBlockLines, newsShown } from "./core.ts"; 4343import { doctor, doctorText, plainError, realProbe, whoami } from "./doctor.ts"; 4444import { runDraftSync, runLand, runSwitch } from "./drafts.ts"; Lines 59–65 at 318 (were 59–64 at 277)
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"; Lines 74–85 at 318 (were 73–82 at 277)
7475} from "./server-choice.ts"; 7576import { installSkill, SKILL, skillPath } from "./skill.ts"; 77+import { stateDir } from "./state-dir.ts"; 7678import { colorsPass, terminalText } from "./terminal-text.ts"; 7779import { runAmend, runDrop, runFollow, runLabel, runLabels, runPluck } from "./versions.ts"; 7880import { runVisibility } from "./visibility-commands.ts"; 7981import { checkVisitor } from "./visitor.ts"; 82+import { handoffText, patFromFile, webLogin } from "./web-session.ts"; 8184interface CommandDef { 8285 readonly flags: FlagSpec; Lines 123–135 at 318 (were 120–130 at 277)
120123 public: "boolean", 121124 private: "boolean", 122125 "token-file": "boolean", 125− "abso init [folder] --project <name> [--agent <name>] [--as-is] [--org <org>] [--public|--private] [--token-file]",
130+ "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]", 127− "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 avcs.json and package.json gives a check or a build to guess, an avcs.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.",
132+ "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.", 128133 run: (args, env) => runInit(args, env), Lines 145–151 at 318 (were 140–146 at 277)
141146 "abso key install [--server <url> [--dir <folder>]] | abso key new <agent> [--server <url> [--dir <folder>]] [--project <name>] [--expires <Nd>] [--role owner|writer|reader] [--print] | abso key list [--agent <name>] [--project <name>] | abso key revoke <id> [--project <name>]", 143− "install reads {key, id} from stdin into .abso/key. With --server, it writes it into a folder not joined yet, so abso join there signs in with the key. new writes the key into that folder and prints only the id; its role is writer unless --role says otherwise (a reader only reads; a writer writes on its own agent's routes; an owner also skips or revokes CI, resumes the queue, syncs git and exports); --print writes the key to stdout instead. list and revoke never print a key. These three read the admin token from AVCS_ADMIN_TOKEN or ~/.abso/admin-token and send it only to a server named in AVCS_ADMIN_SERVERS. An agent does not run them unless a person on the project says so.",
148+ "install reads {key, id} from stdin into .abso/key. With --server, it writes it into a folder not joined yet, so abso join there signs in with the key. new writes the key into that folder and prints only the id; its role is writer unless --role says otherwise (a reader only reads; a writer writes on its own agent's routes; an owner also skips or revokes CI, resumes the queue, syncs git and exports); --print writes the key to stdout instead. list and revoke never print a key. These three read the admin token from ABSO_ADMIN_TOKEN or ~/.abso/admin-token and send it only to a server named in ABSO_ADMIN_SERVERS. An agent does not run them unless a person on the project says so.", 144149 run: async (args, env) => { 145150 const sub = args.positionals[0]; 146151 if (sub === "install" && args.positionals.length === 1) return runKeyInstall(args, env); Lines 213–244 at 318 (were 208–220 at 277)
208213 projects: "string", 218+ "pat-file": "string", 213− "abso login [--no-browser] [--no-ask] [--projects <name,name>] [--role <reader|writer|owner>] [--days <1-90>]",
221+ "abso login [--no-browser] [--no-ask] [--projects <name,name>] [--role <reader|writer|owner>] [--days <1-90>] | abso login --web [--pat-file <file> [--site http://localhost:<port>]]", 215− "Sign this box in once: it opens the approve page in your browser with the code filled in, prints the link and the code too, and waits while a person approves the code on the website, choosing the projects, the highest role and how long. Then abso join in any of those projects gives each agent its own key, with no approval. The box's sign-in is kept in your user folder, never in a project folder, and is never printed. No browser opens with --no-browser or ABSO_NO_BROWSER, over SSH, under CI, or on Linux without a display. In an agent's folder on the same server, it also asks a person in that project to approve it (the person who approved the agent's box, else the project's owners), as an abso ask, so nobody has to relay the code; the box can then be granted that project at no more than the agent's own role. --no-ask shows the code only.",
223+ "Sign this box in once: it opens the approve page in your browser with the code filled in, prints the link and the code too, and waits while a person approves the code on the website, choosing the projects, the highest role and how long. Then abso join in any of those projects gives each agent its own key, with no approval. The box's sign-in is kept in your user folder, never in a project folder, and is never printed. No browser opens with --no-browser or ABSO_NO_BROWSER, over SSH, under CI, or on Linux without a display. In an agent's folder on the same server, it also asks a person in that project to approve it (the person who approved the agent's box, else the project's owners), as an abso ask, so nobody has to relay the code; the box can then be granted that project at no more than the agent's own role. --no-ask shows the code only. --web, on staging only, signs a browser in to the website instead: it prints a link that works once, within a minute, and signs whichever browser opens it in as the person who approved this box, but only to the projects the box was granted and at most as a writer, until the box is revoked or ends (or, with --pat-file, as the test account whose PAT that file holds, at most as a writer). It writes issues, replies, answers, groups and announcements, and changes no members, roles, visibility, keys, boxes or settings. The box's sign-in, the PAT and the session never appear. It goes only to the staging website beside this folder's staging server; any other server, prod included, is refused and nothing is sent. --site, with --pat-file only, points it at a website on this machine (http://localhost or 127.0.0.1).", 216224 run: async (args, env) => { 217225 const server = boxServer(args, env); 226+ if (bool(args, "web")) { 227+ const patFile = str(args, "pat-file"); 228+ const { handoff, site } = await webLogin({ 230+ site: str(args, "site"), 231+ kind: patFile === undefined ? "box" : "pat", 233+ if (patFile !== undefined) return patFromFile(patFile); 234+ const record = readBox(server); 235+ if (record === undefined || record.expiresAt <= Date.now()) 236+ throw new UsageError(`this box isn't signed in to ${server}: abso login first, or --pat-file <file>`); 237+ return record.credential; 240+ return { text: handoffText(handoff, site, patFile === undefined), json: { ...handoff } }; 219243 bool(args, "no-browser") || browserSkip(env.env, process.platform) !== null Lines 350–368 at 318 (were 326–335 at 277)
329− flags: { server: "string", agent: "string", dir: "string", reader: "boolean", "token-file": "boolean" },
330− usage: "abso join <project> [--agent <name>] [--dir <folder>] [--reader] [--token-file]",
358+ "token-file": "boolean", 363+ "abso join <project> [--agent <name>] [--dir <folder>] [--reader] [--token-file] | abso join <project> --local [--agent <name>] [--store <folder>] [--dir <folder>]", 332− "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.",
365+ "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.", Lines 385–391 at 318 (were 352–358 at 277)
353386 usage: 'abso push -m "<why>" [--as-is] [--check ["<command>"]] [--wait <seconds> | --no-wait] [--done]', 355− 'Record, then add your draft to shared. Refused when it collides with work pushed since your last pull, or when lines a pull showed changed on both sides are still untouched (--as-is pushes both sides\' lines anyway). --check "<command>" (e.g. --check "npm run typecheck") first pulls, then runs the command in your box on your draft with newest shared, and pushes only if it exits 0, so two changes that each pass alone can\'t turn shared red. --check alone runs the "build" and then the "check" in the project\'s avcs.json (your draft\'s copy), as the server does on each new version. With the merge queue on ("queue": true in avcs.json), a push to shared is queued and lands only once the project\'s check passes on shared with it on top: push waits up to 100 s for that (--wait <seconds> changes it, --no-wait returns at once), then says it landed (exit 0), was turned back with the check\'s output (exit 2, its changes still in your draft), or is still queued (exit 3; the outcome comes as news). --check alone is skipped then, since the queue runs the check. --done takes your start note back once it\'s pushed: this push finishes that work.',
388+ 'Record, then add your draft to shared. Refused when it collides with work pushed since your last pull, or when lines a pull showed changed on both sides are still untouched (--as-is pushes both sides\' lines anyway). --check "<command>" (e.g. --check "npm run typecheck") first pulls, then runs the command in your box on your draft with newest shared, and pushes only if it exits 0, so two changes that each pass alone can\'t turn shared red. --check alone runs the "build" and then the "check" in the project\'s abso.json (your draft\'s copy), as the server does on each new version. With the merge queue on ("queue": true in abso.json), a push to shared is queued and lands only once the project\'s check passes on shared with it on top: push waits up to 100 s for that (--wait <seconds> changes it, --no-wait returns at once), then says it landed (exit 0), was turned back with the check\'s output (exit 2, its changes still in your draft), or is still queued (exit 3; the outcome comes as news). --check alone is skipped then, since the queue runs the check. --done takes your start note back once it\'s pushed: this push finishes that work.', Lines 433–439 at 318 (were 400–406 at 277)
401434 'abso run [--detach] [--replace] [--fresh] [--box <name>] [--at <version> [--files <glob>]] <command...> | abso run ... -- <program> <arg...> | abso run --parallel "<command>" "<command>"...', 403− "Send the folder to this agent's box, run the command there, and stream its output back. Exits with the command's code. After --, each word goes to the program exactly as typed (quotes, backslashes, regex text); without --, the words are one shell command. The box's stderr comes out on stderr. --detach starts it and prints its id without waiting. While a run is still going in the box, a new one is refused (409, naming it), since it would replace the files under it; --replace stops the old one first. --parallel runs each quoted command at once in the box (one upload), labels each line [1], [2], ..., ends with each one's exit code, and exits with the worst. --at <version> runs that version of the folder's space instead of the folder (for bisecting); with --files <glob>, only the matching files are taken from that version. The folder is never touched. --fetch <glob>[,<glob>...] brings matching files from the box's /w back after the run (see abso fetch); several globs go in one argument, comma-separated (--fetch 'shots/*.png,out/*.json'), as for --files and --with. The box's /w is replaced by your folder on every run; the rest of the box (/tmp, ~/.cache, /w/node_modules) lasts between runs until the box stops (idle 30 minutes, or restarted). abso's own notices go to stderr, apart from the command's output; --quiet drops them (the command's own stderr still comes through). --with <box path>=<local path>[,...] adds files (or a folder's files) for this run only: they go to the box and are never written to your folder or recorded, for an A/B run that leaves the project alone. --box <name> (or AVCS_BOX=<name>) runs in another box of yours, with its own /w and state, so a subagent's runs and yours don't wait on each other; logs and fetch take --box too. After abso prep, a fresh box starts from the prep; --fresh starts this run from the plain image instead.",
436+ "Send the folder to this agent's box, run the command there, and stream its output back. Exits with the command's code. After --, each word goes to the program exactly as typed (quotes, backslashes, regex text); without --, the words are one shell command. The box's stderr comes out on stderr. --detach starts it and prints its id without waiting. While a run is still going in the box, a new one is refused (409, naming it), since it would replace the files under it; --replace stops the old one first. --parallel runs each quoted command at once in the box (one upload), labels each line [1], [2], ..., ends with each one's exit code, and exits with the worst. --at <version> runs that version of the folder's space instead of the folder (for bisecting); with --files <glob>, only the matching files are taken from that version. The folder is never touched. --fetch <glob>[,<glob>...] brings matching files from the box's /w back after the run (see abso fetch); several globs go in one argument, comma-separated (--fetch 'shots/*.png,out/*.json'), as for --files and --with. The box's /w is replaced by your folder on every run; the rest of the box (/tmp, ~/.cache, /w/node_modules) lasts between runs until the box stops (idle 30 minutes, or restarted). abso's own notices go to stderr, apart from the command's output; --quiet drops them (the command's own stderr still comes through). --with <box path>=<local path>[,...] adds files (or a folder's files) for this run only: they go to the box and are never written to your folder or recorded, for an A/B run that leaves the project alone. --box <name> (or ABSO_BOX=<name>) runs in another box of yours, with its own /w and state, so a subagent's runs and yours don't wait on each other; logs and fetch take --box too. After abso prep, a fresh box starts from the prep; --fresh starts this run from the plain image instead.", Lines 648–654 at 318 (were 615–621 at 277)
615648 flags: { version: "string", revoke: "boolean" }, 616649 usage: "abso ci [<version>] | abso ci --revoke", 618− "The project's CI: the server runs avcs.json's setup, build and check on each new version of shared, one job at a time on the newest. abso ci says whether shared is green or red (and since which version, by whom, once a bisect finds it), what is being checked, and the preview link of the newest passing build, which needs no token. abso ci <version> shows that version's job: which step failed, its exit code, and the end of its output. status says the same in a line, and log marks each version of shared. --revoke ends every preview link handed out so far and makes a new one.",
651+ "The project's CI: the server runs abso.json's setup, build and check on each new version of shared, one job at a time on the newest. abso ci says whether shared is green or red (and since which version, by whom, once a bisect finds it), what is being checked, and the preview link of the newest passing build, which needs no token. abso ci <version> shows that version's job: which step failed, its exit code, and the end of its output. status says the same in a line, and log marks each version of shared. --revoke ends every preview link handed out so far and makes a new one.", Lines 674–680 at 318 (were 641–647 at 277)
642675 'abso shot ["/<path>?<query>"] [--scale 0.1-1] [--region x0,y0,x1,y1] [--text] [--tree [--interactive] [--depth N]] [--find "<text>"] [--max-chars N] [--image] [--at <version>] [--eval "<js>"] [--click "x,y[@ms];ref_N[@ms]"] [--mouse x,y|ref_N] [--out <file.png>] [--wait <ms>] [--size <w>x<h>]', 644− "A look at your folder's game, taken in your box: it runs the project's vite dev server and Playwright on that page (default /, a 1280x720 page). Images cost tokens, so read without one when you can: --text prints the page's visible text, --tree its elements (role, name, a ref like ref_12, and its box in page pixels; --interactive only what can be clicked or typed in; --depth N levels), and --find \"<text>\" the elements matching some text; each is capped at --max-chars (default 5000). With none of those, or with --image, it writes a PNG to .avcs/shots/ (never recorded) or --out, and prints its pixel size and about how many tokens reading it costs (width x height / 750). --scale 0.5 halves the width and height (a quarter of the tokens); --region x0,y0,x1,y1 takes part of the page at full detail; they combine. Coordinates are always the page's, whatever the scale or region. To set up a state first, --eval runs JavaScript in the page and --click clicks points (x,y or ref_N; several separated by ;; @ms waits first), in that order, a second after load and two frames after the eval; --mouse x,y or ref_N leaves the pointer there (for hover cards); then it waits --wait ms (default 3000) and looks. It prints --eval's result, page errors and the first 30 console messages. Refs come from --tree or --find on the same page in the same state. --at <version> looks at that version of your folder's space instead of the folder (as abso run --at). Needs vite and playwright in the project's devDependencies; abso prep with npx --no-install playwright install chromium makes it fast.",
677+ "A look at your folder's game, taken in your box: it runs the project's vite dev server and Playwright on that page (default /, a 1280x720 page). Images cost tokens, so read without one when you can: --text prints the page's visible text, --tree its elements (role, name, a ref like ref_12, and its box in page pixels; --interactive only what can be clicked or typed in; --depth N levels), and --find \"<text>\" the elements matching some text; each is capped at --max-chars (default 5000). With none of those, or with --image, it writes a PNG to .abso/shots/ (never recorded) or --out, and prints its pixel size and about how many tokens reading it costs (width x height / 750). --scale 0.5 halves the width and height (a quarter of the tokens); --region x0,y0,x1,y1 takes part of the page at full detail; they combine. Coordinates are always the page's, whatever the scale or region. To set up a state first, --eval runs JavaScript in the page and --click clicks points (x,y or ref_N; several separated by ;; @ms waits first), in that order, a second after load and two frames after the eval; --mouse x,y or ref_N leaves the pointer there (for hover cards); then it waits --wait ms (default 3000) and looks. It prints --eval's result, page errors and the first 30 console messages. Refs come from --tree or --find on the same page in the same state. --at <version> looks at that version of your folder's space instead of the folder (as abso run --at). Needs vite and playwright in the project's devDependencies; abso prep with npx --no-install playwright install chromium makes it fast.", Lines 890–896 at 318 (were 857–863 at 277)
858891 "abso pipeline check [file] [--on push|draft|green|land|hand|schedule [--space <name>] [--pipeline <name>] [--every <when>]] | abso pipeline runs [<run>] [--log <pipeline.job>]", 860− "Read the folder's pipeline file (abso.yml, abso.yaml or avcs.json, or the file named) and say what's wrong with it, place by place: a cycle in needs, a job that doesn't exist, secrets a draft could reach, a key it doesn't know. Exits 1 when it has problems. With --on, it says which pipelines that event starts (in shared, or --space), with their jobs in waves that can run side by side, and why each other pipeline doesn't start. It reads only the file. abso pipeline runs asks the server what the project's pipelines did: the runs, newest first; with a run's number, its jobs (state, why, exit, time, an npm or deploy job's phase); with --log <pipeline.job>, that job's output.",
893+ "Read the folder's pipeline file (abso.yml, abso.yaml or abso.json, or the file named) and say what's wrong with it, place by place: a cycle in needs, a job that doesn't exist, secrets a draft could reach, a key it doesn't know. Exits 1 when it has problems. With --on, it says which pipelines that event starts (in shared, or --space), with their jobs in waves that can run side by side, and why each other pipeline doesn't start. It reads only the file. abso pipeline runs asks the server what the project's pipelines did: the runs, newest first; with a run's number, its jobs (state, why, exit, time, an npm or deploy job's phase); with --log <pipeline.job>, that job's output.", 861894 // Loaded only here, so the yaml package it needs can't stop every other command 862895 // when a checkout lacks it (abso issue 168). 863896 run: async (args, env) => { Lines 995–1010 at 318 (were 962–975 at 277)
964997/** Whether this folder's calls carry a key or token, for how a refusal is worded. False when that can't be told. */ 965−function carriesCredential(env: Env, tokenFileAsked: boolean): boolean {
998+function credentialSent(env: Env, tokenFileAsked: boolean): string | undefined { 9671000 const root = findRoot(env.cwd); 968− return root
969− ? readConfig(root, env.env, tokenFileAsked).token !== undefined
970− : (fromEnv(env.env, "TOKEN") ?? (tokenFileAsked ? tokenFile() : undefined)) !== undefined;
1001+ if (root && readConfig(root, env.env, tokenFileAsked).token === undefined) return undefined; 1002+ if (root && existsSync(join(stateDir(root), "key"))) return "this folder's key"; 1003+ if (fromEnv(env.env, "TOKEN")?.trim()) return "ABSO_TOKEN"; 1004+ if (root && runKey(env.env)) return "this pipeline run's key"; 1005+ return tokenFileAsked && tokenFile() !== undefined ? "the token file, ~/.abso/token" : undefined; 972− return false;
Lines 1021–1035 at 318 (were 986–991 at 277)
9881023export async function main(argv: readonly string[], env: Env): Promise<MainResult> { 1025+ return await runMain(argv, env); 1027+ // A local project's store stays open only while its command runs. 1028+ closeLocalStores(); 1032+async function runMain(argv: readonly string[], env: Env): Promise<MainResult> { 9891033 const command = argv[0]; 9901034 const json = argv.includes("--json") && command !== "run" && command !== "logs"; 9911035 const asked = argv.includes("--token-file"); Lines 1123–1129 at 318 (were 1079–1085 at 277)
10791123 const e = err as Error; 10801124 const code = err instanceof UsageError ? "usage" : err instanceof ApiError ? "server" : "error"; 1082− plainError(err, carriesCredential(env, asked), !asked && tokenFile() !== undefined) ??
1126+ plainError(err, credentialSent(env, asked), !asked && tokenFile() !== undefined) ?? 10831127 (err instanceof UsageError || err instanceof ApiError 10851129 : `${e.message}${e.stack ? `\n${e.stack}` : ""}`); Lines 15–30 at 318 (were 15–23 at 277)
1515export interface NewsTicket { 1616 readonly url: string; 1717 readonly protocols: readonly string[]; 18− readonly expiresAt: number;
18+ /** When the ticket stops working: the server sends an ISO time; milliseconds are taken too. */ 19+ readonly expiresAt: number | string; 22+/** A ticket's expiry in milliseconds, whichever form the server sent; now when it can't be read. */ 23+export function expiresAtMs(ticket: NewsTicket, now: number): number { 24+ const at = typeof ticket.expiresAt === "number" ? ticket.expiresAt : Date.parse(ticket.expiresAt); 25+ return Number.isFinite(at) ? at : now; 2128/** A Monitor lasts at most 30 minutes; the skill re-arms it when it ends. */ 2229export const MONITOR_TIMEOUT_MS = 30 * 60_000; Lines 43–49 at 318 (were 36–42 at 277)
3744/** The text --stream prints: the call to make, then the arguments as one line of JSON. */ 3845export function streamText(ticket: NewsTicket, project: string, agent: string, now = Date.now()): string { 39− const seconds = Math.max(0, Math.round((ticket.expiresAt - now) / 1000));
46+ const seconds = Math.max(0, Math.round((expiresAtMs(ticket, now) - now) / 1000)); 4148 `Open this with Monitor within ${seconds} seconds (the ticket opens ${agent}'s news stream once). When the Monitor ends or the socket closes, run abso news --stream again; the new socket sends what arrived in between.`, 4249 JSON.stringify(monitorArgs(ticket, project, agent)), Lines 55–61 at 318 (were 48–54 at 277)
4956/** How long --stream's mark holds: the Monitor's 30 minutes, and the minute the ticket waits to be used. */ 5057export function streamMarkUntil(ticket: NewsTicket, now: number): number { 51− return Math.max(now, ticket.expiresAt) + MONITOR_TIMEOUT_MS;
58+ return Math.max(now, expiresAtMs(ticket, now)) + MONITOR_TIMEOUT_MS; 5461/** The part of a WebSocket --follow uses: the platform's own, or a test's. */ Lines 94–101 at 318 (were 87–92 at 277)
8794 sleep(ms: number): Promise<void>; 8996 every(ms: number, fn: () => void): () => void; 97+ /** Reads the seat's news, marking it heard (POST news); a frame calls it. Without it, frames are printed as they come. */ 98+ take?(): Promise<readonly string[]>; 9099 /** Called when a socket opens and at each ping: the stream is held until the next ping is due, and a little more. */ 91100 held?(until: number): void; 92101 /** Set when --follow should stop (Ctrl-C, or a test). */ Lines 109–163 at 318 (were 100–109 at 277)
112+ * A frame is a wake (abso 690): on one, read the seat's news (which marks it heard) and print what that answers, one 113+ * read at a time, with frames that arrive meanwhile folded into one more read. When the read answers nothing (a server 114+ * that counts a frame as heard already, or another chat on the seat took it first), the frames themselves are printed. 116+function frameReads(deps: FollowDeps): { frame(text: string): void; idle(): Promise<void> } { 117+ let frames: string[] = []; 118+ /** The lines printed lately, so a frame a read already printed isn't printed again. */ 119+ const shown: string[] = []; 120+ const show = (line: string) => { 123+ if (shown.length > 200) shown.shift(); 125+ let running: Promise<void> | undefined; 127+ const pass = async () => { 130+ const these = frames; 132+ let items: readonly string[] = []; 134+ items = await deps.take!(); 136+ deps.note(`(abso news --follow: couldn't read the news: ${(err as Error).message}; showing the frames)`); 138+ for (const line of items) show(line); 139+ // A frame the read didn't cover still shows: on a server that counts a frame as heard, its item never comes back 140+ // from the read. A catch-up frame names several items, so a frame holding a shown item counts as covered. 141+ for (const frame of these) if (!shown.some((line) => frame.includes(line) || line.includes(frame))) show(frame); 143+ running = undefined; 148+ if (running !== undefined) again = true; 149+ else running = pass(); 151+ idle: () => running ?? Promise.resolve(), 103156 * Holds the seat's stream, printing one line per item, until the key is refused or `stopped()`. 104157 * Returns why it ended. 106159export async function follow(deps: FollowDeps): Promise<{ ended: "refused" | "stopped"; reason: string }> { 160+ const reads = frameReads(deps); 108162 while (!deps.stopped()) { 109163 let ticket: NewsTicket; Lines 186–198 at 318 (were 132–143 at 277)
133187 socket.onmessage = (e) => { 134188 if (typeof e.data !== "string" || e.data === PONG) return; 135− deps.write(e.data);
189+ if (deps.take === undefined) deps.write(e.data); 190+ else reads.frame(e.data); 137192 socket.onerror = () => {}; 138193 socket.onclose = (e) => { 140− done({ code: e.code, reason: e.reason });
195+ void reads.idle().then(() => done({ code: e.code, reason: e.reason })); 143198 if (isRefusal(closed.code)) return { ended: "refused", reason: closed.reason || `closed ${closed.code}` }; Lines 13–19 at 318 (were 13–18 at 277)
Lines 622–629 at 318 (were 621–626 at 277)
621622 const { root, api } = open(env); 622623 const recorded = await recordFolder(root, api); 623624 const ignoredDropped = await dropIgnoredFromDraft(root, api); 625+ // A pull here that never wrote its answer (abso-core 26): this one asks for every file to catch up. 626+ const catchingUp = pullUnfinished(root) && !bool(args, "full"); 624627 const s = await syncFolder(root, api, bool(args, "full")); 625628 const changes = s.written.length + s.deleted.length; 626629 // A renamed file is one line, not an update and a delete. Lines 635–643 at 318 (were 632–637 at 277)
632635 ...droppedIgnoredText(ignoredDropped), 633636 `Pulled to version ${s.version}: ${changes === 0 ? "no files changed" : `${plural(updated.length, "file")} updated, ${removed.length} deleted${s.renamed.length > 0 ? `, ${s.renamed.length} renamed` : ""}`}.`, 634637 ...changedFilesText("pull", updated, removed, s.renamed, bool(args, "verbose")), 639+ ? ["The last pull here didn't finish, so this one asked for every file and wrote the ones that differed."] 635641 ...refusedText(s.refused), 636642 // Ones an earlier sync couldn't write; this sync's are named just above. 637643 ...unwrittenText(s.unwritten, new Set(s.refused.map((r) => r.path))), Lines 6–12 at 318 (were 6–11 at 277)
66import { boxOf, runRun, shellWord, undoGitBashPaths } from "./box-commands.ts"; 77import { type Env, EXIT, type Output, open } from "./command-env.ts"; 88import { fetchedText, fetchFromBox } from "./fetch.ts"; 9+import { stateDir } from "./state-dir.ts"; 910import { untarGz } from "./tar.ts"; 1112/** abso serve [--version N]: a preview of one version of shared at a stable URL, built once on the server (#37). */ Lines 330–344 at 318 (were 329–342 at 277)
330331 const info = lines.find((l) => l.startsWith("ABSO_SHOT_IMAGE ")); 331332 const { root, api } = open(env); 332− void root;
333333 api.box = boxOf(args, env); 334334 const gz = await api.boxFiles(`.abso-shot/${name}`); 335335 const png = gz === null ? undefined : untarGz(gz).find((e) => e.path === `.abso-shot/${name}`); 336336 if (!png || !info) 337337 return { exit: EXIT.error, text: "The screenshot ran but its file was not in the box.", json: { notes } }; 338338 const { w, h } = JSON.parse(info.slice("ABSO_SHOT_IMAGE ".length)) as { w: number; h: number }; 339− const path = resolve(env.cwd, str(args, "out") ?? join(".avcs", "shots", name));
339+ // In the folder's own state folder (.abso/, or .avcs/ in an older folder), which abso never records. 341+ str(args, "out") !== undefined ? resolve(env.cwd, str(args, "out")!) : join(stateDir(root), "shots", name); 340342 mkdirSync(join(path, ".."), { recursive: true }); 341343 writeFileSync(path, png.data); 342344 shot = { path, w, h, bytes: png.data.length, tokens: imageTokens(w, h) }; Lines 14–20 at 318 (were 14–19 at 277)
Lines 40–46 at 318 (were 39–44 at 277)
3940} from "./folder.ts"; 4041import { fileArg } from "./history.ts"; 4142import { modsBehindText } from "./install.ts"; 43+import { isLocal } from "./local-store.ts"; 4244import { withFolderLock } from "./lock.ts"; 4345import { readKnownModes, writeKnownModes } from "./modes.ts"; 4446import { queueText } from "./queue.ts"; Lines 326–336 at 318 (were 324–332 at 277)
324326 const space = (draft: string | null | undefined): string => (draft ? `draft ${draft}` : "shared"); 325327 const parked = (me?.parked ?? []).filter((p) => p.draftChanges > 0); 326328 const credential = credentialLabel(root, config.server, env.env); 327− const behind = await newerClientNote(config.server);
329+ // A local project reaches for nothing on the network, npm included. 330+ const localProject = isLocal(config.server); 331+ const behind = localProject ? undefined : await newerClientNote(config.server); 329− `Project ${config.project}: shared is at version ${status.version}. This folder is ${config.agent}${config.reader || me?.reader ? ", a reader (it records and pushes nothing)" : ""}, working in ${space(me?.draft)}.${config.follow ? ` It follows label ${config.follow}: pulls take it to the newest version with that label.` : ""} Signed in with ${credential.kind}${credential.id ? ` ${credential.id}` : ""}.`,
333+ `Project ${config.project}: shared is at version ${status.version}. This folder is ${config.agent}${config.reader || me?.reader ? ", a reader (it records and pushes nothing)" : ""}, working in ${space(me?.draft)}.${config.follow ? ` It follows label ${config.follow}: pulls take it to the newest version with that label.` : ""}${localProject ? ` It's a local project, in ${join(config.localStore ?? "", config.project)}.` : ` Signed in with ${credential.kind}${credential.id ? ` ${credential.id}` : ""}.`}`, 330334 ...(behind ? [behind] : []), 331335 // Is shared green (#39)? Right under the first line, since it decides what to do next. 332336 ...ciText(status.ci, status.version), Lines 353–359 at 318 (were 349–354 at 277)
349353 ...modsBehindText(env.env), 350354 ...missingText(missing), 351355 ...unwrittenText(unwritten), 356+ ...pullUnfinishedText(root), 352357 ...(crlf.length > 0 354359 `${plural(crlf.length, "file")} differ${crlf.length === 1 ? "s" : ""} from what abso recorded only in line endings (CRLF here; abso records and abso run sends LF). Harmless; abso fix-eol rewrites ${crlf.length === 1 ? "it" : "them"} with LF.`, Lines 3–20 at 318 (were 3–9 at 277)
44import type { VersionRef } from "./api.ts"; 55import { bool, type Parsed, str, UsageError } from "./args.ts"; 6−import { applyAnswer, collisionText, type Env, EXIT, type Output, open, plural, recordFolder } from "./commands.ts";
17+} from "./commands.ts"; 718import { writeConfig } from "./config.ts"; 819import { refusedText } from "./safety.ts"; Lines 155–162 at 318 (were 144–150 at 277)
144155 // Sync now (recording first, as sync does), so the folder is where it now says it is. 145156 const { api } = open(env); 146157 await recordFolder(root, api); 147− const s = await applyAnswer(root, api, await api.sync());
158+ const s = await applyAnswer(root, api, await pullAnswer(root, api)); 148160 const changes = s.written.length + s.deleted.length; 149161 const head = follow 150162 ? `This folder now follows label ${follow}: every pull takes it to the newest version with that label. It is on version ${s.version}.` new file, 141 lines
1+// abso login --web: a staging website session for the person a box is signed in as, opened in an agent's own browser, with 2+// no secret in the agent's hands. The website's /login/handoff takes this box's sign-in (or a test account's PAT, from a file) 3+// and answers a one-use link that works for a minute; opening it signs that browser in. Only the link is printed: never the 4+// box's sign-in, the PAT or the session cookie, which the website sets in the browser itself. 6+import { readFileSync } from "node:fs"; 7+import { UsageError } from "./args.ts"; 9+/** The website beside each staging server. Prod has none here: agents never sign in to the website on prod. */ 10+const STAGING_SITES: Readonly<Record<string, string>> = { 11+ "https://abso-staging.chrisazy.workers.dev": "https://abso-website-staging.chrisazy.workers.dev", 12+ "https://avcs-staging.chrisazy.workers.dev": "https://abso-website-staging.chrisazy.workers.dev", 15+/** What the website answers: the link, when it stops working, and who and until when it signs in. */ 16+export interface Handoff { 17+ readonly url: string; 18+ readonly expiresAt: string; 19+ readonly account: string; 20+ readonly name: string; 21+ readonly sessionEnds: string; 25+ * The website a handoff's credential goes to (Security condition 6, Code Review): the staging website beside the folder's own 26+ * staging server, from the fixed list above, and never an origin from a flag. A server that isn't on the list is refused, 27+ * prod included. --site is only for a test account's PAT on this machine (http://localhost or 127.0.0.1); a box's sign-in 28+ * takes no --site at all. 30+export function siteFor(server: string, site: string | undefined, kind: "box" | "pat"): string { 31+ const origin = new URL(server).origin; 32+ const known = STAGING_SITES[origin]; 33+ if (known === undefined) 34+ throw new UsageError( 35+ `abso login --web is for staging: ${origin} has no staging website beside it that abso knows, and agents never sign in to the website on prod. Nothing was sent.`, 37+ if (site === undefined) return known; 39+ throw new UsageError(`--site isn't taken with a box's sign-in, which goes only to ${known}. Nothing was sent.`); 40+ let url: URL | null = null; 44+ // Not an address: refused below. 46+ if (url === null || url.protocol !== "http:" || (url.hostname !== "localhost" && url.hostname !== "127.0.0.1")) 47+ throw new UsageError( 48+ "--site, with --pat-file, names this machine only (http://localhost:<port> or http://127.0.0.1:<port>). Nothing was sent.", 54+ * abso login --web: where the credential would go is settled before it is read, so a refusal reads and sends nothing 55+ * (Security). `credential` reads the box's sign-in or the PAT only once the website is one it may go to. 57+export async function webLogin(options: { 58+ readonly server: string; 59+ readonly site: string | undefined; 60+ /** A box's sign-in, or a test account's PAT (--pat-file). */ 61+ readonly kind: "box" | "pat"; 62+ readonly credential: () => string; 63+ readonly fetcher?: typeof fetch; 64+}): Promise<{ handoff: Handoff; site: string }> { 65+ const site = siteFor(options.server, options.site, options.kind); 66+ return { handoff: await webHandoff(site, options.credential(), options.fetcher), site }; 69+/** A PAT from the file --pat-file names: read here, never printed. */ 70+export function patFromFile(path: string): string { 73+ text = readFileSync(path, "utf8").trim(); 75+ throw new UsageError(`--pat-file names ${path}, which abso can't read`); 77+ if (!/^abso_pat_[A-Za-z0-9_-]{16,200}$/.test(text)) 78+ throw new UsageError(`--pat-file names ${path}, which doesn't hold a PAT`); 82+/** Words from the website, with any secret this call sent taken out. */ 83+function scrubbed(text: string, secret: string): string { 84+ return text.split(secret).join("[the credential]").slice(0, 300); 87+/** Asks the website for a handoff link with `credential` (a box sign-in or a PAT) in Authorization. */ 88+export async function webHandoff(site: string, credential: string, fetcher: typeof fetch = fetch): Promise<Handoff> { 91+ res = await fetcher(`${site}/login/handoff`, { 93+ headers: { authorization: `Bearer ${credential}`, accept: "application/json" }, 95+ signal: AbortSignal.timeout(30_000), 98+ throw new UsageError(`couldn't reach ${site}: ${scrubbed((err as Error).message, credential)}`); 100+ const text = await res.text().catch(() => ""); 101+ let body: Partial<Handoff> & { error?: unknown } = {}; 103+ body = JSON.parse(text) as typeof body; 105+ // Not JSON: the status says enough. 108+ const why = typeof body.error === "string" ? body.error : `it answered ${res.status}`; 109+ throw new UsageError( 111+ ? `${site} doesn't hand out sign-in links (its key sign-in is off, or it isn't staging)` 112+ : `${site} refused: ${scrubbed(why, credential)}`, 116+ typeof body.url !== "string" || 117+ !body.url.startsWith(`${site}/login/handoff#`) || 118+ typeof body.expiresAt !== "string" || 119+ typeof body.account !== "string" 121+ throw new UsageError(`${site} answered something that isn't a sign-in link`); 124+ expiresAt: body.expiresAt, 125+ account: body.account, 126+ name: typeof body.name === "string" ? body.name : body.account, 127+ sessionEnds: typeof body.sessionEnds === "string" ? body.sessionEnds : body.expiresAt, 131+/** What abso login --web says: the one link, how long it works, who it signs in as, and what it reaches (Security). */ 132+export function handoffText(h: Handoff, site: string, boxed = true, now = Date.now()): string { 133+ const seconds = Math.max(0, Math.round((Date.parse(h.expiresAt) - now) / 1000)); 135+ ? "only to the projects this box was granted, at most as a writer, until the box is revoked or ends" 136+ : "at most as a writer"; 138+ `Open this link in your browser within ${seconds} seconds. It signs that browser in to ${site} as ${h.name}, until ${h.sessionEnds}, and works once. It reaches ${reach}:`, Lines 15–23 at 318 (were 15–20 at 277)
1515// Written with one Windows line ending inside, which arrives as LF. 1616writeFileSync(join(dir, "body.md"), `${BODY.replace("- two\n", "- two\r\n")}\r\n`); 1717writeFileSync(join(dir, "empty.md"), "\n \n"); 18+// A reply as agents write them: prose, a code block and a Windows path, which no shell quoting mangles here. 19+const REPLY = 'Checked it:\n\n```ts\nconst x = "a\\tb";\n```\n\nThe log is in C:\\Users\\me\\repo\\out.txt.'; 20+writeFileSync(join(dir, "reply.md"), `${REPLY}\n`); 1922const ISSUE = { comment: "string", description: "string", title: "string", drop: "boolean" } as const; 2023const parse = (command: string, spec: Record<string, "string" | "boolean">, words: string[], stdin?: string) => Lines 43–56 at 318 (were 40–49 at 277)
43− it("--file gives ask's question, answer's words and announce's text", () => {
46+ it("--file gives ask's question, answer's and reply's words, and announce's text", () => { 4447 assert.deepEqual(parse("ask", { issue: "string" }, ["alice", "--file", "body.md"]).positionals, ["alice", BODY]); 4548 assert.deepEqual(parse("answer", { note: "string" }, ["12", "--file", "body.md"]).positionals, ["12", BODY]); 4649 assert.deepEqual(parse("announce", { to: "string" }, ["--file", "body.md"]).positionals, [BODY]); 50+ const reply = parse("reply", { question: "boolean" }, ["648", "--file", "reply.md", "--question"]); 51+ assert.deepEqual(reply.positionals, ["648", REPLY]); 52+ assert.equal(reply.flags.get("question"), true); 53+ assert.match(bodyFilesHelp("reply", { question: "boolean" })!, /--file <path>/); 4855 () => parse("answer", { note: "string" }, ["12", "words", "--file", "body.md"]), 4956 /--file gives answer's text, so leave the words off the command line/, Lines 3–25 at 318 (were 3–11 at 277)
33import { test } from "node:test"; 44import { CALLER_HEADER, CALLER_MAX, callerHeader, callerPlace, parseCaller } from "../../src/caller.ts"; 55import { Api } from "../src/api.ts"; 6+import { callerFor } from "../src/command-env.ts"; 78const session = "0da5c2b7-ab07-4249-b868-e8f09b6ec7b6"; 10+test("the client sends a hash of the session and only the folder's last part", () => { 11+ const header = callerFor(session, "DESKTOP-1", "C:\\Users\\sam\\repos\\abso\\groups")!; 12+ const caller = parseCaller(header)!; 13+ assert.equal(caller.folder, "groups"); 14+ assert.match(caller.session!, /^[0-9a-f]{16}$/); 15+ assert.notEqual(caller.session, session); 16+ assert.doesNotMatch(Buffer.from(header, "base64url").toString(), /sam|0da5c2b7/); 17+ // The same chat hashes the same way, so the server still tells one chat from another. 18+ assert.equal(parseCaller(callerFor(session, "DESKTOP-1", "/x/groups"))!.session, caller.session); 19+ assert.equal(parseCaller(callerFor(undefined, "box", "/work/über"))!.session, undefined); 20+ assert.equal(callerPlace(caller), "groups on DESKTOP-1"); 923test("a caller goes out and comes back as it was", () => { 1024 const header = callerHeader({ session, machine: "DESKTOP-1", folder: "C:\\Users\\sam\\repos\\abso\\groups" })!; 1125 assert.match(header, /^[A-Za-z0-9_-]+$/); new file, 60 lines
1+// abso ci for a project whose CI is its pipeline file (abso 719): test-byoc on 2026-10-16 had no abso.json, and abso ci 2+// said "nothing to run" while its abso.yml's run 8 was going. The stored run is the project's CI there. 4+import assert from "node:assert/strict"; 5+import { test } from "node:test"; 6+import { builtInHasNothing, runLine, storedRuns } from "../src/ci.ts"; 8+const base = { latest: null, checked: null, running: null, red: null, behind: null } as const; 12+ reason: "nothing to run: no abso.json, and package.json has no test, typecheck or vite", 13+ at: "2026-10-16T16:47:00.000Z", 16+test("the stored runs are read strictly, newest first as the server lists them", () => { 17+ const runs = storedRuns({ 20+ { id: 8, version: 6, state: "running", file: "abso.yml", started: 1 }, 21+ { id: "7", version: 6, state: "failed", file: "abso.yml" }, 22+ { id: 6, version: 5, state: "failed", file: "abso.yml" }, 26+ runs.map((r) => r.id), 29+ assert.deepEqual(storedRuns(null), []); 30+ assert.deepEqual(storedRuns({ runs: "no" }), []); 33+test("a run in a line names its file, its state and where its jobs are", () => { 35+ runLine({ id: 8, version: 6, state: "running", file: "abso.yml" }), 36+ "Pipeline run 8 (abso.yml) is running on version 6. abso pipeline runs 8 shows its jobs.", 39+ runLine({ id: 7, version: 6, state: "failed", file: "abso.yml" }), 40+ "Pipeline run 7 (abso.yml) failed on version 6. abso pipeline runs 7 shows its jobs.", 43+ runLine({ id: 2, version: 1, state: "planned", file: "abso.yml" }), 44+ "Pipeline run 2 (abso.yml) was planned, not run, on version 1. abso pipeline runs 2 shows its jobs.", 48+test("only the built-in check's own nothing to run is set aside, never a red or another skip", () => { 49+ assert.equal(builtInHasNothing({ ...base, skipped: nothing }), true); 50+ assert.equal(builtInHasNothing({ ...base, skipped: { ...nothing, reason: "CI is off" } }), false); 51+ assert.equal(builtInHasNothing({ ...base }), false); 55+ red: { version: 6, agent: null, message: null, lastGood: null }, Lines 211–235 at 318 (were 211–231 at 277)
212212test("plainError words a refusal by whether a credential went, and a server that can't be reached", () => { 213213 const refused = new ApiError("GET /status answered 401: missing or wrong token", 401); 214− assert.equal(plainError(refused, false), "You're not signed in. Run abso login, then abso join <project>.");
215− assert.match(plainError(refused, true)!, /^The server didn't accept this folder's key.*abso doctor checks it/);
214+ assert.equal(plainError(refused, undefined), "You're not signed in. Run abso login, then abso join <project>."); 216+ plainError(refused, "this folder's key")!, 217+ /^The server didn't accept this folder's key.*abso doctor checks it/, 219+ assert.match(plainError(refused, "ABSO_TOKEN")!, /^The server didn't accept ABSO_TOKEN: /); 217− plainError(new ApiError("could not reach https://api.abso.dev: connect ECONNREFUSED"), true),
221+ plainError(new ApiError("could not reach https://api.abso.dev: connect ECONNREFUSED"), "this folder's key"), 218222 "Can't reach https://api.abso.dev: connect ECONNREFUSED. Check your connection; abso doctor checks the rest.", 222226 new ApiError("could not reach http://x: refused. Nothing was pushed. Run the same command again."), 223− true,
227+ "this folder's key", 225229 "Can't reach http://x: refused. Nothing was pushed. Run the same command again.", 227− assert.equal(plainError(new ApiError("GET /log answered 500: boom", 500), true), undefined);
228− assert.equal(plainError(new Error("anything else"), true), undefined);
231+ assert.equal(plainError(new ApiError("GET /log answered 500: boom", 500), "this folder's key"), undefined); 232+ assert.equal(plainError(new Error("anything else"), "this folder's key"), undefined); 231235test("whoami with nothing named shows prod, and names the other servers this box is signed in to", async () => { new file, 60 lines
1+// An init or join that fails against the server leaves the folder as it was, so the same command can run again: 2+// no starting .absoignore or abso.json from init, no .abso/ from join (but a key already here stays). 4+import assert from "node:assert/strict"; 5+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs"; 6+import { tmpdir } from "node:os"; 7+import { join } from "node:path"; 8+import { after, describe, it } from "node:test"; 9+import { main } from "../src/main.ts"; 11+// Nothing listens on port 1, so every call fails to connect. 12+const DOWN = "http://127.0.0.1:1"; 13+const ENV = { ABSO_TOKEN: "test-token-not-secret", ABSO_SERVERS_FILE: "no-servers.json" }; 15+const dirs: string[] = []; 17+ for (const d of dirs) rmSync(d, { recursive: true, force: true, maxRetries: 5 }); 20+function temp(): string { 21+ const d = mkdtempSync(join(tmpdir(), "abso-failed-start-")); 26+async function run(cwd: string, ...argv: string[]): Promise<number> { 27+ return (await main(argv, { cwd, env: ENV, write: () => {} })).exit; 30+describe("a failed start", () => { 31+ it("init takes back the .absoignore and abso.json it wrote", async () => { 33+ writeFileSync(join(dir, "package.json"), `${JSON.stringify({ scripts: { test: "node --test" } })}\n`); 34+ assert.notEqual(await run(dir, "init", "--server", DOWN, "--project", "p", "--agent", "a"), 0); 35+ assert.deepEqual(readdirSync(dir), ["package.json"]); 38+ it("join leaves no .abso folder", async () => { 40+ assert.notEqual(await run(dir, "join", "p", "--server", DOWN, "--agent", "a", "--dir", dir), 0); 41+ assert.equal(existsSync(join(dir, ".abso")), false); 44+ it("join keeps a key that was already here", async () => { 46+ mkdirSync(join(dir, ".abso")); 47+ const key = { server: DOWN, key: "abso_sk_not-a-real-key", id: "k_0123abcd" }; 48+ writeFileSync(join(dir, ".abso", "key"), `${JSON.stringify(key)}\n`); 49+ assert.notEqual(await run(dir, "join", "p", "--server", DOWN, "--agent", "a", "--dir", dir), 0); 50+ assert.deepEqual(readdirSync(join(dir, ".abso")), ["key"]); 53+ it("join with a key it can't read leaves only that key", async () => { 55+ mkdirSync(join(dir, ".abso")); 56+ writeFileSync(join(dir, ".abso", "key"), "{}\n"); 57+ assert.notEqual(await run(dir, "join", "p", "--server", DOWN, "--agent", "a", "--dir", dir), 0); 58+ assert.deepEqual(readdirSync(join(dir, ".abso")), ["key"]); Lines 89–96 at 318 (were 89–94 at 277)
9090 /** The next publish: commit it and answer 500 ('after'), or answer 500 without it ('before'), as a storage reset does. */ 9191 failPublish: "after" | "before" | undefined; 92+ /** How many of the next pulls to carry out and then cut before answering, as an answer that never arrives (abso-core 26). */ 93+ loseSyncAnswers: number; 9294 /** Run the merge queue's rounds now (after queueHold is let go). */ 9395 kickQueue(name: string): Promise<void>; 9496 /** Each run POST's X-Abso-Run-Key, and whether a run started for it. */ Lines 157–163 at 318 (were 155–160 at 277)
155157 boxExtra: undefined, 157159 failPublish: undefined, 158161 kickQueue: async () => {}, 159162 close: async () => {}, Lines 635–645 at 318 (were 632–637 at 277)
632635 ...(typeof body.label === "string" ? { label: body.label } : {}), 633636 ...(body.full === true ? { full: true } : {}), 638+ if (fake.loseSyncAnswers > 0) { 639+ fake.loseSyncAnswers--; 635643 const extra = fake.injectSync; 636644 fake.injectSync = undefined; 637645 if (extra === undefined) return send(res, 200, synced); Lines 26–33 at 318 (were 26–31 at 277)
2626import { clientVersion, headCommit } from "../src/client-version.ts"; Lines 115–142 at 318 (were 113–118 at 277)
118+ it("stamps the command that runs this client's abso hook, where stamp.ts has a HOOK_COMMAND line", () => { 119+ const spec = source({ 121+ "export const STAMP: string | undefined = undefined\nexport const HOOK_COMMAND: readonly string[] | undefined = undefined\n", 123+ const target = join(temp(), "avcs"); 128+ hookCommand: ["C:\\node.exe", "C:\\abso\\client\\abso.ts", "hook"], 131+ read(target, "hooks/stamp.ts"), 132+ "export const STAMP: string | undefined = '0.1.0+702c616'\n" + 133+ 'export const HOOK_COMMAND: readonly string[] | undefined = ["C:\\\\node.exe","C:\\\\abso\\\\client\\\\abso.ts","hook"]\n', 135+ // By default, this checkout's own: the node running it and client/abso.ts. 136+ assert.deepEqual(hookCommand().slice(0, 1), [process.execPath]); 137+ assert.match(hookCommand()[1]!, /client[\\/]abso\.ts$/); 116140 it("moves the files in by rename, what the hook imports first and plugin.json last", () => { 117141 const spec = source(); 118142 const target = join(temp(), "avcs"); Lines 451–460 at 318 (were 427–435 at 277)
427451 assert.equal(client, `abso ${clientVersion()} (${dirname(import.meta.dirname)})`); 430− /^the abso-hooks mod: 0\.1\.0\+aaaaaaa in .*skills[\\/]abso-hooks, installed 2026-10-05 04:30 UTC; this client has 0.2.0(\+[0-9a-f]{7}(\.dirty)?)?: node client\/install-mod\.ts installs it$/,
454+ /^the abso-hooks mod: 0\.1\.0\+aaaaaaa in .*skills[\\/]abso-hooks, installed 2026-10-05 04:30 UTC; this client has 0.2.0(\+[0-9a-f]{7}(\.dirty)?)?: /, 432− assert.equal(view, "the abso-view mod: not installed (node client/install-view.ts)");
456+ assert.ok(mod!.endsWith(`: ${installerCommand("install-mod.ts")} installs it`), mod); 457+ assert.equal(view, `the abso-view mod: not installed (${installerCommand("install-view.ts")})`); 433458 const json = JSON.parse( 434459 (await main(["--version", "--json"], { cwd: config, env: { CLAUDE_CONFIG_DIR: config }, write: () => {} })) Lines 499–505 at 318 (were 474–480 at 277)
474499 const current = (versionReport(env).json.mods as { current: string }[])[0]!.current; 475500 if (/\+[0-9a-f]{7}$/.test(current)) 476501 assert.deepEqual(modsBehindText(env), [ 477− `The avcs mod installed on this machine is 0.1.0+aaaaaaa, and this client has ${current}: node client/install-mod.ts installs it (new chats load it).`,
502+ `The ${AVCS_MOD.name} mod installed on this machine is 0.1.0+aaaaaaa, and this client has ${current}: ${installerCommand("install-mod.ts")} installs it (new chats load it).`, 479504 // A client outside git (an abso folder, a box) can't tell, so it says nothing. 480505 else assert.deepEqual(modsBehindText(env), []); new file, 222 lines
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 { spawnSync } from "node:child_process"; 7+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; 8+import { tmpdir } from "node:os"; 9+import { join } from "node:path"; 10+import { after, before, describe, it } from "node:test"; 11+import { fileURLToPath } from "node:url"; 12+import { closeLocalStores, LOCAL_BASE, localFetch } from "../src/local-store.ts"; 13+import { main } from "../src/main.ts"; 14+import { stateDir } from "../src/state-dir.ts"; 16+const dirs: string[] = []; 17+const temp = (label: string) => { 18+ const d = mkdtempSync(join(tmpdir(), `abso-local-${label}-`)); 23+const outside: string[] = []; 24+const realFetch = globalThis.fetch; 26+ globalThis.fetch = (async (input: unknown) => { 27+ outside.push(String(input instanceof Request ? input.url : input)); 28+ throw new TypeError("network is off in this test"); 32+ globalThis.fetch = realFetch; 33+ for (const d of dirs) rmSync(d, { recursive: true, force: true, maxRetries: 5 }); 34+ assert.deepEqual(outside, [], "nothing reached for the network"); 38+const env = () => ({ ABSO_STORE: store, ABSO_SERVERS_FILE: "no-servers.json", ABSO_HOOK_FORCE: "1" }); 39+async function run(cwd: string, ...argv: string[]): Promise<{ exit: number; out: string; err: string }> { 40+ const r = await main(argv, { cwd, env: env(), write: () => {} }); 41+ return { exit: r.exit, out: r.stdout, err: r.stderr }; 43+const text = (dir: string, rel: string) => readFileSync(join(dir, rel), "utf8"); 45+/** A copy of the client without the open server beside it (a platform that pins only client/) has no local projects to test. */ 46+const noServer = existsSync(fileURLToPath(new URL("../../server/src/router.ts", import.meta.url))) 48+ : "no server/src beside this client, so no local projects"; 50+describe("a local project, with the network off", { skip: noServer }, () => { 54+ store = temp("store"); 57+ it("init --local makes the project in the store, with no sign-in", async () => { 58+ alice = temp("alice"); 59+ writeFileSync(join(alice, "a.txt"), "one\ntwo\nthree\n"); 60+ const r = await run(alice, "init", "--local", "--project", "demo", "--agent", "alice"); 61+ assert.equal(r.exit, 0, r.out + r.err); 62+ assert.match(r.out, /Created project demo at version 0 from 2 text files/, "a.txt and the starting .absoignore"); 63+ assert.doesNotMatch(r.out, /CI has nothing to run/); 64+ assert.match(r.out, /It's a local project: its history is in .*demo, on this machine/); 65+ assert.doesNotMatch(r.out + r.err, /Signing in/); 66+ assert.ok(existsSync(join(store, "demo", "project.sqlite"))); 67+ const config = JSON.parse(readFileSync(join(stateDir(alice), "config.json"), "utf8")); 68+ assert.equal(config.server, "local"); 69+ assert.equal(config.store, undefined, "the store came from ABSO_STORE, so the folder doesn't name it"); 72+ it("record and push make version 1, and log says so", async () => { 73+ writeFileSync(join(alice, "a.txt"), "one\nTWO\nthree\n"); 74+ writeFileSync(join(alice, "b.txt"), "new\n"); 75+ assert.equal((await run(alice, "record")).exit, 0); 76+ const pushed = await run(alice, "push", "-m", "Change two, add b"); 77+ assert.equal(pushed.exit, 0, pushed.out + pushed.err); 78+ assert.match(pushed.out, /Pushed version 1/); 79+ const log = await run(alice, "log"); 80+ assert.equal(log.exit, 0, log.err); 81+ assert.match(log.out, /Change two, add b/); 84+ it("a second folder joins, and pulls what the first pushes", async () => { 86+ const joined = await run(bob, "join", "demo", "--local", "--agent", "bob", "--dir", bob); 87+ assert.equal(joined.exit, 0, joined.out + joined.err); 88+ assert.equal(text(bob, "a.txt"), "one\nTWO\nthree\n"); 89+ assert.equal(text(bob, "b.txt"), "new\n"); 90+ writeFileSync(join(alice, "b.txt"), "new\nmore\n"); 91+ assert.equal((await run(alice, "push", "-m", "More in b")).exit, 0); 92+ const pulled = await run(bob, "pull"); 93+ assert.equal(pulled.exit, 0, pulled.out + pulled.err); 94+ assert.equal(text(bob, "b.txt"), "new\nmore\n"); 97+ it("blame names who wrote each line", async () => { 98+ const r = await run(bob, "blame", "a.txt"); 99+ assert.equal(r.exit, 0, r.err); 100+ assert.match(r.out, /alice/); 101+ assert.match(r.out, /TWO/); 104+ it("a push that collides with work pushed since is held", async () => { 105+ assert.equal((await run(bob, "pull")).exit, 0); 106+ writeFileSync(join(alice, "a.txt"), "one\nalice's\nthree\n"); 107+ assert.equal((await run(alice, "push", "-m", "Alice's two")).exit, 0); 108+ writeFileSync(join(bob, "a.txt"), "one\nbob's\nthree\n"); 109+ const held = await run(bob, "push", "-m", "Bob's two"); 110+ assert.notEqual(held.exit, 0); 111+ assert.match(held.out + held.err, /collision/); 114+ it("issues, asks and news work too, kept in issues.sqlite beside the project", async () => { 115+ const opened = await run(alice, "issue", "new", "Fix the parser", "--agent", "bob"); 116+ assert.equal(opened.exit, 0, opened.out + opened.err); 117+ assert.ok(existsSync(join(store, "demo", "issues.sqlite"))); 118+ const listed = await run(bob, "issues"); 119+ assert.equal(listed.exit, 0, listed.err); 120+ assert.match(listed.out, /Fix the parser/); 121+ const started = await run(bob, "start", "Parser fix", "--issue", "1"); 122+ assert.equal(started.exit, 0, started.out + started.err); 123+ const asked = await run(alice, "ask", "bob", "Which grammar?", "--issue", "1"); 124+ assert.equal(asked.exit, 0, asked.out + asked.err); 125+ const waiting = await run(bob, "waiting", "--mine"); 126+ assert.equal(waiting.exit, 0, waiting.err); 127+ assert.match(waiting.out, /Which grammar\?/); 128+ const answered = await run(bob, "answer", "1", "The new one"); 129+ assert.equal(answered.exit, 0, answered.out + answered.err); 130+ const news = await run(alice, "news"); 131+ assert.equal(news.exit, 0, news.err); 132+ assert.match(news.out, /The new one/); 133+ const issue = await run(alice, "issue", "1"); 134+ assert.match(issue.out, /In progress|bob/); 137+ it("two calls at once on one project are both answered, one after the other", async () => { 138+ // As abso ci and waiting --mine make them, with Promise.all. 139+ const local = localFetch(store); 140+ const answers = await Promise.all([local(`${LOCAL_BASE}/p/demo/queue`), local(`${LOCAL_BASE}/p/demo/queue`)]); 142+ for (const a of answers) assert.equal(a.status, 200, await a.text()); 145+ it("a project's name can't start with a dot, so its folder stays inside the store", async () => { 146+ const dir = temp("dots"); 147+ writeFileSync(join(dir, "a.txt"), "x\n"); 148+ for (const name of ["..", ".hidden"]) { 149+ const r = await run(dir, "init", "--local", "--project", name, "--agent", "a"); 150+ assert.equal(r.exit, 1, r.out + r.err); 151+ // The name rule says why, before any call is made (a ".." would collapse the call's path). 152+ assert.match(r.err, /project names are letters, digits, dot, dash and underscore/); 154+ assert.ok(!existsSync(join(store, "..", "project.sqlite"))); 155+ assert.deepEqual(readdirSync(dir), ["a.txt"], "init left nothing behind"); 159+describe("where a local project's store is", { skip: noServer }, () => { 160+ it("--store inside the folder is kept in its settings and left out of its files", async () => { 161+ store = temp("unused"); 162+ const dir = temp("venv"); 163+ writeFileSync(join(dir, "a.txt"), "x\n"); 164+ const r = await run(dir, "init", "--local", "--project", "beside", "--agent", "a", "--store", ".abso-store"); 165+ assert.equal(r.exit, 0, r.out + r.err); 166+ assert.ok(existsSync(join(dir, ".abso-store", "beside", "project.sqlite"))); 167+ assert.equal(JSON.parse(readFileSync(join(stateDir(dir), "config.json"), "utf8")).store, join(dir, ".abso-store")); 168+ assert.match(text(dir, ".absoignore"), /^\/\.abso-store\/$/m); 169+ assert.match(r.out, /from 2 text files/, "a.txt and .absoignore, not the store"); 170+ // Every later command finds the store from the folder's settings, whatever ABSO_STORE says. 171+ writeFileSync(join(dir, "a.txt"), "y\n"); 172+ assert.equal((await run(dir, "push", "-m", "y")).exit, 0); 175+ it("--local refuses --server, and --store needs --local", async () => { 176+ const dir = temp("refuse"); 177+ mkdirSync(join(dir, "x")); 178+ const both = await run(dir, "init", "--local", "--server", "https://abso.test", "--project", "p"); 179+ assert.match(both.out + both.err, /--local or --server, not both/); 180+ const alone = await run(dir, "init", "--store", "s", "--project", "p"); 181+ assert.match(alone.out + alone.err, /--store goes with --local/); 184+ it("joining a project the store doesn't have leaves nothing behind", async () => { 185+ store = temp("empty"); 186+ const dir = temp("nojoin"); 187+ const r = await run(dir, "join", "nothing", "--local", "--agent", "a", "--dir", dir); 188+ assert.notEqual(r.exit, 0); 189+ assert.match(r.out + r.err, /no local project nothing/); 190+ assert.equal(existsSync(join(dir, ".abso")) || existsSync(join(dir, ".avcs")), false); 194+describe("local commands as their own processes", { skip: noServer }, () => { 195+ // The way people and agents run them: client/abso.ts, a process per command, Node's compile cache as it is. 196+ const entry = fileURLToPath(new URL("../abso.ts", import.meta.url)); 197+ const cli = (cwd: string, processStore: string, ...argv: string[]) => 198+ spawnSync(process.execPath, [entry, ...argv], { 200+ env: { ...process.env, ABSO_STORE: processStore, ABSO_SERVERS_FILE: "no-servers.json" }, 204+ it("init, push, status and log each exit cleanly", () => { 205+ const processStore = temp("process-store"); 206+ const dir = temp("process"); 207+ writeFileSync(join(dir, "a.txt"), "one\n"); 208+ const steps: [string, string[]][] = [ 209+ ["init", ["init", "--local", "--project", "proc", "--agent", "p"]], 210+ ["push", ["push", "-m", "Two"]], 211+ ["status", ["status"]], 214+ for (const [name, argv] of steps) { 215+ if (name === "push") writeFileSync(join(dir, "a.txt"), "one\ntwo\n"); 216+ const r = cli(dir, processStore, ...argv); 217+ assert.equal(r.status, 0, `${name}: exit ${r.status} ${r.signal ?? ""}\n${r.stdout}${r.stderr}`); 218+ if (name === "status") assert.match(r.stdout, /It's a local project, in /); 219+ if (name === "log") assert.match(r.stdout, /Two/); new file, 88 lines
1+// A pull whose answer never arrives (abso-core 26): the server has moved the agent's base, so later pulls 2+// send only what changed since then. The folder notes the pull it started and, until one is written, the 3+// next pull asks for every file and writes the ones that differ. Status says so in the meantime. 5+import assert from "node:assert/strict"; 6+import { existsSync, 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 { type Fake, startFake } from "./fake-server.ts"; 13+const TOKEN = "test-token-not-secret"; 14+const ENV = { AVCS_TOKEN: TOKEN, AVCS_HOOK_FORCE: "1", AVCS_SERVERS_FILE: "no-servers.json" }; 17+const dirs: string[] = []; 19+ fake = await startFake(0, TOKEN); 23+ for (const d of dirs) rmSync(d, { recursive: true, force: true, maxRetries: 5 }); 26+function temp(): string { 27+ const d = mkdtempSync(join(tmpdir(), "abso-lost-pull-")); 32+async function run(cwd: string, ...argv: string[]): Promise<{ exit: number; out: string }> { 33+ const r = await main(argv, { cwd, env: ENV, write: () => {} }); 34+ return { exit: r.exit, out: r.stdout + r.stderr }; 38+/** alice and bob on one project; alice pushes a change and a new file, and bob's pull of them is lost. */ 39+async function lost(): Promise<{ alice: string; bob: string }> { 40+ const name = `lost${++projects}`; 41+ const alice = temp(); 42+ writeFileSync(join(alice, "a.txt"), "one\n"); 44+ (await run(alice, "init", "--server", fake.url, "--project", name, "--agent", "alice", "--as-is")).exit, 48+ assert.equal((await run(bob, "join", name, "--agent", "bob", "--server", fake.url)).exit, 0); 49+ writeFileSync(join(alice, "a.txt"), "two\n"); 50+ writeFileSync(join(alice, "b.txt"), "new\n"); 51+ const pushed = await run(alice, "push", "-m", "Change a.txt and add b.txt"); 52+ assert.equal(pushed.exit, 0, pushed.out); 53+ fake.loseSyncAnswers = 1; 54+ assert.notEqual((await run(bob, "pull")).exit, 0, "the pull whose answer was lost fails"); 55+ return { alice, bob }; 58+const text = (dir: string, rel: string) => readFileSync(join(dir, rel), "utf8"); 60+describe("a pull whose answer never arrives", () => { 61+ it("leaves the folder as it was, and status says a pull didn't finish", async () => { 62+ const { bob } = await lost(); 63+ assert.equal(text(bob, "a.txt"), "one\n"); 64+ assert.equal(existsSync(join(bob, "b.txt")), false); 65+ const status = await run(bob, "status"); 66+ assert.match(status.out, /A pull here didn't finish/); 69+ it("the next pull asks for every file and writes what the lost one would have", async () => { 70+ const { bob } = await lost(); 71+ const pulled = await run(bob, "pull"); 72+ assert.equal(pulled.exit, 0, pulled.out); 73+ assert.match(pulled.out, /The last pull here didn't finish, so this one asked for every file/); 74+ assert.equal(text(bob, "a.txt"), "two\n"); 75+ assert.equal(text(bob, "b.txt"), "new\n"); 76+ assert.doesNotMatch((await run(bob, "status")).out, /A pull here didn't finish/); 77+ const again = await run(bob, "pull"); 78+ assert.doesNotMatch(again.out, /didn't finish/, "once caught up, pulls are plain again"); 81+ it("keeps work done in the folder meanwhile", async () => { 82+ const { bob } = await lost(); 83+ writeFileSync(join(bob, "a.txt"), "bob's own\n"); 84+ const pulled = await run(bob, "pull"); 85+ assert.equal(text(bob, "a.txt"), "bob's own\n", pulled.out); 86+ assert.equal(text(bob, "b.txt"), "new\n"); Lines 3–9 at 318 (were 3–8 at 277)
33import assert from "node:assert/strict"; 44import { test } from "node:test"; Lines 42–52 at 318 (were 41–46 at 277)
4142 assert.match(text[0]!, /within 45 seconds/); 4243 assert.match(text[0]!, /run abso news --stream again/); 4344 assert.deepEqual(JSON.parse(text[1]!), args); 45+ // The server sends the expiry as an ISO time (staging 1418); the countdown and the stream mark read it the same. 46+ const iso = { ...ticket(1), expiresAt: new Date(NOW + 60_000).toISOString() }; 47+ assert.match(streamText(iso, "abso", "fe", NOW + 15_000), /within 45 seconds/); 48+ assert.equal(streamMarkUntil(iso, NOW), NOW + 60_000 + MONITOR_TIMEOUT_MS); 49+ assert.equal(expiresAtMs({ ...ticket(1), expiresAt: "soon" }, NOW), NOW); 4652test("a refusal close stops --follow; any other close opens again, waiting 1 s doubling to a minute", () => { Lines 134–182 at 318 (were 128–133 at 277)
128134 assert.equal(w.notes.length, 0); 137+test("a frame is a wake: --follow reads the news and prints that once; an empty read prints the frames", async () => { 138+ // The server's frames don't count as heard (abso 690): the read takes them, so each item prints once. 139+ const w = world([{ frames: ["fe told you: hello", "cloud asks: ship it?"], close: { code: 1006 } }]); 140+ const reads: string[][] = [["fe told you: hello", "cloud asks: ship it?"], []]; 142+ w.deps.take = async () => { 144+ return reads.shift() ?? []; 146+ await follow(w.deps); 147+ // Two frames, one read in flight: the second folds into one more read, which finds nothing new; its frame was 148+ // already printed by the first read, so nothing prints twice. 149+ assert.equal(calls, 2); 150+ assert.deepEqual(w.lines, ["fe told you: hello", "cloud asks: ship it?"]); 152+ // A server that counts a frame as heard already (staging 1418): the read is empty, so the frame is what shows. 153+ const old = world([{ frames: ["fe told you: hello"], close: { code: 1006 } }]); 154+ old.deps.take = async () => []; 155+ await follow(old.deps); 156+ assert.deepEqual(old.lines, ["fe told you: hello"]); 158+ // On that server a read can find other news waiting: the frame's own item still shows (Code Review, 291). 159+ const mixed = world([{ frames: ["fe told you: hello"], close: { code: 1006 } }]); 160+ mixed.deps.take = async () => ["cloud: an older item"]; 161+ await follow(mixed.deps); 162+ assert.deepEqual(mixed.lines, ["cloud: an older item", "fe told you: hello"]); 164+ // A catch-up frame names the first few waiting items and how many more: the read shows them all, the frame adds nothing. 165+ const catchUp = world([{ frames: ["fe told you: hello\ncloud: ship it?\nand 1 more"], close: { code: 1006 } }]); 166+ catchUp.deps.take = async () => ["fe told you: hello", "cloud: ship it?", "desk: a third"]; 167+ await follow(catchUp.deps); 168+ assert.deepEqual(catchUp.lines, ["fe told you: hello", "cloud: ship it?", "desk: a third"]); 170+ // A read that fails shows the frames and says why. 171+ const down = world([{ frames: ["fe told you: hello"], close: { code: 1006 } }]); 172+ down.deps.take = async () => { 173+ throw new Error("could not reach the server"); 175+ await follow(down.deps); 176+ assert.deepEqual(down.lines, ["fe told you: hello"]); 177+ assert.match(down.notes[0]!, /couldn't read the news: could not reach the server/); 131180test("--follow keeps an idle socket open with a ping the object answers without waking", async () => { 132181 const w = world([{ frames: [], close: { code: 1006 } }]); 133182 const held: number[] = []; new file, 106 lines
1+// abso login --web: a staging website session handed to a browser as a one-use link, with no secret printed. 3+import assert from "node:assert/strict"; 4+import { mkdtempSync, writeFileSync } from "node:fs"; 5+import { tmpdir } from "node:os"; 6+import { join } from "node:path"; 7+import { test } from "node:test"; 8+import { handoffText, patFromFile, siteFor, webHandoff, webLogin } from "../src/web-session.ts"; 10+const SITE = "https://abso-website-staging.chrisazy.workers.dev"; 11+const STAGING = "https://abso-staging.chrisazy.workers.dev"; 12+const BOX = `abso_bx_${"C".repeat(43)}`; 13+const PAT = `abso_pat_${"A".repeat(40)}`; 14+const NOW = Date.UTC(2026, 9, 16, 9, 0, 0); 16+test("the credential goes only to the staging website beside the folder's staging server (Security condition 6)", () => { 17+ assert.equal(siteFor(STAGING, undefined, "box"), SITE); 18+ assert.equal(siteFor("https://avcs-staging.chrisazy.workers.dev/", undefined, "pat"), SITE); 19+ // A server that isn't staging is refused, prod included, whatever is asked. 21+ () => siteFor("https://api.abso.dev", undefined, "box"), 22+ /for staging.*never sign in to the website on prod/, 24+ assert.throws(() => siteFor("https://api.abso.dev", "http://localhost:8871", "pat"), /for staging/); 25+ // A box's sign-in takes no --site, not even the staging website's own address. 26+ assert.throws(() => siteFor(STAGING, SITE, "box"), /isn't taken with a box's sign-in/); 27+ assert.throws(() => siteFor(STAGING, "http://localhost:8871", "box"), /isn't taken with a box's sign-in/); 28+ // A PAT may name this machine over http, and nothing else. 29+ assert.equal(siteFor(STAGING, "http://localhost:8871/x", "pat"), "http://localhost:8871"); 30+ assert.equal(siteFor(STAGING, "http://127.0.0.1:8871", "pat"), "http://127.0.0.1:8871"); 31+ for (const elsewhere of ["https://anywhere.example", SITE, "https://localhost:8871", "not a url"]) 32+ assert.throws(() => siteFor(STAGING, elsewhere, "pat"), /names this machine only/, elsewhere); 35+test("a refused handoff reads no credential and sends no request", async () => { 36+ const sent: string[] = []; 37+ const fetcher = (async (url: string) => (sent.push(url), Response.json({}))) as unknown as typeof fetch; 39+ const credential = () => (read++, BOX); 40+ for (const asked of [ 41+ { server: "https://api.abso.dev", site: undefined, kind: "box" as const }, 42+ { server: STAGING, site: "https://anywhere.example", kind: "box" as const }, 43+ { server: STAGING, site: SITE, kind: "box" as const }, 44+ { server: "https://api.abso.dev", site: "http://localhost:8871", kind: "pat" as const }, 45+ { server: STAGING, site: "https://anywhere.example", kind: "pat" as const }, 47+ await assert.rejects(webLogin({ ...asked, credential, fetcher }), /Nothing was sent/, JSON.stringify(asked)); 48+ assert.deepEqual(sent, []); 49+ assert.equal(read, 0); 50+ // Allowed, it goes to the staging website only. 51+ await webLogin({ server: STAGING, site: undefined, kind: "pat", credential: () => PAT, fetcher }).catch(() => {}); 52+ assert.deepEqual(sent, [`${SITE}/login/handoff`]); 55+test("the credential goes in Authorization only, and the answer is the one link and who it signs in as", async () => { 56+ const seen: { url: string; authorization: string | null; body: unknown }[] = []; 57+ const fetcher = (async (url: string, init: RequestInit) => { 58+ seen.push({ url, authorization: new Headers(init.headers).get("authorization"), body: init.body ?? null }); 59+ return Response.json({ 60+ url: `${SITE}/login/handoff#${"t".repeat(50)}`, 61+ expiresAt: new Date(NOW + 60_000).toISOString(), 62+ account: "acct_person1", 64+ sessionEnds: "2026-10-16T21:00:00.000Z", 67+ const h = await webHandoff(SITE, BOX, fetcher); 68+ assert.deepEqual(seen, [{ url: `${SITE}/login/handoff`, authorization: `Bearer ${BOX}`, body: null }]); 69+ const text = handoffText(h, SITE, true, NOW); 70+ assert.match(text, /within 60 seconds/); 71+ assert.match(text, /as christopher, until 2026-10-16T21:00:00.000Z, and works once/); 72+ assert.match(text, /only to the projects this box was granted, at most as a writer/); 73+ assert.match(handoffText(h, SITE, false, NOW), /It reaches at most as a writer:/); 74+ assert.match(text, /\/login\/handoff#t{50}$/); 75+ assert.doesNotMatch(text + JSON.stringify(h), /abso_bx_/); 78+test("a refusal says why without the credential; an answer that isn't the site's own link is refused", async () => { 79+ const echo = (async () => 80+ Response.json({ error: `that key was refused: ${BOX}` }, { status: 401 })) as unknown as typeof fetch; 81+ await assert.rejects(webHandoff(SITE, BOX, echo), (err: Error) => { 82+ assert.match(err.message, /refused: that key was refused: \[the credential\]/); 83+ assert.doesNotMatch(err.message, /abso_bx_/); 86+ const off = (async () => Response.json({ error: "not found" }, { status: 404 })) as unknown as typeof fetch; 87+ await assert.rejects(webHandoff(SITE, BOX, off), /doesn't hand out sign-in links/); 88+ const elsewhere = (async () => 90+ url: "https://elsewhere.example/login/handoff#x", 91+ expiresAt: new Date(NOW).toISOString(), 93+ })) as unknown as typeof fetch; 94+ await assert.rejects(webHandoff(SITE, BOX, elsewhere), /isn't a sign-in link/); 97+test("--pat-file reads a PAT from its file, and refuses a file that doesn't hold one", () => { 98+ const dir = mkdtempSync(join(tmpdir(), "abso-web-")); 99+ const good = join(dir, "pat"); 100+ writeFileSync(good, `abso_pat_${"A".repeat(40)}\n`); 101+ assert.equal(patFromFile(good), `abso_pat_${"A".repeat(40)}`); 102+ const bad = join(dir, "not"); 103+ writeFileSync(bad, "hello"); 104+ assert.throws(() => patFromFile(bad), /doesn't hold a PAT/); 105+ assert.throws(() => patFromFile(join(dir, "missing")), /can't read/); Lines 31–39 at 318 (were 31–36 at 277)
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. new file, 123 lines
1+// Time and memory of a local project's commands (abso init --local) on a small and a large history: 3+// node scripts/local-measure.ts [versions ...] (default: 20 1000) 5+// Each history is built in this process through the client's main(); then every command is run as its own 6+// `node client/abso.ts` process, the way a person or an agent runs it, five times. It prints the median and slowest 7+// wall time, and the largest peak memory (maxRSS) of those runs, with the store's size on disk. 9+import { spawnSync } from "node:child_process"; 10+import { mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; 11+import { tmpdir } from "node:os"; 12+import { join, resolve } from "node:path"; 13+import { fileURLToPath, pathToFileURL } from "node:url"; 14+import { main } from "../client/src/main.ts"; 16+const ROOT = resolve(fileURLToPath(new URL("..", import.meta.url))); 17+const ENTRY = join(ROOT, "client", "abso.ts"); 21+const sizes = process.argv.slice(2).map(Number); 22+const histories = sizes.length > 0 ? sizes : [20, 1000]; 24+function sizeOf(dir: string): number { 26+ for (const name of readdirSync(dir)) { 27+ const path = join(dir, name); 28+ const s = statSync(path); 29+ total += s.isDirectory() ? sizeOf(path) : s.size; 34+const lines = (file: number, version: number) => 35+ Array.from({ length: 30 }, (_, i) => 36+ i === version % 30 ? `line ${i} of file ${file}, version ${version}` : `line ${i} of file ${file}`, 41+async function build(versions: number): Promise<{ store: string; alice: string; bob: string }> { 42+ const store = mkdtempSync(join(tmpdir(), "abso-measure-store-")); 43+ const alice = mkdtempSync(join(tmpdir(), "abso-measure-alice-")); 44+ const bob = mkdtempSync(join(tmpdir(), "abso-measure-bob-")); 45+ const env = { ABSO_STORE: store, ABSO_SERVERS_FILE: "no-servers.json" }; 46+ const run = async (cwd: string, ...argv: string[]) => { 47+ const r = await main(argv, { cwd, env, write: () => {} }); 48+ if (r.exit !== 0) throw new Error(`${argv.join(" ")}: ${r.stdout}${r.stderr}`); 50+ for (let f = 0; f < FILES; f++) writeFileSync(join(alice, `f${f}.txt`), lines(f, 0)); 51+ await run(alice, "init", "--local", "--project", "measure", "--agent", "alice", "--as-is"); 52+ for (let v = 1; v < versions; v++) { 53+ // Each version changes three files, as a small piece of work does. 54+ for (const f of [v % FILES, (v * 7) % FILES, (v * 13) % FILES]) 55+ writeFileSync(join(alice, `f${f}.txt`), lines(f, v)); 56+ await run(alice, "push", "-m", `Version ${v}`); 58+ await run(bob, "join", "measure", "--local", "--agent", "bob", "--dir", bob); 59+ return { store, alice, bob }; 62+function measure(cwd: string, store: string, argv: string[]): { median: number; slowest: number; rss: number } { 63+ const times: number[] = []; 65+ const preload = join(tmpdir(), `abso-measure-rss-${process.pid}.mjs`); 66+ const out = join(tmpdir(), `abso-measure-rss-${process.pid}.json`); 69+ `import { writeFileSync } from "node:fs";\nprocess.on("exit", () => writeFileSync(${JSON.stringify(out)}, String(process.resourceUsage().maxRSS)));\n`, 71+ for (let i = 0; i < RUNS; i++) { 72+ const started = performance.now(); 73+ const r = spawnSync(process.execPath, ["--import", pathToFileURL(preload).href, ENTRY, ...argv], { 75+ env: { ...process.env, ABSO_STORE: store, ABSO_SERVERS_FILE: "no-servers.json" }, 78+ times.push(performance.now() - started); 79+ if (r.status !== 0 && argv[0] !== "push") throw new Error(`${argv.join(" ")}: ${r.stdout}${r.stderr}`); 85+ ["-e", `process.stdout.write(require("fs").readFileSync(${JSON.stringify(out)}, "utf8"))`], 86+ { encoding: "utf8" }, 91+ times.sort((a, b) => a - b); 92+ return { median: times[Math.floor(RUNS / 2)]!, slowest: times[RUNS - 1]!, rss }; 95+const kb = (n: number) => `${(n / 1024).toFixed(0)} MB`; 96+const ms = (n: number) => `${n.toFixed(0)} ms`; 98+ `Node ${process.versions.node}, ${FILES} files of 30 lines, three files changed per version, ${RUNS} runs each.`, 100+console.log("history | command | median | slowest | peak memory"); 101+for (const versions of histories) { 102+ const started = performance.now(); 103+ const { store, alice, bob } = await build(versions); 104+ const built = performance.now() - started; 105+ const steps: [string, string, string[]][] = [ 106+ ["status", alice, ["status"]], 107+ ["log", alice, ["log"]], 108+ ["blame", alice, ["blame", "f0.txt"]], 109+ ["pull (no change)", bob, ["pull"]], 110+ ["record + push", alice, ["push", "-m", "One more"]], 112+ for (const [name, cwd, argv] of steps) { 113+ if (argv[0] === "push") writeFileSync(join(cwd, "f1.txt"), lines(1, versions + Math.random())); 114+ const m = measure(cwd, store, argv); 116+ `${String(versions).padStart(5)} v | ${name.padEnd(20)} | ${ms(m.median).padStart(8)} | ${ms(m.slowest).padStart(8)} | ${kb(m.rss)}`, 120+ `${String(versions).padStart(5)} v | store on disk ${(sizeOf(store) / 1048576).toFixed(1)} MB, built in-process in ${(built / 1000).toFixed(1)} s`, 122+ for (const d of [store, alice, bob]) rmSync(d, { recursive: true, force: true, maxRetries: 5 }); new file, 87 lines
1+// A local project's store lock under load: 1, 4 and 16 writers pushing to one local project at once. 3+// node scripts/local-writers.ts [writers ...] (default: 1 4 16; PUSHES=10 pushes per writer) 5+// Each writer is its own agent, in its own folder, changing its own file, so nothing collides: what's measured is the 6+// store's lock (one SQLite write transaction per call). Every push is its own `node client/abso.ts push` process, as 7+// an agent runs it. It prints each push's wall time (median, 95th percentile, slowest), the pushes per second across 8+// all writers, and any push that failed. 10+import { spawn } from "node:child_process"; 11+import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; 12+import { tmpdir } from "node:os"; 13+import { join, resolve } from "node:path"; 14+import { fileURLToPath } from "node:url"; 15+import { main } from "../client/src/main.ts"; 17+const ROOT = resolve(fileURLToPath(new URL("..", import.meta.url))); 18+const ENTRY = join(ROOT, "client", "abso.ts"); 19+const PUSHES = Number(process.env.PUSHES ?? 10); 20+const counts = process.argv.slice(2).map(Number); 22+function push(cwd: string, store: string, message: string): Promise<{ ms: number; ok: boolean; out: string }> { 23+ const started = performance.now(); 24+ return new Promise((done) => { 25+ const child = spawn(process.execPath, [ENTRY, "push", "-m", message], { 27+ env: { ...process.env, ABSO_STORE: store, ABSO_SERVERS_FILE: "no-servers.json" }, 30+ child.stdout.on("data", (d) => { 33+ child.stderr.on("data", (d) => { 36+ child.on("close", (code) => done({ ms: performance.now() - started, ok: code === 0, out })); 40+const pct = (sorted: number[], p: number) => sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * p))]!; 41+console.log(`Node ${process.versions.node}, ${PUSHES} pushes per writer, each writer its own agent and file.`); 42+console.log("writers | pushes | median | p95 | slowest | pushes/s | failed"); 43+for (const writers of counts.length > 0 ? counts : [1, 4, 16]) { 44+ const store = mkdtempSync(join(tmpdir(), "abso-writers-store-")); 45+ const folders: string[] = []; 46+ const env = { ABSO_STORE: store, ABSO_SERVERS_FILE: "no-servers.json" }; 47+ const first = mkdtempSync(join(tmpdir(), "abso-writers-w0-")); 48+ writeFileSync(join(first, "readme.txt"), "writers\n"); 49+ const init = await main(["init", "--local", "--project", "writers", "--agent", "w0", "--as-is"], { 54+ if (init.exit !== 0) throw new Error(init.stdout + init.stderr); 56+ for (let w = 1; w < writers; w++) { 57+ const dir = mkdtempSync(join(tmpdir(), `abso-writers-w${w}-`)); 58+ const joined = await main(["join", "writers", "--local", "--agent", `w${w}`, "--dir", dir], { 63+ if (joined.exit !== 0) throw new Error(joined.stdout + joined.stderr); 66+ const times: number[] = []; 67+ const failures: string[] = []; 68+ const started = performance.now(); 70+ folders.map(async (dir, w) => { 71+ for (let i = 0; i < PUSHES; i++) { 72+ writeFileSync(join(dir, `w${w}.txt`), `writer ${w}, push ${i}\n`); 73+ const r = await push(dir, store, `w${w} push ${i}`); 75+ if (!r.ok) failures.push(`w${w} push ${i}: ${r.out.trim().split("\n").slice(-2).join(" / ")}`); 79+ const total = (performance.now() - started) / 1000; 80+ times.sort((a, b) => a - b); 81+ const ms = (n: number) => `${n.toFixed(0)} ms`.padStart(8); 83+ `${String(writers).padStart(7)} | ${String(times.length).padStart(6)} | ${ms(pct(times, 0.5))} | ${ms(pct(times, 0.95))} | ${ms(times.at(-1)!)} | ${(times.length / total).toFixed(1).padStart(8)} | ${failures.length}`, 85+ for (const f of failures.slice(0, 5)) console.log(` ${f}`); 86+ for (const d of [store, ...folders]) rmSync(d, { recursive: true, force: true, maxRetries: 5 }); Lines 572–581 at 318 (were 572–577 at 277)
572572 announcePerson(person: { id: string; name: string }, text: string, to?: string[]) { 573573 return this.project.announcePerson(person, text, to, Date.now()); 575+ /** A seat's earlier chat hears that another chat used the seat (277, groups); as abso's worker has it. */ 576+ seatNotice(agent: string, place: string, key: string) { 577+ return this.project.seatNotice(agent, place, key); 575579 starting(agent: string, text: string | null, files?: string[], options: { issue?: unknown; done?: unknown } = {}) { 576580 return this.project.starting(agent, text, files, Date.now(), options); Lines 7–16 at 318 (were 7–15 at 277)
77export const CALLER_MAX = 512; 99export interface Caller { 10− /** The chat's session id, when abso runs in one (Claude Code's CLAUDE_CODE_SESSION_ID, or the mod's own). */
10+ /** The chat's session, when abso runs in one: the client sends a short SHA-256 of the id, never the id itself. */ 1111 readonly session?: string; 1212 readonly machine: string; 13+ /** The folder's last part: the client sends no more of its path. */ 1314 readonly folder: string; Lines 26–34 at 318 (were 25–31 at 277)
2627function fromB64u(text: string): string { 2728 const bin = atob(text.replace(/-/g, "+").replace(/_/g, "/")); 28− return new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(Uint8Array.from(bin, (c) => c.codePointAt(0)!));
29+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode( 30+ Uint8Array.from(bin, (c) => c.codePointAt(0)!), 3134/** The header for this caller, or undefined when there's nothing usable to say. */ Lines 1524–1562 at 318 (were 1524–1566 at 277)
15241524 * the search never descends below the target's lamport. 15261526 #reaches(from: Iterable<AtomId>, target: AtomId): boolean { 1527− const floor = this.#lamportAt(this.#seq(target));
1528− if (this.#storage) {
1529− return this.withProjectionScratch((scratch) => {
1530− let length = 0;
1531− const push = (id: AtomId): void => {
1532− if (scratch.read("seen", id)) return;
1533− scratch.write("seen", id, true);
1534− scratch.write("stack", String(length++), id);
1535− };
1536− for (const id of from) {
1537− if (id === target) return true;
1538− if (this.#lamportAt(this.#seq(id)) > floor) push(id);
1539− }
1540− while (length > 0) {
1541− const key = String(--length);
1542− const current = scratch.read("stack", key) as AtomId;
1543− scratch.remove("stack", key);
1544− if (this.#lamportAt(this.#seq(current)) <= floor) continue;
1545− for (const dependency of this.atom(current).deps) {
1546− if (dependency === target) return true;
1547− push(dependency);
1548− }
1549− }
1550− return false;
1551− });
1527+ return this.#reachable(from, new Set([target])).has(target); 1531+ * Which of `targets` are reachable along deps from any of `from` (themselves included), in one walk: it never 1532+ * descends below the lowest target's lamport, and stops once every target is found (abso 714, piece 4: record 1533+ * walked once per line writer). 1534+ * The walk's seen marks and stack are in memory, by atom number: one byte and four bytes an atom at most, so about 1535+ * 62 KB on abso's 12,454 atoms and 50 MB at 10 million, under a Worker's 128 MB. They were scratch rows in storage 1536+ * (abso-core 139, bounding memory with the graph), which cost a read and a write per atom visited: on abso's Oct 14 1537+ * tables, 41,000 of a 1470-shaped record's 77,767 statements. 1539+ #reachable(from: Iterable<AtomId>, targets: ReadonlySet<AtomId>): Set<AtomId> { 1540+ const found = new Set<AtomId>(); 1541+ let floor = Number.POSITIVE_INFINITY; 1542+ for (const target of targets) floor = Math.min(floor, this.#lamportAt(this.#seq(target))); 1543+ const seen = new Uint8Array(this.#atoms.length); 1544+ const stack = new Int32Array(this.#atoms.length); 1546+ const visit = (id: AtomId): void => { 1547+ if (targets.has(id)) found.add(id); 1548+ const seq = this.#seq(id); 1549+ if (seen[seq]) return; 1551+ stack[length++] = seq; 1553+ for (const id of from) visit(id); 1554+ while (length > 0 && found.size < targets.size) { 1555+ const seq = stack[--length]!; 1556+ if (this.#lamportAt(seq) <= floor) continue; 1557+ for (const dependency of this.atom(atomId(seq)).deps) visit(dependency); 1553− const seen = new Set<AtomId>();
1554− const stack = [...from];
1555− while (stack.length > 0) {
1556− const cur = stack.pop()!;
1557− if (cur === target) return true;
1558− if (seen.has(cur)) continue;
1559− seen.add(cur);
1560− if (this.#lamportAt(this.#seq(cur)) <= floor) continue;
1561− for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
1562− }
1563− return false;
Lines 1606–1633 at 318 (were 1610–1632 at 277)
16101606 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`); 16121608 // Everything it touches must come from its closure. Derived deps name the 1613− // writers directly, so this is usually one lookup per writer.
1614− const memoryBelow = scratch ? undefined : new Map<AtomId, boolean>();
1615− const below = {
1616− get: (key: AtomId) => (scratch ? (scratch.read("below", key) as boolean | undefined) : memoryBelow!.get(key)),
1617− set: (key: AtomId, value: boolean) => {
1618− if (scratch) scratch.write("below", key, value);
1619− else memoryBelow!.set(key, value);
1620− },
1621− };
1622− const inClosure = (writer: AtomId): boolean => {
1623− let hit = below.get(writer);
1624− if (hit === undefined) {
1625− hit = deps.has(writer) || this.#reaches(atom.deps, writer);
1626− below.set(writer, hit);
1609+ // writers directly, so this is usually one lookup per writer. The writers 1610+ // that aren't deps are walked for together, once (abso 714, piece 4). 1611+ const touched: LineId[] = []; 1612+ for (const run of atom.inserts) if (!isStartNode(run.parent)) touched.push(run.parent); 1613+ for (const m of atom.moves ?? []) { 1614+ touched.push(m.line); 1615+ if (!isStartNode(m.parent)) touched.push(m.parent); 1617+ touched.push(...atom.deletes); 1618+ for (const list of [atom.writes, atom.reads, atom.holds]) 1619+ for (const key of list) { 1620+ const parsed = parseKey(key); 1621+ if (parsed.kind === "line" || ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))) 1622+ touched.push(parsed.node); 1628− return hit;
1629− };
1624+ const beyond = new Set<AtomId>(); 1625+ for (const line of touched) { 1626+ const writer = this.lineAtom(line); 1627+ if (writer !== undefined && !deps.has(writer)) beyond.add(writer); 1629+ const reached = beyond.size > 0 ? this.#reachable(atom.deps, beyond) : beyond; 1630+ const inClosure = (writer: AtomId): boolean => deps.has(writer) || reached.has(writer); 16301631 const checkLine = (line: LineId, what: string): void => { 16311632 const writer = this.lineAtom(line); 16321633 if (writer === undefined) return bad(`${what} names unknown line ${line}`); Lines 10–16 at 318 (were 10–16 at 277)
1010// made when a caller asks for them, and the latest asked for is kept. 1212import type { Graph, RelocationInfo } from "./graph.ts"; 13−import { isStartNode, lineId, seqOf } from "./keys.ts";
13+import { atomId, isStartNode, lineId, seqOf } from "./keys.ts"; 1414import { resolveScratchMoves, scratchLayoutNodes } from "./relocation-scratch.ts"; 1515import { isClosedSet, StableSet } from "./state-source.ts"; 1616import { joinLines } from "./text.ts"; Lines 1095–1108 at 318 (were 1095–1101 at 277)
10971097 *lineChunks(path: string): IterableIterator<() => Iterable<string>> { 1098− for (const n of this.#file(path).vis) yield () => this.graph.textChunks(n);
1098+ // The texts the packed layout already holds, read a page at a time (abso Capacity, 714): a record's diff read each 1099+ // line's own row, 11,873 statements for abso's index.ts. Only a line too long to pack is read in chunks. 1100+ const { vis, visText } = this.#file(path); 1101+ for (let i = 0; i < vis.length; i++) { 1102+ const packed = visText?.[i]; 1103+ if (packed != null) yield () => [packed]; 1104+ else yield () => this.graph.textChunks(vis[i]!); 11011108 /** Visible lines without retaining their text in the view cache. */ Lines 1112–1118 at 318 (were 1105–1111 at 277)
11061113 id: graph.lineIdOf(n), 11071114 text: graph.textOf(n), 1108− atom: graph.idOfSeq(graph.writerSeqOf(n)),
1115+ atom: atomId(graph.writerSeqOf(n)), Lines 1126–1137 at 318 (were 1119–1130 at 277)
11191126 const n = vis[i]!; 11201127 const packed = visText?.[i]; 1122− id: visWriter && visK ? lineId(graph.idOfSeq(visWriter[i]!), visK[i]!) : graph.lineIdOf(n),
1129+ id: visWriter && visK ? lineId(atomId(visWriter[i]!), visK[i]!) : graph.lineIdOf(n), 11231130 textChunks: () => graph.textChunks(n), 11251132 return packed ?? graph.textOf(n); 1127− atom: graph.idOfSeq(visWriter ? visWriter[i]! : graph.writerSeqOf(n)),
1134+ atom: atomId(visWriter ? visWriter[i]! : graph.writerSeqOf(n)), Lines 1143–1156 at 318 (were 1136–1147 at 277)
11361143 const graph = this.graph; 11371144 const { vis, visText, visWriter, visK } = this.#file(path); 11381145 const lines: VisibleLine[] = new Array(vis.length); 1146+ // Writer seqs come from the graph's own layout, so they're named with atomId, not checked by idOfSeq (abso 738): 1147+ // on a stored graph its check read the atom count once a line, about 0.9 s of a warm draft-state on abso. 11391148 for (let i = 0; i < vis.length; i++) { 11401149 const n = vis[i]!; 1142− id: visWriter && visK ? lineId(graph.idOfSeq(visWriter[i]!), visK[i]!) : graph.lineIdOf(n),
1151+ id: visWriter && visK ? lineId(atomId(visWriter[i]!), visK[i]!) : graph.lineIdOf(n), 11431152 text: visText?.[i] ?? graph.textOf(n), 1144− atom: graph.idOfSeq(visWriter ? visWriter[i]! : graph.writerSeqOf(n)),
1153+ atom: atomId(visWriter ? visWriter[i]! : graph.writerSeqOf(n)), 11471156 this.#linesCache = { path, lines }; Lines 1172–1184 at 318 (were 1163–1175 at 277)
11631172 const writer = seqWriter ? seqWriter[i]! : graph.writerSeqOf(n); 11641173 let text: string | undefined; 1166− id: seqWriter && seqK ? lineId(graph.idOfSeq(writer), seqK[i]!) : graph.lineIdOf(n),
1175+ id: seqWriter && seqK ? lineId(atomId(writer), seqK[i]!) : graph.lineIdOf(n), 11681177 text ??= graph.textOf(n); 1171− atom: graph.idOfSeq(writer),
1172− deletedBy: by ? by.map((s) => graph.idOfSeq(s)) : NONE,
1180+ atom: atomId(writer), 1181+ deletedBy: by ? by.map((s) => atomId(s)) : NONE, 11731182 visible: by === undefined, Lines 68–74 at 318 (were 68–74 at 277)
6969 for (const key of claimsOf(atom)) streams.push(g.eachWriterOf(key)); 7070 const theirs: AtomId[] = []; 71− for (const id of orderedClaimants(g, streams)) if (against.has(id)) theirs.push(id);
71+ for (const id of orderedClaimants(streams)) if (against.has(id)) theirs.push(id); 7272 out.set(yours, theirs); Lines 136–142 at 318 (were 136–142 at 277)
137137/** Claim indexes append in canonical seq order. Merge one cursor per current 138138 * atom key, retaining no candidate set proportional to historical claims. */ 139−function* orderedClaimants(g: Graph, streams: IterableIterator<AtomId>[]): IterableIterator<AtomId> {
139+function* orderedClaimants(streams: IterableIterator<AtomId>[]): IterableIterator<AtomId> { 141141 type Head = { id: AtomId; seq: number; stream: number }; 142142 const heap: Head[] = []; Lines 152–162 at 318 (were 152–160 at 277)
155+ // Each claimant's seq from its id, as the graph reads it (abso 738): loading the stored atom for it read a row a 156+ // claimant, most of a warm draft-state's pairing on abso. 155157 const advance = (stream: number) => { 156158 const next = streams[stream]!.next(); 157− if (!next.done) push({ id: next.value, seq: g.atom(next.value).seq, stream });
159+ if (!next.done) push({ id: next.value, seq: seqOf(next.value), stream }); 159161 for (let stream = 0; stream < streams.length; stream++) advance(stream); 160162 let previous = -1; Lines 192–199 at 318 (were 190–197 at 277)
190192 let a = left.next(); 191193 let b = right.next(); 192194 while (!a.done && !b.done) { 193− const x = g.atom(a.value).seq;
194− const y = g.atom(b.value).seq;
195+ const x = seqOf(a.value); 196+ const y = seqOf(b.value); 195197 if (x === y && settled.has(a.value)) return true; 196198 if (x <= y) a = left.next(); 197199 if (y <= x) b = right.next(); Lines 7–13 at 318 (were 7–13 at 277)
77import { type AtomId, type Graph, joinLines, type LineId, type ReadView } from "../../src/engine/index.ts"; 88import { type Origin, touchedFiles } from "./collisions.ts"; 99import { type Definition, definitionsIn, importsOf, usedNames } from "./definitions.ts"; 10−import { definitionsBytes, type KeptParts, usesBytes } from "./kept-parts.ts";
10+import { definitionsBytes, filesBytes, type KeptParts, usesBytes } from "./kept-parts.ts"; 1111import { codeOfLines, declaredIn, holdsNoCode } from "./names.ts"; 1212import { definitionText } from "./news.ts"; 1313import type { Collision } from "./project.ts"; Lines 37–43 at 318 (were 37–43 at 277)
3737 readonly parent: string; 40−/** Definitions in the files newer work touched, before it and with it. */
40+/** Definitions in one file newer work touched, before it and with it. */ 4242 readonly baseDefs: ReturnType<typeof definitionsIn>; 4343 readonly nowDefs: ReturnType<typeof definitionsIn>; Lines 52–62 at 318 (were 52–59 at 277)
5252 readonly #replacedCache = new Map<string, ReadonlySet<string>>(); 5353 /** A draft's uses, kept while it is asked about with the same views: draft collisions ask once per other agent. */ 5454 readonly #usesCache = new WeakMap<ReadonlySet<AtomId>, { view: ReadView; base: ReadView; uses: Uses }>(); 55− /** The newer work's definitions before and after, kept while it is asked about with the same views. */
56− readonly #changedCache = new WeakMap<ReadonlySet<AtomId>, { base: ReadView; now: ReadView; defs: Changed }>();
55+ /** The files the newer work touched, kept while it is asked about with the same views. */ 56+ readonly #touchedCache = new WeakMap< 58+ { base: ReadView; now: ReadView; files: ReadonlySet<string> } 5861 constructor(graph: Graph, origin: (atom: AtomId, spaceName: string) => Origin) { 5962 this.#graph = graph; Lines 124–194 at 318 (were 121–157 at 277)
121124 newer: ReadonlySet<AtomId>, 122125 spaceName: string, 123126 kept?: { parts: KeptParts; uses: string; changed: string }, 127+ names?: ReadonlySet<string>, 129+ * The files the newer work changed, when the caller knows them without placing its lines (land and draft-state: 130+ * shared's kept version files, abso 738); undefined, or one that answers undefined, and they're worked out here. 132+ changedFiles?: () => ReadonlySet<string> | undefined, 124133 ): DefinitionCollision[] { 125134 if (draft.size === 0 || newer.size === 0) return []; 127136 ? kept.parts.get(`uses ${kept.uses}`, () => this.#usesOf(draft, view, baseView), usesBytes) 128137 : this.#usesFor(draft, view, baseView); 129138 if (uses.size === 0) return []; 130− const nowOf = () => (typeof nowView === "function" ? nowView() : nowView);
131− const { baseDefs, nowDefs } = kept
132− ? kept.parts.get(
133− `changed ${kept.changed}`,
134− () => this.#changed(newer, baseView, nowOf()),
135− (c) => definitionsBytes(c.baseDefs) + definitionsBytes(c.nowDefs),
136− )
137− : this.#changedFor(newer, baseView, nowOf());
138− const out: DefinitionCollision[] = [];
139− for (const [name, where] of [...uses].sort(([a], [b]) => (a < b ? -1 : 1))) {
140− // Which definitions the uses mean: the file each use imports the name
141− // from, or its own file when it defines the name at the top level. A
142− // use with neither (a local, a parameter, a global, a name another
143− // language brings in some other way) means none: the rule only speaks
144− // when it knows which definition a use means.
139+ // Only these names can collide (a publish's news, news.ts): a draft that uses none of them has none, and the 140+ // definitions changed since its base needn't be worked out. 141+ if (names && ![...uses.keys()].some((name) => names.has(name))) return []; 142+ // Which definitions the uses mean: the file each use imports the name 143+ // from, or its own file when it defines the name at the top level. A 144+ // use with neither (a local, a parameter, a global, a name another 145+ // language brings in some other way) means none: the rule only speaks 146+ // when it knows which definition a use means. 147+ const scopes = new Map<string, ReadonlySet<string>>(); 148+ for (const [name, where] of uses) { 145149 const scope = new Set<string>(); 146150 for (const w of new Set(where.map((x) => x.file))) { 147151 const from = importsOf(view, w).get(name) ?? (definitionsIn(view, [w]).has(name) ? w : undefined); 148152 if (from !== undefined) scope.add(from); 150− if (scope.size === 0) continue;
151− const inScope = (d: Definition): boolean => scope.has(d.file);
152− const before = baseDefs.get(name)?.filter(inScope);
153− if (!before?.length) continue; // not defined in what the drafter saw: nothing it relies on
154− const after = (nowDefs.get(name) ?? []).filter(inScope);
154+ if (scope.size > 0) scopes.set(name, scope); 156+ if (scopes.size === 0) return []; 157+ const nowOf = () => (typeof nowView === "function" ? nowView() : nowView); 158+ // Only a file the newer work touched can hold a changed definition, and only one a use means can matter: just those 159+ // files are laid out, before and with the newer work (abso 738). Laying out every file the newer work touched cost 160+ // codex-prose-authorship-610's draft-state 494 files a view where its uses reach 7. 164+ ? kept.parts.get(`touched ${kept.changed}`, () => this.#touched(newer, baseView, nowOf()), filesBytes) 165+ : this.#touchedFor(newer, baseView, nowOf())); 166+ const changed = new Map<string, Changed>(); 167+ const changedIn = (file: string): Changed => { 168+ let c = changed.get(file); 170+ const make = (): Changed => ({ 171+ baseDefs: definitionsIn(baseView, [file]), 172+ nowDefs: definitionsIn(nowOf(), [file]), 176+ `changed ${kept.changed} ${file}`, 178+ (d) => definitionsBytes(d.baseDefs) + definitionsBytes(d.nowDefs), 181+ changed.set(file, c); 185+ const out: DefinitionCollision[] = []; 186+ for (const [name, scope] of [...scopes].sort(([a], [b]) => (a < b ? -1 : 1))) { 187+ // In the order the newer work touched its files, as when every touched file was laid out. 188+ const files = [...touched].filter((f) => scope.has(f)); 189+ const before = files.flatMap((f) => changedIn(f).baseDefs.get(name) ?? []); 190+ if (!before.length) continue; // not defined in what the drafter saw: nothing it relies on 191+ const after = files.flatMap((f) => changedIn(f).nowDefs.get(name) ?? []); 155192 if (signature(before) === signature(after)) continue; 156193 // Who changed it: newer writers of the new definition's lines, or newer deleters of the old one's. 157194 const by = new Set<AtomId>(); Lines 199–205 at 318 (were 162–167 at 277)
162199 const first = [...by].sort((p, q) => this.#graph.atom(p).seq - this.#graph.atom(q).seq)[0]; 163200 if (first === undefined) continue; 164201 const origin = this.#origin(first, spaceName); 202+ const where = uses.get(name)!; 165203 const file = where[0]!.file; 166204 const indexes = where.filter((w) => w.file === file).map((w) => w.index); 167205 const lo = Math.min(...indexes); Lines 239–257 at 318 (were 201–220 at 277)
204− /** The newer work's definitions before and after, kept while it is asked about with the same views. */
205− #changedFor(newer: ReadonlySet<AtomId>, baseView: ReadView, now: ReadView): Changed {
206− let changed = this.#changedCache.get(newer);
207− if (!changed || changed.base !== baseView || changed.now !== now) {
208− changed = { base: baseView, now, defs: this.#changed(newer, baseView, now) };
209− this.#changedCache.set(newer, changed);
242+ /** The files the newer work touched, kept while it is asked about with the same views. */ 243+ #touchedFor(newer: ReadonlySet<AtomId>, baseView: ReadView, now: ReadView): ReadonlySet<string> { 244+ let kept = this.#touchedCache.get(newer); 245+ if (!kept || kept.base !== baseView || kept.now !== now) { 246+ kept = { base: baseView, now, files: this.#touched(newer, baseView, now) }; 247+ this.#touchedCache.set(newer, kept); 211− return changed.defs;
214− /** Definitions in the files the newer work touched, before it and with it: only there can one have changed. */
215− #changed(newer: ReadonlySet<AtomId>, baseView: ReadView, now: ReadView): Changed {
216− const touched = touchedFiles(this.#graph, newer, [baseView, now]);
217− return { baseDefs: definitionsIn(baseView, touched), nowDefs: definitionsIn(now, touched) };
252+ /** The files the newer work touched, before it and with it: only there can a definition have changed. */ 253+ #touched(newer: ReadonlySet<AtomId>, baseView: ReadView, now: ReadView): ReadonlySet<string> { 254+ return touchedFiles(this.#graph, newer, [baseView, now]); 220257 /** The names the draft's lines use and don't declare, less those the lines they replaced already used. */ Lines 62–90 at 318 (were 62–67 at 277)
6262 const g = host.graph; 6363 const mine = new Set(draft); 6464 const text = new MoveLineText(g); 65+ // The draft's own lines first, before laying out any file (abso 714, piece 3): a move needs a written line with 66+ // real content whose text the draft also deleted. An edit that only changes lines has none, and laying out its 67+ // files (12k lines twice for one changed line of worker/src/index.ts) cost the whole publish. 68+ const goneIds = new Set<LineId>(); 69+ const goneTexts = new Set<number>(); 70+ for (const id of draft) 71+ for (const line of g.deletedLines(id)) { 73+ goneTexts.add(text.intern(line)); 75+ if (goneTexts.size === 0) return; 77+ for (const id of draft) { 78+ for (const line of g.eachInsertedLine(id)) { 79+ const t = text.intern(line); 80+ if (!text.plain[t] && goneTexts.has(t)) { 6588 const after = host.agentView(agent); 6689 const before = host.beforeDraft 6790 ? host.beforeDraft(agent, draft) Lines 104–111 at 318 (were 81–87 at 277)
81104 for (const file of [...touched].toSorted()) { 82105 let cur: Block | undefined; 83106 before.buildLines(file).forEach((l, i) => { 84− if (g.deletersOf(l.id).some((d) => mine.has(d))) {
107+ // Deleted by the draft: one of its atoms' deleted lines, with no lookup of each line's deleters. 108+ if (goneIds.has(l.id)) { 85109 if (!cur) gone.push((cur = { file, start: i, ids: [], texts: [] })); 86110 cur.ids.push(l.id); 87111 cur.texts.push(text.intern(l.id)); Lines 1–8 at 318 (were 1–8 at 277)
11// What draft collisions work out about each draft and each pair of drafts, kept between calls under a hard byte budget 2−// (abso Capacity, issue 664): the names a draft's new lines use, the definitions a draft's changes touch before and
3−// after, and the names a pair of drafts both define in a file. Keys name everything an entry depends on (shared's
4−// version, a draft's base and atoms), and a call drops every entry it didn't use, so a draft that changes, an agent that
5−// leaves and shared moving on all drop theirs at once.
2+// (abso Capacity, issue 664): the names a draft's new lines use, the files a draft's changes touch and the definitions 3+// in each before and after, and the names a pair of drafts both define in a file. Keys name everything an entry depends 4+// on (shared's version, a draft's base and atoms), and a call drops every entry it didn't use, so a draft that changes, 5+// an agent that leaves and shared moving on all drop theirs at once. 77import { stringBytes } from "../../src/engine/view.ts"; 88import type { Definition } from "./definitions.ts"; Lines 100–109 at 318 (were 100–102 at 277)
100100 n += MAP_ENTRY_BYTES + stringBytes(name) + ARRAY_HEADER_BYTES + where.length * (REFERENCE_BYTES + OBJECT_BYTES); 104+/** A set of paths (the files some work touched). */ 105+export function filesBytes(files: ReadonlySet<string>): number { 106+ let n = MAP_HEADER_BYTES; 107+ for (const file of files) n += MAP_ENTRY_BYTES + stringBytes(file); Lines 29–36 at 318 (were 29–34 at 277)
2929 pairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[]; 3030 describe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision; 3131 definitionRule(): DefinitionRule; 32+ /** The files a space's versions after `from`, up to `to`, changed, when each one's are kept; else undefined. */ 33+ changedSince(space: Space, from: number, to: number): ReadonlySet<string> | undefined; Lines 95–118 at 318 (were 93–103 at 277)
9395 ? host.viewAt(shared, sharedBaseOf(space), changes) 9496 : host.viewAt(space, space.versions.length - 1); 9597 const describeLand = (p: Pair): Collision => host.describe(p, draftView, host.sharedView(), SHARED); 98+ // Where shared changed since the draft's base, from the files each version since kept as it landed (abso 738): working 99+ // it out from the newer atoms placed every line they wrote or deleted, about 30% of a warm draft-state read. 100+ const changed = () => host.changedSince(shared, sharedBaseOf(space), host.version()); 96101 const collisions = [ 97102 ...host.pairs(changes, newer, union).map(describeLand), 100− .collisions(own, draftView, host.viewAt(shared, sharedBaseOf(space)), host.sharedView(), newer, SHARED)
108+ host.viewAt(shared, sharedBaseOf(space)), 101116 .map((d) => d.collision), 103118 return { collisions, newer, union }; Lines 248–298 at 318 (were 248–257 at 277)
248248 viewAt(space: Space, version: number): ReadView; 249249 origin(atom: AtomId, spaceName: string): Origin; 250250 collision(agent: AgentState, pair: Pair): Collision; 251− definitionCollisions(agent: AgentState, newer: ReadonlySet<AtomId>): DefinitionCollision[];
251+ /** `names`: only these can collide; a draft that uses none of them has none (newsForOthers). */ 252+ definitionCollisions( 254+ newer: ReadonlySet<AtomId>, 255+ names?: ReadonlySet<string>, 256+ ): DefinitionCollision[]; 252257 queueNews(agent: AgentState, items: readonly NewsItem[], entries: Entry[]): void; 258+ /** A line for the host's logs (ProjectOptions.logLine). */ 259+ logLine?(line: Record<string, string | number>): void; 261+ * Owed news (abso Capacity, 2026-10-15): when this answers true, a publish leaves its definition news for other 262+ * agents to be worked out after its write (definitionNewsOwed) and hands it to owe instead. 264+ owesDefinitionNews(): boolean; 265+ owe(owed: OwedDefinitionNews): void; 266+ spaceNamed(name: string): Space | undefined; 267+ /** newerFor as it was at `version` of the agent's space. */ 268+ newerAt(agent: AgentState, version: number): ReadonlySet<AtomId>; 269+ /** definitionCollisions against the agent's space at `version`, not its newest. */ 270+ definitionCollisionsAt( 272+ newer: ReadonlySet<AtomId>, 273+ names: ReadonlySet<string>, 275+ ): DefinitionCollision[]; 276+ /** The space's atoms at `version`: setOf as it was then (owed news). */ 277+ setAt(space: Space, version: number): ReadonlySet<AtomId>; 278+ /** collision, with theirs described from the agent's space at `version`, not its newest (owed news). */ 279+ collisionAt(agent: AgentState, pair: Pair, version: number): Collision; 283+ * A publish's news for other agents, not yet worked out: the version it made, and who made it. `all`: everything the 284+ * publish would have told them (same lines, definitions, moves; abso 714). Without it, as owed before 714, only the 285+ * definition news. `names`: the names its definitions changed, once worked out (owedNewsNames). 287+export interface OwedNews { 288+ readonly version: number; 289+ readonly space: string; 290+ readonly publisher: string; 291+ readonly names?: readonly string[]; 292+ readonly all?: boolean; 294+export type OwedDefinitionNews = OwedNews; 255296function lineNews(host: NewsHost, agent: AgentState, pairs: readonly Pair[]): NewsItem[] { 256297 return pairs.map((p) => ({ key: pairKey(p), text: linesText(host.collision(agent, p)) })); Lines 312–319 at 318 (were 271–276 at 277)
271312 just: ReadonlySet<AtomId>, 315+ /** The space's version the moved lines' files are read at: its newest, or an owed publish's own. */ 275318 const g = host.graph; 276319 const movers = [...just].filter((id) => g.atom(id).moves); Lines 326–332 at 318 (were 283–289 at 277)
285328 const was = host.viewAt(space, version - 1); 286− const now = host.viewAt(space, last(space));
329+ const after = host.viewAt(space, now); 287330 const out: NewsItem[] = []; 288331 for (const id of movers) { Lines 335–341 at 318 (were 292–298 at 277)
292335 .filter((k) => k.kind === "pos" && claimed.has(k.node)) 293336 .map((k) => k.node); 294337 if (moved.length === 0) continue; 295− out.push(moveItem(id, host.origin(id, space.name), was.fileOf(moved[0]!), now.fileOf(moved[0]!)));
338+ out.push(moveItem(id, host.origin(id, space.name), was.fileOf(moved[0]!), after.fileOf(moved[0]!))); Lines 363–506 at 318 (were 320–348 at 277)
322365 const just = new Set(space.versions[version]!.atoms); 323− let changedDefinitions: boolean | undefined;
324− const compareDefinitions = () => {
325− // Most publishes change no definition; then only the same-lines rule can bring news.
326− const touched = touchedFiles(host.graph, just, [host.viewAt(space, version - 1), host.viewAt(space, last(space))]);
327− const before = definitionsIn(host.viewAt(space, version - 1), touched);
328− const after = definitionsIn(host.viewAt(space, last(space)), touched);
329− return [...new Set([...before.keys(), ...after.keys()])].some(
330− (name) => !before.has(name) || signature(before.get(name)!) !== signature(after.get(name) ?? []),
331− );
332− };
366+ // The names whose definitions this publish changed, worked out once. Most publishes change none; then only the 367+ // same-lines rule can bring news. A definition collision this publish brings (its `by` in `just`) is one of 368+ // these, so a draft that uses none of them has none, and the rule isn't run for it (abso Capacity, prod abso 369+ // 2026-10-15): it compared definitions in every file changed since each agent's base, for every agent with a draft, 370+ // and a publish touching abso's worker/src/index.ts took 48 s of it. 371+ let changedNames: ReadonlySet<string> | undefined; 372+ // For the host's logs (abso 702): a line as the work starts, written before it, and one as it ends, so work that 373+ // outlives its request still shows. No time in them: a Durable Object's clock stands still in synchronous code. 376+ // Owed (abso 714, Christopher's base fix): on stored tables this news for other agents was most of a publish's one 377+ // write transaction (the same-lines pairs, the definitions, the moves, for every draft: about 10 s for a 30-line 378+ // change to abso's 12k-line index.ts), long enough to time storage out and reset the object (prod abso, 23:32Z 379+ // 2026-10-16). Owing, the publish only notes what it owes, here, once some other agent has a draft; it's worked out 380+ // after the commit, one agent at a time, against this version (newsOwed). Asked only then (news-lazy.test.ts: no 381+ // news work at all otherwise). 382+ let owing: boolean | undefined; 333383 for (const agent of [...host.agents.values()].toSorted((a, b) => (a.name < b.name ? -1 : 1))) { 334384 if (agent === publisher || agent.space !== space.name) continue; 335385 const draft = host.draft(agent); 336386 if (draft.length === 0) continue; 387+ owing ??= host.owesDefinitionNews(); 389+ host.owe({ version, space: space.name, publisher: publisher.name, all: true }); 390+ host.logLine?.({ work: "publishNews", step: "owed", space: space.name, version, publisher: publisher.name }); 394+ host.logLine?.({ work: "publishNews", step: "start", space: space.name, version, publisher: publisher.name }); 337395 const lines = pairsIn(host.graph, draft, just, unionOverlay(host.setOf(space), draft)); 338− changedDefinitions ??= compareDefinitions();
339− const defs = changedDefinitions
340− ? host.definitionCollisions(agent, host.newerFor(agent)).filter((d) => just.has(d.by))
396+ changedNames ??= changedNamesAt(host, space, version); 398+ changedNames.size > 0 399+ ? host.definitionCollisions(agent, host.newerFor(agent), changedNames).filter((d) => just.has(d.by)) 402+ ...lineNews(host, agent, lines), 403+ ...definitionNews(defs), 404+ ...moveNews(host, draft, just, space, version), 406+ news += items.length; 407+ host.queueNews(agent, items, entries); 411+ work: "publishNews", 415+ publisher: publisher.name, 417+ changedNames: changedNames?.size ?? 0, 423+ * The names whose definitions the publish at `version` changed, in the files it touched: before it against its own 424+ * version. Most publishes change none; then only the same-lines rule can bring news. A definition collision the publish 425+ * brings is one of these, so a draft that uses none of them has none (abso Capacity, prod abso 2026-10-15). 427+function changedNamesAt(host: NewsHost, space: Space, version: number): ReadonlySet<string> { 428+ const just = new Set(space.versions[version]!.atoms); 429+ const touched = touchedFiles(host.graph, just, [host.viewAt(space, version - 1), host.viewAt(space, version)]); 430+ const before = definitionsIn(host.viewAt(space, version - 1), touched); 431+ const after = definitionsIn(host.viewAt(space, version), touched); 433+ [...new Set([...before.keys(), ...after.keys()])].filter( 434+ (name) => !before.has(name) || signature(before.get(name)!) !== signature(after.get(name) ?? []), 439+/** owedNews's names, worked out once for a publish (the host keeps them on its row): changedNamesAt its version. */ 440+export function owedNewsNames(host: NewsHost, owed: OwedNews): string[] { 441+ const space = host.spaceNamed(owed.space); 442+ if (!space || owed.version > last(space) || !space.versions[owed.version]) return []; 443+ return [...changedNamesAt(host, space, owed.version)].sort(); 447+ * The definition news a publish owes, worked out as newsForOthers would have at that version: the same agents, the 448+ * same rule against the space at `owed.version` and the work published up to it, the same words and keys. Reads only. 449+ * An agent that has synced past the version since is left out (the version is no longer newer for it), and an item 450+ * an agent was already told (from its own edit since, or this run before) is dropped, as queueNews would. 452+export function newsOwed( 455+ /** Only these agents (owedAgents' names), so a host can work the news out one agent at a time (abso 714). */ 456+ only?: readonly string[], 457+): { agent: string; items: NewsItem[] }[] { 458+ const space = host.spaceNamed(owed.space); 459+ if (!space || owed.version > last(space) || !space.versions[owed.version]) return []; 460+ const just = new Set(space.versions[owed.version]!.atoms); 461+ let names: ReadonlySet<string> | undefined = owed.names ? new Set(owed.names) : undefined; 462+ const out: { agent: string; items: NewsItem[] }[] = []; 463+ for (const agent of [...host.agents.values()].toSorted((a, b) => (a.name < b.name ? -1 : 1))) { 464+ if (only && !only.includes(agent.name)) continue; 465+ if (!owedTo(host, owed, space, agent)) continue; 466+ const draft = host.draft(agent); 467+ names ??= changedNamesAt(host, space, owed.version); 468+ const lines = owed.all 469+ ? pairsIn(host.graph, draft, just, unionOverlay(host.setAt(space, owed.version), draft)).map((p) => ({ 471+ text: linesText(host.collisionAt(agent, p, owed.version)), 342− host.queueNews(
343− agent,
344− [...lineNews(host, agent, lines), ...definitionNews(defs), ...moveNews(host, draft, just, space, version)],
345− entries,
346− );
477+ .definitionCollisionsAt(agent, host.newerAt(agent, owed.version), names, owed.version) 478+ .filter((d) => just.has(d.by)) 480+ const moves = owed.all ? moveNews(host, draft, just, space, owed.version, owed.version) : []; 481+ const items = [...lines, ...definitionNews(defs), ...moves].filter((item) => !agent.told.has(item.key)); 482+ if (items.length > 0) out.push({ agent: agent.name, items }); 486+/** newsOwed, under the name tonight's owed definition news had (abso 2341e805). */ 487+export const definitionNewsOwed = newsOwed; 490+ * The agents a publish's owed news may be for, in the order definitionNewsOwed takes them: every other agent in the 491+ * space, behind the version, with a draft. Cheap (no definition rule), so a host can list them once and then work the 492+ * news out a few at a time, each in its own read (abso 714: one read over every draft reset prod abso's object). 494+export function owedAgents(host: NewsHost, owed: OwedDefinitionNews): string[] { 495+ const space = host.spaceNamed(owed.space); 496+ if (!space || owed.version > last(space) || !space.versions[owed.version]) return []; 497+ return [...host.agents.values()] 498+ .toSorted((a, b) => (a.name < b.name ? -1 : 1)) 499+ .filter((agent) => owedTo(host, owed, space, agent)) 500+ .map((agent) => agent.name); 503+function owedTo(host: NewsHost, owed: OwedDefinitionNews, space: Space, agent: AgentState): boolean { 504+ if (agent.name === owed.publisher || agent.space !== space.name || agent.base >= owed.version) return false; 505+ return host.draft(agent).length > 0; Lines 90–110 at 318 (were 90–95 at 277)
9090 return files && [...files].sort(); 94+ * The files the versions after `from`, up to `to`, changed, from each version's kept row (abso 738): undefined when one 95+ * has none, and the caller works them out from the atoms. Every file whose text differs between the two versions is 96+ * in it, since some version between changed it. 98+ keptChangesSince(space: Space, from: number, to: number): ReadonlySet<string> | undefined { 99+ const out = new Set<string>(); 100+ for (let v = from + 1; v <= to; v++) { 101+ const files = this.#keptFiles(space, v); 102+ if (!files) return undefined; 103+ for (const f of files) out.add(f); 93108 /** keptPaths as a set, kept for the newest version asked: never changed once made, so a view can hold it. */ 94109 keptPathSet(space: Space, version: number): ReadonlySet<string> | undefined { 95110 let fold = this.#keptPaths.get(space); Lines 155–162 at 318 (were 155–160 at 277)
155155 refusals(agent?: string, limit?: number): unknown; 156156 /** A file as it was at a version (#27). */ 157157 fileAt(path: string, version: number, draft: string | null, agent?: string): unknown; 158+ /** fileAt for exactly this spelling, without the version's list of files (version-log.ts fileExactAt). */ 159+ fileExactAt?(path: string, version: number, draft: string | null): unknown; 158160 /** Every file that differs between two versions (#27). */ 159161 compare(from: number, to: number, draft: string | null, agent?: string, summary?: boolean): unknown; 160162 /** Version `version` of shared without the versions in `versions` (without.ts). */ Lines 49–66 at 318 (were 49–54 at 277)
52+ * An agent with nothing of its own sees exactly its base version, so its paths are that version's kept file list 53+ * (pathindex.ts), when there is one: no layout of every known file (abso - Performance, abso 711). 55+function viewPaths(host: SnapshotHost, agent: AgentState): string[] { 57+ agent.mine.length === 0 58+ ? host.keptPaths?.(host.spaceNamed(agent.space === SHARED ? null : agent.space), agent.base) 60+ return kept ?? host.agentView(agent).paths(); 5264 * The paths in an agent's view now (#37): what its folder should hold. 5365 * Reading it changes nothing. Binary files are included. Lines 74–80 at 318 (were 62–68 at 277)
6375 version: agent.base, 6476 draft: agent.space === SHARED ? null : agent.space, 65− files: host.agentView(agent).paths(),
77+ files: viewPaths(host, agent), Lines 106–112 at 318 (were 94–100 at 277)
95107 version: agent.base, 96108 draft: agent.space === SHARED ? null : agent.space, 97− files: host.agentView(agent).paths(),
109+ files: viewPaths(host, agent), Lines 583–604 at 318 (were 583–589 at 277)
583583export type Blobs = Record<string, string | null>; 585585/** What the project needs from the store of binary files' bytes. */ 586+/** One news item a write gave an agent: its text and time, and its entry's place in the log. */ 587+export interface NewsWritten { 588+ readonly agent: string; 589+ readonly text: string; 590+ readonly at: number | null; 591+ /** The news entry's place in the log: later news has a higher one. */ 592+ readonly seq: number; 586595export interface ProjectOptions { 597+ * Told after each write that gave agents news, with each item as the write appended it. It runs inside the write, 598+ * which can still roll back, so a host collects the items and acts on them only once the call has returned. A host 599+ * can then wake a listener for exactly the agents that got news, without reading the log. 601+ newsWritten?: (items: readonly NewsWritten[]) => void; 587602 /** Optional derived atom indexing within persistent graph acceptance. */ 588603 indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void; 589604 /** Private experimental reader route; never falls back for unsupported membership. */ Lines 639–650 at 318 (were 624–629 at 277)
624639 * recent. Without it, all text stays in memory. 626641 entryAt?: (at: number) => Entry; 643+ * One line for the host's logs about long work inside an operation (abso 644+ * 702): written as the work starts and again when it ends, so work that 645+ * outlives its request still shows. Without it, nothing is written. 647+ logLine?: (line: Record<string, string | number>) => void; 628649export interface LogEntry { Lines 105–117 at 318 (were 105–113 at 277)
106106 newsAboutOwnDraft as hostedNewsAboutOwnDraft, 107107 newsForOthers as hostedNewsForOthers, 108+ newsOwed as hostedNewsOwed, 109+ owedAgents as hostedOwedAgents, 110+ owedNewsNames as hostedOwedNewsNames, 114+ type OwedDefinitionNews, 113117} from "./news.ts"; Lines 161–167 at 318 (were 157–162 at 277)
Lines 222–228 at 318 (were 217–222 at 277)
217222 compare as versionCompare, 218223 compareSummary as versionCompareSummary, 219224 fileAt as versionFileAt, 225+ fileExactAt as versionFileExactAt, 220226 log as versionLog, 221227 ribbon as versionRibbon, 222228 show as versionShow, Lines 335–351 at 318 (were 329–337 at 277)
329335 * doesn't depend on it. 331337 checkerReady = false; 339+ * Owed news (abso Capacity, 2026-10-15): a publish's definition news for other agents is left for after its write 340+ * (takeOwedDefinitionNews, definitionNewsOwed, deliverOwedNews). The disk route sets it; the replay engine doesn't. 342+ owesDefinitionNews = false; 343+ #owed: OwedDefinitionNews[] = []; 332344 readonly #now: (() => number) | undefined; 345+ readonly #newsWritten: ((items: readonly NewsWritten[]) => void) | undefined; 333346 readonly #whole: ProjectOptions["whole"]; 334347 readonly #shapes: ProjectOptions["shapes"]; 348+ readonly #logLine: ProjectOptions["logLine"]; 335349 /** For each log position, the newest time up to it (#41): time to position in one search. */ 336350 readonly #timeAt: number[] = []; 337351 /** For each version of shared, the log position of the entry that made it (#41). */ Lines 465–474 at 318 (were 451–458 at 277)
452466 this.#hasBlob = options.hasBlob ?? (() => false); 453467 this.#now = options.now; 468+ this.#newsWritten = options.newsWritten; 454469 this.#whole = options.whole; 455470 this.#shapes = options.shapes; 471+ this.#logLine = options.logLine; 456472 // For tests (#46): AVCS_TEXT_FROM_LOG=1 runs a project on a MemoryStore with its text read back from the store. 458474 (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.AVCS_TEXT_FROM_LOG === Lines 1348–1391 at 318 (were 1332–1337 at 277)
13321348 return hostedAnnouncePerson(this.#announceHost, ...args); 1351+ /** The definition news the writes since the last call owe other agents, handed over once (news.ts). */ 1352+ takeOwedDefinitionNews(): OwedDefinitionNews[] { 1353+ const owed = this.#owed; 1358+ /** What a publish owes, worked out against its version (news.ts newsOwed), for `only` these agents if given. Reads only. */ 1359+ newsOwed(owed: OwedDefinitionNews, only?: readonly string[]): { agent: string; items: NewsItem[] }[] { 1360+ return hostedNewsOwed(this.#newsHost, owed, only); 1363+ /** newsOwed, under the name owed definition news had before abso 714. */ 1364+ definitionNewsOwed(owed: OwedDefinitionNews, only?: readonly string[]): { agent: string; items: NewsItem[] }[] { 1365+ return this.newsOwed(owed, only); 1368+ /** The names a publish's definitions changed (news.ts owedNewsNames), worked out once for its owed news. Reads only. */ 1369+ owedNewsNames(owed: OwedDefinitionNews): string[] { 1370+ return hostedOwedNewsNames(this.#newsHost, owed); 1373+ /** The agents a publish's owed news may be for (news.ts owedAgents). Reads only. */ 1374+ owedAgents(owed: OwedDefinitionNews): string[] { 1375+ return hostedOwedAgents(this.#newsHost, owed); 1378+ /** Tells each agent its owed items, as queueNews does: what an agent was already told adds nothing. */ 1379+ deliverOwedNews(found: readonly { agent: string; items: readonly NewsItem[] }[]): number { 1380+ const entries: Entry[] = []; 1381+ for (const { agent: name, items } of found) { 1382+ const agent = this.#agents.get(name); 1383+ if (agent) this.#queueNews(agent, items, entries); 1385+ this.#flush(entries); 1386+ return entries.length; 13351389 /** A seat's earlier chat hears that another chat just used the seat (announce.ts seatNotice). */ 13361390 seatNotice(...args: Tail<Parameters<typeof hostedSeatNotice>>): ReturnType<typeof hostedSeatNotice> { 13371391 return hostedSeatNotice(this.#announceHost, ...args); Lines 1492–1508 at 318 (were 1438–1443 at 277)
14381492 return hostedOverlapNews(this.#overlapHost, ...args); 1495+ /** The news waiting for an agent, read only: nothing is taken, heard or written. None for an agent it hasn't got. */ 1496+ peekNews(agentName: string): { text: string; at: number | null }[] { 1497+ const agent = typeof agentName === "string" ? this.#agents.get(agentName) : undefined; 1498+ return agent ? agent.news.map((text, i) => ({ text, at: agent.newsAt[i] ?? null })) : []; 1501+ /** Whether the project has this agent. Read only. */ 1502+ hasAgent(agentName: string): boolean { 1503+ return typeof agentName === "string" && this.#agents.get(agentName) !== undefined; 14411506 /** Hand over the news waiting for an agent (collisions, definitions, moves, announcements), once. */ 14421507 news(agentName: string): { news: string[]; items: { text: string; at: number | null }[] } { 14431508 const entries: Entry[] = []; Lines 1782–1796 at 318 (were 1717–1722 at 277)
17171782 if (this.#pending.length === 0) return; 17181783 const out = this.#pending; 17191784 this.#store.append(out); 1785+ if (this.#newsWritten) { 1786+ const items: NewsWritten[] = []; 1787+ out.forEach((entry, i) => { 1788+ if (entry.type !== "news") return; 1789+ for (const text of entry.text) 1790+ items.push({ agent: entry.agent, text, at: entry.time ?? null, seq: this.#stored + i }); 1792+ if (items.length > 0) this.#newsWritten(items); 17201794 this.#persistMutable(); 17211795 // A few more agents' old told lists into their buckets at each write, until every row has moved (writer-agents.ts). 17221796 if (this.#agents instanceof WriterAgents) this.#agents.moveOldTold(OLD_TOLD_PER_WRITE); Lines 2009–2019 at 318 (were 1935–1940 at 277)
19352009 return versionFileAt(this.#logHost, ...args); 2012+ /** fileAt for exactly this spelling, from the file's own lines: no list of the version's files (version-log.ts). */ 2013+ fileExactAt(...args: Tail<Parameters<typeof versionFileExactAt>>): ReturnType<typeof versionFileExactAt> { 2014+ return versionFileExactAt(this.#logHost, ...args); 19382017 /** Every file that differs between two versions of shared (or a named draft) (version-log.ts). */ 19392018 compare(...args: Tail<Parameters<typeof versionCompare>>): ReturnType<typeof versionCompare> { 19402019 return versionCompare(this.#logHost, ...args); Lines 2184–2201 at 318 (were 2105–2112 at 277)
21052184 viewAt: (space, version) => this.#viewAt(space, version), 21062185 origin: (atom, spaceName) => this.#origin(atom, spaceName), 21072186 collision: (agent, pair) => this.#collision(agent, pair), 2108− definitionCollisions: (agent, newer) => this.#definitionCollisions(agent, newer),
2187+ definitionCollisions: (agent, newer, names) => this.#definitionCollisions(agent, newer, names), 21092188 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries), 2189+ logLine: (line) => this.#logLine?.(line), 2190+ owesDefinitionNews: () => this.owesDefinitionNews, 2191+ owe: (owed) => void this.#owed.push(owed), 2192+ spaceNamed: (name) => (name === SHARED ? this.#shared : this.#spaces.get(name)), 2193+ newerAt: (agent, version) => this.#newerFor(agent, version), 2194+ definitionCollisionsAt: (agent, newer, names, version) => 2195+ this.#definitionCollisions(agent, newer, names, version), 2196+ setAt: (space, version) => this.#at(space, version), 2197+ collisionAt: (agent, pair, version) => 2198+ this.#describe(pair, this.#agentView(agent), this.#viewAt(this.#spaceOf(agent), version), agent.space), 21112200 return this.#news; Lines 2499–2507 at 318 (were 2410–2415 at 277)
24102499 pairs: (draft, against, settled) => this.#pairs(draft, against, settled), 24112500 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName), 24122501 definitionRule: () => this.#definitionRule, 2502+ // Only from a stored writer's kept rows, as keptPaths: a project in memory keeps none, and works them out. 2503+ changedSince: (space, from, to) => 2504+ this.#writerStorage ? this.#paths.keptChangesSince(space, from, to) : undefined, 24132505 refuse: (agent, space, via, time, collisions, entries) => 24142506 this.#refuse(agent, space, via, time, collisions, entries), 24152507 requireClosed: (tie, union) => this.#requireClosed(tie, union), Lines 3061–3074 at 318 (were 2969–2981 at 277)
29713063 /** The space's atoms published after the agent's base, by others. */ 2972− #newerFor(agent: AgentState): ReadonlySet<AtomId> {
3064+ /** `upTo`: the work published after the agent's base up to that version only (owed news, news.ts). */ 3065+ #newerFor(agent: AgentState, upTo?: number): ReadonlySet<AtomId> { 29733066 const space = this.#spaceOf(agent); 29743067 const base = this.#at(space, agent.base); 2975− const current = this.#setOf(space);
3068+ const current = upTo === undefined ? this.#setOf(space) : this.#at(space, upTo); 29773070 space.name === SHARED && space.membershipVersion 2978− ? new SharedAdditions(space, agent.base, base, current)
3071+ ? new SharedAdditions(space, agent.base, base, current, upTo ?? last(space)) 29793072 : differenceSet(current, base); 29803073 return differenceSet(newer, new StableOverlaySet(agent.mine)); Lines 3204–3216 at 318 (were 3111–3117 at 277)
31113204 // The changed-definition rule (#11) ------------------------------------------- 31133206 /** The rule for an agent's draft in its space. */ 3114− #definitionCollisions(agent: AgentState, newer: ReadonlySet<AtomId>): DefinitionCollision[] {
3207+ #definitionCollisions( 3209+ newer: ReadonlySet<AtomId>, 3210+ names?: ReadonlySet<string>, 3211+ /** The space's version to compare against: its newest, or an owed publish's (news.ts). */ 3213+ ): DefinitionCollision[] { 31153214 const draft = new Set(this.#draft(agent)); 31163215 if (draft.size === 0 || newer.size === 0) return []; 31173216 const space = this.#spaceOf(agent); Lines 3218–3236 at 318 (were 3119–3131 at 277)
31193218 const base = agent.mine.some((id) => at.has(id)) 31203219 ? this.#view(differenceSet(at, new StableOverlaySet(agent.mine))) 31213220 : this.#viewAt(space, agent.base); 3221+ const to = version ?? last(space); 31223222 return this.#definitionRule.collisions( 31243224 this.#agentView(agent), 3126− this.#viewAt(space, last(space)),
3226+ this.#viewAt(space, to), 3231+ // Where the space changed since the agent's base, from each version's kept files on a stored writer, as land's 3232+ // (abso 714): walking every newer atom for them was 6.5 s of a publish 770 versions behind on abso. 3233+ () => (this.#writerStorage ? this.#paths.keptChangesSince(space, agent.base, to) : undefined), Lines 40–50 at 318 (were 40–45 at 277)
4040 indexVersion?: (version: Published) => void; 4141 /** Version of the selected membership event, independent of later publishes. */ 4242 membershipVersion?: (atom: AtomId, version: number) => number | undefined; 44+ * membershipVersion reading the membership pages first, each page once (abso - Performance, 714): for a walk over 45+ * many atoms, such as SharedAdditions. Most atoms have one event, and the page says its version. 47+ membershipVersions?: () => (atom: AtomId, version: number) => number | undefined; 4348 readonly name: string; 4449 readonly versions: Published[]; 4550 /** Every atom published into this space (for shared, everything in it). */ Lines 63–75 at 318 (were 58–63 at 277)
5964 indexVersion: (version) => indexMembership(storage, prefix, version), 6065 membershipVersion: (atom, version) => membershipEvent(storage, prefix, atom, version)?.version, 66+ membershipVersions: () => { 67+ const pages = new PageReader(storage, prefix); 68+ return (atom, version) => { 69+ const known = pages.versionAt(atom, version); 70+ return known === null ? membershipEvent(storage, prefix, atom, version)?.version : known; 6173 versions: storedArray(storage, `${prefix}:versions`), 6274 own: new StoredSet(storage, `${prefix}:own`), 6375 publishedIn: new StoredMap(storage, `${prefix}:published`), Lines 136–154 at 318 (were 124–129 at 277)
125137 /** Whether atom is present at version, or undefined when its events must be read. */ 126138 presentAt(atom: AtomId, version: number): boolean | undefined { 139+ const code = this.#code(atom); 140+ if (code === undefined || code === MIXED) return undefined; 141+ if (code === NONE) return false; 142+ return version >= code; 144+ /** membershipVersion from the page: the version of its only event, or undefined; null when its events must be read. */ 145+ versionAt(atom: AtomId, version: number): number | undefined | null { 146+ const code = this.#code(atom); 147+ if (code === undefined || code === MIXED) return null; 148+ if (code === NONE) return undefined; 149+ return version >= code ? code : undefined; 151+ #code(atom: AtomId): number | undefined { 127152 this.#kept ??= this.#storage.read(`${this.#prefix}:pages:meta`, "kept") === 1; 128153 if (!this.#kept) return undefined; 129154 const seq = seqOf(atom); Lines 160–166 at 318 (were 135–144 at 277)
135160 if (this.#pages.size >= 64) this.#pages.delete(this.#pages.keys().next().value!); 136161 this.#pages.set(index, page); 138− const code = page[seq % PAGE] ?? NONE;
139− if (code === NONE) return false;
140− if (code === MIXED) return undefined;
141− return version >= code;
163+ return page[seq % PAGE] ?? NONE; Lines 383–399 at 318 (were 361–370 at 277)
361383 readonly baseVersion: number; 362384 readonly base: ReadonlySet<AtomId>; 363385 readonly current: ReadonlySet<AtomId>; 364− constructor(space: Space, baseVersion: number, base: ReadonlySet<AtomId>, current: ReadonlySet<AtomId>) {
386+ /** `endVersion`: the version `current` is (the newest by default; an earlier one for owed news, news.ts). */ 389+ baseVersion: number, 390+ base: ReadonlySet<AtomId>, 391+ current: ReadonlySet<AtomId>, 392+ endVersion = last(space), 366395 if (space.name !== SHARED || !space.membershipVersion) throw Error("shared additions require indexed shared space"); 367− this.endVersion = last(space);
396+ this.endVersion = endVersion; 368397 this.space = space; 369398 this.baseVersion = baseVersion; Lines 403–412 at 318 (were 374–382 at 277)
374403 return this.current.has(id) && !this.base.has(id); 376405 *values(): SetIterator<AtomId> { 406+ const versionOf = this.space.membershipVersions?.() ?? this.space.membershipVersion!; 377407 for (let version = this.baseVersion + 1; version <= this.endVersion; version++) { 378408 for (const id of this.space.versions[version]!.atoms) { 379− if (this.space.membershipVersion!(id, this.endVersion) === version && this.has(id)) yield id;
409+ if (versionOf(id, this.endVersion) === version && this.has(id)) yield id; Lines 16–25 at 318 (were 16–22 at 277)
1717export function clashIn(view: ReadView, touched: Iterable<string>, now: ReadView): string | undefined { 1818 const byKey = new Map<string, string[]>(); 19− for (const p of view.knownPaths()) {
19+ // Every path the graph has ever had, sorted, not the view's known paths (abso Capacity, prod abso 2026-10-15): those 20+ // read every atom's file list, over half of a publish on abso. Each use below keeps only paths the view has a file 21+ // at, and a path the view never had has none, so the answers are the same. 22+ for (const p of [...view.graph.knownFiles()].sort()) { 2023 const k = pathKey(p); 2124 const list = byKey.get(k); 2225 if (list) list.push(p); Lines 73–81 at 318 (were 70–76 at 277)
7073export function spellingOf(view: ReadView, path: string): string { 7174 if (view.hasFile(path)) return path; 7275 const key = pathKey(path); 73− // Known paths first, by key, then only those laid out (#46).
74− const twins = view.knownPaths().filter((p) => pathKey(p) === key && view.hasFile(p));
76+ // Every path the graph has ever had, by key, then only those the view has a file at (#46). Not the view's known paths 77+ // (abso Capacity, 714): those read every atom's membership and file list, 36,360 statements of a record on abso, as 78+ // clashIn found. A path the view never had has no file in it, so the answers are the same. 79+ const twins = [...view.graph.knownFiles()].filter((p) => pathKey(p) === key && view.hasFile(p)); 7580 return twins.length === 1 ? twins[0]! : path; new file, 55 lines
1+// Moves before laying out files (abso 714, piece 3): expressMoves looks at the draft's own written and deleted lines 2+// first, and lays out no file when none of its written lines with real content has a deleted line's text. moves.test.ts 3+// covers the moves themselves. 5+import assert from "node:assert/strict"; 6+import { test } from "node:test"; 7+import type { Graph } from "../../../src/engine/index.ts"; 8+import { type ExpressMovesHost, expressMoves } from "../express-moves.ts"; 9+import type { AgentState } from "../project-types.ts"; 11+/** A draft of two atoms: "del" deletes one line, "add" writes the others. Any view laid out throws. */ 12+function host(deleted: string, written: string[]): ExpressMovesHost { 13+ const texts = [deleted, ...written]; 15+ deletedLines: (id: string) => (id === "del" ? ["line-0"] : []), 16+ *eachInsertedLine(id: string) { 17+ if (id === "add") for (let k = 1; k < texts.length; k++) yield `line-${k}`; 19+ lineN: (line: string) => Number(line.slice("line-".length)), 20+ *textChunks(n: number) { 23+ textOf: (n: number) => texts[n]!, 24+ } as unknown as Graph; 25+ const laidOut = (): never => { 26+ throw new Error("laid out"); 30+ draft: () => ["del", "add"], 32+ beforeDraft: laidOut, 40+const agent = { name: "ann" } as AgentState; 42+test("an edit that only changes lines lays out no file", () => { 43+ expressMoves(host(" return pi * r * r;", [" return Math.PI * r * r;"]), agent, 1, []); 46+test("a deleted text written again with only brackets or blanks in common lays out no file", () => { 47+ expressMoves(host("}", [" const tree = parse(p);", "}", ""]), agent, 1, []); 50+test("a written line with real content that the draft also deleted goes on to the files", () => { 52+ () => expressMoves(host(" return pi * r * r;", ["", " return pi * r * r;"]), agent, 1, []), new file, 49 lines
1+// fileExactAt (version-log.ts, abso Capacity, 2026-10-17): the same answer as fileAt for exactly that spelling, at 2+// every version, read from the file's own lines without the version's list of files. abso's worker/test/ 3+// project-files.test.ts checks it on the disk engine, where the list is what costs. 5+import assert from "node:assert/strict"; 6+import { test } from "node:test"; 7+import { MemoryStore, Project } from "../project.ts"; 9+/** Files added, edited, emptied, made binary and taken out, beside others, over six versions. */ 10+function history(): Project { 11+ const p = new Project(new MemoryStore(), { hasBlob: () => true }); 12+ p.init({ "README.md": "hi\n", "abso.json": '{ "check": "true" }\n', "src/a.ts": "a\n" }, 0); 13+ p.record("ann", { "abso.yml": "pipelines:\n ci:\n on: [push]\n", "docs/abso.yml": "not this one\n" }, 1); 14+ p.publish("ann", "a pipeline", 2); 15+ p.record("ann", { "abso.json": '{ "check": "false" }\n', "empty.txt": "" }, 3, {}, { "abso.yaml": "b".repeat(64) }); 16+ p.publish("ann", "a binary, and an empty file", 4); 17+ p.record("ann", { "abso.yml": null, "avcs.json": "{}\n", "src/a.ts": "" }, 5); 18+ p.publish("ann", "the pipeline gone, a file emptied", 6); 34+test("fileExactAt answers what fileAt answers for the same spelling, at every version", () => { 36+ const last = p.version; 37+ assert.ok(last >= 3); 38+ for (let v = 0; v <= last; v++) 39+ for (const path of PATHS) assert.deepEqual(p.fileExactAt(path, v), p.fileAt(path, v), `${path} at ${v}`); 42+test("a name nothing ever wrote is null, and another spelling is that spelling, not the stored one", () => { 44+ const last = p.version; 45+ assert.deepEqual(p.fileExactAt("never.txt", last), { path: "never.txt", version: last, text: null }); 46+ // fileAt reads the stored spelling for any spelling (#41); fileExactAt reads only the one asked. 47+ assert.equal((p.fileAt("ABSO.json", last) as { text: string | null }).text, '{ "check": "false" }\n'); 48+ assert.deepEqual(p.fileExactAt("ABSO.json", last), { path: "ABSO.json", version: last, text: null }); Lines 105–124 at 318 (were 105–107 at 277)
106106 assert.deepEqual(project.pathsAt(version).files, oracle.draftOf(agent)!.view.paths(), `paths at ${version}`); 109+test("an agent's files on a writer, from its base version's kept list when it has nothing of its own, as the in-memory project says", () => { 110+ // abso - Performance (abso 711): a status for an agent behind shared listed its files by laying out every known file. 111+ const oracle = new Project(new MemoryStore()); 112+ const project = writer(); 115+ // v0 and v1 are behind shared with nothing of their own, v2 is at shared, and bob, cy, dee and eve have drafts. 116+ for (const agent of ["v0", "v1", "v2", "bob", "cy", "dee", "eve"]) { 117+ assert.deepEqual(project.agentPaths(agent), oracle.agentPaths(agent), agent); 118+ assert.deepEqual(project.pathsOf(agent), oracle.pathsOf(agent), `${agent} for a reader`); 120+ assert.deepEqual(project.agentPaths("v0").files, project.pathsAt(0).files); 121+ assert.equal(project.agentPaths("v0").files.includes("src/gone.ts"), true); 122+ assert.equal(project.agentPaths("v1").files.includes("src/gone.ts"), false); 123+ assert.equal(project.agentPaths("eve").files.includes("src/draft-new.ts"), true); new file, 60 lines
1+// abso 702: a publish's news for other agents writes a line as it starts and 2+// one as it ends, through ProjectOptions.logLine, so work that outlives its 3+// request still shows in the host's logs. 5+import assert from "node:assert/strict"; 6+import { test } from "node:test"; 7+import { MemoryStore, Project } from "../project.ts"; 10+ "src/parse.ts": "export function parsePattern(text: string): string {\n return text;\n}\n", 11+ "src/match.ts": 'import { parsePattern } from "./parse.ts";\n\nexport function run(p: string) {\n return p;\n}\n', 14+function setup(lines: Record<string, string | number>[]) { 15+ const project = new Project(new MemoryStore(), { logLine: (line) => lines.push(line) }); 16+ project.init(START, 0); 18+ project.sync("user"); 22+test("a publish with another agent drafting writes a start line and an end line", () => { 23+ const lines: Record<string, string | number>[] = []; 24+ const project = setup(lines); 25+ project.edit("user", { file: "src/match.ts", old: " return p;\n", new: " return parsePattern(p);\n" }, 1); 28+ { file: "src/parse.ts", old: "parsePattern(text: string)", new: "parsePattern(text: string, flags = '')" }, 31+ assert.equal(project.publish("lib", "parsePattern takes flags", 3).ok, true); 33+ const news = lines.filter((l) => l.work === "publishNews"); 35+ news.map((l) => l.step), 38+ assert.equal(news[0]!.publisher, "lib"); 39+ assert.equal(news[1]!.drafts, 1); 40+ assert.equal(news[1]!.changedNames, 1); 41+ assert.equal(news[1]!.news, 1); 44+test("a publish with nobody else drafting writes nothing", () => { 45+ const lines: Record<string, string | number>[] = []; 46+ const project = setup(lines); 47+ project.edit("lib", { file: "src/parse.ts", old: " return text;\n", new: " return text.trim();\n" }, 1); 48+ assert.equal(project.publish("lib", "trim", 2).ok, true); 49+ assert.deepEqual(lines, []); 52+test("without a logLine option, a publish still works", () => { 53+ const project = new Project(new MemoryStore()); 54+ project.init(START, 0); 56+ project.sync("user"); 57+ project.edit("user", { file: "src/match.ts", old: " return p;\n", new: " return parsePattern(p);\n" }, 1); 58+ project.edit("lib", { file: "src/parse.ts", old: " return text;\n", new: " return text.trim();\n" }, 2); 59+ assert.equal(project.publish("lib", "trim", 3).ok, true); new file, 56 lines
1+// A host learns each write's news as the write appends it (newsWritten), and can read an agent's waiting news without 2+// taking it (peekNews), so a listener can be woken for exactly the agents that got news and caught up on connect. 4+import assert from "node:assert/strict"; 5+import { test } from "node:test"; 6+import { MemoryStore, type NewsWritten, Project } from "../project.ts"; 9+ const store = new MemoryStore(); 10+ const written: NewsWritten[][] = []; 11+ const project = new Project(store, { newsWritten: (items) => written.push([...items]) }); 12+ project.init({ "a.txt": "a\n" }, 0); 13+ for (const a of ["builder1", "builder2", "builder3"]) project.sync(a); 15+ return { project, store, written }; 18+test("a write's news is told once, per item, with its agent, text and place in the log", () => { 19+ const { project, store, written } = setup(); 20+ project.announce("builder1", "Ship it", ["builder2", "builder3"], 1); 21+ assert.equal(written.length, 1, "one call for the write"); 22+ const items = written[0]!; 24+ items.map((i) => i.agent), 25+ ["builder2", "builder3"], 27+ for (const item of items) { 28+ assert.match(item.text, /Announcement from builder1.*Ship it/); 29+ assert.equal(store.entries[item.seq]?.type, "news", "seq is the entry's place in the log"); 31+ assert.ok(items[1]!.seq > items[0]!.seq); 34+test("writes with no news, and taking news (heard), tell nothing", () => { 35+ const { project, written } = setup(); 36+ project.announce("builder1", "Ship it", ["builder2"], 1); 38+ project.news("builder2"); 39+ project.sync("builder3"); 40+ assert.deepEqual(written, []); 43+test("peekNews reads waiting news and takes nothing; hasAgent reads only", () => { 44+ const { project, store } = setup(); 45+ project.announce("builder1", "Ship it", ["builder2"], 1); 46+ const length = store.entries.length; 47+ const peeked = project.peekNews("builder2"); 48+ assert.equal(peeked.length, 1); 49+ assert.match(peeked[0]!.text, /Ship it/); 50+ assert.deepEqual(project.peekNews("builder2"), peeked, "still there"); 51+ assert.deepEqual(project.peekNews("nobody"), [], "no agent: none, and none made"); 52+ assert.equal(project.hasAgent("builder2"), true); 53+ assert.equal(project.hasAgent("nobody"), false); 54+ assert.equal(store.entries.length, length, "nothing written"); 55+ assert.equal(project.news("builder2").news.length, 1, "the take still finds it"); new file, 190 lines
1+// Owed news (abso Capacity, 2026-10-15): with owesDefinitionNews set (abso's disk route sets it), a publish leaves its 2+// definition news for other agents for after its write. The same news, against the publish's version; told once; and 3+// the publisher's own answer as before. abso's worker/test/owed-news.test.ts covers the disk route's marker and alarm. 5+import assert from "node:assert/strict"; 6+import { test } from "node:test"; 7+import { MemoryStore, Project } from "../project.ts"; 9+// abso-core's changed-definition.test.ts scenario: parse.ts defines parsePattern, match.ts imports it. 12+ "export function parsePattern(text: string): Node {", 13+ ' return { kind: "lit", text };', 16+ "export interface Node {", 22+ 'import { parsePattern } from "./parse.ts";', 24+ "export function run(p: string) {", 28+ "README.md": "Uses parsePattern.\n", 31+/** bob's draft calls parsePattern; ann's draft changes its signature; cat's touches something else. Nothing published. */ 32+function drafts(project: Project): void { 33+ project.init(START, 0); 39+ { file: "src/match.ts", old: " return p;\n", new: " const tree = parsePattern(p);\n return tree;\n" }, 45+ file: "src/parse.ts", 46+ old: "parsePattern(text: string): Node", 47+ new: "parsePattern(text: string, flags: string): Node", 51+ project.edit("cat", { file: "README.md", old: "Uses parsePattern.", new: "Uses parsePattern, twice." }, 3); 54+const definitionNews = (news: readonly string[]) => news.filter((n) => /definition of parsePattern/.test(n)).sort(); 56+test("the news owed is the news a publish would have told, and the publisher's own answer is the same", () => { 57+ const told = new Project(new MemoryStore()); 59+ const toldAnswer = told.publish("ann", "parsePattern takes flags", 4); 60+ const expected = definitionNews(told.news("bob").news); 61+ assert.equal(expected.length, 1, "the scenario has a definition collision"); 63+ const owing = new Project(new MemoryStore()); 64+ owing.owesDefinitionNews = true; 66+ assert.deepEqual(owing.publish("ann", "parsePattern takes flags", 4), toldAnswer, "the publisher's answer"); 67+ const owed = owing.takeOwedDefinitionNews(); 68+ assert.deepEqual(owed, [{ version: owing.version, space: owed[0]!.space, publisher: "ann", all: true }]); 69+ assert.deepEqual(owing.takeOwedDefinitionNews(), [], "handed over once"); 70+ // Not told yet: bob's news holds no definition news until it's delivered. 71+ assert.deepEqual(definitionNews(owing.news("bob").news), []); 72+ const found = owing.definitionNewsOwed(owed[0]!); 74+ found.map((f) => f.agent), 77+ assert.ok(owing.deliverOwedNews(found) > 0); 78+ assert.deepEqual(definitionNews(owing.news("bob").news), expected); 79+ // Told twice adds nothing, and a run of the read after delivery finds nothing left. 80+ assert.equal(owing.deliverOwedNews(found), 0); 81+ assert.deepEqual(owing.definitionNewsOwed(owed[0]!), []); 84+test("worked out against the publish's version, though more was published before the news went out", () => { 85+ const told = new Project(new MemoryStore()); 87+ told.publish("ann", "parsePattern takes flags", 4); 88+ const expected = definitionNews(told.news("bob").news); 90+ const owing = new Project(new MemoryStore()); 91+ owing.owesDefinitionNews = true; 93+ owing.publish("ann", "parsePattern takes flags", 4); 94+ const [first] = owing.takeOwedDefinitionNews(); 95+ // Then parsePattern is removed, before the first publish's news is out: against the newest version the news 96+ // would say "removes"; against the first publish's, it says "changes", as told at publish time. 101+ file: "src/parse.ts", 102+ old: 'export function parsePattern(text: string, flags: string): Node {\n return { kind: "lit", text };\n}\n', 107+ owing.publish("ann", "parsePattern goes", 6); 108+ assert.ok(owing.deliverOwedNews(owing.definitionNewsOwed(first!)) > 0); 109+ assert.deepEqual(definitionNews(owing.news("bob").news), expected, "the first publish's news, as it was"); 112+test("an agent that synced past the version since isn't told it", () => { 113+ const owing = new Project(new MemoryStore()); 114+ owing.owesDefinitionNews = true; 116+ owing.publish("ann", "parsePattern takes flags", 4); 117+ const [owed] = owing.takeOwedDefinitionNews(); 119+ assert.deepEqual(owing.definitionNewsOwed(owed!), []); 122+test("the replay engine tells it at publish time, as before", () => { 123+ const told = new Project(new MemoryStore()); 125+ told.publish("ann", "parsePattern takes flags", 4); 126+ assert.deepEqual(told.takeOwedDefinitionNews(), []); 127+ assert.equal(definitionNews(told.news("bob").news).length, 1); 130+test("owedAgents lists who may be owed, and the news one agent at a time adds up to the whole (abso 714)", () => { 131+ const owing = new Project(new MemoryStore()); 132+ owing.owesDefinitionNews = true; 134+ owing.publish("ann", "parsePattern takes flags", 4); 135+ const [owed] = owing.takeOwedDefinitionNews(); 136+ assert.deepEqual(owing.owedAgents(owed!), ["bob", "cat"], "every other agent behind it with a draft"); 137+ const whole = owing.definitionNewsOwed(owed!); 138+ assert.equal(whole.length, 1); 140+ owing.owedAgents(owed!).flatMap((agent) => owing.definitionNewsOwed(owed!, [agent])), 144+ assert.deepEqual(owing.owedAgents(owed!), ["cat"], "synced past it"); 147+test("everything a publish tells other agents is owed and told after it, the same news (abso 714)", () => { 148+ // bob's draft calls parsePattern (definition news), dee's changes the line ann's publish changes (same-lines news), 149+ // and cat's touches nothing of it (no news). 150+ const scenario = (project: Project) => { 152+ project.sync("dee"); 155+ { file: "src/parse.ts", old: "parsePattern(text: string): Node", new: "parsePattern(input: string): Node" }, 159+ const told = new Project(new MemoryStore()); 161+ const toldAnswer = told.publish("ann", "parsePattern takes flags", 6); 162+ const expected = Object.fromEntries(["bob", "cat", "dee"].map((a) => [a, told.news(a).news.toSorted()])); 163+ assert.ok(expected.bob!.length > 0 && expected.dee!.length > 0, "the scenario has both kinds of news"); 165+ const owing = new Project(new MemoryStore()); 166+ owing.owesDefinitionNews = true; 168+ assert.deepEqual(owing.publish("ann", "parsePattern takes flags", 6), toldAnswer, "the publisher's answer"); 169+ const [owed] = owing.takeOwedDefinitionNews(); 170+ assert.equal(owed!.all, true); 171+ for (const a of ["bob", "cat", "dee"]) 172+ assert.deepEqual(owing.news(a).news, [], `${a} is told nothing in the publish`); 173+ const names = owing.owedNewsNames(owed!); 174+ assert.deepEqual(names, ["parsePattern"]); 175+ // One agent at a time, as the host works it out. 176+ for (const agent of owing.owedAgents(owed!)) owing.deliverOwedNews(owing.newsOwed({ ...owed!, names }, [agent])); 177+ for (const a of ["bob", "cat", "dee"]) assert.deepEqual(owing.news(a).news.toSorted(), expected[a], a); 178+ // Twice tells nothing more. 179+ assert.deepEqual(owing.newsOwed({ ...owed!, names }), []); 182+test("a publish that no other draft can collide with owes nothing", () => { 183+ const owing = new Project(new MemoryStore()); 184+ owing.owesDefinitionNews = true; 185+ owing.init({ "a.txt": "one\n" }, 0); 187+ owing.edit("ann", { file: "a.txt", old: "one", new: "two" }, 1); 188+ owing.publish("ann", "alone", 2); 189+ assert.deepEqual(owing.takeOwedDefinitionNews(), []); Lines 36–87 at 318 (were 36–38 at 277)
40+test("shared additions read each atom's version from the membership pages, and answer as its events do (abso - Performance, 714)", (t) => { 41+ const storage = new SqlState(); 43+ const membership = new Membership(storage), 44+ space = membership.shared; 45+ const ids = (from: number, to: number) => Array.from({ length: to - from }, (_, i) => `a${from + i}`); 46+ const add = (atoms: string[], dropped: string[] = []) => 47+ addVersion(space, { version: space.versions.length, agent: "test", message: "version", time: 0, atoms, dropped }); 48+ // Three pages of atoms; a5 and a400 dropped and a5 back, a601 added and dropped: their events are read. 51+ add([], ["a5", "a400"]); 55+ const last = space.versions.length - 1; 56+ const { membershipVersions: _pages, ...eventsOnly } = space; 57+ const read = storage.read.bind(storage); 59+ t.mock.method(storage, "read", (collection: string, key: string) => { 60+ if (collection.startsWith('membership:"":events:')) eventReads++; 61+ return read(collection, key); 63+ const walk = (s: typeof space) => { 65+ const out: string[][] = []; 66+ for (let from = 0; from < last; from++) 67+ for (let to = from + 1; to <= last; to++) 68+ out.push([...new SharedAdditions(s, from, membership.at(s, from), membership.at(s, to), to)]); 69+ return { out, eventReads }; 71+ const paged = walk(space); 72+ const events = walk(eventsOnly); 73+ assert.deepEqual(paged.out, events.out); 75+ paged.eventReads < events.eventReads / 10, 76+ `${paged.eventReads} event reads against ${events.eventReads}`, 78+ assert.deepEqual([...new SharedAdditions(space, 1, membership.at(space, 1), membership.at(space, 3), 3)], ["a600"]); 80+ [...new SharedAdditions(space, 2, membership.at(space, 2), membership.at(space, 3), 3)], 83+ assert.deepEqual([...new SharedAdditions(space, 3, membership.at(space, 3), membership.at(space, 5), 5)], []); Lines 244–278 at 318 (were 244–249 at 277)
248+ * fileAt for exactly this spelling, from the file's own lines (abso Capacity, 2026-10-17): no spelling lookup and no 249+ * list of the version's files. fileAt's hasFile answers from the version's whole path list, folded from version 0 250+ * when nothing's kept, and a spelling it doesn't find reads every known path. A name nothing ever wrote is one read. 251+ * The pipeline's project files (abso.yml and the like) are read this way on every tick. 253+export function fileExactAt( 257+ options: { draft?: string | null; agent?: string } = {}, 258+): { path: string; version: number; text: string | null; blob?: string } { 260+ checkReadPath(path); 261+ const space = host.spaceFor(options); 262+ host.checkVersion(space, version); 263+ if (!host.graph.hasAtomsIn(path)) return { path, version, text: null }; 264+ const view = host.viewAt(space, version); 265+ const attrs = view.attrs(path); 266+ // hasFile's own test, without its path list: kept while empty, a link, a binary, or a visible line. 267+ const exists = attrs.exists || attrs.link !== null || attrs.blob !== null || view.lines(path).length > 0; 271+ text: exists ? view.text(path) : null, 272+ ...(attrs.blob !== null ? { blob: attrs.blob } : {}), 247276/** The files that may differ between two versions, and both views: compare's and compareSummary's ground. */