Lines 3–35 at 318 (were 3–17 at 287)
33// `abso help` lists the commands. `abso hook` is the Claude Code hook; it 44// loads only what it needs, since every edit pays for its start-up. 6+import { readFileSync } from "node:fs"; 67import * as nodeModule from "node:module"; 8+import { dirname, join } from "node:path"; 10+const argv = process.argv.slice(2); 13+ * Whether this command opens a local project (abso init --local): --local, or a folder whose config names the server 14+ * "local". Those load the open server's code through a module hook, and with the compile cache on Node 24 crashes. 16+function opensLocal(): boolean { 17+ if (argv.includes("--local")) return true; 18+ for (let dir = process.cwd(); ; dir = dirname(dir)) { 19+ for (const state of [".abso", ".avcs"]) { 21+ return /"server"\s*:\s*"local"/.test(readFileSync(join(dir, state, "config.json"), "utf8")); 24+ if (dirname(dir) === dir) return false; 828// Node keeps the compiled modules (TypeScript already stripped) in a cache in 929// the temp folder. Loading the hook's modules drops from about 55 ms to 11 ms. 1030// Node 20 has no compile cache, and the built client runs there without one. 11−(nodeModule as { enableCompileCache?: () => unknown }).enableCompileCache?.();
31+if (!opensLocal()) (nodeModule as { enableCompileCache?: () => unknown }).enableCompileCache?.(); 13−const argv = process.argv.slice(2);
14−
1533if (argv[0] === "hook") { 1634 const { runHook } = await import("./src/hook.ts"); 1735 const chunks: Buffer[] = []; Lines 3–12 at 318 (were 3–11 at 287)
44import type { On } from "claude-code"; 55import { expect, mock, test } from "claude-code/testing"; 6+import { HOOK_COMMAND } from "./stamp.ts"; 78/** The world beneath the mod: a chat in /w/p, an abso folder when `inFolder`, and a server with `news` waiting. */ 8−function world(on: On, inFolder: boolean, news: string[][]) {
9+function world(on: On, inFolder: boolean, news: string[][], server = "https://avcs.test") { 910 mock.env(on, { AVCS_TOKEN: "test-token" }); 1011 const clock = mock.clock(on, { now: 1_000_000 }); 1112 const asked: string[] = []; Lines 22–28 at 318 (were 21–27 at 287)
2122 on("fs.read", (_$, e) => { 2223 const path = norm(e.path); 2324 if (inFolder && path === "/w/p/.abso/config.json") 24− return { value: JSON.stringify({ server: "https://avcs.test", project: "p", agent: "bob" }) };
25+ return { value: JSON.stringify({ server, project: "p", agent: "bob" }) }; 2526 if (written.has(path)) return { value: written.get(path)! }; 2627 return { deny: `ENOENT: ${path}` }; Lines 115–152 at 318 (were 114–116 at 287)
114115 expect(w.written.get("/w/p/.abso/hook.log") ?? "").toContain("not sent: a NUL byte at line 3"); 115116 expect(w.asked.filter((u) => !u.endsWith("/news"))).toEqual([]); 119+test("a local project's edit goes to abso hook as Claude Code's command hook would get it, and its news to the chat", async ($, on) => { 120+ const w = world(on, true, [], "local"); 121+ w.written.set("/w/p/notes.md", "hello\n"); 122+ on("fs.stat", () => ({ value: { realPath: "/w/p/notes.md" } }) as never); 123+ on("session.id", () => ({ value: "sess" })); 124+ const ran: { argv: readonly string[]; stdin?: string; env?: Record<string, string> }[] = []; 125+ const context = "abso: Announcement from lead: hold pushes"; 126+ on("process.run", (_$, e) => { 127+ ran.push({ argv: e.argv, stdin: e.init?.stdin, env: e.init?.env }); 128+ const stdout = JSON.stringify({ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: context } }); 129+ return { value: { exitCode: 0, stdout, stderr: "" } } as never; 131+ await $.session.start({ cwd: "/w/p" }); 132+ await $.tool.call({ tool: "Write", tool_use_id: "t1", file_path: "/w/p/notes.md", content: "hello\n" } as never); 133+ await w.clock.advance(1_000); 134+ // A local project has no server to call: nothing goes over the network. 135+ expect(w.asked.filter((u) => !u.endsWith("/news"))).toEqual([]); 136+ const log = w.written.get("/w/p/.abso/hook.log") ?? ""; 137+ if (HOOK_COMMAND === undefined) { 138+ // Loaded from a checkout, the mod has no client to hand it to. 139+ expect(ran).toEqual([]); 140+ expect(log).toContain("skipped: a local project"); 143+ expect(ran).toHaveLength(1); 144+ expect(ran[0]!.argv).toEqual(HOOK_COMMAND); 145+ expect(ran[0]!.env).toEqual({ ABSO_HOOK_FORCE: "1" }); 146+ const input = JSON.parse(ran[0]!.stdin ?? "{}") as Record<string, unknown>; 147+ expect(input.session_id).toBe("sess"); 148+ expect(input.tool_name).toBe("Write"); 149+ expect((input.tool_input as Record<string, unknown>).file_path).toBe("/w/p/notes.md"); 150+ expect(log).toContain("handed to abso hook"); 151+ expect(w.appended).toEqual([context]); Lines 33–39 at 318 (were 33–39 at 287)
3535} from "../src/core.ts"; 36−import { STAMP } from "./stamp.ts";
36+import { HOOK_COMMAND, STAMP } from "./stamp.ts"; 3838const TOOLS = ["Edit", "MultiEdit", "Write", "NotebookEdit"]; 3939/** A known copy holding a NUL byte reads as no known copy (the client treats it as binary). */ Lines 184–205 at 318 (were 184–202 at 287)
185185/** A local project's folder (abso init --local): its config names no server. */ 186186const LOCAL_FOLDER = /"server"\s*:\s*"local"/; 187+/** How long abso hook may take on a local project's edit: it waits up to two minutes for the store's lock. */ 188+const LOCAL_HOOK_MS = 150_000; 188190async function run($: Engine, job: Job): Promise<void> { 189191 const started = await $.clock.now().catch(() => job.queuedAt); 190192 let outcome: string; 191193 let news: readonly string[] = []; 194+ /** What abso hook handed back for the agent, on a local project's edit (it keeps the news log itself). */ 195+ let handed: string | undefined; 193197 if ((await readOr($, `${await stateOf($, job.root)}/paused`)) !== undefined) { 194198 outcome = "skipped: recording is paused (abso resume)"; 195199 } else if (/"reader"\s*:\s*true/.test((await readOr($, `${await stateOf($, job.root)}/config.json`)) ?? "")) { 196200 outcome = "skipped: this folder is a reader"; 197201 } else if (LOCAL_FOLDER.test((await readOr($, `${await stateOf($, job.root)}/config.json`)) ?? "")) { 198− // A local project's history is in a store on this machine, which only the abso command opens.
199− outcome = "skipped: a local project; abso record sends its edits";
202+ ({ outcome, context: handed } = await handToClient($, job)); 200203 } else if (await ignored($, job.root, job.rel)) { 201204 outcome = "skipped: ignored path"; 202205 } else if (await isLink($, job.root, job.rel)) { Lines 220–230 at 318 (were 217–227 at 287)
218221 `${new Date(job.queuedAt).toISOString()}\t${job.tool}\t${job.rel}\t${outcome}\t${done - started}ms sending, ${started - job.queuedAt}ms queued (in process, async)\t${CLIENT}`, 220− const context = newsContext(news);
223+ const context = handed ?? newsContext(news); 221224 if (context === undefined) return; 222225 // For anything that shows news later (the avcs-view mod reads it). 223226 const at = new Date(done).toISOString(); 224− await log($, job.root, news.map((n) => `${at}\t${n}`).join("\n"), "news.log");
227+ if (news.length > 0) await log($, job.root, news.map((n) => `${at}\t${n}`).join("\n"), "news.log"); 226229 await $.session.append({ 227230 message: { type: "user", content: [{ type: "text", text: context }] }, Lines 237–279 at 318 (were 234–239 at 287)
241+ * A local project's history is in a store on this machine that only the abso command opens, so its edits go to 242+ * `abso hook` from the checkout this mod was installed from, as Claude Code's command hook would run it. 244+async function handToClient($: Engine, job: Job): Promise<{ outcome: string; context?: string }> { 245+ if (HOOK_COMMAND === undefined || HOOK_COMMAND.length === 0) 248+ "skipped: a local project, and this mod has no abso to hand it to (install-mod.ts adds one); abso record sends it", 251+ session_id: await $.session.id(), 252+ cwd: slash(await $.session.cwd()), 253+ tool_name: job.tool, 254+ tool_input: job.input, 255+ ...(job.agentId ? { agent_id: job.agentId } : {}), 257+ const ran = await $.process.run(HOOK_COMMAND, { 259+ env: { ABSO_HOOK_FORCE: "1" }, 260+ stdin: JSON.stringify(hookInput), 261+ timeoutMs: LOCAL_HOOK_MS, 263+ if (ran.exitCode !== 0) throw new Error(`abso hook exited ${ran.exitCode}: ${ran.stderr.trim().split("\n").at(-1)}`); 264+ // It prints Claude Code's JSON when it has news for the agent, and nothing otherwise. 265+ const out = ran.stdout.trim(); 269+ : (JSON.parse(out) as { hookSpecificOutput?: { additionalContext?: unknown } }).hookSpecificOutput 270+ ?.additionalContext; 272+ outcome: "handed to abso hook (a local project; its own line is just above)", 273+ ...(typeof context === "string" ? { context } : {}), 237277/** Ask for the news waiting for this agent (announcements, collisions) and hand it to the model. */ 238278async function pollNews($: Engine, root: string): Promise<void> { Lines 3–11 at 318 (were 3–5 at 287)
33// this file with the version it installs: plugin.json's, plus the commit 44// (0.1.0+702c616). Loaded straight from a checkout, it stays undefined. 55export const STAMP: string | undefined = undefined; 7+// The command that runs `abso hook` from the checkout the mod was installed 8+// from, as [node, client/abso.ts, "hook"]; the installer writes it too. A 9+// local project's history is in a store on this machine that only the abso 10+// command opens, so the mod hands those edits to it. 11+export const HOOK_COMMAND: readonly string[] | undefined = undefined; Lines 107–114 at 318 (were 107–112 at 287)
108108 const ended = await follow({ 109109 mint: () => api.newsTicket(), 110+ // A frame is a wake: read the news, which marks it heard, and print that (news-stream.ts). 111+ take: async () => newsLines((await api.news()).news), 110112 connect: (url, protocols) => new WebSocket(url, [...protocols]) as unknown as Socket, 111113 write: (line) => { 112114 logNews(root, [line]); Lines 80–122 at 318 (were 80–85 at 287)
83+/** A stored pipeline run as runRuns lists it: what the CI lines need of it. */ 86+ readonly version: number; 87+ readonly state: string; 88+ readonly file: string; 91+/** The stored pipeline runs, newest first, from the server's `pipelines` read; empty for anything else. */ 92+export function storedRuns(raw: unknown): StoredRun[] { 93+ const runs = (raw as { runs?: unknown } | null)?.runs; 94+ if (!Array.isArray(runs)) return []; 96+ (r): r is StoredRun => 97+ typeof r === "object" && 99+ Number.isInteger((r as StoredRun).id) && 100+ Number.isInteger((r as StoredRun).version) && 101+ typeof (r as StoredRun).state === "string" && 102+ typeof (r as StoredRun).file === "string", 106+/** One stored run in a line, with where its jobs are. */ 107+export function runLine(run: StoredRun): string { 108+ const how = run.state === "planned" ? "was planned, not run," : run.state === "running" ? "is running" : run.state; 109+ return `Pipeline run ${run.id} (${run.file}) ${how} on version ${run.version}. abso pipeline runs ${run.id} shows its jobs.`; 113+ * Whether the built-in check (abso.json's setup, build and check) had nothing of its own to run. With stored runs, that is 114+ * about the built-in check, not the project's CI, so it isn't said as the project's (abso 719). 116+export function builtInHasNothing(ci: CiStatus): boolean { 117+ return ci.red === null && ci.skipped?.reason.startsWith("nothing to run") === true; 83120/** A shared version's mark in abso log; "not checked" says nothing, since most versions in a busy hour are covered by a newer one's job. */ 84121export function ciMarkText(mark: CiMark | undefined): string { Lines 180–199 at 318 (were 143–153 at 287)
144181 if (typed !== undefined) { 145182 if (!/^\d+$/.test(typed)) throw new UsageError(`a version is a number (got ${JSON.stringify(typed)})`); 146− const job = await api.ci(Number(typed));
147− return { text: jobText(job).join("\n"), json: { ...job } };
183+ const [job, raw] = await Promise.all([api.ci(Number(typed)), api.pipelineRuns().catch(() => null)]); 184+ const run = storedRuns(raw).find((r) => r.version === job.version); 185+ // A version the built-in check never ran, with a pipeline run of its own: the run is its CI (abso 719). 186+ const text = run !== undefined && job.result === "none" ? [runLine(run)] : jobText(job); 187+ return { text: text.join("\n"), json: { ...job } }; 149− const [ci, status] = await Promise.all([api.ci(), api.status()]);
150− const lines = ciText(ci, status.version);
189+ const [ci, status, raw] = await Promise.all([api.ci(), api.status(), api.pipelineRuns().catch(() => null)]); 190+ const newest = storedRuns(raw)[0]; 192+ newest === undefined 193+ ? ciText(ci, status.version) 194+ : builtInHasNothing(ci) 196+ : [...ciText(ci, status.version), runLine(newest)]; 153199 `shared is at version ${status.version}.`, Lines 2–7 at 318 (were 2–8 at 287)
33import { createHash } from "node:crypto"; 44import { hostname } from "node:os"; 5−import { basename } from "node:path";
65import { callerHeader } from "../../src/caller.ts"; 76import { Api, type News, newsLines, type RunKind, takeSeatNotices } from "./api.ts"; 87import { UsageError } from "./args.ts"; Lines 59–71 at 318 (were 60–66 at 287)
6160export function callerFor(session: string | undefined, machine: string, root: string): string | undefined { 6261 const hashed = session ? createHash("sha256").update(session).digest("hex").slice(0, 16) : undefined; 63− return callerHeader({ session: hashed, machine, folder: basename(root) });
62+ // The last part on either separator, so a Windows path names its folder on any machine. 66+ .filter((p) => p !== "") 68+ return callerHeader({ session: hashed, machine, folder }); Lines 94–101 at 318 (were 94–99 at 287)
9494 /** For tests: the rename that moves each file into place. */ 9595 readonly rename?: (from: string, to: string) => void; 9696 readonly now?: Date; 97+ /** For tests: the command stamped as HOOK_COMMAND, instead of this client's own `abso hook`. */ 98+ readonly hookCommand?: readonly string[]; 99101const RECORD = ".avcs-install.json"; Lines 134–148 at 318 (were 132–137 at 287)
132134 existsSync(at(skillsFolder(AVCS_MOD.name, env), MANIFEST)) || 133135 existsSync(at(skillsFolder(OLD_MOD_NAMES[AVCS_MOD.name]!, env), MANIFEST)); 137+/** Whether the installed abso mod hands a local project's edits to abso hook: it was installed with a HOOK_COMMAND. */ 138+export function modHandsLocal(env: Readonly<Record<string, string | undefined>> = process.env): boolean { 140+ return /HOOK_COMMAND[^=\n]*=\s*\[/.test(readFileSync(at(skillsFolder(AVCS_MOD.name, env), STAMP_FILE), "utf8")); 136147 * After the new mod is in, the folder it replaces (skills/avcs, skills/avcs-view) would load beside it, so it 137148 * is moved, not deleted, to ~/.abso/retired-mods/<name>-<stamp>. Returns where it went, or undefined when there was none. Lines 237–247 at 318 (were 226–233 at 287)
229−/** The files to install, stamped with `version`, in install order. */
230−function filesFor(spec: ModSpec, version: string): Map<string, Buffer> {
240+/** The command that runs this checkout's `abso hook`: what the mod hands a local project's edits to. */ 241+export const hookCommand = (): readonly string[] => [process.execPath, join(CLIENT_DIR, "abso.ts"), "hook"]; 243+/** The files to install, stamped with `version` (and HOOK_COMMAND, where a stamp.ts has it), in install order. */ 244+function filesFor(spec: ModSpec, version: string, hook: readonly string[] = hookCommand()): Map<string, Buffer> { 231245 if (!/^[\w.+-]+$/.test(version)) throw new Error(`can't stamp the version ${JSON.stringify(version)}`); 232246 const out = new Map<string, Buffer>(); 233247 for (const rel of spec.files) { Lines 253–261 at 318 (were 239–245 at 287)
239253 const text = data.toString("utf8"); 240254 const stamped = text.replace(/(STAMP[^=\n]*=\s*)undefined/, `$1'${version}'`); 241255 if (stamped === text) throw new Error(`${rel} has no "STAMP ... = undefined" line to stamp`); 242− data = Buffer.from(stamped);
257+ stamped.replace(/(HOOK_COMMAND[^=\n]*=\s*)undefined/, (_, head: string) => head + JSON.stringify(hook)), 244260 out.set(rel, data); Lines 402–408 at 318 (were 386–392 at 287)
386402export function installMod(spec: ModSpec, options: InstallOptions): Installed { 387403 const target = resolve(options.target); 388404 const version = versionFor(spec, options.commit); 389− const next = filesFor(spec, version);
405+ const next = filesFor(spec, version, options.hookCommand); 390406 const existed = existsSync(target); 391407 mkdirSync(target, { recursive: true }); Lines 28–34 at 318 (were 28–33 at 287)
2828import { ignoredHere } from "./fetch.ts"; 2929import { loadIgnore, relativeTo } from "./folder.ts"; 3030import type { AskReply } from "./issues-wire.ts"; 31+import { isLocal, LOCAL_BASE } from "./local-store.ts"; 3132import { queuedLines, standing } from "./queue.ts"; 3233import { seenText, shortWhen } from "./times.ts"; Lines 37–47 at 318 (were 36–41 at 287)
3637/** The folder, with its Api pointed at the Issues Worker: the token goes only where tokenGoesTo allows, as for the avcs server. */ 3738export function openIssues(env: Env): { root: string; config: Config; api: Api } { 3839 const { root, config, api } = open(env); 40+ // A local project's issues are in its store, where the open server keeps them: at /issues. 41+ if (isLocal(config.server)) { 42+ api.issuesServer = `${LOCAL_BASE}/issues`; 43+ return { root, config, api }; 3945 // An explicit --server goes to that server's own Issues Worker: ABSO_ISSUES_SERVER doesn't redirect it. 4147 (env.server === undefined ? fromEnv(env.env, "ISSUES_SERVER") : undefined) || Lines 32–38 at 318 (were 32–38 at 287)
3232import { elsewhereText } from "./doctor.ts"; 3333import { fromEnv } from "./env-names.ts"; 3434import { clearKnown, loadIgnore, readFolder, writeKnown } from "./folder.ts"; 35−import { installerCommand, modInstalled } from "./install.ts";
35+import { installerCommand, modHandsLocal, modInstalled } from "./install.ts"; 3636import { LOCAL, NO_STORE, storeDir } from "./local-store.ts"; 3737import { type FullMode, foldModes, writeKnownModes } from "./modes.ts"; 3838import { initInOrg, siteOf } from "./orgs.ts"; Lines 154–164 at 318 (were 154–159 at 287)
154154 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`); 155155 const project = str(args, "project"); 156156 if (!project) throw new UsageError("give the project a name with --project <name>"); 157+ // Checked before any call: a name like ".." would otherwise go out as part of the request's path. 158+ if (!NAME.test(project)) 159+ throw new UsageError( 160+ `project names are letters, digits, dot, dash and underscore (got ${JSON.stringify(project)})`, 157162 if (bool(args, "public") && bool(args, "private")) throw new UsageError("--public or --private, not both"); 158163 const local = localFrom(args, env, "init"); 159164 // A box signed in here, and no other credential asked for: the project is made as the person who approved the box, Lines 543–556 at 318 (were 538–545 at 287)
540545function hookHint(env: Readonly<Record<string, string | undefined>>, local = false): string { 541− // The mod sends each edit to the folder's server itself, and a local project has none.
542− if (local) return "abso record sends the edits made here: the abso mod doesn't record local projects yet.";
546+ // A local project has no server: the mod hands its edits to abso hook, when it was installed with one to hand them to. 548+ if (modHandsLocal(env)) 549+ return "Edits made by Claude Code here are recorded by the abso mod on this machine, through abso hook. Anything else: abso record."; 550+ if (modInstalled(env) && !builtCopy()) 551+ return `abso record sends the edits made here: the abso mod on this machine is older than local projects. ${installerCommand("install-mod.ts")} updates it, and new chats load it.`; 552+ return "abso record sends the edits made here, whoever made them."; 543554 if (modInstalled(env)) 544555 return "Edits made by Claude Code here are recorded by the abso mod on this machine, signed in as this folder. Anything else: abso record."; 545556 // A built copy (the npm package) has no installer to point at (abso-core 18). Lines 1–5 at 318 (were 1–3 at 287)
11// The types of local-server.mjs: as much of the open server as the client calls. 22export declare function handle(request: Request, env: unknown, ctx: unknown, issues: unknown): Promise<Response>; 33export declare const ProjectObject: new (ctx: unknown, env: unknown) => object; 4+export declare const IssueProject: new (ctx: unknown, env: unknown) => object; 5+export declare function issuesFetch(request: Request, env: unknown, ctx: unknown, route: unknown): Promise<Response>; Lines 1–7 at 318 (were 1–6 at 287)
1−// The open server's router and project object, for local projects (local-store.ts). Plain JS, with its types in
2−// local-server.d.mts, so the client's typecheck stops here: server/src is typechecked with the Workers' types
1+// The open server's router, project object and issues, for local projects (local-store.ts). Plain JS, with its types 2+// in local-server.d.mts, so the client's typecheck stops here: server/src is typechecked with the Workers' types 33// (server/tsconfig.json). The build and Node follow these imports as usual. 5+export { IssueProject, issuesFetch } from "../../server/src/issues-entry.ts"; 56export { ProjectObject } from "../../server/src/project-object.ts"; 67export { handle } from "../../server/src/router.ts"; Lines 159–166 at 318 (were 159–165 at 287)
160160/** Workers' crypto.DigestStream, which the blob store hashes uploads with. */ 161161async function installDigestStream(): Promise<void> { 162− const c = globalThis.crypto as unknown as { DigestStream?: unknown };
162+ // Through a cast: abso's worker compiles this file too (tool.lock.json), and its types have no globalThis.crypto. 163+ const c = (globalThis as unknown as { crypto: { DigestStream?: unknown } }).crypto; 163164 if (c.DigestStream) return; 164165 const { createHash } = await import("node:crypto"); 165166 class DigestStream extends WritableStream<Uint8Array> { Lines 190–197 at 318 (were 189–194 at 287)
189190 DatabaseSync: new (path: string) => Db; 190191 handle: (request: Request, env: unknown, ctx: unknown, issues: unknown) => Promise<Response>; 191192 ProjectObject: new (ctx: unknown, env: unknown) => object; 193+ IssueProject: new (ctx: unknown, env: unknown) => object; 194+ issuesFetch: (request: Request, env: unknown, ctx: unknown, route: unknown) => Promise<Response>; 193196let server: Promise<Server> | undefined; Lines 224–255 at 318 (were 221–244 at 287)
221224 // copy has it already: the build points the import at the same file (scripts/build-client.mjs). 222225 const standIn = new URL("./durable-object-stand-in.ts", import.meta.url).href; 223226 const mod = (await import("node:module")) as unknown as { 224− registerHooks?: (hooks: unknown) => { deregister(): void };
227+ registerHooks?: (hooks: unknown) => unknown; 226− const hooks = mod.registerHooks?.({
229+ // The hook stays for the rest of the process: deregistering it crashes Node 24 at exit when the compile cache 230+ // is on (client/avcs.ts turns it on). It answers only cloudflare:workers. 231+ mod.registerHooks?.({ 227232 resolve(specifier: string, context: unknown, next: (s: string, c: unknown) => unknown) { 228233 if (specifier === "cloudflare:workers") return { url: standIn, shortCircuit: true }; 229234 return next(specifier, context); 237+ let loaded: typeof import("./local-server.mjs"); 233− const { handle, ProjectObject } = await import("./local-server.mjs");
234− return {
235− DatabaseSync: sqlite.DatabaseSync,
236− handle,
237− ProjectObject,
238− };
239− } finally {
240− hooks?.deregister();
239+ loaded = await import("./local-server.mjs"); 241+ // Nothing is reached for here: a part of the client is missing (its packages not installed, say). 242+ throw new LocalError( 243+ `local projects couldn't load the server's code: ${e instanceof Error ? e.message : String(e)}`, 247+ DatabaseSync: sqlite.DatabaseSync, 248+ handle: loaded.handle, 249+ ProjectObject: loaded.ProjectObject, 250+ IssueProject: loaded.IssueProject, 251+ issuesFetch: loaded.issuesFetch, Lines 265–274 at 318 (were 254–259 at 287)
254265 object: object | undefined; 255266 /** PRAGMA data_version when this process last used the project: it changes when another process writes. */ 256267 seen: number | undefined; 268+ /** The project's issues, asks and news: issues.sqlite beside it, opened when a call first reaches them. */ 269+ issues?: { db: Db; storage: ReturnType<typeof storageOver> }; 270+ /** The issues object for the call under way: made again for each call, as another process may have written. */ 271+ issueObject?: object; 259274/** Every store file this process has open: closed when its command ends (closeLocalStores). */ Lines 284–293 at 318 (were 269–276 at 287)
272−const PROJECT_PATH = /^\/p\/([^/]+)\//;
273−const NAME = /^[A-Za-z0-9._-]{1,100}$/;
287+/** A project's calls, and its issues, asks and news, which the open server keeps at /issues/p/<project>/. */ 288+const PROJECT_PATH = /^(?:\/issues)?\/p\/([^/]+)\//; 289+/** A project's name is also its folder in the store, so it never starts with a dot ("." and ".." would leave it). */ 290+const NAME = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,99}$/; 274291const json = (status: number, body: unknown) => Response.json(body, { status }); Lines 327–365 at 318 (were 310–319 at 287)
313− // Issues, asks and news aren't in local projects yet: a start note's issue hooks find nothing to call.
314− ISSUES_DO: { idFromName: (n: string) => n, get: () => ({}) },
331+ idFromName: (n: string) => n, 332+ get: (n: string) => { 333+ const p = open.get(n); 334+ if (!p || n !== name) throw new LocalError(`no local project ${n}`); 335+ if (p.issues === undefined || !opened.has(p.issues.db)) { 336+ const db = new opening!.DatabaseSync(join(dir, name, "issues.sqlite")); 338+ db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 120000; PRAGMA synchronous = NORMAL"); 339+ p.issues = { db, storage: storageOver(db) }; 341+ // Its writes need no lock of their own: every call holds the project file's (see below). 342+ p.issueObject ??= new opening!.IssueProject( 343+ { id: { toString: () => n, name: n }, storage: p.issues.storage }, 346+ return p.issueObject; 316− return async (input, init = {}) => {
350+ // One call at a time, as a Durable Object takes them: a call holds its project's write transaction across awaits, 351+ // and the connection can't start a second (two calls at once come from Promise.all in ci and waiting --mine). 352+ let last: Promise<unknown> = Promise.resolve(); 353+ return (input, init) => { 354+ const next = last.then( 355+ () => call(input, init), 356+ () => call(input, init), 358+ last = next.catch(() => {}); 362+ async function call(input: string, init: RequestInit = {}): Promise<Response> { 317363 const s = await loadServer(); 319365 const url = new URL(input); Lines 373–382 at 318 (were 327–333 at 287)
327373 headers.set("authorization", `Bearer ${LOCAL_TOKEN}`); 328374 const request = new Request(url, { ...init, headers }); 329375 const waits: Promise<unknown>[] = []; 376+ // Every call, issues ones too, holds the project file's lock, so local writers of the project and of its 377+ // issues take one lock in one order. 330378 p.db.exec("BEGIN IMMEDIATE"); 379+ p.issueObject = undefined; 332381 const version = (p.db.prepare("PRAGMA data_version").get() as { data_version: number }).data_version; 333382 if (p.seen !== undefined && version !== p.seen) p.object = undefined; Lines 384–390 at 318 (were 335–341 at 287)
337386 { waitUntil: (w: Promise<unknown>) => waits.push(w) }, 338− issuesNone,
340389 await Promise.allSettled(waits); 341390 // The answer is read whole before the write is kept, so a body that fails to arrive keeps nothing either. Lines 403–407 at 318 (were 354–360 at 287)
354403 // Where the Workers runtime answers a throw with a 500, so does this. 355404 return json(500, { error: e instanceof Error ? e.message : String(e) }); 357− };
359−
360−const issuesNone = async () => json(404, { error: "issues, asks and news aren't in local projects yet" });
Lines 79–85 at 318 (were 79–84 at 287)
7979import { runAmend, runDrop, runFollow, runLabel, runLabels, runPluck } from "./versions.ts"; 8080import { runVisibility } from "./visibility-commands.ts"; 8181import { checkVisitor } from "./visitor.ts"; 82+import { handoffText, patFromFile, webLogin } from "./web-session.ts"; 8384interface CommandDef { 8485 readonly flags: FlagSpec; Lines 213–244 at 318 (were 212–224 at 287)
212213 projects: "string", 218+ "pat-file": "string", 217− "abso login [--no-browser] [--no-ask] [--projects <name,name>] [--role <reader|writer|owner>] [--days <1-90>]",
221+ "abso login [--no-browser] [--no-ask] [--projects <name,name>] [--role <reader|writer|owner>] [--days <1-90>] | abso login --web [--pat-file <file> [--site http://localhost:<port>]]", 219− "Sign this box in once: it opens the approve page in your browser with the code filled in, prints the link and the code too, and waits while a person approves the code on the website, choosing the projects, the highest role and how long. Then abso join in any of those projects gives each agent its own key, with no approval. The box's sign-in is kept in your user folder, never in a project folder, and is never printed. No browser opens with --no-browser or ABSO_NO_BROWSER, over SSH, under CI, or on Linux without a display. In an agent's folder on the same server, it also asks a person in that project to approve it (the person who approved the agent's box, else the project's owners), as an abso ask, so nobody has to relay the code; the box can then be granted that project at no more than the agent's own role. --no-ask shows the code only.",
223+ "Sign this box in once: it opens the approve page in your browser with the code filled in, prints the link and the code too, and waits while a person approves the code on the website, choosing the projects, the highest role and how long. Then abso join in any of those projects gives each agent its own key, with no approval. The box's sign-in is kept in your user folder, never in a project folder, and is never printed. No browser opens with --no-browser or ABSO_NO_BROWSER, over SSH, under CI, or on Linux without a display. In an agent's folder on the same server, it also asks a person in that project to approve it (the person who approved the agent's box, else the project's owners), as an abso ask, so nobody has to relay the code; the box can then be granted that project at no more than the agent's own role. --no-ask shows the code only. --web, on staging only, signs a browser in to the website instead: it prints a link that works once, within a minute, and signs whichever browser opens it in as the person who approved this box, but only to the projects the box was granted and at most as a writer, until the box is revoked or ends (or, with --pat-file, as the test account whose PAT that file holds, at most as a writer). It writes issues, replies, answers, groups and announcements, and changes no members, roles, visibility, keys, boxes or settings. The box's sign-in, the PAT and the session never appear. It goes only to the staging website beside this folder's staging server; any other server, prod included, is refused and nothing is sent. --site, with --pat-file only, points it at a website on this machine (http://localhost or 127.0.0.1).", 220224 run: async (args, env) => { 221225 const server = boxServer(args, env); 226+ if (bool(args, "web")) { 227+ const patFile = str(args, "pat-file"); 228+ const { handoff, site } = await webLogin({ 230+ site: str(args, "site"), 231+ kind: patFile === undefined ? "box" : "pat", 233+ if (patFile !== undefined) return patFromFile(patFile); 234+ const record = readBox(server); 235+ if (record === undefined || record.expiresAt <= Date.now()) 236+ throw new UsageError(`this box isn't signed in to ${server}: abso login first, or --pat-file <file>`); 237+ return record.credential; 240+ return { text: handoffText(handoff, site, patFile === undefined), json: { ...handoff } }; 223243 bool(args, "no-browser") || browserSkip(env.env, process.platform) !== null Lines 94–101 at 318 (were 94–99 at 287)
9494 sleep(ms: number): Promise<void>; 9696 every(ms: number, fn: () => void): () => void; 97+ /** Reads the seat's news, marking it heard (POST news); a frame calls it. Without it, frames are printed as they come. */ 98+ take?(): Promise<readonly string[]>; 9799 /** Called when a socket opens and at each ping: the stream is held until the next ping is due, and a little more. */ 98100 held?(until: number): void; 99101 /** Set when --follow should stop (Ctrl-C, or a test). */ Lines 109–163 at 318 (were 107–116 at 287)
112+ * A frame is a wake (abso 690): on one, read the seat's news (which marks it heard) and print what that answers, one 113+ * read at a time, with frames that arrive meanwhile folded into one more read. When the read answers nothing (a server 114+ * that counts a frame as heard already, or another chat on the seat took it first), the frames themselves are printed. 116+function frameReads(deps: FollowDeps): { frame(text: string): void; idle(): Promise<void> } { 117+ let frames: string[] = []; 118+ /** The lines printed lately, so a frame a read already printed isn't printed again. */ 119+ const shown: string[] = []; 120+ const show = (line: string) => { 123+ if (shown.length > 200) shown.shift(); 125+ let running: Promise<void> | undefined; 127+ const pass = async () => { 130+ const these = frames; 132+ let items: readonly string[] = []; 134+ items = await deps.take!(); 136+ deps.note(`(abso news --follow: couldn't read the news: ${(err as Error).message}; showing the frames)`); 138+ for (const line of items) show(line); 139+ // A frame the read didn't cover still shows: on a server that counts a frame as heard, its item never comes back 140+ // from the read. A catch-up frame names several items, so a frame holding a shown item counts as covered. 141+ for (const frame of these) if (!shown.some((line) => frame.includes(line) || line.includes(frame))) show(frame); 143+ running = undefined; 148+ if (running !== undefined) again = true; 149+ else running = pass(); 151+ idle: () => running ?? Promise.resolve(), 110156 * Holds the seat's stream, printing one line per item, until the key is refused or `stopped()`. 111157 * Returns why it ended. 113159export async function follow(deps: FollowDeps): Promise<{ ended: "refused" | "stopped"; reason: string }> { 160+ const reads = frameReads(deps); 115162 while (!deps.stopped()) { 116163 let ticket: NewsTicket; Lines 186–198 at 318 (were 139–150 at 287)
140187 socket.onmessage = (e) => { 141188 if (typeof e.data !== "string" || e.data === PONG) return; 142− deps.write(e.data);
189+ if (deps.take === undefined) deps.write(e.data); 190+ else reads.frame(e.data); 144192 socket.onerror = () => {}; 145193 socket.onclose = (e) => { 147− done({ code: e.code, reason: e.reason });
195+ void reads.idle().then(() => done({ code: e.code, reason: e.reason })); 150198 if (isRefusal(closed.code)) return { ended: "refused", reason: closed.reason || `closed ${closed.code}` }; Lines 40–46 at 318 (were 40–45 at 287)
4040} from "./folder.ts"; 4141import { fileArg } from "./history.ts"; 4242import { modsBehindText } from "./install.ts"; 43+import { isLocal } from "./local-store.ts"; 4344import { withFolderLock } from "./lock.ts"; 4445import { readKnownModes, writeKnownModes } from "./modes.ts"; 4546import { queueText } from "./queue.ts"; Lines 326–336 at 318 (were 325–333 at 287)
325326 const space = (draft: string | null | undefined): string => (draft ? `draft ${draft}` : "shared"); 326327 const parked = (me?.parked ?? []).filter((p) => p.draftChanges > 0); 327328 const credential = credentialLabel(root, config.server, env.env); 328− const behind = await newerClientNote(config.server);
329+ // A local project reaches for nothing on the network, npm included. 330+ const localProject = isLocal(config.server); 331+ const behind = localProject ? undefined : await newerClientNote(config.server); 330− `Project ${config.project}: shared is at version ${status.version}. This folder is ${config.agent}${config.reader || me?.reader ? ", a reader (it records and pushes nothing)" : ""}, working in ${space(me?.draft)}.${config.follow ? ` It follows label ${config.follow}: pulls take it to the newest version with that label.` : ""} Signed in with ${credential.kind}${credential.id ? ` ${credential.id}` : ""}.`,
333+ `Project ${config.project}: shared is at version ${status.version}. This folder is ${config.agent}${config.reader || me?.reader ? ", a reader (it records and pushes nothing)" : ""}, working in ${space(me?.draft)}.${config.follow ? ` It follows label ${config.follow}: pulls take it to the newest version with that label.` : ""}${localProject ? ` It's a local project, in ${join(config.localStore ?? "", config.project)}.` : ` Signed in with ${credential.kind}${credential.id ? ` ${credential.id}` : ""}.`}`, 331334 ...(behind ? [behind] : []), 332335 // Is shared green (#39)? Right under the first line, since it decides what to do next. 333336 ...ciText(status.ci, status.version), new file, 141 lines
1+// abso login --web: a staging website session for the person a box is signed in as, opened in an agent's own browser, with 2+// no secret in the agent's hands. The website's /login/handoff takes this box's sign-in (or a test account's PAT, from a file) 3+// and answers a one-use link that works for a minute; opening it signs that browser in. Only the link is printed: never the 4+// box's sign-in, the PAT or the session cookie, which the website sets in the browser itself. 6+import { readFileSync } from "node:fs"; 7+import { UsageError } from "./args.ts"; 9+/** The website beside each staging server. Prod has none here: agents never sign in to the website on prod. */ 10+const STAGING_SITES: Readonly<Record<string, string>> = { 11+ "https://abso-staging.chrisazy.workers.dev": "https://abso-website-staging.chrisazy.workers.dev", 12+ "https://avcs-staging.chrisazy.workers.dev": "https://abso-website-staging.chrisazy.workers.dev", 15+/** What the website answers: the link, when it stops working, and who and until when it signs in. */ 16+export interface Handoff { 17+ readonly url: string; 18+ readonly expiresAt: string; 19+ readonly account: string; 20+ readonly name: string; 21+ readonly sessionEnds: string; 25+ * The website a handoff's credential goes to (Security condition 6, Code Review): the staging website beside the folder's own 26+ * staging server, from the fixed list above, and never an origin from a flag. A server that isn't on the list is refused, 27+ * prod included. --site is only for a test account's PAT on this machine (http://localhost or 127.0.0.1); a box's sign-in 28+ * takes no --site at all. 30+export function siteFor(server: string, site: string | undefined, kind: "box" | "pat"): string { 31+ const origin = new URL(server).origin; 32+ const known = STAGING_SITES[origin]; 33+ if (known === undefined) 34+ throw new UsageError( 35+ `abso login --web is for staging: ${origin} has no staging website beside it that abso knows, and agents never sign in to the website on prod. Nothing was sent.`, 37+ if (site === undefined) return known; 39+ throw new UsageError(`--site isn't taken with a box's sign-in, which goes only to ${known}. Nothing was sent.`); 40+ let url: URL | null = null; 44+ // Not an address: refused below. 46+ if (url === null || url.protocol !== "http:" || (url.hostname !== "localhost" && url.hostname !== "127.0.0.1")) 47+ throw new UsageError( 48+ "--site, with --pat-file, names this machine only (http://localhost:<port> or http://127.0.0.1:<port>). Nothing was sent.", 54+ * abso login --web: where the credential would go is settled before it is read, so a refusal reads and sends nothing 55+ * (Security). `credential` reads the box's sign-in or the PAT only once the website is one it may go to. 57+export async function webLogin(options: { 58+ readonly server: string; 59+ readonly site: string | undefined; 60+ /** A box's sign-in, or a test account's PAT (--pat-file). */ 61+ readonly kind: "box" | "pat"; 62+ readonly credential: () => string; 63+ readonly fetcher?: typeof fetch; 64+}): Promise<{ handoff: Handoff; site: string }> { 65+ const site = siteFor(options.server, options.site, options.kind); 66+ return { handoff: await webHandoff(site, options.credential(), options.fetcher), site }; 69+/** A PAT from the file --pat-file names: read here, never printed. */ 70+export function patFromFile(path: string): string { 73+ text = readFileSync(path, "utf8").trim(); 75+ throw new UsageError(`--pat-file names ${path}, which abso can't read`); 77+ if (!/^abso_pat_[A-Za-z0-9_-]{16,200}$/.test(text)) 78+ throw new UsageError(`--pat-file names ${path}, which doesn't hold a PAT`); 82+/** Words from the website, with any secret this call sent taken out. */ 83+function scrubbed(text: string, secret: string): string { 84+ return text.split(secret).join("[the credential]").slice(0, 300); 87+/** Asks the website for a handoff link with `credential` (a box sign-in or a PAT) in Authorization. */ 88+export async function webHandoff(site: string, credential: string, fetcher: typeof fetch = fetch): Promise<Handoff> { 91+ res = await fetcher(`${site}/login/handoff`, { 93+ headers: { authorization: `Bearer ${credential}`, accept: "application/json" }, 95+ signal: AbortSignal.timeout(30_000), 98+ throw new UsageError(`couldn't reach ${site}: ${scrubbed((err as Error).message, credential)}`); 100+ const text = await res.text().catch(() => ""); 101+ let body: Partial<Handoff> & { error?: unknown } = {}; 103+ body = JSON.parse(text) as typeof body; 105+ // Not JSON: the status says enough. 108+ const why = typeof body.error === "string" ? body.error : `it answered ${res.status}`; 109+ throw new UsageError( 111+ ? `${site} doesn't hand out sign-in links (its key sign-in is off, or it isn't staging)` 112+ : `${site} refused: ${scrubbed(why, credential)}`, 116+ typeof body.url !== "string" || 117+ !body.url.startsWith(`${site}/login/handoff#`) || 118+ typeof body.expiresAt !== "string" || 119+ typeof body.account !== "string" 121+ throw new UsageError(`${site} answered something that isn't a sign-in link`); 124+ expiresAt: body.expiresAt, 125+ account: body.account, 126+ name: typeof body.name === "string" ? body.name : body.account, 127+ sessionEnds: typeof body.sessionEnds === "string" ? body.sessionEnds : body.expiresAt, 131+/** What abso login --web says: the one link, how long it works, who it signs in as, and what it reaches (Security). */ 132+export function handoffText(h: Handoff, site: string, boxed = true, now = Date.now()): string { 133+ const seconds = Math.max(0, Math.round((Date.parse(h.expiresAt) - now) / 1000)); 135+ ? "only to the projects this box was granted, at most as a writer, until the box is revoked or ends" 136+ : "at most as a writer"; 138+ `Open this link in your browser within ${seconds} seconds. It signs that browser in to ${site} as ${h.name}, until ${h.sessionEnds}, and works once. It reaches ${reach}:`, new file, 60 lines
1+// abso ci for a project whose CI is its pipeline file (abso 719): test-byoc on 2026-10-16 had no abso.json, and abso ci 2+// said "nothing to run" while its abso.yml's run 8 was going. The stored run is the project's CI there. 4+import assert from "node:assert/strict"; 5+import { test } from "node:test"; 6+import { builtInHasNothing, runLine, storedRuns } from "../src/ci.ts"; 8+const base = { latest: null, checked: null, running: null, red: null, behind: null } as const; 12+ reason: "nothing to run: no abso.json, and package.json has no test, typecheck or vite", 13+ at: "2026-10-16T16:47:00.000Z", 16+test("the stored runs are read strictly, newest first as the server lists them", () => { 17+ const runs = storedRuns({ 20+ { id: 8, version: 6, state: "running", file: "abso.yml", started: 1 }, 21+ { id: "7", version: 6, state: "failed", file: "abso.yml" }, 22+ { id: 6, version: 5, state: "failed", file: "abso.yml" }, 26+ runs.map((r) => r.id), 29+ assert.deepEqual(storedRuns(null), []); 30+ assert.deepEqual(storedRuns({ runs: "no" }), []); 33+test("a run in a line names its file, its state and where its jobs are", () => { 35+ runLine({ id: 8, version: 6, state: "running", file: "abso.yml" }), 36+ "Pipeline run 8 (abso.yml) is running on version 6. abso pipeline runs 8 shows its jobs.", 39+ runLine({ id: 7, version: 6, state: "failed", file: "abso.yml" }), 40+ "Pipeline run 7 (abso.yml) failed on version 6. abso pipeline runs 7 shows its jobs.", 43+ runLine({ id: 2, version: 1, state: "planned", file: "abso.yml" }), 44+ "Pipeline run 2 (abso.yml) was planned, not run, on version 1. abso pipeline runs 2 shows its jobs.", 48+test("only the built-in check's own nothing to run is set aside, never a red or another skip", () => { 49+ assert.equal(builtInHasNothing({ ...base, skipped: nothing }), true); 50+ assert.equal(builtInHasNothing({ ...base, skipped: { ...nothing, reason: "CI is off" } }), false); 51+ assert.equal(builtInHasNothing({ ...base }), false); 55+ red: { version: 6, agent: null, message: null, lastGood: null }, Lines 26–32 at 318 (were 26–31 at 287)
2626import { clientVersion, headCommit } from "../src/client-version.ts"; Lines 115–142 at 318 (were 114–119 at 287)
118+ it("stamps the command that runs this client's abso hook, where stamp.ts has a HOOK_COMMAND line", () => { 119+ const spec = source({ 121+ "export const STAMP: string | undefined = undefined\nexport const HOOK_COMMAND: readonly string[] | undefined = undefined\n", 123+ const target = join(temp(), "avcs"); 128+ hookCommand: ["C:\\node.exe", "C:\\abso\\client\\abso.ts", "hook"], 131+ read(target, "hooks/stamp.ts"), 132+ "export const STAMP: string | undefined = '0.1.0+702c616'\n" + 133+ 'export const HOOK_COMMAND: readonly string[] | undefined = ["C:\\\\node.exe","C:\\\\abso\\\\client\\\\abso.ts","hook"]\n', 135+ // By default, this checkout's own: the node running it and client/abso.ts. 136+ assert.deepEqual(hookCommand().slice(0, 1), [process.execPath]); 137+ assert.match(hookCommand()[1]!, /client[\\/]abso\.ts$/); 117140 it("moves the files in by rename, what the hook imports first and plugin.json last", () => { 118141 const spec = source(); 119142 const target = join(temp(), "avcs"); Lines 3–15 at 318 (were 3–12 at 287)
33// call that would leave the machine fails the test. 55import assert from "node:assert/strict"; 6−import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6+import { spawnSync } from "node:child_process"; 7+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; 78import { tmpdir } from "node:os"; 89import { join } from "node:path"; 910import { after, before, describe, it } from "node:test"; 11+import { fileURLToPath } from "node:url"; 12+import { closeLocalStores, LOCAL_BASE, localFetch } from "../src/local-store.ts"; 1013import { main } from "../src/main.ts"; 1114import { stateDir } from "../src/state-dir.ts"; Lines 42–53 at 318 (were 39–45 at 287)
4043const text = (dir: string, rel: string) => readFileSync(join(dir, rel), "utf8"); 42−describe("a local project, with the network off", () => {
45+/** A copy of the client without the open server beside it (a platform that pins only client/) has no local projects to test. */ 46+const noServer = existsSync(fileURLToPath(new URL("../../server/src/router.ts", import.meta.url))) 48+ : "no server/src beside this client, so no local projects"; 50+describe("a local project, with the network off", { skip: noServer }, () => { Lines 110–162 at 318 (were 102–110 at 287)
102110 assert.notEqual(held.exit, 0); 103111 assert.match(held.out + held.err, /collision/); 114+ it("issues, asks and news work too, kept in issues.sqlite beside the project", async () => { 115+ const opened = await run(alice, "issue", "new", "Fix the parser", "--agent", "bob"); 116+ assert.equal(opened.exit, 0, opened.out + opened.err); 117+ assert.ok(existsSync(join(store, "demo", "issues.sqlite"))); 118+ const listed = await run(bob, "issues"); 119+ assert.equal(listed.exit, 0, listed.err); 120+ assert.match(listed.out, /Fix the parser/); 121+ const started = await run(bob, "start", "Parser fix", "--issue", "1"); 122+ assert.equal(started.exit, 0, started.out + started.err); 123+ const asked = await run(alice, "ask", "bob", "Which grammar?", "--issue", "1"); 124+ assert.equal(asked.exit, 0, asked.out + asked.err); 125+ const waiting = await run(bob, "waiting", "--mine"); 126+ assert.equal(waiting.exit, 0, waiting.err); 127+ assert.match(waiting.out, /Which grammar\?/); 128+ const answered = await run(bob, "answer", "1", "The new one"); 129+ assert.equal(answered.exit, 0, answered.out + answered.err); 130+ const news = await run(alice, "news"); 131+ assert.equal(news.exit, 0, news.err); 132+ assert.match(news.out, /The new one/); 133+ const issue = await run(alice, "issue", "1"); 134+ assert.match(issue.out, /In progress|bob/); 137+ it("two calls at once on one project are both answered, one after the other", async () => { 138+ // As abso ci and waiting --mine make them, with Promise.all. 139+ const local = localFetch(store); 140+ const answers = await Promise.all([local(`${LOCAL_BASE}/p/demo/queue`), local(`${LOCAL_BASE}/p/demo/queue`)]); 142+ for (const a of answers) assert.equal(a.status, 200, await a.text()); 145+ it("a project's name can't start with a dot, so its folder stays inside the store", async () => { 146+ const dir = temp("dots"); 147+ writeFileSync(join(dir, "a.txt"), "x\n"); 148+ for (const name of ["..", ".hidden"]) { 149+ const r = await run(dir, "init", "--local", "--project", name, "--agent", "a"); 150+ assert.equal(r.exit, 1, r.out + r.err); 151+ // The name rule says why, before any call is made (a ".." would collapse the call's path). 152+ assert.match(r.err, /project names are letters, digits, dot, dash and underscore/); 154+ assert.ok(!existsSync(join(store, "..", "project.sqlite"))); 155+ assert.deepEqual(readdirSync(dir), ["a.txt"], "init left nothing behind"); 107−describe("where a local project's store is", () => {
159+describe("where a local project's store is", { skip: noServer }, () => { 108160 it("--store inside the folder is kept in its settings and left out of its files", async () => { 109161 store = temp("unused"); 110162 const dir = temp("venv"); Lines 190–222 at 318 (were 138–140 at 287)
138190 assert.equal(existsSync(join(dir, ".abso")) || existsSync(join(dir, ".avcs")), false); 194+describe("local commands as their own processes", { skip: noServer }, () => { 195+ // The way people and agents run them: client/abso.ts, a process per command, Node's compile cache as it is. 196+ const entry = fileURLToPath(new URL("../abso.ts", import.meta.url)); 197+ const cli = (cwd: string, processStore: string, ...argv: string[]) => 198+ spawnSync(process.execPath, [entry, ...argv], { 200+ env: { ...process.env, ABSO_STORE: processStore, ABSO_SERVERS_FILE: "no-servers.json" }, 204+ it("init, push, status and log each exit cleanly", () => { 205+ const processStore = temp("process-store"); 206+ const dir = temp("process"); 207+ writeFileSync(join(dir, "a.txt"), "one\n"); 208+ const steps: [string, string[]][] = [ 209+ ["init", ["init", "--local", "--project", "proc", "--agent", "p"]], 210+ ["push", ["push", "-m", "Two"]], 211+ ["status", ["status"]], 214+ for (const [name, argv] of steps) { 215+ if (name === "push") writeFileSync(join(dir, "a.txt"), "one\ntwo\n"); 216+ const r = cli(dir, processStore, ...argv); 217+ assert.equal(r.status, 0, `${name}: exit ${r.status} ${r.signal ?? ""}\n${r.stdout}${r.stderr}`); 218+ if (name === "status") assert.match(r.stdout, /It's a local project, in /); 219+ if (name === "log") assert.match(r.stdout, /Two/); Lines 134–182 at 318 (were 134–139 at 287)
134134 assert.equal(w.notes.length, 0); 137+test("a frame is a wake: --follow reads the news and prints that once; an empty read prints the frames", async () => { 138+ // The server's frames don't count as heard (abso 690): the read takes them, so each item prints once. 139+ const w = world([{ frames: ["fe told you: hello", "cloud asks: ship it?"], close: { code: 1006 } }]); 140+ const reads: string[][] = [["fe told you: hello", "cloud asks: ship it?"], []]; 142+ w.deps.take = async () => { 144+ return reads.shift() ?? []; 146+ await follow(w.deps); 147+ // Two frames, one read in flight: the second folds into one more read, which finds nothing new; its frame was 148+ // already printed by the first read, so nothing prints twice. 149+ assert.equal(calls, 2); 150+ assert.deepEqual(w.lines, ["fe told you: hello", "cloud asks: ship it?"]); 152+ // A server that counts a frame as heard already (staging 1418): the read is empty, so the frame is what shows. 153+ const old = world([{ frames: ["fe told you: hello"], close: { code: 1006 } }]); 154+ old.deps.take = async () => []; 155+ await follow(old.deps); 156+ assert.deepEqual(old.lines, ["fe told you: hello"]); 158+ // On that server a read can find other news waiting: the frame's own item still shows (Code Review, 291). 159+ const mixed = world([{ frames: ["fe told you: hello"], close: { code: 1006 } }]); 160+ mixed.deps.take = async () => ["cloud: an older item"]; 161+ await follow(mixed.deps); 162+ assert.deepEqual(mixed.lines, ["cloud: an older item", "fe told you: hello"]); 164+ // A catch-up frame names the first few waiting items and how many more: the read shows them all, the frame adds nothing. 165+ const catchUp = world([{ frames: ["fe told you: hello\ncloud: ship it?\nand 1 more"], close: { code: 1006 } }]); 166+ catchUp.deps.take = async () => ["fe told you: hello", "cloud: ship it?", "desk: a third"]; 167+ await follow(catchUp.deps); 168+ assert.deepEqual(catchUp.lines, ["fe told you: hello", "cloud: ship it?", "desk: a third"]); 170+ // A read that fails shows the frames and says why. 171+ const down = world([{ frames: ["fe told you: hello"], close: { code: 1006 } }]); 172+ down.deps.take = async () => { 173+ throw new Error("could not reach the server"); 175+ await follow(down.deps); 176+ assert.deepEqual(down.lines, ["fe told you: hello"]); 177+ assert.match(down.notes[0]!, /couldn't read the news: could not reach the server/); 137180test("--follow keeps an idle socket open with a ping the object answers without waking", async () => { 138181 const w = world([{ frames: [], close: { code: 1006 } }]); 139182 const held: number[] = []; new file, 106 lines
1+// abso login --web: a staging website session handed to a browser as a one-use link, with no secret printed. 3+import assert from "node:assert/strict"; 4+import { mkdtempSync, writeFileSync } from "node:fs"; 5+import { tmpdir } from "node:os"; 6+import { join } from "node:path"; 7+import { test } from "node:test"; 8+import { handoffText, patFromFile, siteFor, webHandoff, webLogin } from "../src/web-session.ts"; 10+const SITE = "https://abso-website-staging.chrisazy.workers.dev"; 11+const STAGING = "https://abso-staging.chrisazy.workers.dev"; 12+const BOX = `abso_bx_${"C".repeat(43)}`; 13+const PAT = `abso_pat_${"A".repeat(40)}`; 14+const NOW = Date.UTC(2026, 9, 16, 9, 0, 0); 16+test("the credential goes only to the staging website beside the folder's staging server (Security condition 6)", () => { 17+ assert.equal(siteFor(STAGING, undefined, "box"), SITE); 18+ assert.equal(siteFor("https://avcs-staging.chrisazy.workers.dev/", undefined, "pat"), SITE); 19+ // A server that isn't staging is refused, prod included, whatever is asked. 21+ () => siteFor("https://api.abso.dev", undefined, "box"), 22+ /for staging.*never sign in to the website on prod/, 24+ assert.throws(() => siteFor("https://api.abso.dev", "http://localhost:8871", "pat"), /for staging/); 25+ // A box's sign-in takes no --site, not even the staging website's own address. 26+ assert.throws(() => siteFor(STAGING, SITE, "box"), /isn't taken with a box's sign-in/); 27+ assert.throws(() => siteFor(STAGING, "http://localhost:8871", "box"), /isn't taken with a box's sign-in/); 28+ // A PAT may name this machine over http, and nothing else. 29+ assert.equal(siteFor(STAGING, "http://localhost:8871/x", "pat"), "http://localhost:8871"); 30+ assert.equal(siteFor(STAGING, "http://127.0.0.1:8871", "pat"), "http://127.0.0.1:8871"); 31+ for (const elsewhere of ["https://anywhere.example", SITE, "https://localhost:8871", "not a url"]) 32+ assert.throws(() => siteFor(STAGING, elsewhere, "pat"), /names this machine only/, elsewhere); 35+test("a refused handoff reads no credential and sends no request", async () => { 36+ const sent: string[] = []; 37+ const fetcher = (async (url: string) => (sent.push(url), Response.json({}))) as unknown as typeof fetch; 39+ const credential = () => (read++, BOX); 40+ for (const asked of [ 41+ { server: "https://api.abso.dev", site: undefined, kind: "box" as const }, 42+ { server: STAGING, site: "https://anywhere.example", kind: "box" as const }, 43+ { server: STAGING, site: SITE, kind: "box" as const }, 44+ { server: "https://api.abso.dev", site: "http://localhost:8871", kind: "pat" as const }, 45+ { server: STAGING, site: "https://anywhere.example", kind: "pat" as const }, 47+ await assert.rejects(webLogin({ ...asked, credential, fetcher }), /Nothing was sent/, JSON.stringify(asked)); 48+ assert.deepEqual(sent, []); 49+ assert.equal(read, 0); 50+ // Allowed, it goes to the staging website only. 51+ await webLogin({ server: STAGING, site: undefined, kind: "pat", credential: () => PAT, fetcher }).catch(() => {}); 52+ assert.deepEqual(sent, [`${SITE}/login/handoff`]); 55+test("the credential goes in Authorization only, and the answer is the one link and who it signs in as", async () => { 56+ const seen: { url: string; authorization: string | null; body: unknown }[] = []; 57+ const fetcher = (async (url: string, init: RequestInit) => { 58+ seen.push({ url, authorization: new Headers(init.headers).get("authorization"), body: init.body ?? null }); 59+ return Response.json({ 60+ url: `${SITE}/login/handoff#${"t".repeat(50)}`, 61+ expiresAt: new Date(NOW + 60_000).toISOString(), 62+ account: "acct_person1", 64+ sessionEnds: "2026-10-16T21:00:00.000Z", 67+ const h = await webHandoff(SITE, BOX, fetcher); 68+ assert.deepEqual(seen, [{ url: `${SITE}/login/handoff`, authorization: `Bearer ${BOX}`, body: null }]); 69+ const text = handoffText(h, SITE, true, NOW); 70+ assert.match(text, /within 60 seconds/); 71+ assert.match(text, /as christopher, until 2026-10-16T21:00:00.000Z, and works once/); 72+ assert.match(text, /only to the projects this box was granted, at most as a writer/); 73+ assert.match(handoffText(h, SITE, false, NOW), /It reaches at most as a writer:/); 74+ assert.match(text, /\/login\/handoff#t{50}$/); 75+ assert.doesNotMatch(text + JSON.stringify(h), /abso_bx_/); 78+test("a refusal says why without the credential; an answer that isn't the site's own link is refused", async () => { 79+ const echo = (async () => 80+ Response.json({ error: `that key was refused: ${BOX}` }, { status: 401 })) as unknown as typeof fetch; 81+ await assert.rejects(webHandoff(SITE, BOX, echo), (err: Error) => { 82+ assert.match(err.message, /refused: that key was refused: \[the credential\]/); 83+ assert.doesNotMatch(err.message, /abso_bx_/); 86+ const off = (async () => Response.json({ error: "not found" }, { status: 404 })) as unknown as typeof fetch; 87+ await assert.rejects(webHandoff(SITE, BOX, off), /doesn't hand out sign-in links/); 88+ const elsewhere = (async () => 90+ url: "https://elsewhere.example/login/handoff#x", 91+ expiresAt: new Date(NOW).toISOString(), 93+ })) as unknown as typeof fetch; 94+ await assert.rejects(webHandoff(SITE, BOX, elsewhere), /isn't a sign-in link/); 97+test("--pat-file reads a PAT from its file, and refuses a file that doesn't hold one", () => { 98+ const dir = mkdtempSync(join(tmpdir(), "abso-web-")); 99+ const good = join(dir, "pat"); 100+ writeFileSync(good, `abso_pat_${"A".repeat(40)}\n`); 101+ assert.equal(patFromFile(good), `abso_pat_${"A".repeat(40)}`); 102+ const bad = join(dir, "not"); 103+ writeFileSync(bad, "hello"); 104+ assert.throws(() => patFromFile(bad), /doesn't hold a PAT/); 105+ assert.throws(() => patFromFile(join(dir, "missing")), /can't read/);