Skip to content

abso-core

Public

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

Check passed

Versions 280 to 318

Compare

+1669 −112 in 97 places
Lines 3–35 at 318 (were 3–17 at 280)
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.
55
6+import { readFileSync } from "node:fs";
67import * as nodeModule from "node:module";
8+import { dirname, join } from "node:path";
79
10+const argv = process.argv.slice(2);
12+/**
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.
15+ */
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"]) {
20+ try {
21+ return /"server"\s*:\s*"local"/.test(readFileSync(join(dir, state, "config.json"), "utf8"));
22+ } catch {}
23+ }
24+ if (dirname(dir) === dir) return false;
25+ }
26+}
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?.();
1232
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 280)
33
44import type { On } from "claude-code";
55import { expect, mock, test } from "claude-code/testing";
6+import { HOOK_COMMAND } from "./stamp.ts";
67
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 280)
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}` };
2728 });
Lines 115–152 at 318 (were 114–116 at 280)
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([]);
116117});
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;
130+ });
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");
141+ return;
142+ }
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]);
152+});
Lines 33–39 at 318 (were 33–39 at 280)
3333 uncomposedText,
3434 type Who,
3535} from "../src/core.ts";
36−import { STAMP } from "./stamp.ts";
36+import { HOOK_COMMAND, STAMP } from "./stamp.ts";
3737
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 280)
182182 for (let job = jobs.shift(); job !== undefined; job = jobs.shift()) await run($, job);
183183}
184184
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;
189196 try {
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 280)
211220 job.root,
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}`,
213222 );
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");
219228 try {
220229 await $.session.append({
221230 message: { type: "user", content: [{ type: "text", text: context }] },
Lines 237–279 at 318 (were 228–233 at 280)
228237 }
229238}
230239
240+/**
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.
243+ */
244+async function handToClient($: Engine, job: Job): Promise<{ outcome: string; context?: string }> {
245+ if (HOOK_COMMAND === undefined || HOOK_COMMAND.length === 0)
246+ return {
247+ outcome:
248+ "skipped: a local project, and this mod has no abso to hand it to (install-mod.ts adds one); abso record sends it",
249+ };
250+ const hookInput = {
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 } : {}),
256+ };
257+ const ran = await $.process.run(HOOK_COMMAND, {
258+ cwd: job.root,
259+ env: { ABSO_HOOK_FORCE: "1" },
260+ stdin: JSON.stringify(hookInput),
261+ timeoutMs: LOCAL_HOOK_MS,
262+ });
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();
266+ const context =
267+ out === ""
268+ ? undefined
269+ : (JSON.parse(out) as { hookSpecificOutput?: { additionalContext?: unknown } }).hookSpecificOutput
270+ ?.additionalContext;
271+ return {
272+ outcome: "handed to abso hook (a local project; its own line is just above)",
273+ ...(typeof context === "string" ? { context } : {}),
274+ };
275+}
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> {
233279 try {
Lines 288–294 at 318 (were 242–247 at 280)
242288 project: string;
243289 agent: string;
244290 };
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 280)
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;
6+
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 280)
107107 try {
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 280)
2020 SyncAnswer,
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";
2425import {
2526 boxQuery,
Lines 69–75 at 318 (were 68–73 at 280)
6869 IssueRow,
6970 IssueSearchHit,
7071} from "./issues-wire.ts";
72+import { isLocal, LOCAL_BASE, localFetch, NO_STORE } from "./local-store.ts";
7173import type { Modes } from "./modes.ts";
7274
7375export * from "./api-answers.ts";
Lines 193–205 at 318 (were 191–199 at 280)
191193 caller: string | undefined;
192194
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}`;
195198 }
196199
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}`;
199205 }
Lines 220–231 at 318 (were 214–219 at 280)
214220 * and follows no redirect, so nothing it sends goes anywhere it didn't name (headers() adds no sign-in).
215221 */
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);
228+ }
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 280)
248260 signal: AbortSignal.timeout(timeoutMs),
249261 });
250262 } catch (err) {
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;
252266 const why =
253267 e.name === "TimeoutError"
Lines 1017–1023 at 318 (were 1003–1009 at 280)
10031017 }
10041018
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"), {});
10081022 }
10091023
Lines 2–8 at 318 (were 2–8 at 280)
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.
77
88import { readFileSync } from "node:fs";
Lines 12–18 at 318 (were 12–18 at 280)
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"]);
1616
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 280)
7575 }
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 280)
8080 return lines;
8181}
8282
83+/** A stored pipeline run as runRuns lists it: what the CI lines need of it. */
84+interface StoredRun {
85+ readonly id: number;
86+ readonly version: number;
87+ readonly state: string;
88+ readonly file: string;
89+}
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 [];
95+ return runs.filter(
96+ (r): r is StoredRun =>
97+ typeof r === "object" &&
98+ r !== null &&
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",
103+ );
104+}
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.`;
110+}
112+/**
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).
115+ */
116+export function builtInHasNothing(ci: CiStatus): boolean {
117+ return ci.red === null && ci.skipped?.reason.startsWith("nothing to run") === true;
118+}
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 {
85122 switch (mark) {
Lines 180–199 at 318 (were 143–153 at 280)
143180 }
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 } };
148188 }
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];
191+ const lines =
192+ newest === undefined
193+ ? ciText(ci, status.version)
194+ : builtInHasNothing(ci)
195+ ? [runLine(newest)]
196+ : [...ciText(ci, status.version), runLine(newest)];
151197 return {
152198 text: [
153199 `shared is at version ${status.version}.`,
Lines 1–6 at 318 (were 1–5 at 280)
11// What every abso command shares: its output, its environment, the folder it opens, and the news it took.
22
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 280)
4849 );
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 };
5354}
5455
5556/**
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.
59+ */
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.
63+ const folder =
64+ root
65+ .split(/[\\/]+/)
66+ .filter((p) => p !== "")
67+ .at(-1) ?? "";
68+ return callerHeader({ session: hashed, machine, folder });
69+}
71+/**
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 11–17 at 318 (were 11–16 at 280)
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";
1516
1617/** What .avcs/config.json holds. */
Lines 28–41 at 318 (were 27–36 at 280)
2728 * routes anyone can read and sends no credential. It has no agent; its config holds server, project and this.
2829 */
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;
3033}
3134
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;
3439}
3540
3641export function configPath(root: string): string {
Lines 69–83 at 318 (were 64–74 at 280)
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}"`);
6671 }
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);
6875 return {
6976 server: raw.server!,
7077 project: raw.project!,
7178 agent: raw.agent!,
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 280)
275284
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 } : {}) };
290+ : {
291+ server,
292+ project,
293+ agent,
294+ ...(follow ? { follow } : {}),
295+ ...(reader ? { reader: true } : {}),
296+ ...(store ? { store } : {}),
297+ };
282298 writeFileSync(configPath(root), `${JSON.stringify(written, null, 2)}\n`);
283299 excludeFromGit(root);
284300}
Lines 327–339 at 318 (were 327–339 at 280)
327327
328328/**
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.
331331 */
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 ");
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).
5+
6+export class DurableObject<Env = unknown> {
7+ ctx: unknown;
8+ env: Env;
9+ constructor(ctx: unknown, env: Env) {
10+ this.ctx = ctx;
11+ this.env = env;
12+ }
13+}
Lines 94–101 at 318 (were 94–99 at 280)
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[];
9799}
98100
99101const RECORD = ".avcs-install.json";
Lines 134–148 at 318 (were 132–137 at 280)
132134 existsSync(at(skillsFolder(AVCS_MOD.name, env), MANIFEST)) ||
133135 existsSync(at(skillsFolder(OLD_MOD_NAMES[AVCS_MOD.name]!, env), MANIFEST));
134136
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 {
139+ try {
140+ return /HOOK_COMMAND[^=\n]*=\s*\[/.test(readFileSync(at(skillsFolder(AVCS_MOD.name, env), STAMP_FILE), "utf8"));
141+ } catch {
142+ return false;
143+ }
144+}
135146/**
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 280)
226237 return commit;
227238}
228239
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 280)
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);
256+ data = Buffer.from(
257+ stamped.replace(/(HOOK_COMMAND[^=\n]*=\s*)undefined/, (_, head: string) => head + JSON.stringify(hook)),
258+ );
243259 }
244260 out.set(rel, data);
245261 }
Lines 402–408 at 318 (were 386–392 at 280)
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 });
392408 try {
Lines 533–550 at 318 (were 517–523 at 280)
517533 readonly current: string;
518534}
519535
520−/** `avcs --version`: this client, and the mods installed on this machine, compared with this client's. */
536+/**
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.
539+ */
540+export function installerCommand(installer: string): string {
541+ const command = `node ${join(CLIENT_DIR, installer)}`;
542+ return (process.features as { typescript?: unknown }).typescript
543+ ? command
544+ : `${command} (with Node 22.18 or later, which runs .ts files; this is Node ${process.versions.node})`;
545+}
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>>): {
522549 text: string;
523550 json: Record<string, unknown>;
Lines 581–594 at 318 (were 554–567 at 280)
554581 mods.push(m);
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)})`}`);
558585 continue;
559586 }
560587 const when = m.at ? `, installed ${m.at.slice(0, 16).replace("T", " ")} UTC` : "";
561588 const behind =
562589 builtCopy() || m.version === m.current
563590 ? ""
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}`);
566593 }
567594 return { text: lines.join("\n"), json: { client, folder: CLIENT_DIR, mods } };
Lines 606–611 at 318 (were 579–584 at 280)
579606 .filter((m) => m.version?.includes("+") && /\+[0-9a-f]{7}$/.test(m.current) && m.version !== m.current)
580607 .map(
581608 (m) =>
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).`,
583610 );
584611}
Lines 28–34 at 318 (were 28–33 at 280)
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";
3334
Lines 37–47 at 318 (were 36–41 at 280)
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 };
44+ }
3945 // An explicit --server goes to that server's own Issues Worker: ABSO_ISSUES_SERVER doesn't redirect it.
4046 const server =
4147 (env.server === undefined ? fromEnv(env.env, "ISSUES_SERVER") : undefined) ||
Lines 2–9 at 318 (were 2–9 at 280)
22
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";
99import {
Lines 16–24 at 318 (were 16–24 at 280)
1616 readBox,
1717} from "./box.ts";
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";
2222import {
2323 findRoot,
2424 installKey,
Lines 32–39 at 318 (were 32–38 at 280)
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 280)
101102 return undefined;
102103}
103104
105+/**
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.
108+ */
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");
114+ return undefined;
115+ }
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`,
121+ );
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 } };
125+}
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`);
138+ }
139+ return rel;
140+}
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.`}`;
145+}
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.";
106149
Lines 154–214 at 318 (were 111–152 at 280)
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)})`,
161+ );
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}.
123172`);
124173 return initFromBox(args, env, root, project, server, box);
125174 }
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}`,
129178 );
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}`}.
194+ if (!local)
195+ say(`Signing in with ${credential?.words ?? `no credential: nothing here signs in to ${server}`}.
142196`);
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"]>>;
199+ try {
200+ await uploadBlobs(api, blobs);
201+ answer = await api.init(
202+ Object.fromEntries(files),
203+ modes,
204+ Object.fromEntries([...blobs].map(([rel, b]) => [rel, b.sha])),
205+ );
206+ } catch (error) {
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 });
210+ throw error;
211+ }
150212 writeConfig(root, config);
151213 clearKnown(root);
152214 for (const [rel, text] of files) writeKnown(root, rel, text);
Lines 224–237 at 318 (were 162–173 at 280)
162224 ...(wroteIgnore
163225 ? ["Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore."]
164226 : []),
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),
171235 ].join("\n"),
172236 json: {
173237 project,
Lines 242–248 at 318 (were 178–183 at 280)
178242 wroteAbsoignore: wroteIgnore,
179243 wroteProjectFile: typeof wroteProject === "string" ? null : wroteProject,
180244 leftOut,
245+ ...(local ? { store: local.dir } : {}),
181246 },
182247 };
183248}
Lines 416–431 at 318 (were 351–356 at 280)
351416 };
352417}
353418
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 });
424+ return;
425+ }
426+ for (const entry of readdirSync(dir)) if (entry !== "key") rmSync(join(dir, entry), { recursive: true, force: true });
427+}
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 280)
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);
374452 minted =
375453 box && !hasKey && !fromEnv(env.env, "KEY_FILE") && !tokenFileAsked
Lines 472–511 at 318 (were 394–423 at 280)
394472 agent = free.agent;
395473 minted = { key: free.key, id: free.id };
396474 }
397− const config = { server, project, agent, ...(reader ? { reader: true } : {}) };
475+ const config = { server, project, agent, ...(reader ? { reader: true } : {}), ...local?.settings };
398476 writeConfig(root, config);
399477 clearKnown(root);
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>;
481+ try {
482+ read = readConfig(root, env.env, false);
483+ } catch (error) {
484+ takeBackJoin(root);
485+ throw error;
486+ }
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}`)}.
488+ if (!local)
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}`)}.
406491`,
407− );
492+ );
408493 const api = new Api(settings);
409− let synced: Awaited<ReturnType<typeof syncFolder>>;
494+ let answer: SyncAnswer;
410495 try {
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);
415500 } catch (error) {
501+ // Nothing is written yet: take back what join wrote so it can run again here.
502+ takeBackJoin(root);
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);
420506 }
507+ const synced = await applyAnswer(root, api, answer);
508+ pullWritten(root);
421509 return {
422510 text: [
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 280)
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.`,
428516 ]
429517 : []),
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}`]),
434523 ].join("\n"),
435524 json: {
Lines 542–559 at 318 (were 453–460 at 280)
453542 : [`Nothing is installed yet. Before building or testing here, run ${projectFileName(root)}'s setup: ${setup}`];
454543}
455544
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.
547+ if (local) {
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.";
553+ }
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.`;
460559}
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.
4+
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.
5+
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>>;
24+/**
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.
28+ */
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);
33+ const data =
34+ process.platform === "win32"
35+ ? env.LOCALAPPDATA
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");
40+ try {
41+ const home = homedir();
42+ return home ? join(home, ".local", "share", "abso", "store") : undefined;
43+ } catch {
44+ return undefined;
45+ }
46+}
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 -----------------------------------------------
53+interface Db {
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[];
60+ };
61+ close(): void;
62+}
64+/** A Durable Object's storage: SQL, synchronous transactions, the key-value calls and the alarm, on one database. */
65+function storageOver(db: Db) {
66+ db.exec(
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)",
68+ );
69+ const statements = new Map<string, ReturnType<Db["prepare"]>>();
70+ const prepared = (query: string) => {
71+ let s = statements.get(query);
72+ if (!s) {
73+ s = db.prepare(query);
74+ statements.set(query, s);
75+ }
76+ return s;
77+ };
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);
81+ let depth = 0;
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;
85+ };
86+ const kvPut = (key: string, value: unknown) =>
87+ prepared(
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;
92+ const storage = {
93+ sql: {
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), []);
98+ return {
99+ toArray: () =>
100+ (rows as Record<string, unknown>[]).map((r) =>
101+ Object.fromEntries(Object.entries(r).map(([k, v]) => [k, out(v)])),
102+ ),
103+ };
104+ },
105+ },
106+ transactionSync<T>(fn: () => T): T {
107+ const name = `local_t${depth++}`;
108+ db.exec(`SAVEPOINT ${name}`);
109+ try {
110+ const value = fn();
111+ db.exec(`RELEASE ${name}`);
112+ return value;
113+ } catch (e) {
114+ db.exec(`ROLLBACK TO ${name}; RELEASE ${name}`);
115+ throw e;
116+ } finally {
117+ depth--;
118+ }
119+ },
120+ async transaction<T>(fn: (txn: unknown) => Promise<T>): Promise<T> {
121+ return fn(storage);
122+ },
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])));
126+ },
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);
130+ },
131+ async delete(key: string | string[]) {
132+ if (typeof key === "string") return kvDelete(key);
133+ return key.filter(kvDelete).length;
134+ },
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 }[];
139+ return new Map(
140+ rows.filter((r) => r.key.startsWith(options.prefix ?? "")).map((r) => [r.key, deserialize(r.value)]),
141+ );
142+ },
143+ // The alarm is kept, but nothing in a local project needs it: it pushes out to Artifacts, which is off here.
144+ async getAlarm() {
145+ const row = prepared("SELECT at FROM _local_alarm WHERE id = 0").get() as { at: number | null } | undefined;
146+ return row?.at ?? null;
147+ },
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(
150+ Number(at),
151+ );
152+ },
153+ async deleteAlarm() {
154+ prepared("DELETE FROM _local_alarm WHERE id = 0").run();
155+ },
156+ };
157+ return storage;
158+}
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) => {
172+ done = ok;
173+ });
174+ super({
175+ write: (chunk) => void hash.update(chunk),
176+ close: () => {
177+ const b = hash.digest();
178+ done(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer);
179+ },
180+ });
181+ this.digest = digest;
182+ }
183+ }
184+ c.DigestStream = DigestStream;
185+}
187+// --- Loading the server's code ------------------------------------------------------------------------------------
189+type Server = {
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>;
195+};
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;
209+}
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"] };
217+ try {
218+ sqlite = (await import("node:sqlite")) as unknown as typeof sqlite;
219+ } catch {
220+ throw new LocalError(NODE_TOO_OLD);
221+ }
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;
228+ };
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);
235+ },
236+ });
237+ let loaded: typeof import("./local-server.mjs");
238+ try {
239+ loaded = await import("./local-server.mjs");
240+ } catch (e) {
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)}`,
244+ );
245+ }
246+ return {
247+ DatabaseSync: sqlite.DatabaseSync,
248+ handle: loaded.handle,
249+ ProjectObject: loaded.ProjectObject,
250+ IssueProject: loaded.IssueProject,
251+ issuesFetch: loaded.issuesFetch,
252+ };
253+ })();
254+ return server;
255+}
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 -----------------------------------------------------------------------------------------
262+interface Open {
263+ db: Db;
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;
272+}
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) {
280+ try {
281+ db.close();
282+ } catch {}
283+ }
284+ opened.clear();
285+}
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 });
293+/**
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.
296+ */
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);
308+ opened.add(db);
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);
312+ return project;
313+ };
314+ const env = (name: string) => ({
315+ ABSO_TOKEN: LOCAL_TOKEN,
316+ ABSO_ARTIFACTS: "off",
317+ ABSO_DISK_FIRST: "off",
318+ PROJECT: {
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: () => {} },
325+ env(name),
326+ );
327+ return p.object;
328+ },
329+ },
330+ ISSUES_DO: {
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"));
337+ opened.add(db);
338+ db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 120000; PRAGMA synchronous = NORMAL");
339+ p.issues = { db, storage: storageOver(db) };
340+ }
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 },
344+ env(name),
345+ );
346+ return p.issueObject;
347+ },
348+ },
349+ });
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),
357+ );
358+ last = next.catch(() => {});
359+ return next;
360+ };
362+ async function call(input: string, init: RequestInit = {}): Promise<Response> {
363+ const s = await loadServer();
364+ opening = s;
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;
380+ try {
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(
384+ request,
385+ env(name),
386+ { waitUntil: (w: Promise<unknown>) => waits.push(w) },
387+ s.issuesFetch,
388+ );
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 });
395+ } catch (e) {
396+ try {
397+ p.db.exec("ROLLBACK");
398+ } catch {}
399+ // What the object held in memory may be from the rolled-back call.
400+ p.object = undefined;
401+ p.seen = 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) });
405+ }
406+ }
407+}
Lines 1–8 at 318 (were 1–8 at 280)
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.
33
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 280)
3838 runSync,
3939 takeNews,
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 280)
5959 runWaiting,
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 280)
7374 serverUse,
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";
8083
8184interface CommandDef {
8285 readonly flags: FlagSpec;
Lines 123–135 at 318 (were 120–130 at 280)
120123 public: "boolean",
121124 private: "boolean",
122125 "token-file": "boolean",
126+ local: "boolean",
127+ store: "string",
123128 },
124129 usage:
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]",
126131 about:
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),
129134 },
130135 key: {
Lines 145–151 at 318 (were 140–146 at 280)
140145 usage:
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>]",
142147 about:
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 280)
208213 projects: "string",
209214 role: "string",
210215 days: "string",
216+ web: "boolean",
217+ site: "string",
218+ "pat-file": "string",
211219 },
212220 usage:
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>]]",
214222 about:
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({
229+ server,
230+ site: str(args, "site"),
231+ kind: patFile === undefined ? "box" : "pat",
232+ credential: () => {
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;
238+ },
239+ });
240+ return { text: handoffText(handoff, site, patFile === undefined), json: { ...handoff } };
241+ }
218242 const open =
219243 bool(args, "no-browser") || browserSkip(env.env, process.platform) !== null
220244 ? undefined
Lines 350–368 at 318 (were 326–335 at 280)
326350 },
327351 },
328352 join: {
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]",
353+ flags: {
354+ server: "string",
355+ agent: "string",
356+ dir: "string",
357+ reader: "boolean",
358+ "token-file": "boolean",
359+ local: "boolean",
360+ store: "string",
361+ },
362+ usage:
363+ "abso join <project> [--agent <name>] [--dir <folder>] [--reader] [--token-file] | abso join <project> --local [--agent <name>] [--store <folder>] [--dir <folder>]",
331364 about:
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.",
333366 run: runJoin,
334367 },
335368 record: {
Lines 385–391 at 318 (were 352–358 at 280)
352385 },
353386 usage: 'abso push -m "<why>" [--as-is] [--check ["<command>"]] [--wait <seconds> | --no-wait] [--done]',
354387 about:
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.',
356389 run: runPublish,
357390 },
358391 bisect: {
Lines 433–439 at 318 (were 400–406 at 280)
400433 usage:
401434 'abso run [--detach] [--replace] [--fresh] [--box <name>] [--at <version> [--files <glob>]] <command...> | abso run ... -- <program> <arg...> | abso run --parallel "<command>" "<command>"...',
402435 about:
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.",
404437 rest: true,
405438 run: runRun,
406439 },
Lines 648–654 at 318 (were 615–621 at 280)
615648 flags: { version: "string", revoke: "boolean" },
616649 usage: "abso ci [<version>] | abso ci --revoke",
617650 about:
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.",
619652 run: runCi,
620653 },
621654 shot: {
Lines 674–680 at 318 (were 641–647 at 280)
641674 usage:
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>]',
643676 about:
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.",
645678 run: runShot,
646679 },
647680 prep: {
Lines 890–896 at 318 (were 857–863 at 280)
857890 usage:
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>]",
859892 about:
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 280)
962995}
963996
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 {
966999 try {
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;
9711006 } catch {
972− return false;
1007+ return undefined;
9731008 }
9741009}
9751010
Lines 1021–1035 at 318 (were 986–991 at 280)
9861021}
9871022
9881023export async function main(argv: readonly string[], env: Env): Promise<MainResult> {
1024+ try {
1025+ return await runMain(argv, env);
1026+ } finally {
1027+ // A local project's store stays open only while its command runs.
1028+ closeLocalStores();
1029+ }
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 280)
10791123 const e = err as Error;
10801124 const code = err instanceof UsageError ? "usage" : err instanceof ApiError ? "server" : "error";
10811125 const message =
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
10841128 ? e.message
10851129 : `${e.message}${e.stack ? `\n${e.stack}` : ""}`);
Lines 15–30 at 318 (were 15–23 at 280)
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;
1920}
2021
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;
26+}
2128/** A Monitor lasts at most 30 minutes; the skill re-arms it when it ends. */
2229export const MONITOR_TIMEOUT_MS = 30 * 60_000;
2330
Lines 43–49 at 318 (were 36–42 at 280)
3643
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));
4047 return [
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 280)
4855
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;
5259}
5360
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 280)
8794 sleep(ms: number): Promise<void>;
8895 now(): number;
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 280)
100109}
101110
102111/**
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.
115+ */
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) => {
121+ deps.write(line);
122+ shown.push(line);
123+ if (shown.length > 200) shown.shift();
124+ };
125+ let running: Promise<void> | undefined;
126+ let again = false;
127+ const pass = async () => {
128+ do {
129+ again = false;
130+ const these = frames;
131+ frames = [];
132+ let items: readonly string[] = [];
133+ try {
134+ items = await deps.take!();
135+ } catch (err) {
136+ deps.note(`(abso news --follow: couldn't read the news: ${(err as Error).message}; showing the frames)`);
137+ }
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);
142+ } while (again);
143+ running = undefined;
144+ };
145+ return {
146+ frame(text) {
147+ frames.push(text);
148+ if (running !== undefined) again = true;
149+ else running = pass();
150+ },
151+ idle: () => running ?? Promise.resolve(),
152+ };
153+}
155+/**
103156 * Holds the seat's stream, printing one line per item, until the key is refused or `stopped()`.
104157 * Returns why it ended.
105158 */
106159export async function follow(deps: FollowDeps): Promise<{ ended: "refused" | "stopped"; reason: string }> {
160+ const reads = frameReads(deps);
107161 let wait = 1_000;
108162 while (!deps.stopped()) {
109163 let ticket: NewsTicket;
Lines 186–198 at 318 (were 132–143 at 280)
132186 };
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);
136191 };
137192 socket.onerror = () => {};
138193 socket.onclose = (e) => {
139194 stopPing();
140− done({ code: e.code, reason: e.reason });
195+ void reads.idle().then(() => done({ code: e.code, reason: e.reason }));
141196 };
142197 });
143198 if (isRefusal(closed.code)) return { ended: "refused", reason: closed.reason || `closed ${closed.code}` };
Lines 6–12 at 318 (were 6–11 at 280)
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";
1011
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 280)
329330 if (image) {
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.
340+ const path =
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 40–46 at 318 (were 40–45 at 280)
4040} from "./folder.ts";
4141import { fileArg } from "./history.ts";
4242import { modsBehindText } from "./install.ts";
43+import { isLocal } from "./local-store.ts";
4344import { withFolderLock } from "./lock.ts";
4445import { readKnownModes, writeKnownModes } from "./modes.ts";
4546import { queueText } from "./queue.ts";
Lines 326–336 at 318 (were 325–333 at 280)
325326 const space = (draft: string | null | undefined): string => (draft ? `draft ${draft}` : "shared");
326327 const parked = (me?.parked ?? []).filter((p) => p.draftChanges > 0);
327328 const credential = credentialLabel(root, config.server, env.env);
328− 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);
329332 const lines = [
330− `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}` : ""}.`}`,
331334 ...(behind ? [behind] : []),
332335 // Is shared green (#39)? Right under the first line, since it decides what to do next.
333336 ...ciText(status.ci, status.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.
5+
6+import { readFileSync } from "node:fs";
7+import { UsageError } from "./args.ts";
8+
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",
13+};
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;
22+}
24+/**
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.
29+ */
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.`,
36+ );
37+ if (site === undefined) return known;
38+ if (kind === "box")
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;
41+ try {
42+ url = new URL(site);
43+ } catch {
44+ // Not an address: refused below.
45+ }
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.",
49+ );
50+ return url.origin;
51+}
53+/**
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.
56+ */
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 };
67+}
69+/** A PAT from the file --pat-file names: read here, never printed. */
70+export function patFromFile(path: string): string {
71+ let text: string;
72+ try {
73+ text = readFileSync(path, "utf8").trim();
74+ } catch {
75+ throw new UsageError(`--pat-file names ${path}, which abso can't read`);
76+ }
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`);
79+ return text;
80+}
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);
85+}
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> {
89+ let res: Response;
90+ try {
91+ res = await fetcher(`${site}/login/handoff`, {
92+ method: "POST",
93+ headers: { authorization: `Bearer ${credential}`, accept: "application/json" },
94+ redirect: "error",
95+ signal: AbortSignal.timeout(30_000),
96+ });
97+ } catch (err) {
98+ throw new UsageError(`couldn't reach ${site}: ${scrubbed((err as Error).message, credential)}`);
99+ }
100+ const text = await res.text().catch(() => "");
101+ let body: Partial<Handoff> & { error?: unknown } = {};
102+ try {
103+ body = JSON.parse(text) as typeof body;
104+ } catch {
105+ // Not JSON: the status says enough.
106+ }
107+ if (!res.ok) {
108+ const why = typeof body.error === "string" ? body.error : `it answered ${res.status}`;
109+ throw new UsageError(
110+ res.status === 404
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)}`,
113+ );
114+ }
115+ if (
116+ typeof body.url !== "string" ||
117+ !body.url.startsWith(`${site}/login/handoff#`) ||
118+ typeof body.expiresAt !== "string" ||
119+ typeof body.account !== "string"
120+ )
121+ throw new UsageError(`${site} answered something that isn't a sign-in link`);
122+ return {
123+ url: body.url,
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,
128+ };
129+}
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));
134+ const reach = boxed
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";
137+ return [
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}:`,
139+ h.url,
140+ ].join("\n");
141+}
Lines 15–23 at 318 (were 15–20 at 280)
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`);
1821
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 280)
4043 );
4144 });
4245
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>/);
4754 assert.throws(
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 280)
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";
67
78const session = "0da5c2b7-ab07-4249-b868-e8f09b6ec7b6";
89
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");
21+});
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.
3+
4+import assert from "node:assert/strict";
5+import { test } from "node:test";
6+import { builtInHasNothing, runLine, storedRuns } from "../src/ci.ts";
7+
8+const base = { latest: null, checked: null, running: null, red: null, behind: null } as const;
9+const nothing = {
10+ version: 6,
11+ from: 6,
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",
14+};
16+test("the stored runs are read strictly, newest first as the server lists them", () => {
17+ const runs = storedRuns({
18+ blocked: null,
19+ runs: [
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" },
23+ ],
24+ });
25+ assert.deepEqual(
26+ runs.map((r) => r.id),
27+ [8, 6],
28+ );
29+ assert.deepEqual(storedRuns(null), []);
30+ assert.deepEqual(storedRuns({ runs: "no" }), []);
31+});
33+test("a run in a line names its file, its state and where its jobs are", () => {
34+ assert.equal(
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.",
37+ );
38+ assert.equal(
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.",
41+ );
42+ assert.equal(
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.",
45+ );
46+});
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);
52+ assert.equal(
53+ builtInHasNothing({
54+ ...base,
55+ red: { version: 6, agent: null, message: null, lastGood: null },
56+ skipped: nothing,
57+ }),
58+ false,
59+ );
60+});
Lines 211–235 at 318 (were 211–231 at 280)
211211
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>.");
215+ assert.match(
216+ plainError(refused, "this folder's key")!,
217+ /^The server didn't accept this folder's key.*abso doctor checks it/,
218+ );
219+ assert.match(plainError(refused, "ABSO_TOKEN")!, /^The server didn't accept ABSO_TOKEN: /);
216220 assert.equal(
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.",
219223 );
220224 assert.equal(
221225 plainError(
222226 new ApiError("could not reach http://x: refused. Nothing was pushed. Run the same command again."),
223− true,
227+ "this folder's key",
224228 ),
225229 "Can't reach http://x: refused. Nothing was pushed. Run the same command again.",
226230 );
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);
229233});
230234
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).
3+
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[] = [];
16+after(() => {
17+ for (const d of dirs) rmSync(d, { recursive: true, force: true, maxRetries: 5 });
18+});
20+function temp(): string {
21+ const d = mkdtempSync(join(tmpdir(), "abso-failed-start-"));
22+ dirs.push(d);
23+ return d;
24+}
26+async function run(cwd: string, ...argv: string[]): Promise<number> {
27+ return (await main(argv, { cwd, env: ENV, write: () => {} })).exit;
28+}
30+describe("a failed start", () => {
31+ it("init takes back the .absoignore and abso.json it wrote", async () => {
32+ const dir = temp();
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"]);
36+ });
38+ it("join leaves no .abso folder", async () => {
39+ const dir = temp();
40+ assert.notEqual(await run(dir, "join", "p", "--server", DOWN, "--agent", "a", "--dir", dir), 0);
41+ assert.equal(existsSync(join(dir, ".abso")), false);
42+ });
44+ it("join keeps a key that was already here", async () => {
45+ const dir = temp();
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"]);
51+ });
53+ it("join with a key it can't read leaves only that key", async () => {
54+ const dir = temp();
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"]);
59+ });
60+});
Lines 26–33 at 318 (were 26–31 at 280)
2626import { clientVersion, headCommit } from "../src/client-version.ts";
2727import {
2828 AVCS_MOD,
29+ hookCommand,
30+ installerCommand,
2931 installMod,
3032 keptModCommit,
3133 type ModSpec,
Lines 115–142 at 318 (were 113–118 at 280)
113115 );
114116 });
115117
118+ it("stamps the command that runs this client's abso hook, where stamp.ts has a HOOK_COMMAND line", () => {
119+ const spec = source({
120+ "hooks/stamp.ts":
121+ "export const STAMP: string | undefined = undefined\nexport const HOOK_COMMAND: readonly string[] | undefined = undefined\n",
122+ });
123+ const target = join(temp(), "avcs");
124+ installMod(spec, {
125+ target,
126+ check: pass,
127+ commit: "702c616",
128+ hookCommand: ["C:\\node.exe", "C:\\abso\\client\\abso.ts", "hook"],
129+ });
130+ assert.equal(
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',
134+ );
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$/);
138+ });
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 280)
427451 assert.equal(client, `abso ${clientVersion()} (${dirname(import.meta.dirname)})`);
428452 assert.match(
429453 mod!,
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)?)?: /,
431455 );
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: () => {} }))
435460 .stdout,
Lines 499–505 at 318 (were 474–480 at 280)
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).`,
478503 ]);
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.
4+
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}-`));
19+ dirs.push(d);
20+ return d;
21+};
23+const outside: string[] = [];
24+const realFetch = globalThis.fetch;
25+before(() => {
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");
29+ }) as typeof fetch;
30+});
31+after(() => {
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");
35+});
37+let store: string;
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 };
42+}
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)))
47+ ? false
48+ : "no server/src beside this client, so no local projects";
50+describe("a local project, with the network off", { skip: noServer }, () => {
51+ let alice: string;
52+ let bob: string;
53+ before(() => {
54+ store = temp("store");
55+ });
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");
70+ });
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/);
82+ });
84+ it("a second folder joins, and pulls what the first pushes", async () => {
85+ bob = temp("bob");
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");
95+ });
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/);
102+ });
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/);
112+ });
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/);
135+ });
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`)]);
141+ closeLocalStores();
142+ for (const a of answers) assert.equal(a.status, 200, await a.text());
143+ });
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/);
153+ }
154+ assert.ok(!existsSync(join(store, "..", "project.sqlite")));
155+ assert.deepEqual(readdirSync(dir), ["a.txt"], "init left nothing behind");
156+ });
157+});
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);
173+ });
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/);
182+ });
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);
191+ });
192+});
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], {
199+ cwd,
200+ env: { ...process.env, ABSO_STORE: processStore, ABSO_SERVERS_FILE: "no-servers.json" },
201+ encoding: "utf8",
202+ });
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"]],
212+ ["log", ["log"]],
213+ ];
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/);
220+ }
221+ });
222+});
Lines 3–9 at 318 (were 3–8 at 280)
33import assert from "node:assert/strict";
44import { test } from "node:test";
55import {
6+ expiresAtMs,
67 type FollowDeps,
78 follow,
89 isRefusal,
Lines 42–52 at 318 (were 41–46 at 280)
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);
4450});
4551
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 280)
128134 assert.equal(w.notes.length, 0);
129135});
130136
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?"], []];
141+ let calls = 0;
142+ w.deps.take = async () => {
143+ calls++;
144+ return reads.shift() ?? [];
145+ };
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");
174+ };
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/);
178+});
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.
2+
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";
9+
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.
20+ assert.throws(
21+ () => siteFor("https://api.abso.dev", undefined, "box"),
22+ /for staging.*never sign in to the website on prod/,
23+ );
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);
33+});
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;
38+ let read = 0;
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 },
46+ ])
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`]);
53+});
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",
63+ name: "christopher",
64+ sessionEnds: "2026-10-16T21:00:00.000Z",
65+ });
66+ }) as typeof fetch;
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_/);
76+});
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_/);
84+ return true;
85+ });
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 () =>
89+ Response.json({
90+ url: "https://elsewhere.example/login/handoff#x",
91+ expiresAt: new Date(NOW).toISOString(),
92+ account: "acct_x",
93+ })) as unknown as typeof fetch;
94+ await assert.rejects(webHandoff(SITE, BOX, elsewhere), /isn't a sign-in link/);
95+});
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/);
106+});
MCP
compare on this site's /mcp
CLI
abso diff 280 318 client --json
JSON
/christopher/abso-core/compare/280..318?file=client&format=json