{"draft":null,"from":277,"to":318,"files":[{"path":"client/src/announce.ts","added":2,"removed":0,"diff":"--- a/client/src/announce.ts\n+++ b/client/src/announce.ts\n@@ -107,6 +107,8 @@\n \t\ttry {\n \t\t\tconst ended = await follow({\n \t\t\t\tmint: () => api.newsTicket(),\n+\t\t\t\t// A frame is a wake: read the news, which marks it heard, and print that (news-stream.ts).\n+\t\t\t\ttake: async () => newsLines((await api.news()).news),\n \t\t\t\tconnect: (url, protocols) => new WebSocket(url, [...protocols]) as unknown as Socket,\n \t\t\t\twrite: (line) => {\n \t\t\t\t\tlogNews(root, [line]);"},{"path":"client/src/api.ts","added":16,"removed":2,"diff":"--- a/client/src/api.ts\n+++ b/client/src/api.ts\n@@ -20,6 +20,7 @@\n \tSyncAnswer,\n } from \"./api-answers.ts\";\n import { ApiError, errorSentence, neverSent } from \"./api-error.ts\";\n+import { UsageError } from \"./args.ts\";\n import type { AutosettleAnswer, AutosettleMode } from \"./autosettle-commands.ts\";\n import {\n \tboxQuery,\n@@ -68,6 +69,7 @@\n \tIssueRow,\n \tIssueSearchHit,\n } from \"./issues-wire.ts\";\n+import { isLocal, LOCAL_BASE, localFetch, NO_STORE } from \"./local-store.ts\";\n import type { Modes } from \"./modes.ts\";\n \n export * from \"./api-answers.ts\";\n@@ -191,9 +193,13 @@\n \tcaller: string | undefined;\n \n \turl(path: string, server = this.config.server): string {\n-\t\treturn `${server.replace(/\\/+$/, \"\")}/p/${encodeURIComponent(this.config.project)}${path}`;\n+\t\tconst base = isLocal(server) ? LOCAL_BASE : server;\n+\t\treturn `${base.replace(/\\/+$/, \"\")}/p/${encodeURIComponent(this.config.project)}${path}`;\n \t}\n \n+\t/** A local project's calls: answered in this process (local-store.ts). */\n+\tprivate local: ((input: string, init?: RequestInit) => Promise<Response>) | undefined;\n+\n \tagentPath(action: string): string {\n \t\treturn `/a/${encodeURIComponent(this.config.agent)}/${action}`;\n \t}\n@@ -214,6 +220,12 @@\n \t * and follows no redirect, so nothing it sends goes anywhere it didn't name (headers() adds no sign-in).\n \t */\n \tsend(url: string, init: RequestInit = {}): Promise<Response> {\n+\t\tif (isLocal(this.config.server)) {\n+\t\t\tconst dir = this.config.localStore;\n+\t\t\tif (dir === undefined) return Promise.reject(new UsageError(NO_STORE));\n+\t\t\tthis.local ??= localFetch(dir);\n+\t\t\treturn this.local(url, init);\n+\t\t}\n \t\tif (!this.config.visitor) return fetch(url, init);\n \t\tif ((init.method ?? \"GET\") !== \"GET\")\n \t\t\treturn Promise.reject(new ApiError(\"a folder that reads signed out sends only reads\"));\n@@ -248,6 +260,8 @@\n \t\t\t\t\tsignal: AbortSignal.timeout(timeoutMs),\n \t\t\t\t});\n \t\t\t} catch (err) {\n+\t\t\t\t// A local project's refusal (no store, a Node without SQLite) says itself.\n+\t\t\t\tif (err instanceof UsageError) throw err;\n \t\t\t\tconst e = err as Error;\n \t\t\t\tconst why =\n \t\t\t\t\te.name === \"TimeoutError\"\n@@ -1003,7 +1017,7 @@\n \t}\n \n \t/** A ticket that opens this agent's news stream once, within a minute (abso 690; news-stream.ts). */\n-\tnewsTicket(): Promise<{ url: string; protocols: string[]; expiresAt: number }> {\n+\tnewsTicket(): Promise<{ url: string; protocols: string[]; expiresAt: number | string }> {\n \t\treturn this.json(\"POST\", this.agentPath(\"news/ticket\"), {});\n \t}\n "},{"path":"client/src/body-files.ts","added":3,"removed":3,"diff":"--- a/client/src/body-files.ts\n+++ b/client/src/body-files.ts\n@@ -2,7 +2,7 @@\n // passes a native command's argument badly, so a multi-line --comment,\n // --description or answer reached the server cut to its first line, and nobody\n // knew. Any text flag also takes --<flag>-file <path>, and the commands whose\n-// text is their words (ask, answer, announce) take --file <path>. A path of -\n+// text is their words (ask, answer, reply, announce) take --file <path>. A path of -\n // reads stdin. The file's text arrives whole on any shell.\n \n import { readFileSync } from \"node:fs\";\n@@ -12,7 +12,7 @@\n /** The text flags a command may take from a file instead. */\n const BODY_FLAGS = [\"message\", \"comment\", \"object\", \"description\", \"note\"] as const;\n /** Commands whose text is their last words: --file gives those words. */\n-const WORDS_FROM_FILE = new Set([\"ask\", \"answer\", \"announce\"]);\n+const WORDS_FROM_FILE = new Set([\"ask\", \"answer\", \"reply\", \"announce\"]);\n \n /** The command's flags, plus a -file twin for each text flag it takes, and --file where its words are its text. */\n export function withBodyFiles(command: string, spec: FlagSpec): FlagSpec {\n@@ -75,7 +75,7 @@\n \t}\n \tconst path = flags.get(\"file\");\n \tif (WORDS_FROM_FILE.has(command) && typeof path === \"string\") {\n-\t\t// ask <who> and answer <ask> keep their first word; announce's words are all text.\n+\t\t// ask <who>, answer <ask> and reply <ask> keep their first word; announce's words are all text.\n \t\tconst keep = command === \"announce\" ? 0 : 1;\n \t\tif (positionals.length > keep)\n \t\t\tthrow new UsageError(`--file gives ${command}'s text, so leave the words off the command line`);"},{"path":"client/src/ci.ts","added":50,"removed":4,"diff":"--- a/client/src/ci.ts\n+++ b/client/src/ci.ts\n@@ -80,6 +80,43 @@\n \treturn lines;\n }\n \n+/** A stored pipeline run as runRuns lists it: what the CI lines need of it. */\n+interface StoredRun {\n+\treadonly id: number;\n+\treadonly version: number;\n+\treadonly state: string;\n+\treadonly file: string;\n+}\n+\n+/** The stored pipeline runs, newest first, from the server's `pipelines` read; empty for anything else. */\n+export function storedRuns(raw: unknown): StoredRun[] {\n+\tconst runs = (raw as { runs?: unknown } | null)?.runs;\n+\tif (!Array.isArray(runs)) return [];\n+\treturn runs.filter(\n+\t\t(r): r is StoredRun =>\n+\t\t\ttypeof r === \"object\" &&\n+\t\t\tr !== null &&\n+\t\t\tNumber.isInteger((r as StoredRun).id) &&\n+\t\t\tNumber.isInteger((r as StoredRun).version) &&\n+\t\t\ttypeof (r as StoredRun).state === \"string\" &&\n+\t\t\ttypeof (r as StoredRun).file === \"string\",\n+\t);\n+}\n+\n+/** One stored run in a line, with where its jobs are. */\n+export function runLine(run: StoredRun): string {\n+\tconst how = run.state === \"planned\" ? \"was planned, not run,\" : run.state === \"running\" ? \"is running\" : run.state;\n+\treturn `Pipeline run ${run.id} (${run.file}) ${how} on version ${run.version}. abso pipeline runs ${run.id} shows its jobs.`;\n+}\n+\n+/**\n+ * Whether the built-in check (abso.json's setup, build and check) had nothing of its own to run. With stored runs, that is\n+ * about the built-in check, not the project's CI, so it isn't said as the project's (abso 719).\n+ */\n+export function builtInHasNothing(ci: CiStatus): boolean {\n+\treturn ci.red === null && ci.skipped?.reason.startsWith(\"nothing to run\") === true;\n+}\n+\n /** 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. */\n export function ciMarkText(mark: CiMark | undefined): string {\n \tswitch (mark) {\n@@ -143,11 +180,20 @@\n \t\t}\n \t\tif (typed !== undefined) {\n \t\t\tif (!/^\\d+$/.test(typed)) throw new UsageError(`a version is a number (got ${JSON.stringify(typed)})`);\n-\t\t\tconst job = await api.ci(Number(typed));\n-\t\t\treturn { text: jobText(job).join(\"\\n\"), json: { ...job } };\n+\t\t\tconst [job, raw] = await Promise.all([api.ci(Number(typed)), api.pipelineRuns().catch(() => null)]);\n+\t\t\tconst run = storedRuns(raw).find((r) => r.version === job.version);\n+\t\t\t// A version the built-in check never ran, with a pipeline run of its own: the run is its CI (abso 719).\n+\t\t\tconst text = run !== undefined && job.result === \"none\" ? [runLine(run)] : jobText(job);\n+\t\t\treturn { text: text.join(\"\\n\"), json: { ...job } };\n \t\t}\n-\t\tconst [ci, status] = await Promise.all([api.ci(), api.status()]);\n-\t\tconst lines = ciText(ci, status.version);\n+\t\tconst [ci, status, raw] = await Promise.all([api.ci(), api.status(), api.pipelineRuns().catch(() => null)]);\n+\t\tconst newest = storedRuns(raw)[0];\n+\t\tconst lines =\n+\t\t\tnewest === undefined\n+\t\t\t\t? ciText(ci, status.version)\n+\t\t\t\t: builtInHasNothing(ci)\n+\t\t\t\t\t? [runLine(newest)]\n+\t\t\t\t\t: [...ciText(ci, status.version), runLine(newest)];\n \t\treturn {\n \t\t\ttext: [\n \t\t\t\t`shared is at version ${status.version}.`,"},{"path":"client/src/command-env.ts","added":17,"removed":1,"diff":"--- a/client/src/command-env.ts\n+++ b/client/src/command-env.ts\n@@ -1,5 +1,6 @@\n // What every abso command shares: its output, its environment, the folder it opens, and the news it took.\n \n+import { createHash } from \"node:crypto\";\n import { hostname } from \"node:os\";\n import { callerHeader } from \"../../src/caller.ts\";\n import { Api, type News, newsLines, type RunKind, takeSeatNotices } from \"./api.ts\";\n@@ -48,11 +49,26 @@\n \t\t);\n \tconst config = readConfig(root, env.env, env.tokenFile === true);\n \tconst api = new Api(config);\n-\tapi.caller = callerHeader({ session: env.env.CLAUDE_CODE_SESSION_ID, machine: hostname(), folder: root });\n+\tapi.caller = callerFor(env.env.CLAUDE_CODE_SESSION_ID, hostname(), root);\n \treturn { root, config, api };\n }\n \n /**\n+ * The caller header for this chat, computer and folder. The chat's session id goes as a short SHA-256 of it and the\n+ * folder as its last part, so neither the raw id nor the path (which names the person) leaves the machine.\n+ */\n+export function callerFor(session: string | undefined, machine: string, root: string): string | undefined {\n+\tconst hashed = session ? createHash(\"sha256\").update(session).digest(\"hex\").slice(0, 16) : undefined;\n+\t// The last part on either separator, so a Windows path names its folder on any machine.\n+\tconst folder =\n+\t\troot\n+\t\t\t.split(/[\\\\/]+/)\n+\t\t\t.filter((p) => p !== \"\")\n+\t\t\t.at(-1) ?? \"\";\n+\treturn callerHeader({ session: hashed, machine, folder });\n+}\n+\n+/**\n  * News a command took from the server while recording first. main() prints it\n  * after whatever the command says, so every command that takes news shows it\n  * (#37, News Report: sync, run and diff took it, wrote it to .avcs/news.log and"},{"path":"client/src/commands.ts","added":47,"removed":1,"diff":"--- a/client/src/commands.ts\n+++ b/client/src/commands.ts\n@@ -7,6 +7,7 @@\n // The engine's own key, so both sides match spellings the same way (#49). Not in core.ts: the edit mod installs core.ts alone.\n import {\n \ttype Api,\n+\tApiError,\n \ttype Collision,\n \ttype FileChange,\n \ttype MergedLine,\n@@ -431,9 +432,54 @@\n  * overwritten.\n  */\n export async function syncFolder(root: string, api: Api, full = false): Promise<Applied> {\n-\treturn applyAnswer(root, api, await api.sync({ full }));\n+\tconst applied = await applyAnswer(root, api, await pullAnswer(root, api, full));\n+\tpullWritten(root);\n+\treturn applied;\n }\n \n+const PULLING_FILE = \"pulling.json\";\n+\n+/**\n+ * Whether a pull here asked the server and never wrote its answer (abso-core 26): it timed out, or stopped\n+ * partway. The server moved the agent's base when it answered, and later pulls send only what changed since\n+ * that base, so the files it would have written stay behind until a pull asks for every file.\n+ */\n+export function pullUnfinished(root: string): boolean {\n+\treturn existsSync(join(stateDir(root), PULLING_FILE));\n+}\n+\n+/**\n+ * Ask the server for a pull, noting first that one is under way, so a pull whose answer never gets written\n+ * leaves the note behind. With that note, or `full`, it asks for every file in the agent's view, which the\n+ * folder's own checks then write only where the folder differs. pullWritten takes the note away.\n+ */\n+export async function pullAnswer(root: string, api: Api, full = false): Promise<SyncAnswer> {\n+\tconst unfinished = pullUnfinished(root);\n+\twriteFileAtomic(join(stateDir(root), PULLING_FILE), `${JSON.stringify({ at: new Date().toISOString() })}\\n`);\n+\tif (!full && !unfinished) return api.sync();\n+\ttry {\n+\t\treturn await api.sync({ full: true });\n+\t} catch (err) {\n+\t\t// A server from before full pulls (501): the plain pull is still better than none.\n+\t\tif (unfinished && !full && err instanceof ApiError && err.status === 501) return api.sync();\n+\t\tthrow err;\n+\t}\n+}\n+\n+/** The pull's answer is written into the folder: take away pullAnswer's note. */\n+export function pullWritten(root: string): void {\n+\trmSync(join(stateDir(root), PULLING_FILE), { force: true });\n+}\n+\n+/** Status's line, and pull's when it caught up. */\n+export function pullUnfinishedText(root: string): string[] {\n+\treturn pullUnfinished(root)\n+\t\t? [\n+\t\t\t\t\"A pull here didn't finish (its answer never arrived or wasn't written), so files may be behind this folder's base. abso pull fetches every file and writes the ones that differ.\",\n+\t\t\t]\n+\t\t: [];\n+}\n+\n /** What writing a sync or switch answer into the folder did. */\n export interface Applied {\n \treadonly version: number;"},{"path":"client/src/config.ts","added":19,"removed":3,"diff":"--- a/client/src/config.ts\n+++ b/client/src/config.ts\n@@ -11,6 +11,7 @@\n import { UsageError } from \"./args.ts\";\n import { type MachineServers, machineServers, TOKEN_SERVERS, tokenGoesTo, trustedList } from \"./core.ts\";\n import { fromEnv } from \"./env-names.ts\";\n+import { isLocal, storeDir } from \"./local-store.ts\";\n import { homeFile, stateDir } from \"./state-dir.ts\";\n \n /** What .avcs/config.json holds. */\n@@ -27,10 +28,14 @@\n \t * routes anyone can read and sends no credential. It has no agent; its config holds server, project and this.\n \t */\n \treadonly visitor?: boolean;\n+\t/** A local project's store (abso init --local --store), when it isn't the machine's own: ABSO_STORE or the OS data folder. */\n+\treadonly store?: string;\n }\n \n export interface Config extends Settings {\n \treadonly token?: string;\n+\t/** For a local project (server \"local\"): the store folder its history is in, or undefined when there's none to use. */\n+\treadonly localStore?: string;\n }\n \n export function configPath(root: string): string {\n@@ -64,11 +69,15 @@\n \tfor (const key of [\"server\", \"project\", \"agent\"] as const) {\n \t\tif (typeof raw[key] !== \"string\" || raw[key] === \"\") throw new Error(`${configPath(root)} has no \"${key}\"`);\n \t}\n-\tconst token = tokenFor(raw.server!, env, root, tokenFileOk);\n+\t// A local project's calls never leave this process, so no credential goes with them.\n+\tconst local = isLocal(raw.server);\n+\tconst token = local ? undefined : tokenFor(raw.server!, env, root, tokenFileOk);\n \treturn {\n \t\tserver: raw.server!,\n \t\tproject: raw.project!,\n \t\tagent: raw.agent!,\n+\t\t...(typeof raw.store === \"string\" && raw.store !== \"\" ? { store: raw.store } : {}),\n+\t\t...(local ? { localStore: storeDir(env, raw.store, root) } : {}),\n \t\t...(typeof raw.follow === \"string\" && raw.follow !== \"\" ? { follow: raw.follow } : {}),\n \t\t...(raw.reader === true ? { reader: true } : {}),\n \t\t...(token ? { token } : {}),\n@@ -275,10 +284,17 @@\n \n export function writeConfig(root: string, settings: Settings): void {\n \tmkdirSync(stateDir(root), { recursive: true });\n-\tconst { server, project, agent, follow, reader, visitor } = settings;\n+\tconst { server, project, agent, follow, reader, visitor, store } = settings;\n \tconst written = visitor\n \t\t? { server, project, visitor: true }\n-\t\t: { server, project, agent, ...(follow ? { follow } : {}), ...(reader ? { reader: true } : {}) };\n+\t\t: {\n+\t\t\t\tserver,\n+\t\t\t\tproject,\n+\t\t\t\tagent,\n+\t\t\t\t...(follow ? { follow } : {}),\n+\t\t\t\t...(reader ? { reader: true } : {}),\n+\t\t\t\t...(store ? { store } : {}),\n+\t\t\t};\n \twriteFileSync(configPath(root), `${JSON.stringify(written, null, 2)}\\n`);\n \texcludeFromGit(root);\n }"},{"path":"client/src/doctor.ts","added":4,"removed":4,"diff":"--- a/client/src/doctor.ts\n+++ b/client/src/doctor.ts\n@@ -327,13 +327,13 @@\n \n /**\n  * The commonest failures in plain words, with the next step: no credential, a credential the server refuses, and a\n- * server that can't be reached. Anything else is left as it was. `signedIn` is whether the call carried a key or token.\n+ * server that can't be reached. Anything else is left as it was. `sent` names the key or token the call carried, if any.\n  */\n-export function plainError(err: unknown, signedIn: boolean, tokenFileUnasked = false): string | undefined {\n+export function plainError(err: unknown, sent: string | undefined, tokenFileUnasked = false): string | undefined {\n \tif (!(err instanceof ApiError)) return undefined;\n \tif (err.status === 401)\n-\t\treturn signedIn\n-\t\t\t? `The server didn't accept this folder's key: it may be revoked or expired. abso doctor checks it. (${err.message})`\n+\t\treturn sent !== undefined\n+\t\t\t? `The server didn't accept ${sent}: it may be revoked or expired. abso doctor checks it. (${err.message})`\n \t\t\t: `You're not signed in. Run abso login, then abso join <project>.${tokenFileUnasked ? \" ~/.abso/token is used only with --token-file.\" : \"\"}`;\n \tif (err.status === undefined && err.message.startsWith(\"could not reach \")) {\n \t\tconst said = err.message.replace(/^could not reach /, \"Can't reach \");"},{"path":"client/src/drafts.ts","added":6,"removed":2,"diff":"--- a/client/src/drafts.ts\n+++ b/client/src/drafts.ts\n@@ -19,6 +19,8 @@\n \ttype Output,\n \topen,\n \tplural,\n+\tpullAnswer,\n+\tpullWritten,\n \trecordedFirst,\n \trecordFolder,\n } from \"./commands.ts\";\n@@ -57,9 +59,10 @@\n \tnote(answer.files);\n \tconst switched = await applyAnswer(root, api, answer);\n \t// The switch brings back the space as it was when parked; sync straight away so the folder shows it as it is now (#22).\n-\tconst syncAnswer = await api.sync();\n+\tconst syncAnswer = await pullAnswer(root, api);\n \tnote(syncAnswer.files);\n \tconst synced = await applyAnswer(root, api, syncAnswer);\n+\tpullWritten(root);\n \tconst touched = new Set([...switched.written, ...switched.deleted, ...synced.written, ...synced.deleted]);\n \tconst written: string[] = [];\n \tconst deleted: string[] = [];\n@@ -148,7 +151,8 @@\n \tconst moved = await api.draftSync();\n \t// Bring the moved draft's new view into this folder straight away.\n \tconst recorded = await recordFolder(root, api);\n-\tconst applied = await applyAnswer(root, api, await api.sync());\n+\tconst applied = await applyAnswer(root, api, await pullAnswer(root, api));\n+\tpullWritten(root);\n \tconst lines = [\n \t\t`Moved draft ${moved.draft} onto shared version ${moved.sharedBase} (the draft is at version ${moved.version}).`,\n \t\t...recordedFirst(recorded),"},{"path":"client/src/durable-object-stand-in.ts","added":13,"removed":0,"diff":"--- /dev/null\n+++ b/client/src/durable-object-stand-in.ts\n@@ -0,0 +1,13 @@\n+// What `import { DurableObject } from \"cloudflare:workers\"` gives the open server's code when it runs inside the client\n+// for a local project (local-store.ts): a base class that keeps the object's state and settings, which is all the\n+// project object takes from it. The build points that import here (scripts/build-client.mjs); run as .ts files, a\n+// module hook does (local-store.ts).\n+\n+export class DurableObject<Env = unknown> {\n+\tctx: unknown;\n+\tenv: Env;\n+\tconstructor(ctx: unknown, env: Env) {\n+\t\tthis.ctx = ctx;\n+\t\tthis.env = env;\n+\t}\n+}"},{"path":"client/src/install.ts","added":35,"removed":8,"diff":"--- a/client/src/install.ts\n+++ b/client/src/install.ts\n@@ -94,6 +94,8 @@\n \t/** For tests: the rename that moves each file into place. */\n \treadonly rename?: (from: string, to: string) => void;\n \treadonly now?: Date;\n+\t/** For tests: the command stamped as HOOK_COMMAND, instead of this client's own `abso hook`. */\n+\treadonly hookCommand?: readonly string[];\n }\n \n const RECORD = \".avcs-install.json\";\n@@ -132,6 +134,15 @@\n \texistsSync(at(skillsFolder(AVCS_MOD.name, env), MANIFEST)) ||\n \texistsSync(at(skillsFolder(OLD_MOD_NAMES[AVCS_MOD.name]!, env), MANIFEST));\n \n+/** Whether the installed abso mod hands a local project's edits to abso hook: it was installed with a HOOK_COMMAND. */\n+export function modHandsLocal(env: Readonly<Record<string, string | undefined>> = process.env): boolean {\n+\ttry {\n+\t\treturn /HOOK_COMMAND[^=\\n]*=\\s*\\[/.test(readFileSync(at(skillsFolder(AVCS_MOD.name, env), STAMP_FILE), \"utf8\"));\n+\t} catch {\n+\t\treturn false;\n+\t}\n+}\n+\n /**\n  * After the new mod is in, the folder it replaces (skills/avcs, skills/avcs-view) would load beside it, so it\n  * is moved, not deleted, to ~/.abso/retired-mods/<name>-<stamp>. Returns where it went, or undefined when there was none.\n@@ -226,8 +237,11 @@\n \treturn commit;\n }\n \n-/** The files to install, stamped with `version`, in install order. */\n-function filesFor(spec: ModSpec, version: string): Map<string, Buffer> {\n+/** The command that runs this checkout's `abso hook`: what the mod hands a local project's edits to. */\n+export const hookCommand = (): readonly string[] => [process.execPath, join(CLIENT_DIR, \"abso.ts\"), \"hook\"];\n+\n+/** The files to install, stamped with `version` (and HOOK_COMMAND, where a stamp.ts has it), in install order. */\n+function filesFor(spec: ModSpec, version: string, hook: readonly string[] = hookCommand()): Map<string, Buffer> {\n \tif (!/^[\\w.+-]+$/.test(version)) throw new Error(`can't stamp the version ${JSON.stringify(version)}`);\n \tconst out = new Map<string, Buffer>();\n \tfor (const rel of spec.files) {\n@@ -239,7 +253,9 @@\n \t\t\tconst text = data.toString(\"utf8\");\n \t\t\tconst stamped = text.replace(/(STAMP[^=\\n]*=\\s*)undefined/, `$1'${version}'`);\n \t\t\tif (stamped === text) throw new Error(`${rel} has no \"STAMP ... = undefined\" line to stamp`);\n-\t\t\tdata = Buffer.from(stamped);\n+\t\t\tdata = Buffer.from(\n+\t\t\t\tstamped.replace(/(HOOK_COMMAND[^=\\n]*=\\s*)undefined/, (_, head: string) => head + JSON.stringify(hook)),\n+\t\t\t);\n \t\t}\n \t\tout.set(rel, data);\n \t}\n@@ -386,7 +402,7 @@\n export function installMod(spec: ModSpec, options: InstallOptions): Installed {\n \tconst target = resolve(options.target);\n \tconst version = versionFor(spec, options.commit);\n-\tconst next = filesFor(spec, version);\n+\tconst next = filesFor(spec, version, options.hookCommand);\n \tconst existed = existsSync(target);\n \tmkdirSync(target, { recursive: true });\n \ttry {\n@@ -517,7 +533,18 @@\n \treadonly current: string;\n }\n \n-/** `avcs --version`: this client, and the mods installed on this machine, compared with this client's. */\n+/**\n+ * The command that runs one of this client's installers (client/install-mod.ts or install-view.ts), by its full\n+ * path. They are .ts files, which Node runs itself from 22.18, so on an older Node it says which one it needs.\n+ */\n+export function installerCommand(installer: string): string {\n+\tconst command = `node ${join(CLIENT_DIR, installer)}`;\n+\treturn (process.features as { typescript?: unknown }).typescript\n+\t\t? command\n+\t\t: `${command} (with Node 22.18 or later, which runs .ts files; this is Node ${process.versions.node})`;\n+}\n+\n+/** `abso --version`: this client, and the mods installed on this machine, compared with this client's. */\n export function versionReport(env: Readonly<Record<string, string | undefined>>): {\n \ttext: string;\n \tjson: Record<string, unknown>;\n@@ -554,14 +581,14 @@\n \t\tmods.push(m);\n \t\t// A built copy has no mod files to compare with or install from: it reports what is installed.\n \t\tif (m.version === undefined) {\n-\t\t\tlines.push(`the ${m.name} mod: not installed${builtCopy() ? \"\" : ` (node client/${installer})`}`);\n+\t\t\tlines.push(`the ${m.name} mod: not installed${builtCopy() ? \"\" : ` (${installerCommand(installer)})`}`);\n \t\t\tcontinue;\n \t\t}\n \t\tconst when = m.at ? `, installed ${m.at.slice(0, 16).replace(\"T\", \" \")} UTC` : \"\";\n \t\tconst behind =\n \t\t\tbuiltCopy() || m.version === m.current\n \t\t\t\t? \"\"\n-\t\t\t\t: `; this client has ${m.current}: node client/${installer} installs it`;\n+\t\t\t\t: `; this client has ${m.current}: ${installerCommand(installer)} installs it`;\n \t\tlines.push(`the ${m.name} mod: ${m.version} in ${m.folder}${when}${behind}`);\n \t}\n \treturn { text: lines.join(\"\\n\"), json: { client, folder: CLIENT_DIR, mods } };\n@@ -579,6 +606,6 @@\n \t\t.filter((m) => m.version?.includes(\"+\") && /\\+[0-9a-f]{7}$/.test(m.current) && m.version !== m.current)\n \t\t.map(\n \t\t\t(m) =>\n-\t\t\t\t`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).`,\n+\t\t\t\t`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).`,\n \t\t);\n }"},{"path":"client/src/issues.ts","added":6,"removed":0,"diff":"--- a/client/src/issues.ts\n+++ b/client/src/issues.ts\n@@ -28,6 +28,7 @@\n import { ignoredHere } from \"./fetch.ts\";\n import { loadIgnore, relativeTo } from \"./folder.ts\";\n import type { AskReply } from \"./issues-wire.ts\";\n+import { isLocal, LOCAL_BASE } from \"./local-store.ts\";\n import { queuedLines, standing } from \"./queue.ts\";\n import { seenText, shortWhen } from \"./times.ts\";\n \n@@ -36,6 +37,11 @@\n /** The folder, with its Api pointed at the Issues Worker: the token goes only where tokenGoesTo allows, as for the avcs server. */\n export function openIssues(env: Env): { root: string; config: Config; api: Api } {\n \tconst { root, config, api } = open(env);\n+\t// A local project's issues are in its store, where the open server keeps them: at /issues.\n+\tif (isLocal(config.server)) {\n+\t\tapi.issuesServer = `${LOCAL_BASE}/issues`;\n+\t\treturn { root, config, api };\n+\t}\n \t// An explicit --server goes to that server's own Issues Worker: ABSO_ISSUES_SERVER doesn't redirect it.\n \tconst server =\n \t\t(env.server === undefined ? fromEnv(env.env, \"ISSUES_SERVER\") : undefined) ||"},{"path":"client/src/join-commands.ts","added":137,"removed":38,"diff":"--- a/client/src/join-commands.ts\n+++ b/client/src/join-commands.ts\n@@ -2,8 +2,8 @@\n \n import { randomUUID } from \"node:crypto\";\n import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from \"node:fs\";\n-import { join, relative, resolve } from \"node:path\";\n-import { Api, ApiError } from \"./api.ts\";\n+import { isAbsolute, join, relative, resolve, sep } from \"node:path\";\n+import { Api, ApiError, type SyncAnswer } from \"./api.ts\";\n import { bool, type Parsed, str, UsageError } from \"./args.ts\";\n import { writeKnownBlobs } from \"./blobs.ts\";\n import {\n@@ -16,9 +16,9 @@\n \treadBox,\n } from \"./box.ts\";\n import { STARTING_ABSOIGNORE } from \"./check-ignore.ts\";\n-import { CLIENT_DIR } from \"./client-version.ts\";\n+import { builtCopy } from \"./client-version.ts\";\n import { type Env, type Output, plural } from \"./command-env.ts\";\n-import { leftOutText, syncFolder, uploadBlobs } from \"./commands.ts\";\n+import { applyAnswer, leftOutText, pullAnswer, pullWritten, syncFolder, uploadBlobs } from \"./commands.ts\";\n import {\n \tfindRoot,\n \tinstallKey,\n@@ -32,7 +32,8 @@\n import { elsewhereText } from \"./doctor.ts\";\n import { fromEnv } from \"./env-names.ts\";\n import { clearKnown, loadIgnore, readFolder, writeKnown } from \"./folder.ts\";\n-import { modInstalled } from \"./install.ts\";\n+import { installerCommand, modHandsLocal, modInstalled } from \"./install.ts\";\n+import { LOCAL, NO_STORE, storeDir } from \"./local-store.ts\";\n import { type FullMode, foldModes, writeKnownModes } from \"./modes.ts\";\n import { initInOrg, siteOf } from \"./orgs.ts\";\n import { projectFileName, readProjectFile, startingProjectFileText, writeStartingProjectFile } from \"./project-file.ts\";\n@@ -101,6 +102,48 @@\n \treturn undefined;\n }\n \n+/**\n+ * --local (abso init, abso join): the project's history is in a store on this machine, not on a server. The store is\n+ * --store, else ABSO_STORE, else the OS's data folder; one given with --store is kept in the folder's config.\n+ */\n+function localFrom(args: Parsed, env: Env, command: string): { dir: string; settings: { store?: string } } | undefined {\n+\tconst store = str(args, \"store\");\n+\tif (!bool(args, \"local\")) {\n+\t\tif (store !== undefined)\n+\t\t\tthrow new UsageError(\"--store goes with --local: it says where a local project's history is\");\n+\t\treturn undefined;\n+\t}\n+\tif (str(args, \"server\") !== undefined)\n+\t\tthrow new UsageError(\"--local or --server, not both: a local project has no server\");\n+\tif (str(args, \"org\") !== undefined || bool(args, \"public\") || bool(args, \"private\") || bool(args, \"reader\"))\n+\t\tthrow new UsageError(\n+\t\t\t`abso ${command} --local takes --project, --agent, --store and --as-is; a local project has no server to share it`,\n+\t\t);\n+\tconst dir = storeDir(env.env, store, env.cwd);\n+\tif (dir === undefined) throw new UsageError(NO_STORE);\n+\treturn { dir, settings: store === undefined ? {} : { store: dir } };\n+}\n+\n+/** A store inside the project folder is left out of its files: a line in .absoignore. Its relative path, if so. */\n+function ignoreStoreInside(root: string, dir: string): string | undefined {\n+\tconst rel = relative(root, dir);\n+\tif (rel === \"\" || rel.startsWith(\"..\") || isAbsolute(rel)) return undefined;\n+\tconst line = `/${rel.split(sep).join(\"/\")}/`;\n+\tconst file = join(root, \".absoignore\");\n+\tconst had = existsSync(file) ? readFileSync(file, \"utf8\") : \"\";\n+\tconst lines = had.split(/\\r?\\n/);\n+\tif (!lines.includes(line)) {\n+\t\tconst gap = had === \"\" || had.endsWith(\"\\n\") ? \"\" : \"\\n\";\n+\t\twriteFileSync(file, `${had}${gap}${line}\\n`);\n+\t}\n+\treturn rel;\n+}\n+\n+/** What init and join say about a local project's store. */\n+function localText(dir: string, project: string, ignored?: string): string {\n+\treturn `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.`}`;\n+}\n+\n /** Why a token file is no fallback: said when one is here and nothing else signs in. */\n const TOKEN_FILE_ASKED = \"~/.abso/token is used only with --token-file.\";\n \n@@ -111,42 +154,61 @@\n \tif (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);\n \tconst project = str(args, \"project\");\n \tif (!project) throw new UsageError(\"give the project a name with --project <name>\");\n+\t// Checked before any call: a name like \"..\" would otherwise go out as part of the request's path.\n+\tif (!NAME.test(project))\n+\t\tthrow new UsageError(\n+\t\t\t`project names are letters, digits, dot, dash and underscore (got ${JSON.stringify(project)})`,\n+\t\t);\n \tif (bool(args, \"public\") && bool(args, \"private\")) throw new UsageError(\"--public or --private, not both\");\n+\tconst local = localFrom(args, env, \"init\");\n \t// A box signed in here, and no other credential asked for: the project is made as the person who approved the box,\n \t// the way the website makes one (abso 663). The token file only with --token-file, never by itself.\n-\tconst server = serverFrom(args, env);\n-\tconst box = readBox(server);\n-\tconst credential = tokenCredential(args, env.env, server, root);\n+\tconst server = local ? LOCAL : serverFrom(args, env);\n+\tconst box = local ? undefined : readBox(server);\n+\tconst credential = local ? undefined : tokenCredential(args, env.env, server, root);\n \tconst say = env.writeErr ?? env.write;\n \tif (box && credential === undefined) {\n \t\tsay(`Signing in with this box's sign-in, ${box.id}.\n `);\n \t\treturn initFromBox(args, env, root, project, server, box);\n \t}\n-\tif (credential === undefined && tokenFile() !== undefined)\n+\tif (!local && credential === undefined && tokenFile() !== undefined)\n \t\tthrow new UsageError(\n \t\t\t`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}`,\n \t\t);\n \tconst org = str(args, \"org\");\n \tif (org !== undefined) return initInOrg(org, server);\n-\tconst config = makeSettings(args, env, project);\n+\tconst config: Settings = local\n+\t\t? { server: LOCAL, project, agent: agentFrom(args, str(args, \"agent\") ?? defaultAgentName()), ...local.settings }\n+\t\t: makeSettings(args, env, project);\n \tconst asIs = bool(args, \"as-is\");\n \tconst absoignore = join(root, \".absoignore\");\n \tconst wroteIgnore = !asIs && !existsSync(absoignore) && !existsSync(join(root, \".avcsignore\"));\n \tif (wroteIgnore) writeFileSync(absoignore, STARTING_ABSOIGNORE);\n+\t// A store kept inside the project folder, like a virtual environment, isn't the project's files.\n+\tconst ignoredStore = local ? ignoreStoreInside(root, local.dir) : undefined;\n \t// What the server runs on each new version (#39), guessed from package.json; recorded with the rest.\n \tconst wroteProject = asIs ? \"exists\" : writeStartingProjectFile(root);\n \tconst { files, blobs, modes, leftOut } = readFolder(root, loadIgnore(root));\n \tconst token = credential?.token;\n-\tsay(`Signing in with ${credential?.words ?? `no credential: nothing here signs in to ${server}`}.\n+\tif (!local)\n+\t\tsay(`Signing in with ${credential?.words ?? `no credential: nothing here signs in to ${server}`}.\n `);\n-\tconst api = new Api({ ...config, ...(token ? { token } : {}) });\n-\tawait uploadBlobs(api, blobs);\n-\tconst answer = await api.init(\n-\t\tObject.fromEntries(files),\n-\t\tmodes,\n-\t\tObject.fromEntries([...blobs].map(([rel, b]) => [rel, b.sha])),\n-\t);\n+\tconst api = new Api({ ...config, ...(token ? { token } : {}), ...(local ? { localStore: local.dir } : {}) });\n+\tlet answer: Awaited<ReturnType<Api[\"init\"]>>;\n+\ttry {\n+\t\tawait uploadBlobs(api, blobs);\n+\t\tanswer = await api.init(\n+\t\t\tObject.fromEntries(files),\n+\t\t\tmodes,\n+\t\t\tObject.fromEntries([...blobs].map(([rel, b]) => [rel, b.sha])),\n+\t\t);\n+\t} catch (error) {\n+\t\t// No project was made: the starting files init wrote go too, so the folder is as it was.\n+\t\tif (wroteIgnore) rmSync(absoignore, { force: true });\n+\t\tif (typeof wroteProject !== \"string\") rmSync(join(root, projectFileName(root)), { force: true });\n+\t\tthrow error;\n+\t}\n \twriteConfig(root, config);\n \tclearKnown(root);\n \tfor (const [rel, text] of files) writeKnown(root, rel, text);\n@@ -162,12 +224,14 @@\n \t\t\t...(wroteIgnore\n \t\t\t\t? [\"Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore.\"]\n \t\t\t\t: []),\n-\t\t\t...startingProjectFileText(wroteProject),\n+\t\t\t// A local project has no CI to run abso.json, so no word about one that isn't there.\n+\t\t\t...(local && wroteProject === \"nothing\" ? [] : startingProjectFileText(wroteProject)),\n \t\t\t...(answer.skipped && answer.skipped.length > 0 ? [`The server skipped: ${answer.skipped.join(\", \")}.`] : []),\n+\t\t\t...(local ? [localText(local.dir, project, ignoredStore)] : []),\n \t\t\t`This folder is agent ${config.agent}. Settings are in .abso/config.json.`,\n \t\t\t...refusedText(synced.refused),\n \t\t\t...(synced.kept.length > 0 ? [`Kept your copy of ${synced.kept.join(\", \")}.`] : []),\n-\t\t\thookHint(env.env),\n+\t\t\thookHint(env.env, local !== undefined),\n \t\t].join(\"\\n\"),\n \t\tjson: {\n \t\t\tproject,\n@@ -178,6 +242,7 @@\n \t\t\twroteAbsoignore: wroteIgnore,\n \t\t\twroteProjectFile: typeof wroteProject === \"string\" ? null : wroteProject,\n \t\t\tleftOut,\n+\t\t\t...(local ? { store: local.dir } : {}),\n \t\t},\n \t};\n }\n@@ -351,6 +416,16 @@\n \t};\n }\n \n+/** A join that failed before writing files: its state goes, but a key (already here, or made for it) stays for the next try. */\n+function takeBackJoin(root: string): void {\n+\tconst dir = stateDir(root);\n+\tif (!existsSync(join(dir, \"key\"))) {\n+\t\trmSync(dir, { recursive: true, force: true });\n+\t\treturn;\n+\t}\n+\tfor (const entry of readdirSync(dir)) if (entry !== \"key\") rmSync(join(dir, entry), { recursive: true, force: true });\n+}\n+\n export async function runJoin(args: Parsed, env: Env): Promise<Output> {\n \tif (args.positionals.length !== 1) throw new UsageError(\"join takes the project name: abso join <project>\");\n \tconst project = args.positionals[0]!;\n@@ -362,14 +437,17 @@\n \tmkdirSync(root, { recursive: true });\n \tif (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);\n \tconst reader = bool(args, \"reader\");\n-\tconst server = serverFrom(args, env);\n-\tconst box = readBox(server);\n-\tconst hasKey = existsSync(join(stateDir(root), \"key\"));\n-\tconst credential = tokenCredential(args, env.env, server, root);\n+\t// A local project: no box, key or credential, and the agent is --agent or this computer's name.\n+\tconst local = localFrom(args, env, \"join\");\n+\tconst server = local ? LOCAL : serverFrom(args, env);\n+\tconst box = local ? undefined : readBox(server);\n+\tconst hasKey = !local && existsSync(join(stateDir(root), \"key\"));\n+\tconst credential = local ? undefined : tokenCredential(args, env.env, server, root);\n \tconst tokenFileAsked = bool(args, \"token-file\");\n \tlet agent: string;\n \tlet minted: { key: string; id: string } | undefined;\n-\tif (str(args, \"agent\") !== undefined) {\n+\tif (local) agent = agentFrom(args, str(args, \"agent\") ?? defaultAgentName());\n+\telse if (str(args, \"agent\") !== undefined) {\n \t\tagent = agentFrom(args);\n \t\tminted =\n \t\t\tbox && !hasKey && !fromEnv(env.env, \"KEY_FILE\") && !tokenFileAsked\n@@ -394,30 +472,40 @@\n \t\tagent = free.agent;\n \t\tminted = { key: free.key, id: free.id };\n \t}\n-\tconst config = { server, project, agent, ...(reader ? { reader: true } : {}) };\n+\tconst config = { server, project, agent, ...(reader ? { reader: true } : {}), ...local?.settings };\n \twriteConfig(root, config);\n \tclearKnown(root);\n \tif (minted) installKey(root, JSON.stringify(minted));\n \t// The token file only with --token-file: readConfig reads it otherwise.\n-\tconst read = readConfig(root, env.env, false);\n+\tlet read: ReturnType<typeof readConfig>;\n+\ttry {\n+\t\tread = readConfig(root, env.env, false);\n+\t} catch (error) {\n+\t\ttakeBackJoin(root);\n+\t\tthrow error;\n+\t}\n \tconst settings = tokenFileAsked ? { ...read, token: credential?.token } : read;\n-\t(env.writeErr ?? env.write)(\n-\t\t`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}`)}.\n+\tif (!local)\n+\t\t(env.writeErr ?? env.write)(\n+\t\t\t`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}`)}.\n `,\n-\t);\n+\t\t);\n \tconst api = new Api(settings);\n-\tlet synced: Awaited<ReturnType<typeof syncFolder>>;\n+\tlet answer: SyncAnswer;\n \ttry {\n \t\t// Before the sync, so the server never takes a record from this folder.\n \t\tif (reader) await api.reader(true);\n \t\t// Every file, even when the server has seen this agent sync before: its plain sync answer would hold only what changed since (#37).\n-\t\tsynced = await syncFolder(root, api, true);\n+\t\tanswer = await pullAnswer(root, api, true);\n \t} catch (error) {\n+\t\t// Nothing is written yet: take back what join wrote so it can run again here.\n+\t\ttakeBackJoin(root);\n \t\tif (!(error instanceof ApiError && error.status === 401 && !box && !settings.token)) throw error;\n-\t\trmSync(stateDir(root), { recursive: true, force: true });\n \t\tconst why = await signedOut(config.server, project);\n \t\tthrow new UsageError(!tokenFileAsked && tokenFile() !== undefined ? `${why} ${TOKEN_FILE_ASKED}` : why);\n \t}\n+\tconst synced = await applyAnswer(root, api, answer);\n+\tpullWritten(root);\n \treturn {\n \t\ttext: [\n \t\t\t`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.` : \"\"}`,\n@@ -427,9 +515,10 @@\n \t\t\t\t\t\t`These files were already here and differ from shared, so they were left alone: ${synced.kept.join(\", \")}. abso record sends them as your changes.`,\n \t\t\t\t\t]\n \t\t\t\t: []),\n+\t\t\t...(local ? [localText(local.dir, project)] : []),\n \t\t\t...emptyHint(synced.version, synced.written.length, synced.kept.length, reader),\n \t\t\t...setupHint(root),\n-\t\t\thookHint(env.env),\n+\t\t\thookHint(env.env, local !== undefined),\n \t\t\t...(root === resolve(env.cwd) ? [] : [`cd ${relative(env.cwd, root) || root}`]),\n \t\t].join(\"\\n\"),\n \t\tjson: {\n@@ -453,8 +542,18 @@\n \t\t: [`Nothing is installed yet. Before building or testing here, run ${projectFileName(root)}'s setup: ${setup}`];\n }\n \n-function hookHint(env: Readonly<Record<string, string | undefined>>): string {\n-\treturn modInstalled(env)\n-\t\t? \"Edits made by Claude Code here are recorded by the abso mod on this machine, signed in as this folder. Anything else: abso record.\"\n-\t\t: `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.`;\n+function hookHint(env: Readonly<Record<string, string | undefined>>, local = false): string {\n+\t// A local project has no server: the mod hands its edits to abso hook, when it was installed with one to hand them to.\n+\tif (local) {\n+\t\tif (modHandsLocal(env))\n+\t\t\treturn \"Edits made by Claude Code here are recorded by the abso mod on this machine, through abso hook. Anything else: abso record.\";\n+\t\tif (modInstalled(env) && !builtCopy())\n+\t\t\treturn `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.`;\n+\t\treturn \"abso record sends the edits made here, whoever made them.\";\n+\t}\n+\tif (modInstalled(env))\n+\t\treturn \"Edits made by Claude Code here are recorded by the abso mod on this machine, signed in as this folder. Anything else: abso record.\";\n+\t// A built copy (the npm package) has no installer to point at (abso-core 18).\n+\tif (builtCopy()) return \"abso record sends the edits made here, whoever made them.\";\n+\treturn `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.`;\n }"},{"path":"client/src/local-server.d.mts","added":5,"removed":0,"diff":"--- /dev/null\n+++ b/client/src/local-server.d.mts\n@@ -0,0 +1,5 @@\n+// The types of local-server.mjs: as much of the open server as the client calls.\n+export declare function handle(request: Request, env: unknown, ctx: unknown, issues: unknown): Promise<Response>;\n+export declare const ProjectObject: new (ctx: unknown, env: unknown) => object;\n+export declare const IssueProject: new (ctx: unknown, env: unknown) => object;\n+export declare function issuesFetch(request: Request, env: unknown, ctx: unknown, route: unknown): Promise<Response>;"},{"path":"client/src/local-server.mjs","added":7,"removed":0,"diff":"--- /dev/null\n+++ b/client/src/local-server.mjs\n@@ -0,0 +1,7 @@\n+// The open server's router, project object and issues, for local projects (local-store.ts). Plain JS, with its types\n+// in local-server.d.mts, so the client's typecheck stops here: server/src is typechecked with the Workers' types\n+// (server/tsconfig.json). The build and Node follow these imports as usual.\n+\n+export { IssueProject, issuesFetch } from \"../../server/src/issues-entry.ts\";\n+export { ProjectObject } from \"../../server/src/project-object.ts\";\n+export { handle } from \"../../server/src/router.ts\";"},{"path":"client/src/local-store.ts","added":407,"removed":0,"diff":"--- /dev/null\n+++ b/client/src/local-store.ts\n@@ -0,0 +1,407 @@\n+// Local projects (abso init --local): the open server's own router and project object (server/src) run in this\n+// process, over Node's SQLite, so a project needs no server, account or network. Each project is one SQLite file in a\n+// store folder. Every call runs in one SQLite write transaction, which is the store's lock: another process's call\n+// waits for it, and a process that dies mid-call leaves nothing half-written.\n+\n+import { existsSync, mkdirSync } from \"node:fs\";\n+import { homedir } from \"node:os\";\n+import { join, resolve } from \"node:path\";\n+import { deserialize, serialize } from \"node:v8\";\n+import { UsageError } from \"./args.ts\";\n+import { fromEnv } from \"./env-names.ts\";\n+\n+/** The server a local folder's config names. */\n+export const LOCAL = \"local\";\n+/** The address the client's calls use for a local project; they never leave this process. */\n+export const LOCAL_BASE = \"http://local.abso.invalid\";\n+/** The shared token the in-process server is given, and that its calls carry. Not a secret: nothing listens. */\n+const LOCAL_TOKEN = \"local-store\";\n+\n+export const isLocal = (server: string | undefined): boolean => server === LOCAL;\n+\n+type EnvMap = Readonly<Record<string, string | undefined>>;\n+\n+/**\n+ * Where local projects live: the folder's own store (--store, kept in its config), else ABSO_STORE, else the OS's\n+ * per-user data folder. Undefined when there is none to use (no data folder and nothing named), so nothing assumes a\n+ * writable home folder.\n+ */\n+export function storeDir(env: EnvMap, configured?: string, cwd = process.cwd()): string | undefined {\n+\tif (configured) return resolve(cwd, configured);\n+\tconst named = fromEnv(env, \"STORE\");\n+\tif (named) return resolve(cwd, named);\n+\tconst data =\n+\t\tprocess.platform === \"win32\"\n+\t\t\t? env.LOCALAPPDATA\n+\t\t\t: process.platform === \"darwin\"\n+\t\t\t\t? env.HOME && join(env.HOME, \"Library\", \"Application Support\")\n+\t\t\t\t: env.XDG_DATA_HOME || (env.HOME ? join(env.HOME, \".local\", \"share\") : undefined);\n+\tif (data) return join(data, \"abso\", \"store\");\n+\ttry {\n+\t\tconst home = homedir();\n+\t\treturn home ? join(home, \".local\", \"share\", \"abso\", \"store\") : undefined;\n+\t} catch {\n+\t\treturn undefined;\n+\t}\n+}\n+\n+export const NO_STORE =\n+\t\"there's no folder for local projects here: set ABSO_STORE to one, or give abso init --local a --store <folder>\";\n+\n+// --- The Workers runtime's parts the server uses, over node:sqlite -----------------------------------------------\n+\n+interface Db {\n+\texec(sql: string): void;\n+\tprepare(sql: string): {\n+\t\tall(...args: unknown[]): unknown[];\n+\t\trun(...args: unknown[]): unknown;\n+\t\tget(...args: unknown[]): unknown;\n+\t\tcolumns(): unknown[];\n+\t};\n+\tclose(): void;\n+}\n+\n+/** A Durable Object's storage: SQL, synchronous transactions, the key-value calls and the alarm, on one database. */\n+function storageOver(db: Db) {\n+\tdb.exec(\n+\t\t\"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)\",\n+\t);\n+\tconst statements = new Map<string, ReturnType<Db[\"prepare\"]>>();\n+\tconst prepared = (query: string) => {\n+\t\tlet s = statements.get(query);\n+\t\tif (!s) {\n+\t\t\ts = db.prepare(query);\n+\t\t\tstatements.set(query, s);\n+\t\t}\n+\t\treturn s;\n+\t};\n+\t// Workers takes and gives BLOB columns as ArrayBuffers; node:sqlite as Uint8Arrays.\n+\tconst bind = (v: unknown) => (v instanceof ArrayBuffer ? new Uint8Array(v) : v);\n+\tconst out = (v: unknown) => (v instanceof Uint8Array ? v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength) : v);\n+\tlet depth = 0;\n+\tconst kvGet = (key: string) => {\n+\t\tconst row = prepared(\"SELECT value FROM _local_kv WHERE key = ?\").get(key) as { value: Uint8Array } | undefined;\n+\t\treturn row ? deserialize(row.value) : undefined;\n+\t};\n+\tconst kvPut = (key: string, value: unknown) =>\n+\t\tprepared(\n+\t\t\t\"INSERT INTO _local_kv (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value\",\n+\t\t).run(key, serialize(value));\n+\tconst kvDelete = (key: string) =>\n+\t\t(prepared(\"DELETE FROM _local_kv WHERE key = ?\").run(key) as { changes: number | bigint }).changes > 0;\n+\tconst storage = {\n+\t\tsql: {\n+\t\t\texec(query: string, ...bindings: unknown[]) {\n+\t\t\t\tconst statement = prepared(query);\n+\t\t\t\tconst args = bindings.map(bind);\n+\t\t\t\tconst rows = statement.columns().length > 0 ? statement.all(...args) : (statement.run(...args), []);\n+\t\t\t\treturn {\n+\t\t\t\t\ttoArray: () =>\n+\t\t\t\t\t\t(rows as Record<string, unknown>[]).map((r) =>\n+\t\t\t\t\t\t\tObject.fromEntries(Object.entries(r).map(([k, v]) => [k, out(v)])),\n+\t\t\t\t\t\t),\n+\t\t\t\t};\n+\t\t\t},\n+\t\t},\n+\t\ttransactionSync<T>(fn: () => T): T {\n+\t\t\tconst name = `local_t${depth++}`;\n+\t\t\tdb.exec(`SAVEPOINT ${name}`);\n+\t\t\ttry {\n+\t\t\t\tconst value = fn();\n+\t\t\t\tdb.exec(`RELEASE ${name}`);\n+\t\t\t\treturn value;\n+\t\t\t} catch (e) {\n+\t\t\t\tdb.exec(`ROLLBACK TO ${name}; RELEASE ${name}`);\n+\t\t\t\tthrow e;\n+\t\t\t} finally {\n+\t\t\t\tdepth--;\n+\t\t\t}\n+\t\t},\n+\t\tasync transaction<T>(fn: (txn: unknown) => Promise<T>): Promise<T> {\n+\t\t\treturn fn(storage);\n+\t\t},\n+\t\tasync get(key: string | string[]) {\n+\t\t\tif (typeof key === \"string\") return kvGet(key);\n+\t\t\treturn new Map(key.flatMap((k) => (kvGet(k) === undefined ? [] : [[k, kvGet(k)] as const])));\n+\t\t},\n+\t\tasync put(key: string | Record<string, unknown>, value?: unknown) {\n+\t\t\tif (typeof key === \"string\") kvPut(key, value);\n+\t\t\telse for (const [k, v] of Object.entries(key)) kvPut(k, v);\n+\t\t},\n+\t\tasync delete(key: string | string[]) {\n+\t\t\tif (typeof key === \"string\") return kvDelete(key);\n+\t\t\treturn key.filter(kvDelete).length;\n+\t\t},\n+\t\tasync list(options: { prefix?: string } = {}) {\n+\t\t\tconst rows = prepared(\"SELECT key, value FROM _local_kv WHERE key >= ? ORDER BY key\").all(\n+\t\t\t\toptions.prefix ?? \"\",\n+\t\t\t) as { key: string; value: Uint8Array }[];\n+\t\t\treturn new Map(\n+\t\t\t\trows.filter((r) => r.key.startsWith(options.prefix ?? \"\")).map((r) => [r.key, deserialize(r.value)]),\n+\t\t\t);\n+\t\t},\n+\t\t// The alarm is kept, but nothing in a local project needs it: it pushes out to Artifacts, which is off here.\n+\t\tasync getAlarm() {\n+\t\t\tconst row = prepared(\"SELECT at FROM _local_alarm WHERE id = 0\").get() as { at: number | null } | undefined;\n+\t\t\treturn row?.at ?? null;\n+\t\t},\n+\t\tasync setAlarm(at: number | Date) {\n+\t\t\tprepared(\"INSERT INTO _local_alarm (id, at) VALUES (0, ?) ON CONFLICT (id) DO UPDATE SET at = excluded.at\").run(\n+\t\t\t\tNumber(at),\n+\t\t\t);\n+\t\t},\n+\t\tasync deleteAlarm() {\n+\t\t\tprepared(\"DELETE FROM _local_alarm WHERE id = 0\").run();\n+\t\t},\n+\t};\n+\treturn storage;\n+}\n+\n+/** Workers' crypto.DigestStream, which the blob store hashes uploads with. */\n+async function installDigestStream(): Promise<void> {\n+\t// Through a cast: abso's worker compiles this file too (tool.lock.json), and its types have no globalThis.crypto.\n+\tconst c = (globalThis as unknown as { crypto: { DigestStream?: unknown } }).crypto;\n+\tif (c.DigestStream) return;\n+\tconst { createHash } = await import(\"node:crypto\");\n+\tclass DigestStream extends WritableStream<Uint8Array> {\n+\t\treadonly digest: Promise<ArrayBuffer>;\n+\t\tconstructor(algorithm: string) {\n+\t\t\tconst hash = createHash(algorithm.replace(\"-\", \"\").toLowerCase());\n+\t\t\tlet done!: (b: ArrayBuffer) => void;\n+\t\t\tconst digest = new Promise<ArrayBuffer>((ok) => {\n+\t\t\t\tdone = ok;\n+\t\t\t});\n+\t\t\tsuper({\n+\t\t\t\twrite: (chunk) => void hash.update(chunk),\n+\t\t\t\tclose: () => {\n+\t\t\t\t\tconst b = hash.digest();\n+\t\t\t\t\tdone(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer);\n+\t\t\t\t},\n+\t\t\t});\n+\t\t\tthis.digest = digest;\n+\t\t}\n+\t}\n+\tc.DigestStream = DigestStream;\n+}\n+\n+// --- Loading the server's code ------------------------------------------------------------------------------------\n+\n+type Server = {\n+\tDatabaseSync: new (path: string) => Db;\n+\thandle: (request: Request, env: unknown, ctx: unknown, issues: unknown) => Promise<Response>;\n+\tProjectObject: new (ctx: unknown, env: unknown) => object;\n+\tIssueProject: new (ctx: unknown, env: unknown) => object;\n+\tissuesFetch: (request: Request, env: unknown, ctx: unknown, route: unknown) => Promise<Response>;\n+};\n+let server: Promise<Server> | undefined;\n+\n+/** Node's SQLite says it's experimental on every start; that line would land in every local command's output. */\n+function quietSqliteWarning(): void {\n+\tconst emit = process.emitWarning;\n+\tif ((emit as { quiet?: boolean }).quiet) return;\n+\tconst quiet = ((warning: string | Error, ...rest: unknown[]) => {\n+\t\tconst text = typeof warning === \"string\" ? warning : warning.message;\n+\t\tif (text.startsWith(\"SQLite is an experimental feature\")) return;\n+\t\treturn (emit as (...a: unknown[]) => void).call(process, warning, ...rest);\n+\t}) as typeof process.emitWarning;\n+\t(quiet as unknown as { quiet: boolean }).quiet = true;\n+\tprocess.emitWarning = quiet;\n+}\n+\n+export const NODE_TOO_OLD = `local projects need Node 22.13 or later, for its built-in SQLite; this is Node ${process.versions.node}`;\n+\n+function loadServer(): Promise<Server> {\n+\tserver ??= (async () => {\n+\t\tquietSqliteWarning();\n+\t\tlet sqlite: { DatabaseSync: Server[\"DatabaseSync\"] };\n+\t\ttry {\n+\t\t\tsqlite = (await import(\"node:sqlite\")) as unknown as typeof sqlite;\n+\t\t} catch {\n+\t\t\tthrow new LocalError(NODE_TOO_OLD);\n+\t\t}\n+\t\tawait installDigestStream();\n+\t\t// Run as .ts files, the server's `import { DurableObject } from \"cloudflare:workers\"` needs a stand-in. A built\n+\t\t// copy has it already: the build points the import at the same file (scripts/build-client.mjs).\n+\t\tconst standIn = new URL(\"./durable-object-stand-in.ts\", import.meta.url).href;\n+\t\tconst mod = (await import(\"node:module\")) as unknown as {\n+\t\t\tregisterHooks?: (hooks: unknown) => unknown;\n+\t\t};\n+\t\t// The hook stays for the rest of the process: deregistering it crashes Node 24 at exit when the compile cache\n+\t\t// is on (client/avcs.ts turns it on). It answers only cloudflare:workers.\n+\t\tmod.registerHooks?.({\n+\t\t\tresolve(specifier: string, context: unknown, next: (s: string, c: unknown) => unknown) {\n+\t\t\t\tif (specifier === \"cloudflare:workers\") return { url: standIn, shortCircuit: true };\n+\t\t\t\treturn next(specifier, context);\n+\t\t\t},\n+\t\t});\n+\t\tlet loaded: typeof import(\"./local-server.mjs\");\n+\t\ttry {\n+\t\t\tloaded = await import(\"./local-server.mjs\");\n+\t\t} catch (e) {\n+\t\t\t// Nothing is reached for here: a part of the client is missing (its packages not installed, say).\n+\t\t\tthrow new LocalError(\n+\t\t\t\t`local projects couldn't load the server's code: ${e instanceof Error ? e.message : String(e)}`,\n+\t\t\t);\n+\t\t}\n+\t\treturn {\n+\t\t\tDatabaseSync: sqlite.DatabaseSync,\n+\t\t\thandle: loaded.handle,\n+\t\t\tProjectObject: loaded.ProjectObject,\n+\t\t\tIssueProject: loaded.IssueProject,\n+\t\t\tissuesFetch: loaded.issuesFetch,\n+\t\t};\n+\t})();\n+\treturn server;\n+}\n+\n+/** What stops a local project from opening at all: said plainly, like a usage error. */\n+export class LocalError extends UsageError {}\n+\n+// --- One store, as a fetch -----------------------------------------------------------------------------------------\n+\n+interface Open {\n+\tdb: Db;\n+\tstorage: ReturnType<typeof storageOver>;\n+\tobject: object | undefined;\n+\t/** PRAGMA data_version when this process last used the project: it changes when another process writes. */\n+\tseen: number | undefined;\n+\t/** The project's issues, asks and news: issues.sqlite beside it, opened when a call first reaches them. */\n+\tissues?: { db: Db; storage: ReturnType<typeof storageOver> };\n+\t/** The issues object for the call under way: made again for each call, as another process may have written. */\n+\tissueObject?: object;\n+}\n+\n+/** Every store file this process has open: closed when its command ends (closeLocalStores). */\n+const opened = new Set<Db>();\n+\n+/** Closes every local project this process opened. Its next call opens them again. */\n+export function closeLocalStores(): void {\n+\tfor (const db of opened) {\n+\t\ttry {\n+\t\t\tdb.close();\n+\t\t} catch {}\n+\t}\n+\topened.clear();\n+}\n+\n+/** A project's calls, and its issues, asks and news, which the open server keeps at /issues/p/<project>/. */\n+const PROJECT_PATH = /^(?:\\/issues)?\\/p\\/([^/]+)\\//;\n+/** A project's name is also its folder in the store, so it never starts with a dot (\".\" and \"..\" would leave it). */\n+const NAME = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,99}$/;\n+const json = (status: number, body: unknown) => Response.json(body, { status });\n+\n+/**\n+ * The fetch a local folder's calls go through: each call is answered by the open server's router, in this process,\n+ * against the project's SQLite file in `dir`. Only init makes a project's file.\n+ */\n+export function localFetch(dir: string): (input: string, init?: RequestInit) => Promise<Response> {\n+\tconst open = new Map<string, Open>();\n+\tlet opening: Server | undefined;\n+\tconst openProject = (name: string, create: boolean): Open | undefined => {\n+\t\tconst existing = open.get(name);\n+\t\tif (existing && opened.has(existing.db)) return existing;\n+\t\tconst folder = join(dir, name);\n+\t\tconst file = join(folder, \"project.sqlite\");\n+\t\tif (create) mkdirSync(folder, { recursive: true });\n+\t\telse if (!existsSync(file)) return undefined;\n+\t\tconst db = new opening!.DatabaseSync(file);\n+\t\topened.add(db);\n+\t\tdb.exec(\"PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 120000; PRAGMA synchronous = NORMAL\");\n+\t\tconst project = { db, storage: storageOver(db), object: undefined, seen: undefined };\n+\t\topen.set(name, project);\n+\t\treturn project;\n+\t};\n+\tconst env = (name: string) => ({\n+\t\tABSO_TOKEN: LOCAL_TOKEN,\n+\t\tABSO_ARTIFACTS: \"off\",\n+\t\tABSO_DISK_FIRST: \"off\",\n+\t\tPROJECT: {\n+\t\t\tidFromName: (n: string) => n,\n+\t\t\tget: (n: string) => {\n+\t\t\t\tconst p = open.get(n);\n+\t\t\t\tif (!p || n !== name) throw new LocalError(`no local project ${n}`);\n+\t\t\t\tp.object ??= new opening!.ProjectObject(\n+\t\t\t\t\t{ id: { toString: () => n, name: n }, storage: p.storage, waitUntil: () => {} },\n+\t\t\t\t\tenv(name),\n+\t\t\t\t);\n+\t\t\t\treturn p.object;\n+\t\t\t},\n+\t\t},\n+\t\tISSUES_DO: {\n+\t\t\tidFromName: (n: string) => n,\n+\t\t\tget: (n: string) => {\n+\t\t\t\tconst p = open.get(n);\n+\t\t\t\tif (!p || n !== name) throw new LocalError(`no local project ${n}`);\n+\t\t\t\tif (p.issues === undefined || !opened.has(p.issues.db)) {\n+\t\t\t\t\tconst db = new opening!.DatabaseSync(join(dir, name, \"issues.sqlite\"));\n+\t\t\t\t\topened.add(db);\n+\t\t\t\t\tdb.exec(\"PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 120000; PRAGMA synchronous = NORMAL\");\n+\t\t\t\t\tp.issues = { db, storage: storageOver(db) };\n+\t\t\t\t}\n+\t\t\t\t// Its writes need no lock of their own: every call holds the project file's (see below).\n+\t\t\t\tp.issueObject ??= new opening!.IssueProject(\n+\t\t\t\t\t{ id: { toString: () => n, name: n }, storage: p.issues.storage },\n+\t\t\t\t\tenv(name),\n+\t\t\t\t);\n+\t\t\t\treturn p.issueObject;\n+\t\t\t},\n+\t\t},\n+\t});\n+\t// One call at a time, as a Durable Object takes them: a call holds its project's write transaction across awaits,\n+\t// and the connection can't start a second (two calls at once come from Promise.all in ci and waiting --mine).\n+\tlet last: Promise<unknown> = Promise.resolve();\n+\treturn (input, init) => {\n+\t\tconst next = last.then(\n+\t\t\t() => call(input, init),\n+\t\t\t() => call(input, init),\n+\t\t);\n+\t\tlast = next.catch(() => {});\n+\t\treturn next;\n+\t};\n+\n+\tasync function call(input: string, init: RequestInit = {}): Promise<Response> {\n+\t\tconst s = await loadServer();\n+\t\topening = s;\n+\t\tconst url = new URL(input);\n+\t\tconst match = PROJECT_PATH.exec(url.pathname);\n+\t\tif (!match) return json(404, { error: \"a local store answers only project calls\" });\n+\t\tconst name = decodeURIComponent(match[1]!);\n+\t\tif (!NAME.test(name)) return json(400, { error: \"project names use letters, digits, '.', '_' and '-'\" });\n+\t\tconst p = openProject(name, url.pathname === `/p/${match[1]}/init`);\n+\t\tif (!p) return json(404, { error: `no local project ${name} in ${dir}` });\n+\t\tconst headers = new Headers(init.headers);\n+\t\theaders.set(\"authorization\", `Bearer ${LOCAL_TOKEN}`);\n+\t\tconst request = new Request(url, { ...init, headers });\n+\t\tconst waits: Promise<unknown>[] = [];\n+\t\t// Every call, issues ones too, holds the project file's lock, so local writers of the project and of its\n+\t\t// issues take one lock in one order.\n+\t\tp.db.exec(\"BEGIN IMMEDIATE\");\n+\t\tp.issueObject = undefined;\n+\t\ttry {\n+\t\t\tconst version = (p.db.prepare(\"PRAGMA data_version\").get() as { data_version: number }).data_version;\n+\t\t\tif (p.seen !== undefined && version !== p.seen) p.object = undefined;\n+\t\t\tconst response = await s.handle(\n+\t\t\t\trequest,\n+\t\t\t\tenv(name),\n+\t\t\t\t{ waitUntil: (w: Promise<unknown>) => waits.push(w) },\n+\t\t\t\ts.issuesFetch,\n+\t\t\t);\n+\t\t\tawait Promise.allSettled(waits);\n+\t\t\t// The answer is read whole before the write is kept, so a body that fails to arrive keeps nothing either.\n+\t\t\tconst body = await response.arrayBuffer();\n+\t\t\tp.db.exec(\"COMMIT\");\n+\t\t\tp.seen = (p.db.prepare(\"PRAGMA data_version\").get() as { data_version: number }).data_version;\n+\t\t\treturn new Response(body, { status: response.status, headers: response.headers });\n+\t\t} catch (e) {\n+\t\t\ttry {\n+\t\t\t\tp.db.exec(\"ROLLBACK\");\n+\t\t\t} catch {}\n+\t\t\t// What the object held in memory may be from the rolled-back call.\n+\t\t\tp.object = undefined;\n+\t\t\tp.seen = undefined;\n+\t\t\tif (e instanceof LocalError) throw e;\n+\t\t\t// Where the Workers runtime answers a throw with a 500, so does this.\n+\t\t\treturn json(500, { error: e instanceof Error ? e.message : String(e) });\n+\t\t}\n+\t}\n+}"},{"path":"client/src/main.ts","added":66,"removed":22,"diff":"--- a/client/src/main.ts\n+++ b/client/src/main.ts\n@@ -1,8 +1,8 @@\n // The command table and the dispatcher. main() returns what to print and the\n // exit code instead of printing, so tests can call it directly.\n \n-import { readFileSync } from \"node:fs\";\n-import { resolve } from \"node:path\";\n+import { existsSync, readFileSync } from \"node:fs\";\n+import { join, resolve } from \"node:path\";\n import { runAnnounce, runNews, runStart } from \"./announce.ts\";\n import { ApiError } from \"./api.ts\";\n import { bool, type FlagSpec, type Parsed, parseArgs, str, UsageError } from \"./args.ts\";\n@@ -38,7 +38,7 @@\n \trunSync,\n \ttakeNews,\n } from \"./commands.ts\";\n-import { configPath, findRoot, installKey, isVisitor, readConfig, tokenFile } from \"./config.ts\";\n+import { configPath, findRoot, installKey, isVisitor, readConfig, runKey, tokenFile } from \"./config.ts\";\n import { newsBlockLines, newsShown } from \"./core.ts\";\n import { doctor, doctorText, plainError, realProbe, whoami } from \"./doctor.ts\";\n import { runDraftSync, runLand, runSwitch } from \"./drafts.ts\";\n@@ -59,6 +59,7 @@\n \trunWaiting,\n } from \"./issues.ts\";\n import { adminToken, adminTokenWords, issuedPublic, keyList, keyListText, keyNew, keyRevoke } from \"./key-admin.ts\";\n+import { closeLocalStores } from \"./local-store.ts\";\n import { browserSkip, openInBrowser } from \"./open-browser.ts\";\n import { runOrg, runOrgs } from \"./orgs.ts\";\n import { runUnqueue } from \"./queue.ts\";\n@@ -73,10 +74,12 @@\n \tserverUse,\n } from \"./server-choice.ts\";\n import { installSkill, SKILL, skillPath } from \"./skill.ts\";\n+import { stateDir } from \"./state-dir.ts\";\n import { colorsPass, terminalText } from \"./terminal-text.ts\";\n import { runAmend, runDrop, runFollow, runLabel, runLabels, runPluck } from \"./versions.ts\";\n import { runVisibility } from \"./visibility-commands.ts\";\n import { checkVisitor } from \"./visitor.ts\";\n+import { handoffText, patFromFile, webLogin } from \"./web-session.ts\";\n \n interface CommandDef {\n \treadonly flags: FlagSpec;\n@@ -120,11 +123,13 @@\n \t\t\tpublic: \"boolean\",\n \t\t\tprivate: \"boolean\",\n \t\t\t\"token-file\": \"boolean\",\n+\t\t\tlocal: \"boolean\",\n+\t\t\tstore: \"string\",\n \t\t},\n \t\tusage:\n-\t\t\t\"abso init [folder] --project <name> [--agent <name>] [--as-is] [--org <org>] [--public|--private] [--token-file]\",\n+\t\t\t\"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]\",\n \t\tabout:\n-\t\t\t\"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.\",\n+\t\t\t\"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.\",\n \t\trun: (args, env) => runInit(args, env),\n \t},\n \tkey: {\n@@ -140,7 +145,7 @@\n \t\tusage:\n \t\t\t\"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>]\",\n \t\tabout:\n-\t\t\t\"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.\",\n+\t\t\t\"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.\",\n \t\trun: async (args, env) => {\n \t\t\tconst sub = args.positionals[0];\n \t\t\tif (sub === \"install\" && args.positionals.length === 1) return runKeyInstall(args, env);\n@@ -208,13 +213,32 @@\n \t\t\tprojects: \"string\",\n \t\t\trole: \"string\",\n \t\t\tdays: \"string\",\n+\t\t\tweb: \"boolean\",\n+\t\t\tsite: \"string\",\n+\t\t\t\"pat-file\": \"string\",\n \t\t},\n \t\tusage:\n-\t\t\t\"abso login [--no-browser] [--no-ask] [--projects <name,name>] [--role <reader|writer|owner>] [--days <1-90>]\",\n+\t\t\t\"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>]]\",\n \t\tabout:\n-\t\t\t\"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.\",\n+\t\t\t\"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).\",\n \t\trun: async (args, env) => {\n \t\t\tconst server = boxServer(args, env);\n+\t\t\tif (bool(args, \"web\")) {\n+\t\t\t\tconst patFile = str(args, \"pat-file\");\n+\t\t\t\tconst { handoff, site } = await webLogin({\n+\t\t\t\t\tserver,\n+\t\t\t\t\tsite: str(args, \"site\"),\n+\t\t\t\t\tkind: patFile === undefined ? \"box\" : \"pat\",\n+\t\t\t\t\tcredential: () => {\n+\t\t\t\t\t\tif (patFile !== undefined) return patFromFile(patFile);\n+\t\t\t\t\t\tconst record = readBox(server);\n+\t\t\t\t\t\tif (record === undefined || record.expiresAt <= Date.now())\n+\t\t\t\t\t\t\tthrow new UsageError(`this box isn't signed in to ${server}: abso login first, or --pat-file <file>`);\n+\t\t\t\t\t\treturn record.credential;\n+\t\t\t\t\t},\n+\t\t\t\t});\n+\t\t\t\treturn { text: handoffText(handoff, site, patFile === undefined), json: { ...handoff } };\n+\t\t\t}\n \t\t\tconst open =\n \t\t\t\tbool(args, \"no-browser\") || browserSkip(env.env, process.platform) !== null\n \t\t\t\t\t? undefined\n@@ -326,10 +350,19 @@\n \t\t},\n \t},\n \tjoin: {\n-\t\tflags: { server: \"string\", agent: \"string\", dir: \"string\", reader: \"boolean\", \"token-file\": \"boolean\" },\n-\t\tusage: \"abso join <project> [--agent <name>] [--dir <folder>] [--reader] [--token-file]\",\n+\t\tflags: {\n+\t\t\tserver: \"string\",\n+\t\t\tagent: \"string\",\n+\t\t\tdir: \"string\",\n+\t\t\treader: \"boolean\",\n+\t\t\t\"token-file\": \"boolean\",\n+\t\t\tlocal: \"boolean\",\n+\t\t\tstore: \"string\",\n+\t\t},\n+\t\tusage:\n+\t\t\t\"abso join <project> [--agent <name>] [--dir <folder>] [--reader] [--token-file] | abso join <project> --local [--agent <name>] [--store <folder>] [--dir <folder>]\",\n \t\tabout:\n-\t\t\t\"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.\",\n+\t\t\t\"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.\",\n \t\trun: runJoin,\n \t},\n \trecord: {\n@@ -352,7 +385,7 @@\n \t\t},\n \t\tusage: 'abso push -m \"<why>\" [--as-is] [--check [\"<command>\"]] [--wait <seconds> | --no-wait] [--done]',\n \t\tabout:\n-\t\t\t'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.',\n+\t\t\t'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.',\n \t\trun: runPublish,\n \t},\n \tbisect: {\n@@ -400,7 +433,7 @@\n \t\tusage:\n \t\t\t'abso run [--detach] [--replace] [--fresh] [--box <name>] [--at <version> [--files <glob>]] <command...> | abso run ... -- <program> <arg...> | abso run --parallel \"<command>\" \"<command>\"...',\n \t\tabout:\n-\t\t\t\"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.\",\n+\t\t\t\"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.\",\n \t\trest: true,\n \t\trun: runRun,\n \t},\n@@ -615,7 +648,7 @@\n \t\tflags: { version: \"string\", revoke: \"boolean\" },\n \t\tusage: \"abso ci [<version>] | abso ci --revoke\",\n \t\tabout:\n-\t\t\t\"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.\",\n+\t\t\t\"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.\",\n \t\trun: runCi,\n \t},\n \tshot: {\n@@ -641,7 +674,7 @@\n \t\tusage:\n \t\t\t'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>]',\n \t\tabout:\n-\t\t\t\"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.\",\n+\t\t\t\"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.\",\n \t\trun: runShot,\n \t},\n \tprep: {\n@@ -857,7 +890,7 @@\n \t\tusage:\n \t\t\t\"abso pipeline check [file] [--on push|draft|green|land|hand|schedule [--space <name>] [--pipeline <name>] [--every <when>]] | abso pipeline runs [<run>] [--log <pipeline.job>]\",\n \t\tabout:\n-\t\t\t\"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.\",\n+\t\t\t\"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.\",\n \t\t// Loaded only here, so the yaml package it needs can't stop every other command\n \t\t// when a checkout lacks it (abso issue 168).\n \t\trun: async (args, env) => {\n@@ -962,14 +995,16 @@\n }\n \n /** Whether this folder's calls carry a key or token, for how a refusal is worded. False when that can't be told. */\n-function carriesCredential(env: Env, tokenFileAsked: boolean): boolean {\n+function credentialSent(env: Env, tokenFileAsked: boolean): string | undefined {\n \ttry {\n \t\tconst root = findRoot(env.cwd);\n-\t\treturn root\n-\t\t\t? readConfig(root, env.env, tokenFileAsked).token !== undefined\n-\t\t\t: (fromEnv(env.env, \"TOKEN\") ?? (tokenFileAsked ? tokenFile() : undefined)) !== undefined;\n+\t\tif (root && readConfig(root, env.env, tokenFileAsked).token === undefined) return undefined;\n+\t\tif (root && existsSync(join(stateDir(root), \"key\"))) return \"this folder's key\";\n+\t\tif (fromEnv(env.env, \"TOKEN\")?.trim()) return \"ABSO_TOKEN\";\n+\t\tif (root && runKey(env.env)) return \"this pipeline run's key\";\n+\t\treturn tokenFileAsked && tokenFile() !== undefined ? \"the token file, ~/.abso/token\" : undefined;\n \t} catch {\n-\t\treturn false;\n+\t\treturn undefined;\n \t}\n }\n \n@@ -986,6 +1021,15 @@\n }\n \n export async function main(argv: readonly string[], env: Env): Promise<MainResult> {\n+\ttry {\n+\t\treturn await runMain(argv, env);\n+\t} finally {\n+\t\t// A local project's store stays open only while its command runs.\n+\t\tcloseLocalStores();\n+\t}\n+}\n+\n+async function runMain(argv: readonly string[], env: Env): Promise<MainResult> {\n \tconst command = argv[0];\n \tconst json = argv.includes(\"--json\") && command !== \"run\" && command !== \"logs\";\n \tconst asked = argv.includes(\"--token-file\");\n@@ -1079,7 +1123,7 @@\n \t\tconst e = err as Error;\n \t\tconst code = err instanceof UsageError ? \"usage\" : err instanceof ApiError ? \"server\" : \"error\";\n \t\tconst message =\n-\t\t\tplainError(err, carriesCredential(env, asked), !asked && tokenFile() !== undefined) ??\n+\t\t\tplainError(err, credentialSent(env, asked), !asked && tokenFile() !== undefined) ??\n \t\t\t(err instanceof UsageError || err instanceof ApiError\n \t\t\t\t? e.message\n \t\t\t\t: `${e.message}${e.stack ? `\\n${e.stack}` : \"\"}`);"},{"path":"client/src/news-stream.ts","added":60,"removed":5,"diff":"--- a/client/src/news-stream.ts\n+++ b/client/src/news-stream.ts\n@@ -15,9 +15,16 @@\n export interface NewsTicket {\n \treadonly url: string;\n \treadonly protocols: readonly string[];\n-\treadonly expiresAt: number;\n+\t/** When the ticket stops working: the server sends an ISO time; milliseconds are taken too. */\n+\treadonly expiresAt: number | string;\n }\n \n+/** A ticket's expiry in milliseconds, whichever form the server sent; now when it can't be read. */\n+export function expiresAtMs(ticket: NewsTicket, now: number): number {\n+\tconst at = typeof ticket.expiresAt === \"number\" ? ticket.expiresAt : Date.parse(ticket.expiresAt);\n+\treturn Number.isFinite(at) ? at : now;\n+}\n+\n /** A Monitor lasts at most 30 minutes; the skill re-arms it when it ends. */\n export const MONITOR_TIMEOUT_MS = 30 * 60_000;\n \n@@ -36,7 +43,7 @@\n \n /** The text --stream prints: the call to make, then the arguments as one line of JSON. */\n export function streamText(ticket: NewsTicket, project: string, agent: string, now = Date.now()): string {\n-\tconst seconds = Math.max(0, Math.round((ticket.expiresAt - now) / 1000));\n+\tconst seconds = Math.max(0, Math.round((expiresAtMs(ticket, now) - now) / 1000));\n \treturn [\n \t\t`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.`,\n \t\tJSON.stringify(monitorArgs(ticket, project, agent)),\n@@ -48,7 +55,7 @@\n \n /** How long --stream's mark holds: the Monitor's 30 minutes, and the minute the ticket waits to be used. */\n export function streamMarkUntil(ticket: NewsTicket, now: number): number {\n-\treturn Math.max(now, ticket.expiresAt) + MONITOR_TIMEOUT_MS;\n+\treturn Math.max(now, expiresAtMs(ticket, now)) + MONITOR_TIMEOUT_MS;\n }\n \n /** The part of a WebSocket --follow uses: the platform's own, or a test's. */\n@@ -87,6 +94,8 @@\n \tsleep(ms: number): Promise<void>;\n \tnow(): number;\n \tevery(ms: number, fn: () => void): () => void;\n+\t/** Reads the seat's news, marking it heard (POST news); a frame calls it. Without it, frames are printed as they come. */\n+\ttake?(): Promise<readonly string[]>;\n \t/** Called when a socket opens and at each ping: the stream is held until the next ping is due, and a little more. */\n \theld?(until: number): void;\n \t/** Set when --follow should stop (Ctrl-C, or a test). */\n@@ -100,10 +109,55 @@\n }\n \n /**\n+ * A frame is a wake (abso 690): on one, read the seat's news (which marks it heard) and print what that answers, one\n+ * read at a time, with frames that arrive meanwhile folded into one more read. When the read answers nothing (a server\n+ * that counts a frame as heard already, or another chat on the seat took it first), the frames themselves are printed.\n+ */\n+function frameReads(deps: FollowDeps): { frame(text: string): void; idle(): Promise<void> } {\n+\tlet frames: string[] = [];\n+\t/** The lines printed lately, so a frame a read already printed isn't printed again. */\n+\tconst shown: string[] = [];\n+\tconst show = (line: string) => {\n+\t\tdeps.write(line);\n+\t\tshown.push(line);\n+\t\tif (shown.length > 200) shown.shift();\n+\t};\n+\tlet running: Promise<void> | undefined;\n+\tlet again = false;\n+\tconst pass = async () => {\n+\t\tdo {\n+\t\t\tagain = false;\n+\t\t\tconst these = frames;\n+\t\t\tframes = [];\n+\t\t\tlet items: readonly string[] = [];\n+\t\t\ttry {\n+\t\t\t\titems = await deps.take!();\n+\t\t\t} catch (err) {\n+\t\t\t\tdeps.note(`(abso news --follow: couldn't read the news: ${(err as Error).message}; showing the frames)`);\n+\t\t\t}\n+\t\t\tfor (const line of items) show(line);\n+\t\t\t// A frame the read didn't cover still shows: on a server that counts a frame as heard, its item never comes back\n+\t\t\t// from the read. A catch-up frame names several items, so a frame holding a shown item counts as covered.\n+\t\t\tfor (const frame of these) if (!shown.some((line) => frame.includes(line) || line.includes(frame))) show(frame);\n+\t\t} while (again);\n+\t\trunning = undefined;\n+\t};\n+\treturn {\n+\t\tframe(text) {\n+\t\t\tframes.push(text);\n+\t\t\tif (running !== undefined) again = true;\n+\t\t\telse running = pass();\n+\t\t},\n+\t\tidle: () => running ?? Promise.resolve(),\n+\t};\n+}\n+\n+/**\n  * Holds the seat's stream, printing one line per item, until the key is refused or `stopped()`.\n  * Returns why it ended.\n  */\n export async function follow(deps: FollowDeps): Promise<{ ended: \"refused\" | \"stopped\"; reason: string }> {\n+\tconst reads = frameReads(deps);\n \tlet wait = 1_000;\n \twhile (!deps.stopped()) {\n \t\tlet ticket: NewsTicket;\n@@ -132,12 +186,13 @@\n \t\t\t};\n \t\t\tsocket.onmessage = (e) => {\n \t\t\t\tif (typeof e.data !== \"string\" || e.data === PONG) return;\n-\t\t\t\tdeps.write(e.data);\n+\t\t\t\tif (deps.take === undefined) deps.write(e.data);\n+\t\t\t\telse reads.frame(e.data);\n \t\t\t};\n \t\t\tsocket.onerror = () => {};\n \t\t\tsocket.onclose = (e) => {\n \t\t\t\tstopPing();\n-\t\t\t\tdone({ code: e.code, reason: e.reason });\n+\t\t\t\tvoid reads.idle().then(() => done({ code: e.code, reason: e.reason }));\n \t\t\t};\n \t\t});\n \t\tif (isRefusal(closed.code)) return { ended: \"refused\", reason: closed.reason || `closed ${closed.code}` };"},{"path":"client/src/publish-commands.ts","added":6,"removed":0,"diff":"--- a/client/src/publish-commands.ts\n+++ b/client/src/publish-commands.ts\n@@ -13,6 +13,7 @@\n \tFOLDER_LOG_LIMIT,\n \tLISTED,\n \tmeantBinary,\n+\tpullUnfinished,\n \tREADER_REFUSES,\n \trecordedFirst,\n \trecordFolder,\n@@ -621,6 +622,8 @@\n \tconst { root, api } = open(env);\n \tconst recorded = await recordFolder(root, api);\n \tconst ignoredDropped = await dropIgnoredFromDraft(root, api);\n+\t// A pull here that never wrote its answer (abso-core 26): this one asks for every file to catch up.\n+\tconst catchingUp = pullUnfinished(root) && !bool(args, \"full\");\n \tconst s = await syncFolder(root, api, bool(args, \"full\"));\n \tconst changes = s.written.length + s.deleted.length;\n \t// A renamed file is one line, not an update and a delete.\n@@ -632,6 +635,9 @@\n \t\t...droppedIgnoredText(ignoredDropped),\n \t\t`Pulled to version ${s.version}: ${changes === 0 ? \"no files changed\" : `${plural(updated.length, \"file\")} updated, ${removed.length} deleted${s.renamed.length > 0 ? `, ${s.renamed.length} renamed` : \"\"}`}.`,\n \t\t...changedFilesText(\"pull\", updated, removed, s.renamed, bool(args, \"verbose\")),\n+\t\t...(catchingUp\n+\t\t\t? [\"The last pull here didn't finish, so this one asked for every file and wrote the ones that differed.\"]\n+\t\t\t: []),\n \t\t...refusedText(s.refused),\n \t\t// Ones an earlier sync couldn't write; this sync's are named just above.\n \t\t...unwrittenText(s.unwritten, new Set(s.refused.map((r) => r.path))),"},{"path":"client/src/serve-commands.ts","added":4,"removed":2,"diff":"--- a/client/src/serve-commands.ts\n+++ b/client/src/serve-commands.ts\n@@ -6,6 +6,7 @@\n import { boxOf, runRun, shellWord, undoGitBashPaths } from \"./box-commands.ts\";\n import { type Env, EXIT, type Output, open } from \"./command-env.ts\";\n import { fetchedText, fetchFromBox } from \"./fetch.ts\";\n+import { stateDir } from \"./state-dir.ts\";\n import { untarGz } from \"./tar.ts\";\n \n /** abso serve [--version N]: a preview of one version of shared at a stable URL, built once on the server (#37). */\n@@ -329,14 +330,15 @@\n \tif (image) {\n \t\tconst info = lines.find((l) => l.startsWith(\"ABSO_SHOT_IMAGE \"));\n \t\tconst { root, api } = open(env);\n-\t\tvoid root;\n \t\tapi.box = boxOf(args, env);\n \t\tconst gz = await api.boxFiles(`.abso-shot/${name}`);\n \t\tconst png = gz === null ? undefined : untarGz(gz).find((e) => e.path === `.abso-shot/${name}`);\n \t\tif (!png || !info)\n \t\t\treturn { exit: EXIT.error, text: \"The screenshot ran but its file was not in the box.\", json: { notes } };\n \t\tconst { w, h } = JSON.parse(info.slice(\"ABSO_SHOT_IMAGE \".length)) as { w: number; h: number };\n-\t\tconst path = resolve(env.cwd, str(args, \"out\") ?? join(\".avcs\", \"shots\", name));\n+\t\t// In the folder's own state folder (.abso/, or .avcs/ in an older folder), which abso never records.\n+\t\tconst path =\n+\t\t\tstr(args, \"out\") !== undefined ? resolve(env.cwd, str(args, \"out\")!) : join(stateDir(root), \"shots\", name);\n \t\tmkdirSync(join(path, \"..\"), { recursive: true });\n \t\twriteFileSync(path, png.data);\n \t\tshot = { path, w, h, bytes: png.data.length, tokens: imageTokens(w, h) };"},{"path":"client/src/status-commands.ts","added":7,"removed":2,"diff":"--- a/client/src/status-commands.ts\n+++ b/client/src/status-commands.ts\n@@ -14,6 +14,7 @@\n import {\n \tLISTED,\n \tleftOutText,\n+\tpullUnfinishedText,\n \tREADER_REFUSES,\n \treadUnwritten,\n \trecordedFirst,\n@@ -39,6 +40,7 @@\n } from \"./folder.ts\";\n import { fileArg } from \"./history.ts\";\n import { modsBehindText } from \"./install.ts\";\n+import { isLocal } from \"./local-store.ts\";\n import { withFolderLock } from \"./lock.ts\";\n import { readKnownModes, writeKnownModes } from \"./modes.ts\";\n import { queueText } from \"./queue.ts\";\n@@ -324,9 +326,11 @@\n \tconst space = (draft: string | null | undefined): string => (draft ? `draft ${draft}` : \"shared\");\n \tconst parked = (me?.parked ?? []).filter((p) => p.draftChanges > 0);\n \tconst credential = credentialLabel(root, config.server, env.env);\n-\tconst behind = await newerClientNote(config.server);\n+\t// A local project reaches for nothing on the network, npm included.\n+\tconst localProject = isLocal(config.server);\n+\tconst behind = localProject ? undefined : await newerClientNote(config.server);\n \tconst lines = [\n-\t\t`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}` : \"\"}.`,\n+\t\t`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}` : \"\"}.`}`,\n \t\t...(behind ? [behind] : []),\n \t\t// Is shared green (#39)? Right under the first line, since it decides what to do next.\n \t\t...ciText(status.ci, status.version),\n@@ -349,6 +353,7 @@\n \t\t...modsBehindText(env.env),\n \t\t...missingText(missing),\n \t\t...unwrittenText(unwritten),\n+\t\t...pullUnfinishedText(root),\n \t\t...(crlf.length > 0\n \t\t\t? [\n \t\t\t\t\t`${plural(crlf.length, \"file\")} differ${crlf.length === 1 ? \"s\" : \"\"} from what abso recorded only in line endings (CRLF here; abso records and abso run sends LF). Harmless; abso fix-eol rewrites ${crlf.length === 1 ? \"it\" : \"them\"} with LF.`,"},{"path":"client/src/versions.ts","added":14,"removed":2,"diff":"--- a/client/src/versions.ts\n+++ b/client/src/versions.ts\n@@ -3,7 +3,18 @@\n \n import type { VersionRef } from \"./api.ts\";\n import { bool, type Parsed, str, UsageError } from \"./args.ts\";\n-import { applyAnswer, collisionText, type Env, EXIT, type Output, open, plural, recordFolder } from \"./commands.ts\";\n+import {\n+\tapplyAnswer,\n+\tcollisionText,\n+\ttype Env,\n+\tEXIT,\n+\ttype Output,\n+\topen,\n+\tplural,\n+\tpullAnswer,\n+\tpullWritten,\n+\trecordFolder,\n+} from \"./commands.ts\";\n import { writeConfig } from \"./config.ts\";\n import { refusedText } from \"./safety.ts\";\n \n@@ -144,7 +155,8 @@\n \t// Sync now (recording first, as sync does), so the folder is where it now says it is.\n \tconst { api } = open(env);\n \tawait recordFolder(root, api);\n-\tconst s = await applyAnswer(root, api, await api.sync());\n+\tconst s = await applyAnswer(root, api, await pullAnswer(root, api));\n+\tpullWritten(root);\n \tconst changes = s.written.length + s.deleted.length;\n \tconst head = follow\n \t\t? `This folder now follows label ${follow}: every pull takes it to the newest version with that label. It is on version ${s.version}.`"},{"path":"client/src/web-session.ts","added":141,"removed":0,"diff":"--- /dev/null\n+++ b/client/src/web-session.ts\n@@ -0,0 +1,141 @@\n+// abso login --web: a staging website session for the person a box is signed in as, opened in an agent's own browser, with\n+// 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)\n+// and answers a one-use link that works for a minute; opening it signs that browser in. Only the link is printed: never the\n+// box's sign-in, the PAT or the session cookie, which the website sets in the browser itself.\n+\n+import { readFileSync } from \"node:fs\";\n+import { UsageError } from \"./args.ts\";\n+\n+/** The website beside each staging server. Prod has none here: agents never sign in to the website on prod. */\n+const STAGING_SITES: Readonly<Record<string, string>> = {\n+\t\"https://abso-staging.chrisazy.workers.dev\": \"https://abso-website-staging.chrisazy.workers.dev\",\n+\t\"https://avcs-staging.chrisazy.workers.dev\": \"https://abso-website-staging.chrisazy.workers.dev\",\n+};\n+\n+/** What the website answers: the link, when it stops working, and who and until when it signs in. */\n+export interface Handoff {\n+\treadonly url: string;\n+\treadonly expiresAt: string;\n+\treadonly account: string;\n+\treadonly name: string;\n+\treadonly sessionEnds: string;\n+}\n+\n+/**\n+ * The website a handoff's credential goes to (Security condition 6, Code Review): the staging website beside the folder's own\n+ * staging server, from the fixed list above, and never an origin from a flag. A server that isn't on the list is refused,\n+ * 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\n+ * takes no --site at all.\n+ */\n+export function siteFor(server: string, site: string | undefined, kind: \"box\" | \"pat\"): string {\n+\tconst origin = new URL(server).origin;\n+\tconst known = STAGING_SITES[origin];\n+\tif (known === undefined)\n+\t\tthrow new UsageError(\n+\t\t\t`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.`,\n+\t\t);\n+\tif (site === undefined) return known;\n+\tif (kind === \"box\")\n+\t\tthrow new UsageError(`--site isn't taken with a box's sign-in, which goes only to ${known}. Nothing was sent.`);\n+\tlet url: URL | null = null;\n+\ttry {\n+\t\turl = new URL(site);\n+\t} catch {\n+\t\t// Not an address: refused below.\n+\t}\n+\tif (url === null || url.protocol !== \"http:\" || (url.hostname !== \"localhost\" && url.hostname !== \"127.0.0.1\"))\n+\t\tthrow new UsageError(\n+\t\t\t\"--site, with --pat-file, names this machine only (http://localhost:<port> or http://127.0.0.1:<port>). Nothing was sent.\",\n+\t\t);\n+\treturn url.origin;\n+}\n+\n+/**\n+ * abso login --web: where the credential would go is settled before it is read, so a refusal reads and sends nothing\n+ * (Security). `credential` reads the box's sign-in or the PAT only once the website is one it may go to.\n+ */\n+export async function webLogin(options: {\n+\treadonly server: string;\n+\treadonly site: string | undefined;\n+\t/** A box's sign-in, or a test account's PAT (--pat-file). */\n+\treadonly kind: \"box\" | \"pat\";\n+\treadonly credential: () => string;\n+\treadonly fetcher?: typeof fetch;\n+}): Promise<{ handoff: Handoff; site: string }> {\n+\tconst site = siteFor(options.server, options.site, options.kind);\n+\treturn { handoff: await webHandoff(site, options.credential(), options.fetcher), site };\n+}\n+\n+/** A PAT from the file --pat-file names: read here, never printed. */\n+export function patFromFile(path: string): string {\n+\tlet text: string;\n+\ttry {\n+\t\ttext = readFileSync(path, \"utf8\").trim();\n+\t} catch {\n+\t\tthrow new UsageError(`--pat-file names ${path}, which abso can't read`);\n+\t}\n+\tif (!/^abso_pat_[A-Za-z0-9_-]{16,200}$/.test(text))\n+\t\tthrow new UsageError(`--pat-file names ${path}, which doesn't hold a PAT`);\n+\treturn text;\n+}\n+\n+/** Words from the website, with any secret this call sent taken out. */\n+function scrubbed(text: string, secret: string): string {\n+\treturn text.split(secret).join(\"[the credential]\").slice(0, 300);\n+}\n+\n+/** Asks the website for a handoff link with `credential` (a box sign-in or a PAT) in Authorization. */\n+export async function webHandoff(site: string, credential: string, fetcher: typeof fetch = fetch): Promise<Handoff> {\n+\tlet res: Response;\n+\ttry {\n+\t\tres = await fetcher(`${site}/login/handoff`, {\n+\t\t\tmethod: \"POST\",\n+\t\t\theaders: { authorization: `Bearer ${credential}`, accept: \"application/json\" },\n+\t\t\tredirect: \"error\",\n+\t\t\tsignal: AbortSignal.timeout(30_000),\n+\t\t});\n+\t} catch (err) {\n+\t\tthrow new UsageError(`couldn't reach ${site}: ${scrubbed((err as Error).message, credential)}`);\n+\t}\n+\tconst text = await res.text().catch(() => \"\");\n+\tlet body: Partial<Handoff> & { error?: unknown } = {};\n+\ttry {\n+\t\tbody = JSON.parse(text) as typeof body;\n+\t} catch {\n+\t\t// Not JSON: the status says enough.\n+\t}\n+\tif (!res.ok) {\n+\t\tconst why = typeof body.error === \"string\" ? body.error : `it answered ${res.status}`;\n+\t\tthrow new UsageError(\n+\t\t\tres.status === 404\n+\t\t\t\t? `${site} doesn't hand out sign-in links (its key sign-in is off, or it isn't staging)`\n+\t\t\t\t: `${site} refused: ${scrubbed(why, credential)}`,\n+\t\t);\n+\t}\n+\tif (\n+\t\ttypeof body.url !== \"string\" ||\n+\t\t!body.url.startsWith(`${site}/login/handoff#`) ||\n+\t\ttypeof body.expiresAt !== \"string\" ||\n+\t\ttypeof body.account !== \"string\"\n+\t)\n+\t\tthrow new UsageError(`${site} answered something that isn't a sign-in link`);\n+\treturn {\n+\t\turl: body.url,\n+\t\texpiresAt: body.expiresAt,\n+\t\taccount: body.account,\n+\t\tname: typeof body.name === \"string\" ? body.name : body.account,\n+\t\tsessionEnds: typeof body.sessionEnds === \"string\" ? body.sessionEnds : body.expiresAt,\n+\t};\n+}\n+\n+/** What abso login --web says: the one link, how long it works, who it signs in as, and what it reaches (Security). */\n+export function handoffText(h: Handoff, site: string, boxed = true, now = Date.now()): string {\n+\tconst seconds = Math.max(0, Math.round((Date.parse(h.expiresAt) - now) / 1000));\n+\tconst reach = boxed\n+\t\t? \"only to the projects this box was granted, at most as a writer, until the box is revoked or ends\"\n+\t\t: \"at most as a writer\";\n+\treturn [\n+\t\t`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}:`,\n+\t\th.url,\n+\t].join(\"\\n\");\n+}"}],"unmatched":[]}