{"draft":null,"from":3,"to":318,"files":[{"path":"client/src/join-commands.ts","added":454,"removed":56,"diff":"--- a/client/src/join-commands.ts\n+++ b/client/src/join-commands.ts\n@@ -1,32 +1,57 @@\n // abso init and abso join: start a project from a folder, or join one into a folder.\n \n-import { existsSync, mkdirSync, rmSync, statSync, writeFileSync } from \"node:fs\";\n-import { join, resolve } from \"node:path\";\n-import { Api, ApiError } from \"./api.ts\";\n+import { randomUUID } from \"node:crypto\";\n+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from \"node:fs\";\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 { mintKey, readBox } from \"./box.ts\";\n-import { STARTING_AVCSIGNORE } from \"./check-ignore.ts\";\n-import { CLIENT_DIR } from \"./client-version.ts\";\n+import {\n+\ttype BoxRecord,\n+\tboxCreateProject,\n+\tdefaultAgentName,\n+\tmintFreeName,\n+\tmintKey,\n+\ttype NewProject,\n+\treadBox,\n+} from \"./box.ts\";\n+import { STARTING_ABSOIGNORE } from \"./check-ignore.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 { AVCS_DIR, findRoot, installKey, readConfig, type Settings, tokenFor, writeConfig } from \"./config.ts\";\n+import { applyAnswer, leftOutText, pullAnswer, pullWritten, syncFolder, uploadBlobs } from \"./commands.ts\";\n+import {\n+\tfindRoot,\n+\tinstallKey,\n+\treadConfig,\n+\trunKey,\n+\ttype Settings,\n+\ttokenFile,\n+\ttrustedToken,\n+\twriteConfig,\n+} from \"./config.ts\";\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 { PROJECT_FILE, readProjectFile, startingProjectFileText, writeStartingProjectFile } from \"./project-file.ts\";\n+import { initInOrg, siteOf } from \"./orgs.ts\";\n+import { projectFileName, readProjectFile, startingProjectFileText, writeStartingProjectFile } from \"./project-file.ts\";\n import { refusedText } from \"./safety.ts\";\n+import { chooseServer, serverFlag } from \"./server-choice.ts\";\n+import { OLD_STATE_DIR, STATE_DIR, stateDir } from \"./state-dir.ts\";\n \n-function serverFrom(args: Parsed, env: Env): string {\n-\tconst server = str(args, \"server\") ?? env.env.AVCS_SERVER;\n-\tif (!server) throw new UsageError(\"give the server with --server <url> (or AVCS_SERVER)\");\n-\treturn server;\n+/** The server to join or start on, in the order every command picks one (server-choice.ts chooseServer). */\n+export function serverFrom(args: Parsed, env: Pick<Env, \"env\" | \"cwd\">): string {\n+\treturn chooseServer(serverFlag(args), env.cwd, env.env);\n }\n \n-function agentFrom(args: Parsed): string {\n-\tconst agent = str(args, \"agent\");\n+const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n+\n+function agentFrom(args: Parsed, named?: string): string {\n+\tconst agent = named ?? str(args, \"agent\");\n \tif (!agent) throw new UsageError(\"give this folder's agent name with --agent <name>\");\n-\tif (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(agent))\n+\tif (!NAME.test(agent))\n \t\tthrow new UsageError(`agent names are letters, digits, dot, dash and underscore (got ${JSON.stringify(agent)})`);\n \treturn agent;\n }\n@@ -35,29 +60,155 @@\n \treturn { server: serverFrom(args, env), project, agent: agentFrom(args) };\n }\n \n+/**\n+ * A new project has nothing in it yet: say what comes next, since the join itself wrote nothing. Not for a reader, which\n+ * can't push, or when files were already in the folder (the join's own line names them).\n+ */\n+export function emptyHint(version: number, written: number, kept: number, reader: boolean): string[] {\n+\tif (reader || version !== 0 || written > 0 || kept > 0) return [];\n+\treturn ['The project is empty. Put its files in this folder, then abso push -m \"why\" publishes them.'];\n+}\n+\n+/** A credential other than the box's, and how init and join name it when they say what they sign in with. */\n+export interface Credential {\n+\treadonly token: string | undefined;\n+\treadonly words: string;\n+}\n+\n+/**\n+ * What init and join sign in with when it isn't the box's sign-in. The machine's token file only with --token-file, and\n+ * never into a folder that already has a key; else a token the environment names (ABSO_TOKEN, or a pipeline run's\n+ * ABSO_KEY_FILE); else none. The token file is never read unasked, so a project is never made or joined with a shared\n+ * credential nobody chose.\n+ */\n+export function tokenCredential(\n+\targs: Parsed,\n+\tenv: Env[\"env\"],\n+\tserver: string,\n+\troot: string,\n+\tfile: () => string | undefined = tokenFile,\n+): Credential | undefined {\n+\tif (bool(args, \"token-file\")) {\n+\t\tif (existsSync(join(stateDir(root), \"key\")))\n+\t\t\tthrow new UsageError(`${root} already has a key, so it signs in with that: leave off --token-file`);\n+\t\tconst token = trustedToken(server, env, file());\n+\t\tif (!token) throw new UsageError(\"--token-file reads ~/.abso/token, and this machine has none\");\n+\t\treturn { token, words: \"the token file, ~/.abso/token, as --token-file asks\" };\n+\t}\n+\tconst named = fromEnv(env, \"TOKEN\")?.trim();\n+\tif (named) return { token: trustedToken(server, env, named), words: \"ABSO_TOKEN\" };\n+\tconst run = runKey(env);\n+\tif (run) return { token: trustedToken(server, env, run), words: \"a pipeline run's key (ABSO_KEY_FILE)\" };\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 export async function runInit(args: Parsed, env: Env): Promise<Output> {\n \tif (args.positionals.length > 1) throw new UsageError(\"init takes one folder\");\n \tconst root = resolve(env.cwd, args.positionals[0] ?? \".\");\n \tif (!existsSync(root) || !statSync(root).isDirectory()) throw new UsageError(`${root} is not a folder`);\n-\tif (findRoot(root) === root) throw new UsageError(`${root} already has .avcs/config.json`);\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-\tconst config = makeSettings(args, env, project);\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 = 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 (!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: 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 avcsignore = join(root, \".avcsignore\");\n-\tconst wroteIgnore = !asIs && !existsSync(avcsignore);\n-\tif (wroteIgnore) writeFileSync(avcsignore, STARTING_AVCSIGNORE);\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 = tokenFor(config.server, env.env);\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 token = credential?.token;\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 } : {}), ...(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@@ -71,14 +222,16 @@\n \t\t\t`Created project ${project} at version ${answer.version} from ${plural(files.size, \"text file\")} in ${root}.`,\n \t\t\t...leftOutText(leftOut),\n \t\t\t...(wroteIgnore\n-\t\t\t\t? [\"Wrote a starting .avcsignore (Claude Code state and operating system files); edit it like .gitignore.\"]\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`This folder is agent ${config.agent}. Settings are in .avcs/config.json.`,\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@@ -86,52 +239,287 @@\n \t\t\tfiles: files.size,\n \t\t\troot,\n \t\t\tagent: config.agent,\n-\t\t\twroteAvcsignore: wroteIgnore,\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 \n+/** The most a new project's folder may be from a box: the server takes a body up to 25 MB, base64 and JSON included. */\n+const BOX_INIT_MAX = 24 * 1024 * 1024;\n+/** The Idempotency-Key of an abso init that didn't finish, so running it again makes the same project (abso 663). */\n+const INIT_KEY = \"init-key\";\n+\n+/**\n+ * abso init from a signed-in box (abso 663): the server makes the project as the person who approved the box, the way the\n+ * website's New project does (owner, visibility, address), with the folder as its first version. This folder then\n+ * joins it like abso join, with its own key from the box, so it works at once with no new approval.\n+ */\n+async function initFromBox(\n+\targs: Parsed,\n+\tenv: Env,\n+\troot: string,\n+\tproject: string,\n+\tserver: string,\n+\tbox: BoxRecord,\n+): Promise<Output> {\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+\tconst named = str(args, \"agent\");\n+\tif (named !== undefined) agentFrom(args);\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+\tconst wroteProject = asIs ? \"exists\" : writeStartingProjectFile(root);\n+\tconst { files, blobs, leftOut } = readFolder(root, loadIgnore(root));\n+\tconst listed: NonNullable<NewProject[\"files\"]>[number][] = [\n+\t\t...[...files].map(([path, text]) => ({ path, text })),\n+\t\t...[...blobs].map(([path, b]) => ({ path, base64: Buffer.from(b.bytes).toString(\"base64\") })),\n+\t];\n+\tconst org = str(args, \"org\");\n+\tconst body: NewProject = {\n+\t\tname: project,\n+\t\t...(org === undefined ? {} : { owner: org }),\n+\t\t...(bool(args, \"public\")\n+\t\t\t? { visibility: \"public\" as const }\n+\t\t\t: bool(args, \"private\")\n+\t\t\t\t? { visibility: \"private\" as const }\n+\t\t\t\t: {}),\n+\t\t...(listed.length > 0 ? { files: listed } : {}),\n+\t};\n+\tif (JSON.stringify(body).length > BOX_INIT_MAX)\n+\t\tthrow new UsageError(\n+\t\t\t`${root} is over 24 MB to send. Make ${project} with abso init on a smaller folder (or on the website), then copy the rest in and push.`,\n+\t\t);\n+\t// One key per folder until it finishes: running the same abso init again is the same project, never a second.\n+\tconst keyPath = join(stateDir(root), INIT_KEY);\n+\tlet key = existsSync(keyPath) ? readFileSync(keyPath, \"utf8\").trim() : \"\";\n+\tif (!/^[0-9a-f-]{36}$/.test(key)) {\n+\t\tkey = randomUUID();\n+\t\tmkdirSync(stateDir(root), { recursive: true });\n+\t\twriteFileSync(keyPath, key);\n+\t}\n+\tconst made = await boxCreateProject(box, body, key);\n+\tconst visibility = typeof made.visibility === \"string\" ? made.visibility : \"private\";\n+\tconst minted =\n+\t\tnamed !== undefined\n+\t\t\t? { ...(await mintKey(box, project, named)), agent: named }\n+\t\t\t: await mintFreeName(box, project, defaultAgentName());\n+\tconst config = { server, project, agent: minted.agent };\n+\twriteConfig(root, config);\n+\tclearKnown(root);\n+\tinstallKey(root, JSON.stringify({ key: minted.key, id: minted.id }));\n+\trmSync(keyPath, { force: true });\n+\tconst synced = await syncFolder(root, new Api(readConfig(root, env.env)), true);\n+\tconst owner = org ?? \"you\";\n+\treturn {\n+\t\ttext: [\n+\t\t\t`Created project ${project} (${visibility}, owned by ${owner}) at version ${synced.version} from ${plural(listed.length, \"file\")} in ${root}.`,\n+\t\t\t...leftOutText(leftOut),\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`This folder is agent ${minted.agent}, with its own key, ${minted.id}, made from this box's sign-in. Settings are in .abso/config.json.`,\n+\t\t\t...refusedText(synced.refused),\n+\t\t\t...(synced.written.length > 0 ? [`Wrote ${plural(synced.written.length, \"file\")} from shared.`] : []),\n+\t\t\thookHint(env.env),\n+\t\t].join(\"\\n\"),\n+\t\tjson: {\n+\t\t\tproject,\n+\t\t\tid: made.id ?? null,\n+\t\t\towner: made.owner ?? null,\n+\t\t\tvisibility,\n+\t\t\tversion: synced.version,\n+\t\t\tfiles: listed.length,\n+\t\t\troot,\n+\t\t\tagent: minted.agent,\n+\t\t\tkey_id: minted.id,\n+\t\t\twroteAbsoignore: wroteIgnore,\n+\t\t\twroteProjectFile: typeof wroteProject === \"string\" ? null : wroteProject,\n+\t\t\tleftOut,\n+\t\t},\n+\t};\n+}\n+\n+/**\n+ * Where abso join writes: --dir, else here when --agent is given (as before, so a folder prepared with\n+ * abso key install --server is joined where its key is). With no --agent: here when this folder is empty, else\n+ * ./<project>, which has to be new or empty so nobody's files are written over. A folder holding only abso's own\n+ * state folder counts as empty.\n+ */\n+export function joinFolder(args: Parsed, env: Pick<Env, \"cwd\">, project: string): string {\n+\tconst dir = str(args, \"dir\");\n+\tif (dir !== undefined) return resolve(env.cwd, dir);\n+\tif (str(args, \"agent\") !== undefined) return resolve(env.cwd);\n+\tconst empty = (path: string) => readdirSync(path).every((name) => name === STATE_DIR || name === OLD_STATE_DIR);\n+\tif (empty(env.cwd)) return resolve(env.cwd);\n+\tconst sub = resolve(env.cwd, project);\n+\tif (existsSync(sub) && (!statSync(sub).isDirectory() || !empty(sub)))\n+\t\tthrow new UsageError(`${sub} already has files in it: say where to join with --dir <folder>`);\n+\treturn sub;\n+}\n+\n+/** Signed out, the server doesn't say who owns a project, and the website puts every project under this one owner for now. */\n+const SITE_OWNER = \"christopher\";\n+\n+/**\n+ * Whether anyone can read the project: its status answers with no credentials. Only the answer's code\n+ * counts, never its body, and no redirect is followed. A private project and a missing one look the same.\n+ */\n+export async function isPublic(server: string, project: string): Promise<boolean> {\n+\ttry {\n+\t\tconst response = await fetch(new URL(`/p/${encodeURIComponent(project)}/status`, server), {\n+\t\t\tredirect: \"error\",\n+\t\t\tsignal: AbortSignal.timeout(3000),\n+\t\t});\n+\t\treturn response.status === 200;\n+\t} catch {\n+\t\treturn false;\n+\t}\n+}\n+\n+/**\n+ * Why a join failed signed out. Without --reader, the client reads only as an agent, which needs a\n+ * sign-in; a public project is read signed out on the website, or with abso join --reader.\n+ */\n+async function signedOut(server: string, project: string): Promise<string> {\n+\treturn (await isPublic(server, project))\n+\t\t? `${project} is public: read it at ${siteOf(server)}/${SITE_OWNER}/${project} (every page is also JSON), or here with abso join ${project} --reader. To work on it: abso login.`\n+\t\t: `This box isn't signed in to ${server}. abso login signs it in.${elsewhereText(server, `abso join ${project}`)}`;\n+}\n+\n+/** A folder that reads a public project signed out: no agent, no key, no copy of the files. */\n+async function joinAsVisitor(root: string, server: string, project: string, env: Env): Promise<Output> {\n+\twriteConfig(root, { server, project, agent: \"\", visitor: true });\n+\tconst api = new Api(readConfig(root, env.env));\n+\tlet version: number;\n+\ttry {\n+\t\tversion = (await api.status()).version;\n+\t} catch (error) {\n+\t\trmSync(stateDir(root), { recursive: true, force: true });\n+\t\tthrow error;\n+\t}\n+\treturn {\n+\t\ttext: [\n+\t\t\t`Joined ${project} to read it signed out, at version ${version}, in ${root}. Nothing is sent with a sign-in, and nothing here is recorded.`,\n+\t\t\t`This folder holds no copy of the files: abso files lists them, abso show ${version}:<file> prints one, and status, log, blame, why, where, issues, issue and search read the rest.`,\n+\t\t\t`To work on ${project}: abso login, then abso join ${project} in a new folder.`,\n+\t\t\t...(root === resolve(env.cwd) ? [] : [`cd ${relative(env.cwd, root) || root}`]),\n+\t\t].join(\"\\n\"),\n+\t\tjson: { project, visitor: true, version, root },\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)\n-\t\tthrow new UsageError(\"join takes the project name: abso join <project> --agent <name>\");\n+\tif (args.positionals.length !== 1) throw new UsageError(\"join takes the project name: abso join <project>\");\n \tconst project = args.positionals[0]!;\n-\tconst root = resolve(env.cwd, str(args, \"dir\") ?? \".\");\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+\tconst root = joinFolder(args, env, project);\n \tmkdirSync(root, { recursive: true });\n-\tif (findRoot(root) === root) throw new UsageError(`${root} already has .avcs/config.json`);\n+\tif (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);\n \tconst reader = bool(args, \"reader\");\n-\tconst config = { ...makeSettings(args, env, project), ...(reader ? { reader: true } : {}) };\n-\tconst box = readBox(config.server);\n-\tconst minted =\n-\t\tbox && !existsSync(join(root, AVCS_DIR, \"key\")) ? await mintKey(box, project, config.agent) : undefined;\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 (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+\t\t\t\t? await mintKey(box, project, agent)\n+\t\t\t\t: undefined;\n+\t} else if (fromEnv(env.env, \"KEY_FILE\")) {\n+\t\t// A pipeline run's key (ABSO_KEY_FILE) belongs to one agent, which the runner names in ABSO_AGENT.\n+\t\tconst named = fromEnv(env.env, \"AGENT\");\n+\t\tif (!named)\n+\t\t\tthrow new UsageError(\"a pipeline run's key joins as its own agent: give it with --agent <name> or ABSO_AGENT\");\n+\t\tagent = agentFrom(args, named);\n+\t} else {\n+\t\t// No --agent: the box's name, or the next free -2, -3. Not signed in, --reader reads a public project signed out.\n+\t\tif (!box && reader && !hasKey && (await isPublic(server, project)))\n+\t\t\treturn joinAsVisitor(root, server, project, env);\n+\t\tif (!box)\n+\t\t\tthrow new UsageError(\n+\t\t\t\t`${await signedOut(server, project)} (A folder that already has a key joins with --agent <name>.)`,\n+\t\t\t);\n+\t\tif (hasKey) throw new UsageError(`${root} already has a key: give its agent's name with --agent <name>`);\n+\t\tconst free = await mintFreeName(box, project, defaultAgentName());\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 } : {}), ...local?.settings };\n \twriteConfig(root, config);\n \tclearKnown(root);\n \tif (minted) installKey(root, JSON.stringify(minted));\n-\tconst settings = readConfig(root, env.env);\n+\t// The token file only with --token-file: readConfig reads it otherwise.\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+\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\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(join(root, AVCS_DIR), { recursive: true, force: true });\n-\t\tthrow new UsageError(`This box isn't signed in to ${config.server}. abso login signs it in.`);\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, sync, log, show, files and export work, and nothing it does is recorded or published.\" : \"\"}${minted ? ` It signs in with its own key, ${minted.id}, made from this box's sign-in.` : \"\"}`,\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 \t\t\t...refusedText(synced.refused),\n \t\t\t...(synced.kept.length > 0\n \t\t\t\t? [\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 \t\t\tproject,\n@@ -145,17 +533,27 @@\n \t};\n }\n \n-/** What to run before building or testing here (#43, Engine): a joined folder has the project's files, not what avcs.json's setup installs. */\n+/** What to run before building or testing here (#43): a joined folder has the project's files, not what avcs.json's setup installs. */\n function setupHint(root: string): string[] {\n \tconst read = readProjectFile(root);\n \tconst setup = read !== null && \"file\" in read ? read.file.setup : \"\";\n \treturn setup === \"\"\n \t\t? []\n-\t\t: [`Nothing is installed yet. Before building or testing here, run ${PROJECT_FILE}'s setup: ${setup}`];\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 avcs 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 avcs 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 }"}],"unmatched":[]}