Skip to content

abso-core

Public

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

Check passed

Versions 287 to 318

Compare

+2000 −195 in 120 places
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.
55
6+import { readFileSync } from "node:fs";
67import * as nodeModule from "node:module";
8+import { dirname, join } from "node:path";
79
10+const argv = process.argv.slice(2);
12+/**
13+ * Whether this command opens a local project (abso init --local): --local, or a folder whose config names the server
14+ * "local". Those load the open server's code through a module hook, and with the compile cache on Node 24 crashes.
15+ */
16+function opensLocal(): boolean {
17+ if (argv.includes("--local")) return true;
18+ for (let dir = process.cwd(); ; dir = dirname(dir)) {
19+ for (const state of [".abso", ".avcs"]) {
20+ try {
21+ return /"server"\s*:\s*"local"/.test(readFileSync(join(dir, state, "config.json"), "utf8"));
22+ } catch {}
23+ }
24+ if (dirname(dir) === dir) return false;
25+ }
26+}
828// Node keeps the compiled modules (TypeScript already stripped) in a cache in
929// the temp folder. Loading the hook's modules drops from about 55 ms to 11 ms.
1030// Node 20 has no compile cache, and the built client runs there without one.
11−(nodeModule as { enableCompileCache?: () => unknown }).enableCompileCache?.();
31+if (!opensLocal()) (nodeModule as { enableCompileCache?: () => unknown }).enableCompileCache?.();
1232
13−const argv = process.argv.slice(2);
14−
1533if (argv[0] === "hook") {
1634 const { runHook } = await import("./src/hook.ts");
1735 const chunks: Buffer[] = [];
Lines 3–12 at 318 (were 3–11 at 287)
33
44import type { On } from "claude-code";
55import { expect, mock, test } from "claude-code/testing";
6+import { HOOK_COMMAND } from "./stamp.ts";
67
78/** The world beneath the mod: a chat in /w/p, an abso folder when `inFolder`, and a server with `news` waiting. */
8−function world(on: On, inFolder: boolean, news: string[][]) {
9+function world(on: On, inFolder: boolean, news: string[][], server = "https://avcs.test") {
910 mock.env(on, { AVCS_TOKEN: "test-token" });
1011 const clock = mock.clock(on, { now: 1_000_000 });
1112 const asked: string[] = [];
Lines 22–28 at 318 (were 21–27 at 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}` };
2728 });
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([]);
116117});
119+test("a local project's edit goes to abso hook as Claude Code's command hook would get it, and its news to the chat", async ($, on) => {
120+ const w = world(on, true, [], "local");
121+ w.written.set("/w/p/notes.md", "hello\n");
122+ on("fs.stat", () => ({ value: { realPath: "/w/p/notes.md" } }) as never);
123+ on("session.id", () => ({ value: "sess" }));
124+ const ran: { argv: readonly string[]; stdin?: string; env?: Record<string, string> }[] = [];
125+ const context = "abso: Announcement from lead: hold pushes";
126+ on("process.run", (_$, e) => {
127+ ran.push({ argv: e.argv, stdin: e.init?.stdin, env: e.init?.env });
128+ const stdout = JSON.stringify({ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: context } });
129+ return { value: { exitCode: 0, stdout, stderr: "" } } as never;
130+ });
131+ await $.session.start({ cwd: "/w/p" });
132+ await $.tool.call({ tool: "Write", tool_use_id: "t1", file_path: "/w/p/notes.md", content: "hello\n" } as never);
133+ await w.clock.advance(1_000);
134+ // A local project has no server to call: nothing goes over the network.
135+ expect(w.asked.filter((u) => !u.endsWith("/news"))).toEqual([]);
136+ const log = w.written.get("/w/p/.abso/hook.log") ?? "";
137+ if (HOOK_COMMAND === undefined) {
138+ // Loaded from a checkout, the mod has no client to hand it to.
139+ expect(ran).toEqual([]);
140+ expect(log).toContain("skipped: a local project");
141+ return;
142+ }
143+ expect(ran).toHaveLength(1);
144+ expect(ran[0]!.argv).toEqual(HOOK_COMMAND);
145+ expect(ran[0]!.env).toEqual({ ABSO_HOOK_FORCE: "1" });
146+ const input = JSON.parse(ran[0]!.stdin ?? "{}") as Record<string, unknown>;
147+ expect(input.session_id).toBe("sess");
148+ expect(input.tool_name).toBe("Write");
149+ expect((input.tool_input as Record<string, unknown>).file_path).toBe("/w/p/notes.md");
150+ expect(log).toContain("handed to abso hook");
151+ expect(w.appended).toEqual([context]);
152+});
Lines 33–39 at 318 (were 33–39 at 287)
3333 uncomposedText,
3434 type Who,
3535} from "../src/core.ts";
36−import { STAMP } from "./stamp.ts";
36+import { HOOK_COMMAND, STAMP } from "./stamp.ts";
3737
3838const TOOLS = ["Edit", "MultiEdit", "Write", "NotebookEdit"];
3939/** A known copy holding a NUL byte reads as no known copy (the client treats it as binary). */
Lines 184–205 at 318 (were 184–202 at 287)
184184
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;
187189
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;
192196 try {
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)
217220 job.root,
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}`,
219222 );
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");
225228 try {
226229 await $.session.append({
227230 message: { type: "user", content: [{ type: "text", text: context }] },
Lines 237–279 at 318 (were 234–239 at 287)
234237 }
235238}
236239
240+/**
241+ * A local project's history is in a store on this machine that only the abso command opens, so its edits go to
242+ * `abso hook` from the checkout this mod was installed from, as Claude Code's command hook would run it.
243+ */
244+async function handToClient($: Engine, job: Job): Promise<{ outcome: string; context?: string }> {
245+ if (HOOK_COMMAND === undefined || HOOK_COMMAND.length === 0)
246+ return {
247+ outcome:
248+ "skipped: a local project, and this mod has no abso to hand it to (install-mod.ts adds one); abso record sends it",
249+ };
250+ const hookInput = {
251+ session_id: await $.session.id(),
252+ cwd: slash(await $.session.cwd()),
253+ tool_name: job.tool,
254+ tool_input: job.input,
255+ ...(job.agentId ? { agent_id: job.agentId } : {}),
256+ };
257+ const ran = await $.process.run(HOOK_COMMAND, {
258+ cwd: job.root,
259+ env: { ABSO_HOOK_FORCE: "1" },
260+ stdin: JSON.stringify(hookInput),
261+ timeoutMs: LOCAL_HOOK_MS,
262+ });
263+ if (ran.exitCode !== 0) throw new Error(`abso hook exited ${ran.exitCode}: ${ran.stderr.trim().split("\n").at(-1)}`);
264+ // It prints Claude Code's JSON when it has news for the agent, and nothing otherwise.
265+ const out = ran.stdout.trim();
266+ const context =
267+ out === ""
268+ ? undefined
269+ : (JSON.parse(out) as { hookSpecificOutput?: { additionalContext?: unknown } }).hookSpecificOutput
270+ ?.additionalContext;
271+ return {
272+ outcome: "handed to abso hook (a local project; its own line is just above)",
273+ ...(typeof context === "string" ? { context } : {}),
274+ };
275+}
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> {
239279 try {
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;
6+
7+// The command that runs `abso hook` from the checkout the mod was installed
8+// from, as [node, client/abso.ts, "hook"]; the installer writes it too. A
9+// local project's history is in a store on this machine that only the abso
10+// command opens, so the mod hands those edits to it.
11+export const HOOK_COMMAND: readonly string[] | undefined = undefined;
Lines 107–114 at 318 (were 107–112 at 287)
107107 try {
108108 const ended = await follow({
109109 mint: () => api.newsTicket(),
110+ // A frame is a wake: read the news, which marks it heard, and print that (news-stream.ts).
111+ take: async () => newsLines((await api.news()).news),
110112 connect: (url, protocols) => new WebSocket(url, [...protocols]) as unknown as Socket,
111113 write: (line) => {
112114 logNews(root, [line]);
Lines 80–122 at 318 (were 80–85 at 287)
8080 return lines;
8181}
8282
83+/** A stored pipeline run as runRuns lists it: what the CI lines need of it. */
84+interface StoredRun {
85+ readonly id: number;
86+ readonly version: number;
87+ readonly state: string;
88+ readonly file: string;
89+}
91+/** The stored pipeline runs, newest first, from the server's `pipelines` read; empty for anything else. */
92+export function storedRuns(raw: unknown): StoredRun[] {
93+ const runs = (raw as { runs?: unknown } | null)?.runs;
94+ if (!Array.isArray(runs)) return [];
95+ return runs.filter(
96+ (r): r is StoredRun =>
97+ typeof r === "object" &&
98+ r !== null &&
99+ Number.isInteger((r as StoredRun).id) &&
100+ Number.isInteger((r as StoredRun).version) &&
101+ typeof (r as StoredRun).state === "string" &&
102+ typeof (r as StoredRun).file === "string",
103+ );
104+}
106+/** One stored run in a line, with where its jobs are. */
107+export function runLine(run: StoredRun): string {
108+ const how = run.state === "planned" ? "was planned, not run," : run.state === "running" ? "is running" : run.state;
109+ return `Pipeline run ${run.id} (${run.file}) ${how} on version ${run.version}. abso pipeline runs ${run.id} shows its jobs.`;
110+}
112+/**
113+ * Whether the built-in check (abso.json's setup, build and check) had nothing of its own to run. With stored runs, that is
114+ * about the built-in check, not the project's CI, so it isn't said as the project's (abso 719).
115+ */
116+export function builtInHasNothing(ci: CiStatus): boolean {
117+ return ci.red === null && ci.skipped?.reason.startsWith("nothing to run") === true;
118+}
83120/** A shared version's mark in abso log; "not checked" says nothing, since most versions in a busy hour are covered by a newer one's job. */
84121export function ciMarkText(mark: CiMark | undefined): string {
85122 switch (mark) {
Lines 180–199 at 318 (were 143–153 at 287)
143180 }
144181 if (typed !== undefined) {
145182 if (!/^\d+$/.test(typed)) throw new UsageError(`a version is a number (got ${JSON.stringify(typed)})`);
146− const job = await api.ci(Number(typed));
147− return { text: jobText(job).join("\n"), json: { ...job } };
183+ const [job, raw] = await Promise.all([api.ci(Number(typed)), api.pipelineRuns().catch(() => null)]);
184+ const run = storedRuns(raw).find((r) => r.version === job.version);
185+ // A version the built-in check never ran, with a pipeline run of its own: the run is its CI (abso 719).
186+ const text = run !== undefined && job.result === "none" ? [runLine(run)] : jobText(job);
187+ return { text: text.join("\n"), json: { ...job } };
148188 }
149− const [ci, status] = await Promise.all([api.ci(), api.status()]);
150− const lines = ciText(ci, status.version);
189+ const [ci, status, raw] = await Promise.all([api.ci(), api.status(), api.pipelineRuns().catch(() => null)]);
190+ const newest = storedRuns(raw)[0];
191+ const lines =
192+ newest === undefined
193+ ? ciText(ci, status.version)
194+ : builtInHasNothing(ci)
195+ ? [runLine(newest)]
196+ : [...ciText(ci, status.version), runLine(newest)];
151197 return {
152198 text: [
153199 `shared is at version ${status.version}.`,
Lines 2–7 at 318 (were 2–8 at 287)
22
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)
6059 */
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.
63+ const folder =
64+ root
65+ .split(/[\\/]+/)
66+ .filter((p) => p !== "")
67+ .at(-1) ?? "";
68+ return callerHeader({ session: hashed, machine, folder });
6469}
6570
6671/**
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[];
9799}
98100
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));
134136
137+/** Whether the installed abso mod hands a local project's edits to abso hook: it was installed with a HOOK_COMMAND. */
138+export function modHandsLocal(env: Readonly<Record<string, string | undefined>> = process.env): boolean {
139+ try {
140+ return /HOOK_COMMAND[^=\n]*=\s*\[/.test(readFileSync(at(skillsFolder(AVCS_MOD.name, env), STAMP_FILE), "utf8"));
141+ } catch {
142+ return false;
143+ }
144+}
135146/**
136147 * After the new mod is in, the folder it replaces (skills/avcs, skills/avcs-view) would load beside it, so it
137148 * is moved, not deleted, to ~/.abso/retired-mods/<name>-<stamp>. Returns where it went, or undefined when there was none.
Lines 237–247 at 318 (were 226–233 at 287)
226237 return commit;
227238}
228239
229−/** The files to install, stamped with `version`, in install order. */
230−function filesFor(spec: ModSpec, version: string): Map<string, Buffer> {
240+/** The command that runs this checkout's `abso hook`: what the mod hands a local project's edits to. */
241+export const hookCommand = (): readonly string[] => [process.execPath, join(CLIENT_DIR, "abso.ts"), "hook"];
243+/** The files to install, stamped with `version` (and HOOK_COMMAND, where a stamp.ts has it), in install order. */
244+function filesFor(spec: ModSpec, version: string, hook: readonly string[] = hookCommand()): Map<string, Buffer> {
231245 if (!/^[\w.+-]+$/.test(version)) throw new Error(`can't stamp the version ${JSON.stringify(version)}`);
232246 const out = new Map<string, Buffer>();
233247 for (const rel of spec.files) {
Lines 253–261 at 318 (were 239–245 at 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);
256+ data = Buffer.from(
257+ stamped.replace(/(HOOK_COMMAND[^=\n]*=\s*)undefined/, (_, head: string) => head + JSON.stringify(hook)),
258+ );
243259 }
244260 out.set(rel, data);
245261 }
Lines 402–408 at 318 (were 386–392 at 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 });
392408 try {
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";
3334
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 };
44+ }
3945 // An explicit --server goes to that server's own Issues Worker: ABSO_ISSUES_SERVER doesn't redirect it.
4046 const server =
4147 (env.server === undefined ? fromEnv(env.env, "ISSUES_SERVER") : undefined) ||
Lines 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)})`,
161+ );
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)
538543}
539544
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.
547+ if (local) {
548+ if (modHandsLocal(env))
549+ return "Edits made by Claude Code here are recorded by the abso mod on this machine, through abso hook. Anything else: abso record.";
550+ if (modInstalled(env) && !builtCopy())
551+ return `abso record sends the edits made here: the abso mod on this machine is older than local projects. ${installerCommand("install-mod.ts")} updates it, and new chats load it.`;
552+ return "abso record sends the edits made here, whoever made them.";
553+ }
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.
44
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)
159159
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>;
192195};
193196let server: Promise<Server> | undefined;
194197
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;
225228 };
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);
230235 },
231236 });
237+ let loaded: typeof import("./local-server.mjs");
232238 try {
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");
240+ } catch (e) {
241+ // Nothing is reached for here: a part of the client is missing (its packages not installed, say).
242+ throw new LocalError(
243+ `local projects couldn't load the server's code: ${e instanceof Error ? e.message : String(e)}`,
244+ );
241245 }
246+ return {
247+ DatabaseSync: sqlite.DatabaseSync,
248+ handle: loaded.handle,
249+ ProjectObject: loaded.ProjectObject,
250+ IssueProject: loaded.IssueProject,
251+ issuesFetch: loaded.issuesFetch,
252+ };
242253 })();
243254 return server;
244255}
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;
257272}
258273
259274/** Every store file this process has open: closed when its command ends (closeLocalStores). */
Lines 284–293 at 318 (were 269–276 at 287)
269284 opened.clear();
270285}
271286
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 });
275292
276293/**
Lines 327–365 at 318 (were 310–319 at 287)
310327 return p.object;
311328 },
312329 },
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: () => ({}) },
330+ ISSUES_DO: {
331+ idFromName: (n: string) => n,
332+ get: (n: string) => {
333+ const p = open.get(n);
334+ if (!p || n !== name) throw new LocalError(`no local project ${n}`);
335+ if (p.issues === undefined || !opened.has(p.issues.db)) {
336+ const db = new opening!.DatabaseSync(join(dir, name, "issues.sqlite"));
337+ opened.add(db);
338+ db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 120000; PRAGMA synchronous = NORMAL");
339+ p.issues = { db, storage: storageOver(db) };
340+ }
341+ // Its writes need no lock of their own: every call holds the project file's (see below).
342+ p.issueObject ??= new opening!.IssueProject(
343+ { id: { toString: () => n, name: n }, storage: p.issues.storage },
344+ env(name),
345+ );
346+ return p.issueObject;
347+ },
348+ },
315349 });
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),
357+ );
358+ last = next.catch(() => {});
359+ return next;
360+ };
362+ async function call(input: string, init: RequestInit = {}): Promise<Response> {
317363 const s = await loadServer();
318364 opening = s;
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;
331380 try {
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)
335384 request,
336385 env(name),
337386 { waitUntil: (w: Promise<unknown>) => waits.push(w) },
338− issuesNone,
387+ s.issuesFetch,
339388 );
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) });
356405 }
357− };
406+ }
358407}
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";
8283
8384interface CommandDef {
8485 readonly flags: FlagSpec;
Lines 213–244 at 318 (were 212–224 at 287)
212213 projects: "string",
213214 role: "string",
214215 days: "string",
216+ web: "boolean",
217+ site: "string",
218+ "pat-file": "string",
215219 },
216220 usage:
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>]]",
218222 about:
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({
229+ server,
230+ site: str(args, "site"),
231+ kind: patFile === undefined ? "box" : "pat",
232+ credential: () => {
233+ if (patFile !== undefined) return patFromFile(patFile);
234+ const record = readBox(server);
235+ if (record === undefined || record.expiresAt <= Date.now())
236+ throw new UsageError(`this box isn't signed in to ${server}: abso login first, or --pat-file <file>`);
237+ return record.credential;
238+ },
239+ });
240+ return { text: handoffText(handoff, site, patFile === undefined), json: { ...handoff } };
241+ }
222242 const open =
223243 bool(args, "no-browser") || browserSkip(env.env, process.platform) !== null
224244 ? undefined
Lines 94–101 at 318 (were 94–99 at 287)
9494 sleep(ms: number): Promise<void>;
9595 now(): number;
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)
107109}
108110
109111/**
112+ * A frame is a wake (abso 690): on one, read the seat's news (which marks it heard) and print what that answers, one
113+ * read at a time, with frames that arrive meanwhile folded into one more read. When the read answers nothing (a server
114+ * that counts a frame as heard already, or another chat on the seat took it first), the frames themselves are printed.
115+ */
116+function frameReads(deps: FollowDeps): { frame(text: string): void; idle(): Promise<void> } {
117+ let frames: string[] = [];
118+ /** The lines printed lately, so a frame a read already printed isn't printed again. */
119+ const shown: string[] = [];
120+ const show = (line: string) => {
121+ deps.write(line);
122+ shown.push(line);
123+ if (shown.length > 200) shown.shift();
124+ };
125+ let running: Promise<void> | undefined;
126+ let again = false;
127+ const pass = async () => {
128+ do {
129+ again = false;
130+ const these = frames;
131+ frames = [];
132+ let items: readonly string[] = [];
133+ try {
134+ items = await deps.take!();
135+ } catch (err) {
136+ deps.note(`(abso news --follow: couldn't read the news: ${(err as Error).message}; showing the frames)`);
137+ }
138+ for (const line of items) show(line);
139+ // A frame the read didn't cover still shows: on a server that counts a frame as heard, its item never comes back
140+ // from the read. A catch-up frame names several items, so a frame holding a shown item counts as covered.
141+ for (const frame of these) if (!shown.some((line) => frame.includes(line) || line.includes(frame))) show(frame);
142+ } while (again);
143+ running = undefined;
144+ };
145+ return {
146+ frame(text) {
147+ frames.push(text);
148+ if (running !== undefined) again = true;
149+ else running = pass();
150+ },
151+ idle: () => running ?? Promise.resolve(),
152+ };
153+}
155+/**
110156 * Holds the seat's stream, printing one line per item, until the key is refused or `stopped()`.
111157 * Returns why it ended.
112158 */
113159export async function follow(deps: FollowDeps): Promise<{ ended: "refused" | "stopped"; reason: string }> {
160+ const reads = frameReads(deps);
114161 let wait = 1_000;
115162 while (!deps.stopped()) {
116163 let ticket: NewsTicket;
Lines 186–198 at 318 (were 139–150 at 287)
139186 };
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);
143191 };
144192 socket.onerror = () => {};
145193 socket.onclose = (e) => {
146194 stopPing();
147− done({ code: e.code, reason: e.reason });
195+ void reads.idle().then(() => done({ code: e.code, reason: e.reason }));
148196 };
149197 });
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);
329332 const lines = [
330− `Project ${config.project}: shared is at version ${status.version}. This folder is ${config.agent}${config.reader || me?.reader ? ", a reader (it records and pushes nothing)" : ""}, working in ${space(me?.draft)}.${config.follow ? ` It follows label ${config.follow}: pulls take it to the newest version with that label.` : ""} Signed in with ${credential.kind}${credential.id ? ` ${credential.id}` : ""}.`,
333+ `Project ${config.project}: shared is at version ${status.version}. This folder is ${config.agent}${config.reader || me?.reader ? ", a reader (it records and pushes nothing)" : ""}, working in ${space(me?.draft)}.${config.follow ? ` It follows label ${config.follow}: pulls take it to the newest version with that label.` : ""}${localProject ? ` It's a local project, in ${join(config.localStore ?? "", config.project)}.` : ` Signed in with ${credential.kind}${credential.id ? ` ${credential.id}` : ""}.`}`,
331334 ...(behind ? [behind] : []),
332335 // Is shared green (#39)? Right under the first line, since it decides what to do next.
333336 ...ciText(status.ci, status.version),
new file, 141 lines
1+// abso login --web: a staging website session for the person a box is signed in as, opened in an agent's own browser, with
2+// no secret in the agent's hands. The website's /login/handoff takes this box's sign-in (or a test account's PAT, from a file)
3+// and answers a one-use link that works for a minute; opening it signs that browser in. Only the link is printed: never the
4+// box's sign-in, the PAT or the session cookie, which the website sets in the browser itself.
5+
6+import { readFileSync } from "node:fs";
7+import { UsageError } from "./args.ts";
8+
9+/** The website beside each staging server. Prod has none here: agents never sign in to the website on prod. */
10+const STAGING_SITES: Readonly<Record<string, string>> = {
11+ "https://abso-staging.chrisazy.workers.dev": "https://abso-website-staging.chrisazy.workers.dev",
12+ "https://avcs-staging.chrisazy.workers.dev": "https://abso-website-staging.chrisazy.workers.dev",
13+};
15+/** What the website answers: the link, when it stops working, and who and until when it signs in. */
16+export interface Handoff {
17+ readonly url: string;
18+ readonly expiresAt: string;
19+ readonly account: string;
20+ readonly name: string;
21+ readonly sessionEnds: string;
22+}
24+/**
25+ * The website a handoff's credential goes to (Security condition 6, Code Review): the staging website beside the folder's own
26+ * staging server, from the fixed list above, and never an origin from a flag. A server that isn't on the list is refused,
27+ * prod included. --site is only for a test account's PAT on this machine (http://localhost or 127.0.0.1); a box's sign-in
28+ * takes no --site at all.
29+ */
30+export function siteFor(server: string, site: string | undefined, kind: "box" | "pat"): string {
31+ const origin = new URL(server).origin;
32+ const known = STAGING_SITES[origin];
33+ if (known === undefined)
34+ throw new UsageError(
35+ `abso login --web is for staging: ${origin} has no staging website beside it that abso knows, and agents never sign in to the website on prod. Nothing was sent.`,
36+ );
37+ if (site === undefined) return known;
38+ if (kind === "box")
39+ throw new UsageError(`--site isn't taken with a box's sign-in, which goes only to ${known}. Nothing was sent.`);
40+ let url: URL | null = null;
41+ try {
42+ url = new URL(site);
43+ } catch {
44+ // Not an address: refused below.
45+ }
46+ if (url === null || url.protocol !== "http:" || (url.hostname !== "localhost" && url.hostname !== "127.0.0.1"))
47+ throw new UsageError(
48+ "--site, with --pat-file, names this machine only (http://localhost:<port> or http://127.0.0.1:<port>). Nothing was sent.",
49+ );
50+ return url.origin;
51+}
53+/**
54+ * abso login --web: where the credential would go is settled before it is read, so a refusal reads and sends nothing
55+ * (Security). `credential` reads the box's sign-in or the PAT only once the website is one it may go to.
56+ */
57+export async function webLogin(options: {
58+ readonly server: string;
59+ readonly site: string | undefined;
60+ /** A box's sign-in, or a test account's PAT (--pat-file). */
61+ readonly kind: "box" | "pat";
62+ readonly credential: () => string;
63+ readonly fetcher?: typeof fetch;
64+}): Promise<{ handoff: Handoff; site: string }> {
65+ const site = siteFor(options.server, options.site, options.kind);
66+ return { handoff: await webHandoff(site, options.credential(), options.fetcher), site };
67+}
69+/** A PAT from the file --pat-file names: read here, never printed. */
70+export function patFromFile(path: string): string {
71+ let text: string;
72+ try {
73+ text = readFileSync(path, "utf8").trim();
74+ } catch {
75+ throw new UsageError(`--pat-file names ${path}, which abso can't read`);
76+ }
77+ if (!/^abso_pat_[A-Za-z0-9_-]{16,200}$/.test(text))
78+ throw new UsageError(`--pat-file names ${path}, which doesn't hold a PAT`);
79+ return text;
80+}
82+/** Words from the website, with any secret this call sent taken out. */
83+function scrubbed(text: string, secret: string): string {
84+ return text.split(secret).join("[the credential]").slice(0, 300);
85+}
87+/** Asks the website for a handoff link with `credential` (a box sign-in or a PAT) in Authorization. */
88+export async function webHandoff(site: string, credential: string, fetcher: typeof fetch = fetch): Promise<Handoff> {
89+ let res: Response;
90+ try {
91+ res = await fetcher(`${site}/login/handoff`, {
92+ method: "POST",
93+ headers: { authorization: `Bearer ${credential}`, accept: "application/json" },
94+ redirect: "error",
95+ signal: AbortSignal.timeout(30_000),
96+ });
97+ } catch (err) {
98+ throw new UsageError(`couldn't reach ${site}: ${scrubbed((err as Error).message, credential)}`);
99+ }
100+ const text = await res.text().catch(() => "");
101+ let body: Partial<Handoff> & { error?: unknown } = {};
102+ try {
103+ body = JSON.parse(text) as typeof body;
104+ } catch {
105+ // Not JSON: the status says enough.
106+ }
107+ if (!res.ok) {
108+ const why = typeof body.error === "string" ? body.error : `it answered ${res.status}`;
109+ throw new UsageError(
110+ res.status === 404
111+ ? `${site} doesn't hand out sign-in links (its key sign-in is off, or it isn't staging)`
112+ : `${site} refused: ${scrubbed(why, credential)}`,
113+ );
114+ }
115+ if (
116+ typeof body.url !== "string" ||
117+ !body.url.startsWith(`${site}/login/handoff#`) ||
118+ typeof body.expiresAt !== "string" ||
119+ typeof body.account !== "string"
120+ )
121+ throw new UsageError(`${site} answered something that isn't a sign-in link`);
122+ return {
123+ url: body.url,
124+ expiresAt: body.expiresAt,
125+ account: body.account,
126+ name: typeof body.name === "string" ? body.name : body.account,
127+ sessionEnds: typeof body.sessionEnds === "string" ? body.sessionEnds : body.expiresAt,
128+ };
129+}
131+/** What abso login --web says: the one link, how long it works, who it signs in as, and what it reaches (Security). */
132+export function handoffText(h: Handoff, site: string, boxed = true, now = Date.now()): string {
133+ const seconds = Math.max(0, Math.round((Date.parse(h.expiresAt) - now) / 1000));
134+ const reach = boxed
135+ ? "only to the projects this box was granted, at most as a writer, until the box is revoked or ends"
136+ : "at most as a writer";
137+ return [
138+ `Open this link in your browser within ${seconds} seconds. It signs that browser in to ${site} as ${h.name}, until ${h.sessionEnds}, and works once. It reaches ${reach}:`,
139+ h.url,
140+ ].join("\n");
141+}
new file, 60 lines
1+// abso ci for a project whose CI is its pipeline file (abso 719): test-byoc on 2026-10-16 had no abso.json, and abso ci
2+// said "nothing to run" while its abso.yml's run 8 was going. The stored run is the project's CI there.
3+
4+import assert from "node:assert/strict";
5+import { test } from "node:test";
6+import { builtInHasNothing, runLine, storedRuns } from "../src/ci.ts";
7+
8+const base = { latest: null, checked: null, running: null, red: null, behind: null } as const;
9+const nothing = {
10+ version: 6,
11+ from: 6,
12+ reason: "nothing to run: no abso.json, and package.json has no test, typecheck or vite",
13+ at: "2026-10-16T16:47:00.000Z",
14+};
16+test("the stored runs are read strictly, newest first as the server lists them", () => {
17+ const runs = storedRuns({
18+ blocked: null,
19+ runs: [
20+ { id: 8, version: 6, state: "running", file: "abso.yml", started: 1 },
21+ { id: "7", version: 6, state: "failed", file: "abso.yml" },
22+ { id: 6, version: 5, state: "failed", file: "abso.yml" },
23+ ],
24+ });
25+ assert.deepEqual(
26+ runs.map((r) => r.id),
27+ [8, 6],
28+ );
29+ assert.deepEqual(storedRuns(null), []);
30+ assert.deepEqual(storedRuns({ runs: "no" }), []);
31+});
33+test("a run in a line names its file, its state and where its jobs are", () => {
34+ assert.equal(
35+ runLine({ id: 8, version: 6, state: "running", file: "abso.yml" }),
36+ "Pipeline run 8 (abso.yml) is running on version 6. abso pipeline runs 8 shows its jobs.",
37+ );
38+ assert.equal(
39+ runLine({ id: 7, version: 6, state: "failed", file: "abso.yml" }),
40+ "Pipeline run 7 (abso.yml) failed on version 6. abso pipeline runs 7 shows its jobs.",
41+ );
42+ assert.equal(
43+ runLine({ id: 2, version: 1, state: "planned", file: "abso.yml" }),
44+ "Pipeline run 2 (abso.yml) was planned, not run, on version 1. abso pipeline runs 2 shows its jobs.",
45+ );
46+});
48+test("only the built-in check's own nothing to run is set aside, never a red or another skip", () => {
49+ assert.equal(builtInHasNothing({ ...base, skipped: nothing }), true);
50+ assert.equal(builtInHasNothing({ ...base, skipped: { ...nothing, reason: "CI is off" } }), false);
51+ assert.equal(builtInHasNothing({ ...base }), false);
52+ assert.equal(
53+ builtInHasNothing({
54+ ...base,
55+ red: { version: 6, agent: null, message: null, lastGood: null },
56+ skipped: nothing,
57+ }),
58+ false,
59+ );
60+});
Lines 26–32 at 318 (were 26–31 at 287)
2626import { clientVersion, headCommit } from "../src/client-version.ts";
2727import {
2828 AVCS_MOD,
29+ hookCommand,
2930 installerCommand,
3031 installMod,
3132 keptModCommit,
Lines 115–142 at 318 (were 114–119 at 287)
114115 );
115116 });
116117
118+ it("stamps the command that runs this client's abso hook, where stamp.ts has a HOOK_COMMAND line", () => {
119+ const spec = source({
120+ "hooks/stamp.ts":
121+ "export const STAMP: string | undefined = undefined\nexport const HOOK_COMMAND: readonly string[] | undefined = undefined\n",
122+ });
123+ const target = join(temp(), "avcs");
124+ installMod(spec, {
125+ target,
126+ check: pass,
127+ commit: "702c616",
128+ hookCommand: ["C:\\node.exe", "C:\\abso\\client\\abso.ts", "hook"],
129+ });
130+ assert.equal(
131+ read(target, "hooks/stamp.ts"),
132+ "export const STAMP: string | undefined = '0.1.0+702c616'\n" +
133+ 'export const HOOK_COMMAND: readonly string[] | undefined = ["C:\\\\node.exe","C:\\\\abso\\\\client\\\\abso.ts","hook"]\n',
134+ );
135+ // By default, this checkout's own: the node running it and client/abso.ts.
136+ assert.deepEqual(hookCommand().slice(0, 1), [process.execPath]);
137+ assert.match(hookCommand()[1]!, /client[\\/]abso\.ts$/);
138+ });
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.
44
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";
1215
Lines 42–53 at 318 (were 39–45 at 287)
3942}
4043const text = (dir: string, rel: string) => readFileSync(join(dir, rel), "utf8");
4144
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)))
47+ ? false
48+ : "no server/src beside this client, so no local projects";
50+describe("a local project, with the network off", { skip: noServer }, () => {
4351 let alice: string;
4452 let bob: string;
4553 before(() => {
Lines 110–162 at 318 (were 102–110 at 287)
102110 assert.notEqual(held.exit, 0);
103111 assert.match(held.out + held.err, /collision/);
104112 });
114+ it("issues, asks and news work too, kept in issues.sqlite beside the project", async () => {
115+ const opened = await run(alice, "issue", "new", "Fix the parser", "--agent", "bob");
116+ assert.equal(opened.exit, 0, opened.out + opened.err);
117+ assert.ok(existsSync(join(store, "demo", "issues.sqlite")));
118+ const listed = await run(bob, "issues");
119+ assert.equal(listed.exit, 0, listed.err);
120+ assert.match(listed.out, /Fix the parser/);
121+ const started = await run(bob, "start", "Parser fix", "--issue", "1");
122+ assert.equal(started.exit, 0, started.out + started.err);
123+ const asked = await run(alice, "ask", "bob", "Which grammar?", "--issue", "1");
124+ assert.equal(asked.exit, 0, asked.out + asked.err);
125+ const waiting = await run(bob, "waiting", "--mine");
126+ assert.equal(waiting.exit, 0, waiting.err);
127+ assert.match(waiting.out, /Which grammar\?/);
128+ const answered = await run(bob, "answer", "1", "The new one");
129+ assert.equal(answered.exit, 0, answered.out + answered.err);
130+ const news = await run(alice, "news");
131+ assert.equal(news.exit, 0, news.err);
132+ assert.match(news.out, /The new one/);
133+ const issue = await run(alice, "issue", "1");
134+ assert.match(issue.out, /In progress|bob/);
135+ });
137+ it("two calls at once on one project are both answered, one after the other", async () => {
138+ // As abso ci and waiting --mine make them, with Promise.all.
139+ const local = localFetch(store);
140+ const answers = await Promise.all([local(`${LOCAL_BASE}/p/demo/queue`), local(`${LOCAL_BASE}/p/demo/queue`)]);
141+ closeLocalStores();
142+ for (const a of answers) assert.equal(a.status, 200, await a.text());
143+ });
145+ it("a project's name can't start with a dot, so its folder stays inside the store", async () => {
146+ const dir = temp("dots");
147+ writeFileSync(join(dir, "a.txt"), "x\n");
148+ for (const name of ["..", ".hidden"]) {
149+ const r = await run(dir, "init", "--local", "--project", name, "--agent", "a");
150+ assert.equal(r.exit, 1, r.out + r.err);
151+ // The name rule says why, before any call is made (a ".." would collapse the call's path).
152+ assert.match(r.err, /project names are letters, digits, dot, dash and underscore/);
153+ }
154+ assert.ok(!existsSync(join(store, "..", "project.sqlite")));
155+ assert.deepEqual(readdirSync(dir), ["a.txt"], "init left nothing behind");
156+ });
105157});
106158
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);
139191 });
140192});
194+describe("local commands as their own processes", { skip: noServer }, () => {
195+ // The way people and agents run them: client/abso.ts, a process per command, Node's compile cache as it is.
196+ const entry = fileURLToPath(new URL("../abso.ts", import.meta.url));
197+ const cli = (cwd: string, processStore: string, ...argv: string[]) =>
198+ spawnSync(process.execPath, [entry, ...argv], {
199+ cwd,
200+ env: { ...process.env, ABSO_STORE: processStore, ABSO_SERVERS_FILE: "no-servers.json" },
201+ encoding: "utf8",
202+ });
204+ it("init, push, status and log each exit cleanly", () => {
205+ const processStore = temp("process-store");
206+ const dir = temp("process");
207+ writeFileSync(join(dir, "a.txt"), "one\n");
208+ const steps: [string, string[]][] = [
209+ ["init", ["init", "--local", "--project", "proc", "--agent", "p"]],
210+ ["push", ["push", "-m", "Two"]],
211+ ["status", ["status"]],
212+ ["log", ["log"]],
213+ ];
214+ for (const [name, argv] of steps) {
215+ if (name === "push") writeFileSync(join(dir, "a.txt"), "one\ntwo\n");
216+ const r = cli(dir, processStore, ...argv);
217+ assert.equal(r.status, 0, `${name}: exit ${r.status} ${r.signal ?? ""}\n${r.stdout}${r.stderr}`);
218+ if (name === "status") assert.match(r.stdout, /It's a local project, in /);
219+ if (name === "log") assert.match(r.stdout, /Two/);
220+ }
221+ });
222+});
Lines 134–182 at 318 (were 134–139 at 287)
134134 assert.equal(w.notes.length, 0);
135135});
136136
137+test("a frame is a wake: --follow reads the news and prints that once; an empty read prints the frames", async () => {
138+ // The server's frames don't count as heard (abso 690): the read takes them, so each item prints once.
139+ const w = world([{ frames: ["fe told you: hello", "cloud asks: ship it?"], close: { code: 1006 } }]);
140+ const reads: string[][] = [["fe told you: hello", "cloud asks: ship it?"], []];
141+ let calls = 0;
142+ w.deps.take = async () => {
143+ calls++;
144+ return reads.shift() ?? [];
145+ };
146+ await follow(w.deps);
147+ // Two frames, one read in flight: the second folds into one more read, which finds nothing new; its frame was
148+ // already printed by the first read, so nothing prints twice.
149+ assert.equal(calls, 2);
150+ assert.deepEqual(w.lines, ["fe told you: hello", "cloud asks: ship it?"]);
152+ // A server that counts a frame as heard already (staging 1418): the read is empty, so the frame is what shows.
153+ const old = world([{ frames: ["fe told you: hello"], close: { code: 1006 } }]);
154+ old.deps.take = async () => [];
155+ await follow(old.deps);
156+ assert.deepEqual(old.lines, ["fe told you: hello"]);
158+ // On that server a read can find other news waiting: the frame's own item still shows (Code Review, 291).
159+ const mixed = world([{ frames: ["fe told you: hello"], close: { code: 1006 } }]);
160+ mixed.deps.take = async () => ["cloud: an older item"];
161+ await follow(mixed.deps);
162+ assert.deepEqual(mixed.lines, ["cloud: an older item", "fe told you: hello"]);
164+ // A catch-up frame names the first few waiting items and how many more: the read shows them all, the frame adds nothing.
165+ const catchUp = world([{ frames: ["fe told you: hello\ncloud: ship it?\nand 1 more"], close: { code: 1006 } }]);
166+ catchUp.deps.take = async () => ["fe told you: hello", "cloud: ship it?", "desk: a third"];
167+ await follow(catchUp.deps);
168+ assert.deepEqual(catchUp.lines, ["fe told you: hello", "cloud: ship it?", "desk: a third"]);
170+ // A read that fails shows the frames and says why.
171+ const down = world([{ frames: ["fe told you: hello"], close: { code: 1006 } }]);
172+ down.deps.take = async () => {
173+ throw new Error("could not reach the server");
174+ };
175+ await follow(down.deps);
176+ assert.deepEqual(down.lines, ["fe told you: hello"]);
177+ assert.match(down.notes[0]!, /couldn't read the news: could not reach the server/);
178+});
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.
2+
3+import assert from "node:assert/strict";
4+import { mkdtempSync, writeFileSync } from "node:fs";
5+import { tmpdir } from "node:os";
6+import { join } from "node:path";
7+import { test } from "node:test";
8+import { handoffText, patFromFile, siteFor, webHandoff, webLogin } from "../src/web-session.ts";
9+
10+const SITE = "https://abso-website-staging.chrisazy.workers.dev";
11+const STAGING = "https://abso-staging.chrisazy.workers.dev";
12+const BOX = `abso_bx_${"C".repeat(43)}`;
13+const PAT = `abso_pat_${"A".repeat(40)}`;
14+const NOW = Date.UTC(2026, 9, 16, 9, 0, 0);
16+test("the credential goes only to the staging website beside the folder's staging server (Security condition 6)", () => {
17+ assert.equal(siteFor(STAGING, undefined, "box"), SITE);
18+ assert.equal(siteFor("https://avcs-staging.chrisazy.workers.dev/", undefined, "pat"), SITE);
19+ // A server that isn't staging is refused, prod included, whatever is asked.
20+ assert.throws(
21+ () => siteFor("https://api.abso.dev", undefined, "box"),
22+ /for staging.*never sign in to the website on prod/,
23+ );
24+ assert.throws(() => siteFor("https://api.abso.dev", "http://localhost:8871", "pat"), /for staging/);
25+ // A box's sign-in takes no --site, not even the staging website's own address.
26+ assert.throws(() => siteFor(STAGING, SITE, "box"), /isn't taken with a box's sign-in/);
27+ assert.throws(() => siteFor(STAGING, "http://localhost:8871", "box"), /isn't taken with a box's sign-in/);
28+ // A PAT may name this machine over http, and nothing else.
29+ assert.equal(siteFor(STAGING, "http://localhost:8871/x", "pat"), "http://localhost:8871");
30+ assert.equal(siteFor(STAGING, "http://127.0.0.1:8871", "pat"), "http://127.0.0.1:8871");
31+ for (const elsewhere of ["https://anywhere.example", SITE, "https://localhost:8871", "not a url"])
32+ assert.throws(() => siteFor(STAGING, elsewhere, "pat"), /names this machine only/, elsewhere);
33+});
35+test("a refused handoff reads no credential and sends no request", async () => {
36+ const sent: string[] = [];
37+ const fetcher = (async (url: string) => (sent.push(url), Response.json({}))) as unknown as typeof fetch;
38+ let read = 0;
39+ const credential = () => (read++, BOX);
40+ for (const asked of [
41+ { server: "https://api.abso.dev", site: undefined, kind: "box" as const },
42+ { server: STAGING, site: "https://anywhere.example", kind: "box" as const },
43+ { server: STAGING, site: SITE, kind: "box" as const },
44+ { server: "https://api.abso.dev", site: "http://localhost:8871", kind: "pat" as const },
45+ { server: STAGING, site: "https://anywhere.example", kind: "pat" as const },
46+ ])
47+ await assert.rejects(webLogin({ ...asked, credential, fetcher }), /Nothing was sent/, JSON.stringify(asked));
48+ assert.deepEqual(sent, []);
49+ assert.equal(read, 0);
50+ // Allowed, it goes to the staging website only.
51+ await webLogin({ server: STAGING, site: undefined, kind: "pat", credential: () => PAT, fetcher }).catch(() => {});
52+ assert.deepEqual(sent, [`${SITE}/login/handoff`]);
53+});
55+test("the credential goes in Authorization only, and the answer is the one link and who it signs in as", async () => {
56+ const seen: { url: string; authorization: string | null; body: unknown }[] = [];
57+ const fetcher = (async (url: string, init: RequestInit) => {
58+ seen.push({ url, authorization: new Headers(init.headers).get("authorization"), body: init.body ?? null });
59+ return Response.json({
60+ url: `${SITE}/login/handoff#${"t".repeat(50)}`,
61+ expiresAt: new Date(NOW + 60_000).toISOString(),
62+ account: "acct_person1",
63+ name: "christopher",
64+ sessionEnds: "2026-10-16T21:00:00.000Z",
65+ });
66+ }) as typeof fetch;
67+ const h = await webHandoff(SITE, BOX, fetcher);
68+ assert.deepEqual(seen, [{ url: `${SITE}/login/handoff`, authorization: `Bearer ${BOX}`, body: null }]);
69+ const text = handoffText(h, SITE, true, NOW);
70+ assert.match(text, /within 60 seconds/);
71+ assert.match(text, /as christopher, until 2026-10-16T21:00:00.000Z, and works once/);
72+ assert.match(text, /only to the projects this box was granted, at most as a writer/);
73+ assert.match(handoffText(h, SITE, false, NOW), /It reaches at most as a writer:/);
74+ assert.match(text, /\/login\/handoff#t{50}$/);
75+ assert.doesNotMatch(text + JSON.stringify(h), /abso_bx_/);
76+});
78+test("a refusal says why without the credential; an answer that isn't the site's own link is refused", async () => {
79+ const echo = (async () =>
80+ Response.json({ error: `that key was refused: ${BOX}` }, { status: 401 })) as unknown as typeof fetch;
81+ await assert.rejects(webHandoff(SITE, BOX, echo), (err: Error) => {
82+ assert.match(err.message, /refused: that key was refused: \[the credential\]/);
83+ assert.doesNotMatch(err.message, /abso_bx_/);
84+ return true;
85+ });
86+ const off = (async () => Response.json({ error: "not found" }, { status: 404 })) as unknown as typeof fetch;
87+ await assert.rejects(webHandoff(SITE, BOX, off), /doesn't hand out sign-in links/);
88+ const elsewhere = (async () =>
89+ Response.json({
90+ url: "https://elsewhere.example/login/handoff#x",
91+ expiresAt: new Date(NOW).toISOString(),
92+ account: "acct_x",
93+ })) as unknown as typeof fetch;
94+ await assert.rejects(webHandoff(SITE, BOX, elsewhere), /isn't a sign-in link/);
95+});
97+test("--pat-file reads a PAT from its file, and refuses a file that doesn't hold one", () => {
98+ const dir = mkdtempSync(join(tmpdir(), "abso-web-"));
99+ const good = join(dir, "pat");
100+ writeFileSync(good, `abso_pat_${"A".repeat(40)}\n`);
101+ assert.equal(patFromFile(good), `abso_pat_${"A".repeat(40)}`);
102+ const bad = join(dir, "not");
103+ writeFileSync(bad, "hello");
104+ assert.throws(() => patFromFile(bad), /doesn't hold a PAT/);
105+ assert.throws(() => patFromFile(join(dir, "missing")), /can't read/);
106+});
new file, 123 lines
1+// Time and memory of a local project's commands (abso init --local) on a small and a large history:
2+//
3+// node scripts/local-measure.ts [versions ...] (default: 20 1000)
4+//
5+// Each history is built in this process through the client's main(); then every command is run as its own
6+// `node client/abso.ts` process, the way a person or an agent runs it, five times. It prints the median and slowest
7+// wall time, and the largest peak memory (maxRSS) of those runs, with the store's size on disk.
8+
9+import { spawnSync } from "node:child_process";
10+import { mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
11+import { tmpdir } from "node:os";
12+import { join, resolve } from "node:path";
13+import { fileURLToPath, pathToFileURL } from "node:url";
14+import { main } from "../client/src/main.ts";
16+const ROOT = resolve(fileURLToPath(new URL("..", import.meta.url)));
17+const ENTRY = join(ROOT, "client", "abso.ts");
18+const FILES = 40;
19+const RUNS = 5;
21+const sizes = process.argv.slice(2).map(Number);
22+const histories = sizes.length > 0 ? sizes : [20, 1000];
24+function sizeOf(dir: string): number {
25+ let total = 0;
26+ for (const name of readdirSync(dir)) {
27+ const path = join(dir, name);
28+ const s = statSync(path);
29+ total += s.isDirectory() ? sizeOf(path) : s.size;
30+ }
31+ return total;
32+}
34+const lines = (file: number, version: number) =>
35+ Array.from({ length: 30 }, (_, i) =>
36+ i === version % 30 ? `line ${i} of file ${file}, version ${version}` : `line ${i} of file ${file}`,
37+ )
38+ .join("\n")
39+ .concat("\n");
41+async function build(versions: number): Promise<{ store: string; alice: string; bob: string }> {
42+ const store = mkdtempSync(join(tmpdir(), "abso-measure-store-"));
43+ const alice = mkdtempSync(join(tmpdir(), "abso-measure-alice-"));
44+ const bob = mkdtempSync(join(tmpdir(), "abso-measure-bob-"));
45+ const env = { ABSO_STORE: store, ABSO_SERVERS_FILE: "no-servers.json" };
46+ const run = async (cwd: string, ...argv: string[]) => {
47+ const r = await main(argv, { cwd, env, write: () => {} });
48+ if (r.exit !== 0) throw new Error(`${argv.join(" ")}: ${r.stdout}${r.stderr}`);
49+ };
50+ for (let f = 0; f < FILES; f++) writeFileSync(join(alice, `f${f}.txt`), lines(f, 0));
51+ await run(alice, "init", "--local", "--project", "measure", "--agent", "alice", "--as-is");
52+ for (let v = 1; v < versions; v++) {
53+ // Each version changes three files, as a small piece of work does.
54+ for (const f of [v % FILES, (v * 7) % FILES, (v * 13) % FILES])
55+ writeFileSync(join(alice, `f${f}.txt`), lines(f, v));
56+ await run(alice, "push", "-m", `Version ${v}`);
57+ }
58+ await run(bob, "join", "measure", "--local", "--agent", "bob", "--dir", bob);
59+ return { store, alice, bob };
60+}
62+function measure(cwd: string, store: string, argv: string[]): { median: number; slowest: number; rss: number } {
63+ const times: number[] = [];
64+ let rss = 0;
65+ const preload = join(tmpdir(), `abso-measure-rss-${process.pid}.mjs`);
66+ const out = join(tmpdir(), `abso-measure-rss-${process.pid}.json`);
67+ writeFileSync(
68+ preload,
69+ `import { writeFileSync } from "node:fs";\nprocess.on("exit", () => writeFileSync(${JSON.stringify(out)}, String(process.resourceUsage().maxRSS)));\n`,
70+ );
71+ for (let i = 0; i < RUNS; i++) {
72+ const started = performance.now();
73+ const r = spawnSync(process.execPath, ["--import", pathToFileURL(preload).href, ENTRY, ...argv], {
74+ cwd,
75+ env: { ...process.env, ABSO_STORE: store, ABSO_SERVERS_FILE: "no-servers.json" },
76+ encoding: "utf8",
77+ });
78+ times.push(performance.now() - started);
79+ if (r.status !== 0 && argv[0] !== "push") throw new Error(`${argv.join(" ")}: ${r.stdout}${r.stderr}`);
80+ rss = Math.max(
81+ rss,
82+ Number(
83+ spawnSync(
84+ process.execPath,
85+ ["-e", `process.stdout.write(require("fs").readFileSync(${JSON.stringify(out)}, "utf8"))`],
86+ { encoding: "utf8" },
87+ ).stdout,
88+ ),
89+ );
90+ }
91+ times.sort((a, b) => a - b);
92+ return { median: times[Math.floor(RUNS / 2)]!, slowest: times[RUNS - 1]!, rss };
93+}
95+const kb = (n: number) => `${(n / 1024).toFixed(0)} MB`;
96+const ms = (n: number) => `${n.toFixed(0)} ms`;
97+console.log(
98+ `Node ${process.versions.node}, ${FILES} files of 30 lines, three files changed per version, ${RUNS} runs each.`,
99+);
100+console.log("history | command | median | slowest | peak memory");
101+for (const versions of histories) {
102+ const started = performance.now();
103+ const { store, alice, bob } = await build(versions);
104+ const built = performance.now() - started;
105+ const steps: [string, string, string[]][] = [
106+ ["status", alice, ["status"]],
107+ ["log", alice, ["log"]],
108+ ["blame", alice, ["blame", "f0.txt"]],
109+ ["pull (no change)", bob, ["pull"]],
110+ ["record + push", alice, ["push", "-m", "One more"]],
111+ ];
112+ for (const [name, cwd, argv] of steps) {
113+ if (argv[0] === "push") writeFileSync(join(cwd, "f1.txt"), lines(1, versions + Math.random()));
114+ const m = measure(cwd, store, argv);
115+ console.log(
116+ `${String(versions).padStart(5)} v | ${name.padEnd(20)} | ${ms(m.median).padStart(8)} | ${ms(m.slowest).padStart(8)} | ${kb(m.rss)}`,
117+ );
118+ }
119+ console.log(
120+ `${String(versions).padStart(5)} v | store on disk ${(sizeOf(store) / 1048576).toFixed(1)} MB, built in-process in ${(built / 1000).toFixed(1)} s`,
121+ );
122+ for (const d of [store, alice, bob]) rmSync(d, { recursive: true, force: true, maxRetries: 5 });
123+}
new file, 87 lines
1+// A local project's store lock under load: 1, 4 and 16 writers pushing to one local project at once.
2+//
3+// node scripts/local-writers.ts [writers ...] (default: 1 4 16; PUSHES=10 pushes per writer)
4+//
5+// Each writer is its own agent, in its own folder, changing its own file, so nothing collides: what's measured is the
6+// store's lock (one SQLite write transaction per call). Every push is its own `node client/abso.ts push` process, as
7+// an agent runs it. It prints each push's wall time (median, 95th percentile, slowest), the pushes per second across
8+// all writers, and any push that failed.
9+
10+import { spawn } from "node:child_process";
11+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
12+import { tmpdir } from "node:os";
13+import { join, resolve } from "node:path";
14+import { fileURLToPath } from "node:url";
15+import { main } from "../client/src/main.ts";
17+const ROOT = resolve(fileURLToPath(new URL("..", import.meta.url)));
18+const ENTRY = join(ROOT, "client", "abso.ts");
19+const PUSHES = Number(process.env.PUSHES ?? 10);
20+const counts = process.argv.slice(2).map(Number);
22+function push(cwd: string, store: string, message: string): Promise<{ ms: number; ok: boolean; out: string }> {
23+ const started = performance.now();
24+ return new Promise((done) => {
25+ const child = spawn(process.execPath, [ENTRY, "push", "-m", message], {
26+ cwd,
27+ env: { ...process.env, ABSO_STORE: store, ABSO_SERVERS_FILE: "no-servers.json" },
28+ });
29+ let out = "";
30+ child.stdout.on("data", (d) => {
31+ out += d;
32+ });
33+ child.stderr.on("data", (d) => {
34+ out += d;
35+ });
36+ child.on("close", (code) => done({ ms: performance.now() - started, ok: code === 0, out }));
37+ });
38+}
40+const pct = (sorted: number[], p: number) => sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * p))]!;
41+console.log(`Node ${process.versions.node}, ${PUSHES} pushes per writer, each writer its own agent and file.`);
42+console.log("writers | pushes | median | p95 | slowest | pushes/s | failed");
43+for (const writers of counts.length > 0 ? counts : [1, 4, 16]) {
44+ const store = mkdtempSync(join(tmpdir(), "abso-writers-store-"));
45+ const folders: string[] = [];
46+ const env = { ABSO_STORE: store, ABSO_SERVERS_FILE: "no-servers.json" };
47+ const first = mkdtempSync(join(tmpdir(), "abso-writers-w0-"));
48+ writeFileSync(join(first, "readme.txt"), "writers\n");
49+ const init = await main(["init", "--local", "--project", "writers", "--agent", "w0", "--as-is"], {
50+ cwd: first,
51+ env,
52+ write: () => {},
53+ });
54+ if (init.exit !== 0) throw new Error(init.stdout + init.stderr);
55+ folders.push(first);
56+ for (let w = 1; w < writers; w++) {
57+ const dir = mkdtempSync(join(tmpdir(), `abso-writers-w${w}-`));
58+ const joined = await main(["join", "writers", "--local", "--agent", `w${w}`, "--dir", dir], {
59+ cwd: dir,
60+ env,
61+ write: () => {},
62+ });
63+ if (joined.exit !== 0) throw new Error(joined.stdout + joined.stderr);
64+ folders.push(dir);
65+ }
66+ const times: number[] = [];
67+ const failures: string[] = [];
68+ const started = performance.now();
69+ await Promise.all(
70+ folders.map(async (dir, w) => {
71+ for (let i = 0; i < PUSHES; i++) {
72+ writeFileSync(join(dir, `w${w}.txt`), `writer ${w}, push ${i}\n`);
73+ const r = await push(dir, store, `w${w} push ${i}`);
74+ times.push(r.ms);
75+ if (!r.ok) failures.push(`w${w} push ${i}: ${r.out.trim().split("\n").slice(-2).join(" / ")}`);
76+ }
77+ }),
78+ );
79+ const total = (performance.now() - started) / 1000;
80+ times.sort((a, b) => a - b);
81+ const ms = (n: number) => `${n.toFixed(0)} ms`.padStart(8);
82+ console.log(
83+ `${String(writers).padStart(7)} | ${String(times.length).padStart(6)} | ${ms(pct(times, 0.5))} | ${ms(pct(times, 0.95))} | ${ms(times.at(-1)!)} | ${(times.length / total).toFixed(1).padStart(8)} | ${failures.length}`,
84+ );
85+ for (const f of failures.slice(0, 5)) console.log(` ${f}`);
86+ for (const d of [store, ...folders]) rmSync(d, { recursive: true, force: true, maxRetries: 5 });
87+}
Lines 1524–1562 at 318 (were 1524–1566 at 287)
15241524 * the search never descends below the target's lamport.
15251525 */
15261526 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
1527− const floor = this.#lamportAt(this.#seq(target));
1528− if (this.#storage) {
1529− return this.withProjectionScratch((scratch) => {
1530− let length = 0;
1531− const push = (id: AtomId): void => {
1532− if (scratch.read("seen", id)) return;
1533− scratch.write("seen", id, true);
1534− scratch.write("stack", String(length++), id);
1535− };
1536− for (const id of from) {
1537− if (id === target) return true;
1538− if (this.#lamportAt(this.#seq(id)) > floor) push(id);
1539− }
1540− while (length > 0) {
1541− const key = String(--length);
1542− const current = scratch.read("stack", key) as AtomId;
1543− scratch.remove("stack", key);
1544− if (this.#lamportAt(this.#seq(current)) <= floor) continue;
1545− for (const dependency of this.atom(current).deps) {
1546− if (dependency === target) return true;
1547− push(dependency);
1548− }
1549− }
1550− return false;
1551− });
1527+ return this.#reachable(from, new Set([target])).has(target);
1528+ }
1530+ /**
1531+ * Which of `targets` are reachable along deps from any of `from` (themselves included), in one walk: it never
1532+ * descends below the lowest target's lamport, and stops once every target is found (abso 714, piece 4: record
1533+ * walked once per line writer).
1534+ * The walk's seen marks and stack are in memory, by atom number: one byte and four bytes an atom at most, so about
1535+ * 62 KB on abso's 12,454 atoms and 50 MB at 10 million, under a Worker's 128 MB. They were scratch rows in storage
1536+ * (abso-core 139, bounding memory with the graph), which cost a read and a write per atom visited: on abso's Oct 14
1537+ * tables, 41,000 of a 1470-shaped record's 77,767 statements.
1538+ */
1539+ #reachable(from: Iterable<AtomId>, targets: ReadonlySet<AtomId>): Set<AtomId> {
1540+ const found = new Set<AtomId>();
1541+ let floor = Number.POSITIVE_INFINITY;
1542+ for (const target of targets) floor = Math.min(floor, this.#lamportAt(this.#seq(target)));
1543+ const seen = new Uint8Array(this.#atoms.length);
1544+ const stack = new Int32Array(this.#atoms.length);
1545+ let length = 0;
1546+ const visit = (id: AtomId): void => {
1547+ if (targets.has(id)) found.add(id);
1548+ const seq = this.#seq(id);
1549+ if (seen[seq]) return;
1550+ seen[seq] = 1;
1551+ stack[length++] = seq;
1552+ };
1553+ for (const id of from) visit(id);
1554+ while (length > 0 && found.size < targets.size) {
1555+ const seq = stack[--length]!;
1556+ if (this.#lamportAt(seq) <= floor) continue;
1557+ for (const dependency of this.atom(atomId(seq)).deps) visit(dependency);
15521558 }
1553− const seen = new Set<AtomId>();
1554− const stack = [...from];
1555− while (stack.length > 0) {
1556− const cur = stack.pop()!;
1557− if (cur === target) return true;
1558− if (seen.has(cur)) continue;
1559− seen.add(cur);
1560− if (this.#lamportAt(this.#seq(cur)) <= floor) continue;
1561− for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
1562− }
1563− return false;
1559+ return found;
15641560 }
15651561
15661562 /**
Lines 1606–1633 at 318 (were 1610–1632 at 287)
16101606 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
16111607
16121608 // Everything it touches must come from its closure. Derived deps name the
1613− // writers directly, so this is usually one lookup per writer.
1614− const memoryBelow = scratch ? undefined : new Map<AtomId, boolean>();
1615− const below = {
1616− get: (key: AtomId) => (scratch ? (scratch.read("below", key) as boolean | undefined) : memoryBelow!.get(key)),
1617− set: (key: AtomId, value: boolean) => {
1618− if (scratch) scratch.write("below", key, value);
1619− else memoryBelow!.set(key, value);
1620− },
1621− };
1622− const inClosure = (writer: AtomId): boolean => {
1623− let hit = below.get(writer);
1624− if (hit === undefined) {
1625− hit = deps.has(writer) || this.#reaches(atom.deps, writer);
1626− below.set(writer, hit);
1609+ // writers directly, so this is usually one lookup per writer. The writers
1610+ // that aren't deps are walked for together, once (abso 714, piece 4).
1611+ const touched: LineId[] = [];
1612+ for (const run of atom.inserts) if (!isStartNode(run.parent)) touched.push(run.parent);
1613+ for (const m of atom.moves ?? []) {
1614+ touched.push(m.line);
1615+ if (!isStartNode(m.parent)) touched.push(m.parent);
1616+ }
1617+ touched.push(...atom.deletes);
1618+ for (const list of [atom.writes, atom.reads, atom.holds])
1619+ for (const key of list) {
1620+ const parsed = parseKey(key);
1621+ if (parsed.kind === "line" || ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node)))
1622+ touched.push(parsed.node);
16271623 }
1628− return hit;
1629− };
1624+ const beyond = new Set<AtomId>();
1625+ for (const line of touched) {
1626+ const writer = this.lineAtom(line);
1627+ if (writer !== undefined && !deps.has(writer)) beyond.add(writer);
1628+ }
1629+ const reached = beyond.size > 0 ? this.#reachable(atom.deps, beyond) : beyond;
1630+ const inClosure = (writer: AtomId): boolean => deps.has(writer) || reached.has(writer);
16301631 const checkLine = (line: LineId, what: string): void => {
16311632 const writer = this.lineAtom(line);
16321633 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
Lines 10–16 at 318 (were 10–16 at 287)
1010// made when a caller asks for them, and the latest asked for is kept.
1111
1212import type { Graph, RelocationInfo } from "./graph.ts";
13−import { isStartNode, lineId, seqOf } from "./keys.ts";
13+import { atomId, isStartNode, lineId, seqOf } from "./keys.ts";
1414import { resolveScratchMoves, scratchLayoutNodes } from "./relocation-scratch.ts";
1515import { isClosedSet, StableSet } from "./state-source.ts";
1616import { joinLines } from "./text.ts";
Lines 1095–1108 at 318 (were 1095–1101 at 287)
10951095 }
10961096
10971097 *lineChunks(path: string): IterableIterator<() => Iterable<string>> {
1098− for (const n of this.#file(path).vis) yield () => this.graph.textChunks(n);
1098+ // The texts the packed layout already holds, read a page at a time (abso Capacity, 714): a record's diff read each
1099+ // line's own row, 11,873 statements for abso's index.ts. Only a line too long to pack is read in chunks.
1100+ const { vis, visText } = this.#file(path);
1101+ for (let i = 0; i < vis.length; i++) {
1102+ const packed = visText?.[i];
1103+ if (packed != null) yield () => [packed];
1104+ else yield () => this.graph.textChunks(vis[i]!);
1105+ }
10991106 }
11001107
11011108 /** Visible lines without retaining their text in the view cache. */
Lines 1112–1118 at 318 (were 1105–1111 at 287)
11051112 yield {
11061113 id: graph.lineIdOf(n),
11071114 text: graph.textOf(n),
1108− atom: graph.idOfSeq(graph.writerSeqOf(n)),
1115+ atom: atomId(graph.writerSeqOf(n)),
11091116 };
11101117 }
11111118
Lines 1126–1137 at 318 (were 1119–1130 at 287)
11191126 const n = vis[i]!;
11201127 const packed = visText?.[i];
11211128 lines[i] = {
1122− id: visWriter && visK ? lineId(graph.idOfSeq(visWriter[i]!), visK[i]!) : graph.lineIdOf(n),
1129+ id: visWriter && visK ? lineId(atomId(visWriter[i]!), visK[i]!) : graph.lineIdOf(n),
11231130 textChunks: () => graph.textChunks(n),
11241131 get text() {
11251132 return packed ?? graph.textOf(n);
11261133 },
1127− atom: graph.idOfSeq(visWriter ? visWriter[i]! : graph.writerSeqOf(n)),
1134+ atom: atomId(visWriter ? visWriter[i]! : graph.writerSeqOf(n)),
11281135 };
11291136 }
11301137 return lines;
Lines 1143–1156 at 318 (were 1136–1147 at 287)
11361143 const graph = this.graph;
11371144 const { vis, visText, visWriter, visK } = this.#file(path);
11381145 const lines: VisibleLine[] = new Array(vis.length);
1146+ // Writer seqs come from the graph's own layout, so they're named with atomId, not checked by idOfSeq (abso 738):
1147+ // on a stored graph its check read the atom count once a line, about 0.9 s of a warm draft-state on abso.
11391148 for (let i = 0; i < vis.length; i++) {
11401149 const n = vis[i]!;
11411150 lines[i] = {
1142− id: visWriter && visK ? lineId(graph.idOfSeq(visWriter[i]!), visK[i]!) : graph.lineIdOf(n),
1151+ id: visWriter && visK ? lineId(atomId(visWriter[i]!), visK[i]!) : graph.lineIdOf(n),
11431152 text: visText?.[i] ?? graph.textOf(n),
1144− atom: graph.idOfSeq(visWriter ? visWriter[i]! : graph.writerSeqOf(n)),
1153+ atom: atomId(visWriter ? visWriter[i]! : graph.writerSeqOf(n)),
11451154 };
11461155 }
11471156 this.#linesCache = { path, lines };
Lines 1172–1184 at 318 (were 1163–1175 at 287)
11631172 const writer = seqWriter ? seqWriter[i]! : graph.writerSeqOf(n);
11641173 let text: string | undefined;
11651174 out[i] = {
1166− id: seqWriter && seqK ? lineId(graph.idOfSeq(writer), seqK[i]!) : graph.lineIdOf(n),
1175+ id: seqWriter && seqK ? lineId(atomId(writer), seqK[i]!) : graph.lineIdOf(n),
11671176 get text() {
11681177 text ??= graph.textOf(n);
11691178 return text;
11701179 },
1171− atom: graph.idOfSeq(writer),
1172− deletedBy: by ? by.map((s) => graph.idOfSeq(s)) : NONE,
1180+ atom: atomId(writer),
1181+ deletedBy: by ? by.map((s) => atomId(s)) : NONE,
11731182 visible: by === undefined,
11741183 };
11751184 }
Lines 68–74 at 318 (were 68–74 at 287)
6868 }
6969 for (const key of claimsOf(atom)) streams.push(g.eachWriterOf(key));
7070 const theirs: AtomId[] = [];
71− for (const id of orderedClaimants(g, streams)) if (against.has(id)) theirs.push(id);
71+ for (const id of orderedClaimants(streams)) if (against.has(id)) theirs.push(id);
7272 out.set(yours, theirs);
7373 }
7474 return out;
Lines 136–142 at 318 (were 136–142 at 287)
136136
137137/** Claim indexes append in canonical seq order. Merge one cursor per current
138138 * atom key, retaining no candidate set proportional to historical claims. */
139−function* orderedClaimants(g: Graph, streams: IterableIterator<AtomId>[]): IterableIterator<AtomId> {
139+function* orderedClaimants(streams: IterableIterator<AtomId>[]): IterableIterator<AtomId> {
140140 try {
141141 type Head = { id: AtomId; seq: number; stream: number };
142142 const heap: Head[] = [];
Lines 152–162 at 318 (were 152–160 at 287)
152152 }
153153 heap[at] = head;
154154 };
155+ // Each claimant's seq from its id, as the graph reads it (abso 738): loading the stored atom for it read a row a
156+ // claimant, most of a warm draft-state's pairing on abso.
155157 const advance = (stream: number) => {
156158 const next = streams[stream]!.next();
157− if (!next.done) push({ id: next.value, seq: g.atom(next.value).seq, stream });
159+ if (!next.done) push({ id: next.value, seq: seqOf(next.value), stream });
158160 };
159161 for (let stream = 0; stream < streams.length; stream++) advance(stream);
160162 let previous = -1;
Lines 192–199 at 318 (were 190–197 at 287)
190192 let a = left.next();
191193 let b = right.next();
192194 while (!a.done && !b.done) {
193− const x = g.atom(a.value).seq;
194− const y = g.atom(b.value).seq;
195+ const x = seqOf(a.value);
196+ const y = seqOf(b.value);
195197 if (x === y && settled.has(a.value)) return true;
196198 if (x <= y) a = left.next();
197199 if (y <= x) b = right.next();
Lines 7–13 at 318 (were 7–13 at 287)
77import { type AtomId, type Graph, joinLines, type LineId, type ReadView } from "../../src/engine/index.ts";
88import { type Origin, touchedFiles } from "./collisions.ts";
99import { type Definition, definitionsIn, importsOf, usedNames } from "./definitions.ts";
10−import { definitionsBytes, type KeptParts, usesBytes } from "./kept-parts.ts";
10+import { definitionsBytes, filesBytes, type KeptParts, usesBytes } from "./kept-parts.ts";
1111import { codeOfLines, declaredIn, holdsNoCode } from "./names.ts";
1212import { definitionText } from "./news.ts";
1313import type { Collision } from "./project.ts";
Lines 37–43 at 318 (were 37–43 at 287)
3737 readonly parent: string;
3838}
3939
40−/** Definitions in the files newer work touched, before it and with it. */
40+/** Definitions in one file newer work touched, before it and with it. */
4141interface Changed {
4242 readonly baseDefs: ReturnType<typeof definitionsIn>;
4343 readonly nowDefs: ReturnType<typeof definitionsIn>;
Lines 52–62 at 318 (were 52–59 at 287)
5252 readonly #replacedCache = new Map<string, ReadonlySet<string>>();
5353 /** A draft's uses, kept while it is asked about with the same views: draft collisions ask once per other agent. */
5454 readonly #usesCache = new WeakMap<ReadonlySet<AtomId>, { view: ReadView; base: ReadView; uses: Uses }>();
55− /** The newer work's definitions before and after, kept while it is asked about with the same views. */
56− readonly #changedCache = new WeakMap<ReadonlySet<AtomId>, { base: ReadView; now: ReadView; defs: Changed }>();
55+ /** The files the newer work touched, kept while it is asked about with the same views. */
56+ readonly #touchedCache = new WeakMap<
57+ ReadonlySet<AtomId>,
58+ { base: ReadView; now: ReadView; files: ReadonlySet<string> }
59+ >();
5760
5861 constructor(graph: Graph, origin: (atom: AtomId, spaceName: string) => Origin) {
5962 this.#graph = graph;
Lines 125–135 at 318 (were 122–127 at 287)
122125 spaceName: string,
123126 kept?: { parts: KeptParts; uses: string; changed: string },
124127 names?: ReadonlySet<string>,
128+ /**
129+ * The files the newer work changed, when the caller knows them without placing its lines (land and draft-state:
130+ * shared's kept version files, abso 738); undefined, or one that answers undefined, and they're worked out here.
131+ */
132+ changedFiles?: () => ReadonlySet<string> | undefined,
125133 ): DefinitionCollision[] {
126134 if (draft.size === 0 || newer.size === 0) return [];
127135 const uses = kept
Lines 139–194 at 318 (were 131–161 at 287)
131139 // Only these names can collide (a publish's news, news.ts): a draft that uses none of them has none, and the
132140 // definitions changed since its base needn't be worked out.
133141 if (names && ![...uses.keys()].some((name) => names.has(name))) return [];
134− const nowOf = () => (typeof nowView === "function" ? nowView() : nowView);
135− const { baseDefs, nowDefs } = kept
136− ? kept.parts.get(
137− `changed ${kept.changed}`,
138− () => this.#changed(newer, baseView, nowOf()),
139− (c) => definitionsBytes(c.baseDefs) + definitionsBytes(c.nowDefs),
140− )
141− : this.#changedFor(newer, baseView, nowOf());
142− const out: DefinitionCollision[] = [];
143− for (const [name, where] of [...uses].sort(([a], [b]) => (a < b ? -1 : 1))) {
144− // Which definitions the uses mean: the file each use imports the name
145− // from, or its own file when it defines the name at the top level. A
146− // use with neither (a local, a parameter, a global, a name another
147− // language brings in some other way) means none: the rule only speaks
148− // when it knows which definition a use means.
142+ // Which definitions the uses mean: the file each use imports the name
143+ // from, or its own file when it defines the name at the top level. A
144+ // use with neither (a local, a parameter, a global, a name another
145+ // language brings in some other way) means none: the rule only speaks
146+ // when it knows which definition a use means.
147+ const scopes = new Map<string, ReadonlySet<string>>();
148+ for (const [name, where] of uses) {
149149 const scope = new Set<string>();
150150 for (const w of new Set(where.map((x) => x.file))) {
151151 const from = importsOf(view, w).get(name) ?? (definitionsIn(view, [w]).has(name) ? w : undefined);
152152 if (from !== undefined) scope.add(from);
153153 }
154− if (scope.size === 0) continue;
155− const inScope = (d: Definition): boolean => scope.has(d.file);
156− const before = baseDefs.get(name)?.filter(inScope);
157− if (!before?.length) continue; // not defined in what the drafter saw: nothing it relies on
158− const after = (nowDefs.get(name) ?? []).filter(inScope);
154+ if (scope.size > 0) scopes.set(name, scope);
155+ }
156+ if (scopes.size === 0) return [];
157+ const nowOf = () => (typeof nowView === "function" ? nowView() : nowView);
158+ // Only a file the newer work touched can hold a changed definition, and only one a use means can matter: just those
159+ // files are laid out, before and with the newer work (abso 738). Laying out every file the newer work touched cost
160+ // codex-prose-authorship-610's draft-state 494 files a view where its uses reach 7.
161+ const touched =
162+ changedFiles?.() ??
163+ (kept
164+ ? kept.parts.get(`touched ${kept.changed}`, () => this.#touched(newer, baseView, nowOf()), filesBytes)
165+ : this.#touchedFor(newer, baseView, nowOf()));
166+ const changed = new Map<string, Changed>();
167+ const changedIn = (file: string): Changed => {
168+ let c = changed.get(file);
169+ if (!c) {
170+ const make = (): Changed => ({
171+ baseDefs: definitionsIn(baseView, [file]),
172+ nowDefs: definitionsIn(nowOf(), [file]),
173+ });
174+ c = kept
175+ ? kept.parts.get(
176+ `changed ${kept.changed} ${file}`,
177+ make,
178+ (d) => definitionsBytes(d.baseDefs) + definitionsBytes(d.nowDefs),
179+ )
180+ : make();
181+ changed.set(file, c);
182+ }
183+ return c;
184+ };
185+ const out: DefinitionCollision[] = [];
186+ for (const [name, scope] of [...scopes].sort(([a], [b]) => (a < b ? -1 : 1))) {
187+ // In the order the newer work touched its files, as when every touched file was laid out.
188+ const files = [...touched].filter((f) => scope.has(f));
189+ const before = files.flatMap((f) => changedIn(f).baseDefs.get(name) ?? []);
190+ if (!before.length) continue; // not defined in what the drafter saw: nothing it relies on
191+ const after = files.flatMap((f) => changedIn(f).nowDefs.get(name) ?? []);
159192 if (signature(before) === signature(after)) continue;
160193 // Who changed it: newer writers of the new definition's lines, or newer deleters of the old one's.
161194 const by = new Set<AtomId>();
Lines 199–205 at 318 (were 166–171 at 287)
166199 const first = [...by].sort((p, q) => this.#graph.atom(p).seq - this.#graph.atom(q).seq)[0];
167200 if (first === undefined) continue;
168201 const origin = this.#origin(first, spaceName);
202+ const where = uses.get(name)!;
169203 const file = where[0]!.file;
170204 const indexes = where.filter((w) => w.file === file).map((w) => w.index);
171205 const lo = Math.min(...indexes);
Lines 239–257 at 318 (were 205–224 at 287)
205239 return kept.uses;
206240 }
207241
208− /** The newer work's definitions before and after, kept while it is asked about with the same views. */
209− #changedFor(newer: ReadonlySet<AtomId>, baseView: ReadView, now: ReadView): Changed {
210− let changed = this.#changedCache.get(newer);
211− if (!changed || changed.base !== baseView || changed.now !== now) {
212− changed = { base: baseView, now, defs: this.#changed(newer, baseView, now) };
213− this.#changedCache.set(newer, changed);
242+ /** The files the newer work touched, kept while it is asked about with the same views. */
243+ #touchedFor(newer: ReadonlySet<AtomId>, baseView: ReadView, now: ReadView): ReadonlySet<string> {
244+ let kept = this.#touchedCache.get(newer);
245+ if (!kept || kept.base !== baseView || kept.now !== now) {
246+ kept = { base: baseView, now, files: this.#touched(newer, baseView, now) };
247+ this.#touchedCache.set(newer, kept);
214248 }
215− return changed.defs;
249+ return kept.files;
216250 }
217251
218− /** Definitions in the files the newer work touched, before it and with it: only there can one have changed. */
219− #changed(newer: ReadonlySet<AtomId>, baseView: ReadView, now: ReadView): Changed {
220− const touched = touchedFiles(this.#graph, newer, [baseView, now]);
221− return { baseDefs: definitionsIn(baseView, touched), nowDefs: definitionsIn(now, touched) };
252+ /** The files the newer work touched, before it and with it: only there can a definition have changed. */
253+ #touched(newer: ReadonlySet<AtomId>, baseView: ReadView, now: ReadView): ReadonlySet<string> {
254+ return touchedFiles(this.#graph, newer, [baseView, now]);
222255 }
223256
224257 /** The names the draft's lines use and don't declare, less those the lines they replaced already used. */
Lines 62–90 at 318 (were 62–67 at 287)
6262 const g = host.graph;
6363 const mine = new Set(draft);
6464 const text = new MoveLineText(g);
65+ // The draft's own lines first, before laying out any file (abso 714, piece 3): a move needs a written line with
66+ // real content whose text the draft also deleted. An edit that only changes lines has none, and laying out its
67+ // files (12k lines twice for one changed line of worker/src/index.ts) cost the whole publish.
68+ const goneIds = new Set<LineId>();
69+ const goneTexts = new Set<number>();
70+ for (const id of draft)
71+ for (const line of g.deletedLines(id)) {
72+ goneIds.add(line);
73+ goneTexts.add(text.intern(line));
74+ }
75+ if (goneTexts.size === 0) return;
76+ let moved = false;
77+ for (const id of draft) {
78+ for (const line of g.eachInsertedLine(id)) {
79+ const t = text.intern(line);
80+ if (!text.plain[t] && goneTexts.has(t)) {
81+ moved = true;
82+ break;
83+ }
84+ }
85+ if (moved) break;
86+ }
87+ if (!moved) return;
6588 const after = host.agentView(agent);
6689 const before = host.beforeDraft
6790 ? host.beforeDraft(agent, draft)
Lines 104–111 at 318 (were 81–87 at 287)
81104 for (const file of [...touched].toSorted()) {
82105 let cur: Block | undefined;
83106 before.buildLines(file).forEach((l, i) => {
84− if (g.deletersOf(l.id).some((d) => mine.has(d))) {
107+ // Deleted by the draft: one of its atoms' deleted lines, with no lookup of each line's deleters.
108+ if (goneIds.has(l.id)) {
85109 if (!cur) gone.push((cur = { file, start: i, ids: [], texts: [] }));
86110 cur.ids.push(l.id);
87111 cur.texts.push(text.intern(l.id));
Lines 1–8 at 318 (were 1–8 at 287)
11// What draft collisions work out about each draft and each pair of drafts, kept between calls under a hard byte budget
2−// (abso Capacity, issue 664): the names a draft's new lines use, the definitions a draft's changes touch before and
3−// after, and the names a pair of drafts both define in a file. Keys name everything an entry depends on (shared's
4−// version, a draft's base and atoms), and a call drops every entry it didn't use, so a draft that changes, an agent that
5−// leaves and shared moving on all drop theirs at once.
2+// (abso Capacity, issue 664): the names a draft's new lines use, the files a draft's changes touch and the definitions
3+// in each before and after, and the names a pair of drafts both define in a file. Keys name everything an entry depends
4+// on (shared's version, a draft's base and atoms), and a call drops every entry it didn't use, so a draft that changes,
5+// an agent that leaves and shared moving on all drop theirs at once.
66
77import { stringBytes } from "../../src/engine/view.ts";
88import type { Definition } from "./definitions.ts";
Lines 100–109 at 318 (were 100–102 at 287)
100100 n += MAP_ENTRY_BYTES + stringBytes(name) + ARRAY_HEADER_BYTES + where.length * (REFERENCE_BYTES + OBJECT_BYTES);
101101 return n;
102102}
104+/** A set of paths (the files some work touched). */
105+export function filesBytes(files: ReadonlySet<string>): number {
106+ let n = MAP_HEADER_BYTES;
107+ for (const file of files) n += MAP_ENTRY_BYTES + stringBytes(file);
108+ return n;
109+}
Lines 29–36 at 318 (were 29–34 at 287)
2929 pairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[];
3030 describe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision;
3131 definitionRule(): DefinitionRule;
32+ /** The files a space's versions after `from`, up to `to`, changed, when each one's are kept; else undefined. */
33+ changedSince(space: Space, from: number, to: number): ReadonlySet<string> | undefined;
3234 refuse(
3335 agent: AgentState,
3436 space: Space,
Lines 95–118 at 318 (were 93–103 at 287)
9395 ? host.viewAt(shared, sharedBaseOf(space), changes)
9496 : host.viewAt(space, space.versions.length - 1);
9597 const describeLand = (p: Pair): Collision => host.describe(p, draftView, host.sharedView(), SHARED);
98+ // Where shared changed since the draft's base, from the files each version since kept as it landed (abso 738): working
99+ // it out from the newer atoms placed every line they wrote or deleted, about 30% of a warm draft-state read.
100+ const changed = () => host.changedSince(shared, sharedBaseOf(space), host.version());
96101 const collisions = [
97102 ...host.pairs(changes, newer, union).map(describeLand),
98103 ...host
99104 .definitionRule()
100− .collisions(own, draftView, host.viewAt(shared, sharedBaseOf(space)), host.sharedView(), newer, SHARED)
105+ .collisions(
106+ own,
107+ draftView,
108+ host.viewAt(shared, sharedBaseOf(space)),
109+ host.sharedView(),
110+ newer,
111+ SHARED,
112+ undefined,
113+ undefined,
114+ changed,
115+ )
101116 .map((d) => d.collision),
102117 ];
103118 return { collisions, newer, union };
Lines 257–298 at 318 (were 257–264 at 287)
257257 queueNews(agent: AgentState, items: readonly NewsItem[], entries: Entry[]): void;
258258 /** A line for the host's logs (ProjectOptions.logLine). */
259259 logLine?(line: Record<string, string | number>): void;
260+ /**
261+ * Owed news (abso Capacity, 2026-10-15): when this answers true, a publish leaves its definition news for other
262+ * agents to be worked out after its write (definitionNewsOwed) and hands it to owe instead.
263+ */
264+ owesDefinitionNews(): boolean;
265+ owe(owed: OwedDefinitionNews): void;
266+ spaceNamed(name: string): Space | undefined;
267+ /** newerFor as it was at `version` of the agent's space. */
268+ newerAt(agent: AgentState, version: number): ReadonlySet<AtomId>;
269+ /** definitionCollisions against the agent's space at `version`, not its newest. */
270+ definitionCollisionsAt(
271+ agent: AgentState,
272+ newer: ReadonlySet<AtomId>,
273+ names: ReadonlySet<string>,
274+ version: number,
275+ ): DefinitionCollision[];
276+ /** The space's atoms at `version`: setOf as it was then (owed news). */
277+ setAt(space: Space, version: number): ReadonlySet<AtomId>;
278+ /** collision, with theirs described from the agent's space at `version`, not its newest (owed news). */
279+ collisionAt(agent: AgentState, pair: Pair, version: number): Collision;
260280}
261281
282+/**
283+ * A publish's news for other agents, not yet worked out: the version it made, and who made it. `all`: everything the
284+ * publish would have told them (same lines, definitions, moves; abso 714). Without it, as owed before 714, only the
285+ * definition news. `names`: the names its definitions changed, once worked out (owedNewsNames).
286+ */
287+export interface OwedNews {
288+ readonly version: number;
289+ readonly space: string;
290+ readonly publisher: string;
291+ readonly names?: readonly string[];
292+ readonly all?: boolean;
293+}
294+export type OwedDefinitionNews = OwedNews;
262296function lineNews(host: NewsHost, agent: AgentState, pairs: readonly Pair[]): NewsItem[] {
263297 return pairs.map((p) => ({ key: pairKey(p), text: linesText(host.collision(agent, p)) }));
264298}
Lines 312–319 at 318 (were 278–283 at 287)
278312 just: ReadonlySet<AtomId>,
279313 space: Space,
280314 version: number,
315+ /** The space's version the moved lines' files are read at: its newest, or an owed publish's own. */
316+ now = last(space),
281317): NewsItem[] {
282318 const g = host.graph;
283319 const movers = [...just].filter((id) => g.atom(id).moves);
Lines 326–332 at 318 (were 290–296 at 287)
290326 }
291327 }
292328 const was = host.viewAt(space, version - 1);
293− const now = host.viewAt(space, last(space));
329+ const after = host.viewAt(space, now);
294330 const out: NewsItem[] = [];
295331 for (const id of movers) {
296332 const moved = g
Lines 335–341 at 318 (were 299–305 at 287)
299335 .filter((k) => k.kind === "pos" && claimed.has(k.node))
300336 .map((k) => k.node);
301337 if (moved.length === 0) continue;
302− out.push(moveItem(id, host.origin(id, space.name), was.fileOf(moved[0]!), now.fileOf(moved[0]!)));
338+ out.push(moveItem(id, host.origin(id, space.name), was.fileOf(moved[0]!), after.fileOf(moved[0]!)));
303339 }
304340 return out;
305341}
Lines 372–408 at 318 (were 336–367 at 287)
336372 // For the host's logs (abso 702): a line as the work starts, written before it, and one as it ends, so work that
337373 // outlives its request still shows. No time in them: a Durable Object's clock stands still in synchronous code.
338374 let drafts = 0;
339− let files = 0;
340375 let news = 0;
341− const compareDefinitions = (): ReadonlySet<string> => {
342− const touched = touchedFiles(host.graph, just, [host.viewAt(space, version - 1), host.viewAt(space, last(space))]);
343− files = touched.size;
344− const before = definitionsIn(host.viewAt(space, version - 1), touched);
345− const after = definitionsIn(host.viewAt(space, last(space)), touched);
346− return new Set(
347− [...new Set([...before.keys(), ...after.keys()])].filter(
348− (name) => !before.has(name) || signature(before.get(name)!) !== signature(after.get(name) ?? []),
349− ),
350− );
351− };
376+ // Owed (abso 714, Christopher's base fix): on stored tables this news for other agents was most of a publish's one
377+ // write transaction (the same-lines pairs, the definitions, the moves, for every draft: about 10 s for a 30-line
378+ // change to abso's 12k-line index.ts), long enough to time storage out and reset the object (prod abso, 23:32Z
379+ // 2026-10-16). Owing, the publish only notes what it owes, here, once some other agent has a draft; it's worked out
380+ // after the commit, one agent at a time, against this version (newsOwed). Asked only then (news-lazy.test.ts: no
381+ // news work at all otherwise).
382+ let owing: boolean | undefined;
352383 for (const agent of [...host.agents.values()].toSorted((a, b) => (a.name < b.name ? -1 : 1))) {
353384 if (agent === publisher || agent.space !== space.name) continue;
354385 const draft = host.draft(agent);
355386 if (draft.length === 0) continue;
387+ owing ??= host.owesDefinitionNews();
388+ if (owing) {
389+ host.owe({ version, space: space.name, publisher: publisher.name, all: true });
390+ host.logLine?.({ work: "publishNews", step: "owed", space: space.name, version, publisher: publisher.name });
391+ return;
392+ }
356393 if (drafts++ === 0)
357394 host.logLine?.({ work: "publishNews", step: "start", space: space.name, version, publisher: publisher.name });
358395 const lines = pairsIn(host.graph, draft, just, unionOverlay(host.setOf(space), draft));
359− changedNames ??= compareDefinitions();
396+ changedNames ??= changedNamesAt(host, space, version);
360397 const defs =
361398 changedNames.size > 0
362399 ? host.definitionCollisions(agent, host.newerFor(agent), changedNames).filter((d) => just.has(d.by))
363400 : [];
364− const items = [...lineNews(host, agent, lines), ...definitionNews(defs), ...moveNews(host, draft, just, space, version)];
401+ const items = [
402+ ...lineNews(host, agent, lines),
403+ ...definitionNews(defs),
404+ ...moveNews(host, draft, just, space, version),
405+ ];
365406 news += items.length;
366407 host.queueNews(agent, items, entries);
367408 }
Lines 414–506 at 318 (were 373–380 at 287)
373414 version,
374415 publisher: publisher.name,
375416 drafts,
376− files,
377417 changedNames: changedNames?.size ?? 0,
378418 news,
379419 });
380420}
422+/**
423+ * The names whose definitions the publish at `version` changed, in the files it touched: before it against its own
424+ * version. Most publishes change none; then only the same-lines rule can bring news. A definition collision the publish
425+ * brings is one of these, so a draft that uses none of them has none (abso Capacity, prod abso 2026-10-15).
426+ */
427+function changedNamesAt(host: NewsHost, space: Space, version: number): ReadonlySet<string> {
428+ const just = new Set(space.versions[version]!.atoms);
429+ const touched = touchedFiles(host.graph, just, [host.viewAt(space, version - 1), host.viewAt(space, version)]);
430+ const before = definitionsIn(host.viewAt(space, version - 1), touched);
431+ const after = definitionsIn(host.viewAt(space, version), touched);
432+ return new Set(
433+ [...new Set([...before.keys(), ...after.keys()])].filter(
434+ (name) => !before.has(name) || signature(before.get(name)!) !== signature(after.get(name) ?? []),
435+ ),
436+ );
437+}
439+/** owedNews's names, worked out once for a publish (the host keeps them on its row): changedNamesAt its version. */
440+export function owedNewsNames(host: NewsHost, owed: OwedNews): string[] {
441+ const space = host.spaceNamed(owed.space);
442+ if (!space || owed.version > last(space) || !space.versions[owed.version]) return [];
443+ return [...changedNamesAt(host, space, owed.version)].sort();
444+}
446+/**
447+ * The definition news a publish owes, worked out as newsForOthers would have at that version: the same agents, the
448+ * same rule against the space at `owed.version` and the work published up to it, the same words and keys. Reads only.
449+ * An agent that has synced past the version since is left out (the version is no longer newer for it), and an item
450+ * an agent was already told (from its own edit since, or this run before) is dropped, as queueNews would.
451+ */
452+export function newsOwed(
453+ host: NewsHost,
454+ owed: OwedNews,
455+ /** Only these agents (owedAgents' names), so a host can work the news out one agent at a time (abso 714). */
456+ only?: readonly string[],
457+): { agent: string; items: NewsItem[] }[] {
458+ const space = host.spaceNamed(owed.space);
459+ if (!space || owed.version > last(space) || !space.versions[owed.version]) return [];
460+ const just = new Set(space.versions[owed.version]!.atoms);
461+ let names: ReadonlySet<string> | undefined = owed.names ? new Set(owed.names) : undefined;
462+ const out: { agent: string; items: NewsItem[] }[] = [];
463+ for (const agent of [...host.agents.values()].toSorted((a, b) => (a.name < b.name ? -1 : 1))) {
464+ if (only && !only.includes(agent.name)) continue;
465+ if (!owedTo(host, owed, space, agent)) continue;
466+ const draft = host.draft(agent);
467+ names ??= changedNamesAt(host, space, owed.version);
468+ const lines = owed.all
469+ ? pairsIn(host.graph, draft, just, unionOverlay(host.setAt(space, owed.version), draft)).map((p) => ({
470+ key: pairKey(p),
471+ text: linesText(host.collisionAt(agent, p, owed.version)),
472+ }))
473+ : [];
474+ const defs =
475+ names.size > 0
476+ ? host
477+ .definitionCollisionsAt(agent, host.newerAt(agent, owed.version), names, owed.version)
478+ .filter((d) => just.has(d.by))
479+ : [];
480+ const moves = owed.all ? moveNews(host, draft, just, space, owed.version, owed.version) : [];
481+ const items = [...lines, ...definitionNews(defs), ...moves].filter((item) => !agent.told.has(item.key));
482+ if (items.length > 0) out.push({ agent: agent.name, items });
483+ }
484+ return out;
485+}
486+/** newsOwed, under the name tonight's owed definition news had (abso 2341e805). */
487+export const definitionNewsOwed = newsOwed;
489+/**
490+ * The agents a publish's owed news may be for, in the order definitionNewsOwed takes them: every other agent in the
491+ * space, behind the version, with a draft. Cheap (no definition rule), so a host can list them once and then work the
492+ * news out a few at a time, each in its own read (abso 714: one read over every draft reset prod abso's object).
493+ */
494+export function owedAgents(host: NewsHost, owed: OwedDefinitionNews): string[] {
495+ const space = host.spaceNamed(owed.space);
496+ if (!space || owed.version > last(space) || !space.versions[owed.version]) return [];
497+ return [...host.agents.values()]
498+ .toSorted((a, b) => (a.name < b.name ? -1 : 1))
499+ .filter((agent) => owedTo(host, owed, space, agent))
500+ .map((agent) => agent.name);
501+}
503+function owedTo(host: NewsHost, owed: OwedDefinitionNews, space: Space, agent: AgentState): boolean {
504+ if (agent.name === owed.publisher || agent.space !== space.name || agent.base >= owed.version) return false;
505+ return host.draft(agent).length > 0;
506+}
Lines 90–110 at 318 (were 90–95 at 287)
9090 return files && [...files].sort();
9191 }
9292
93+ /**
94+ * The files the versions after `from`, up to `to`, changed, from each version's kept row (abso 738): undefined when one
95+ * has none, and the caller works them out from the atoms. Every file whose text differs between the two versions is
96+ * in it, since some version between changed it.
97+ */
98+ keptChangesSince(space: Space, from: number, to: number): ReadonlySet<string> | undefined {
99+ const out = new Set<string>();
100+ for (let v = from + 1; v <= to; v++) {
101+ const files = this.#keptFiles(space, v);
102+ if (!files) return undefined;
103+ for (const f of files) out.add(f);
104+ }
105+ return out;
106+ }
93108 /** keptPaths as a set, kept for the newest version asked: never changed once made, so a view can hold it. */
94109 keptPathSet(space: Space, version: number): ReadonlySet<string> | undefined {
95110 let fold = this.#keptPaths.get(space);
Lines 155–162 at 318 (were 155–160 at 287)
155155 refusals(agent?: string, limit?: number): unknown;
156156 /** A file as it was at a version (#27). */
157157 fileAt(path: string, version: number, draft: string | null, agent?: string): unknown;
158+ /** fileAt for exactly this spelling, without the version's list of files (version-log.ts fileExactAt). */
159+ fileExactAt?(path: string, version: number, draft: string | null): unknown;
158160 /** Every file that differs between two versions (#27). */
159161 compare(from: number, to: number, draft: string | null, agent?: string, summary?: boolean): unknown;
160162 /** Version `version` of shared without the versions in `versions` (without.ts). */
Lines 49–66 at 318 (were 49–54 at 287)
4949}
5050
5151/**
52+ * An agent with nothing of its own sees exactly its base version, so its paths are that version's kept file list
53+ * (pathindex.ts), when there is one: no layout of every known file (abso - Performance, abso 711).
54+ */
55+function viewPaths(host: SnapshotHost, agent: AgentState): string[] {
56+ const kept =
57+ agent.mine.length === 0
58+ ? host.keptPaths?.(host.spaceNamed(agent.space === SHARED ? null : agent.space), agent.base)
59+ : undefined;
60+ return kept ?? host.agentView(agent).paths();
61+}
63+/**
5264 * The paths in an agent's view now (#37): what its folder should hold.
5365 * Reading it changes nothing. Binary files are included.
5466 */
Lines 74–80 at 318 (were 62–68 at 287)
6274 return {
6375 version: agent.base,
6476 draft: agent.space === SHARED ? null : agent.space,
65− files: host.agentView(agent).paths(),
77+ files: viewPaths(host, agent),
6678 };
6779}
6880
Lines 106–112 at 318 (were 94–100 at 287)
94106 agent: agent.name,
95107 version: agent.base,
96108 draft: agent.space === SHARED ? null : agent.space,
97− files: host.agentView(agent).paths(),
109+ files: viewPaths(host, agent),
98110 };
99111}
100112
Lines 583–604 at 318 (were 583–589 at 287)
583583export type Blobs = Record<string, string | null>;
584584
585585/** What the project needs from the store of binary files' bytes. */
586+/** One news item a write gave an agent: its text and time, and its entry's place in the log. */
587+export interface NewsWritten {
588+ readonly agent: string;
589+ readonly text: string;
590+ readonly at: number | null;
591+ /** The news entry's place in the log: later news has a higher one. */
592+ readonly seq: number;
593+}
586595export interface ProjectOptions {
596+ /**
597+ * Told after each write that gave agents news, with each item as the write appended it. It runs inside the write,
598+ * which can still roll back, so a host collects the items and acts on them only once the call has returned. A host
599+ * can then wake a listener for exactly the agents that got news, without reading the log.
600+ */
601+ newsWritten?: (items: readonly NewsWritten[]) => void;
587602 /** Optional derived atom indexing within persistent graph acceptance. */
588603 indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
589604 /** Private experimental reader route; never falls back for unsupported membership. */
Lines 105–117 at 318 (were 105–113 at 287)
105105 addressedItem,
106106 newsAboutOwnDraft as hostedNewsAboutOwnDraft,
107107 newsForOthers as hostedNewsForOthers,
108+ newsOwed as hostedNewsOwed,
109+ owedAgents as hostedOwedAgents,
110+ owedNewsNames as hostedOwedNewsNames,
108111 markedItem,
109112 type NewsHost,
110113 type NewsItem,
114+ type OwedDefinitionNews,
111115 reviewItem,
112116 settledItem,
113117} from "./news.ts";
Lines 161–167 at 318 (were 157–162 at 287)
157161 LandAnswer,
158162 MergedLine,
159163 Modes,
164+ NewsWritten,
160165 NoteAnswer,
161166 NoteBody,
162167 NoteRecord,
Lines 222–228 at 318 (were 217–222 at 287)
217222 compare as versionCompare,
218223 compareSummary as versionCompareSummary,
219224 fileAt as versionFileAt,
225+ fileExactAt as versionFileExactAt,
220226 log as versionLog,
221227 ribbon as versionRibbon,
222228 show as versionShow,
Lines 335–348 at 318 (were 329–335 at 287)
329335 * doesn't depend on it.
330336 */
331337 checkerReady = false;
338+ /**
339+ * Owed news (abso Capacity, 2026-10-15): a publish's definition news for other agents is left for after its write
340+ * (takeOwedDefinitionNews, definitionNewsOwed, deliverOwedNews). The disk route sets it; the replay engine doesn't.
341+ */
342+ owesDefinitionNews = false;
343+ #owed: OwedDefinitionNews[] = [];
332344 readonly #now: (() => number) | undefined;
345+ readonly #newsWritten: ((items: readonly NewsWritten[]) => void) | undefined;
333346 readonly #whole: ProjectOptions["whole"];
334347 readonly #shapes: ProjectOptions["shapes"];
335348 readonly #logLine: ProjectOptions["logLine"];
Lines 465–471 at 318 (were 452–457 at 287)
452465 }
453466 this.#hasBlob = options.hasBlob ?? (() => false);
454467 this.#now = options.now;
468+ this.#newsWritten = options.newsWritten;
455469 this.#whole = options.whole;
456470 this.#shapes = options.shapes;
457471 this.#logLine = options.logLine;
Lines 1348–1391 at 318 (were 1334–1339 at 287)
13341348 return hostedAnnouncePerson(this.#announceHost, ...args);
13351349 }
13361350
1351+ /** The definition news the writes since the last call owe other agents, handed over once (news.ts). */
1352+ takeOwedDefinitionNews(): OwedDefinitionNews[] {
1353+ const owed = this.#owed;
1354+ this.#owed = [];
1355+ return owed;
1356+ }
1358+ /** What a publish owes, worked out against its version (news.ts newsOwed), for `only` these agents if given. Reads only. */
1359+ newsOwed(owed: OwedDefinitionNews, only?: readonly string[]): { agent: string; items: NewsItem[] }[] {
1360+ return hostedNewsOwed(this.#newsHost, owed, only);
1361+ }
1363+ /** newsOwed, under the name owed definition news had before abso 714. */
1364+ definitionNewsOwed(owed: OwedDefinitionNews, only?: readonly string[]): { agent: string; items: NewsItem[] }[] {
1365+ return this.newsOwed(owed, only);
1366+ }
1368+ /** The names a publish's definitions changed (news.ts owedNewsNames), worked out once for its owed news. Reads only. */
1369+ owedNewsNames(owed: OwedDefinitionNews): string[] {
1370+ return hostedOwedNewsNames(this.#newsHost, owed);
1371+ }
1373+ /** The agents a publish's owed news may be for (news.ts owedAgents). Reads only. */
1374+ owedAgents(owed: OwedDefinitionNews): string[] {
1375+ return hostedOwedAgents(this.#newsHost, owed);
1376+ }
1378+ /** Tells each agent its owed items, as queueNews does: what an agent was already told adds nothing. */
1379+ deliverOwedNews(found: readonly { agent: string; items: readonly NewsItem[] }[]): number {
1380+ const entries: Entry[] = [];
1381+ for (const { agent: name, items } of found) {
1382+ const agent = this.#agents.get(name);
1383+ if (agent) this.#queueNews(agent, items, entries);
1384+ }
1385+ this.#flush(entries);
1386+ return entries.length;
1387+ }
13371389 /** A seat's earlier chat hears that another chat just used the seat (announce.ts seatNotice). */
13381390 seatNotice(...args: Tail<Parameters<typeof hostedSeatNotice>>): ReturnType<typeof hostedSeatNotice> {
13391391 return hostedSeatNotice(this.#announceHost, ...args);
Lines 1492–1508 at 318 (were 1440–1445 at 287)
14401492 return hostedOverlapNews(this.#overlapHost, ...args);
14411493 }
14421494
1495+ /** The news waiting for an agent, read only: nothing is taken, heard or written. None for an agent it hasn't got. */
1496+ peekNews(agentName: string): { text: string; at: number | null }[] {
1497+ const agent = typeof agentName === "string" ? this.#agents.get(agentName) : undefined;
1498+ return agent ? agent.news.map((text, i) => ({ text, at: agent.newsAt[i] ?? null })) : [];
1499+ }
1501+ /** Whether the project has this agent. Read only. */
1502+ hasAgent(agentName: string): boolean {
1503+ return typeof agentName === "string" && this.#agents.get(agentName) !== undefined;
1504+ }
14431506 /** Hand over the news waiting for an agent (collisions, definitions, moves, announcements), once. */
14441507 news(agentName: string): { news: string[]; items: { text: string; at: number | null }[] } {
14451508 const entries: Entry[] = [];
Lines 1782–1796 at 318 (were 1719–1724 at 287)
17191782 if (this.#pending.length === 0) return;
17201783 const out = this.#pending;
17211784 this.#store.append(out);
1785+ if (this.#newsWritten) {
1786+ const items: NewsWritten[] = [];
1787+ out.forEach((entry, i) => {
1788+ if (entry.type !== "news") return;
1789+ for (const text of entry.text)
1790+ items.push({ agent: entry.agent, text, at: entry.time ?? null, seq: this.#stored + i });
1791+ });
1792+ if (items.length > 0) this.#newsWritten(items);
1793+ }
17221794 this.#persistMutable();
17231795 // A few more agents' old told lists into their buckets at each write, until every row has moved (writer-agents.ts).
17241796 if (this.#agents instanceof WriterAgents) this.#agents.moveOldTold(OLD_TOLD_PER_WRITE);
Lines 2009–2019 at 318 (were 1937–1942 at 287)
19372009 return versionFileAt(this.#logHost, ...args);
19382010 }
19392011
2012+ /** fileAt for exactly this spelling, from the file's own lines: no list of the version's files (version-log.ts). */
2013+ fileExactAt(...args: Tail<Parameters<typeof versionFileExactAt>>): ReturnType<typeof versionFileExactAt> {
2014+ return versionFileExactAt(this.#logHost, ...args);
2015+ }
19402017 /** Every file that differs between two versions of shared (or a named draft) (version-log.ts). */
19412018 compare(...args: Tail<Parameters<typeof versionCompare>>): ReturnType<typeof versionCompare> {
19422019 return versionCompare(this.#logHost, ...args);
Lines 2187–2201 at 318 (were 2110–2115 at 287)
21102187 definitionCollisions: (agent, newer, names) => this.#definitionCollisions(agent, newer, names),
21112188 queueNews: (agent, items, entries) => this.#queueNews(agent, items, entries),
21122189 logLine: (line) => this.#logLine?.(line),
2190+ owesDefinitionNews: () => this.owesDefinitionNews,
2191+ owe: (owed) => void this.#owed.push(owed),
2192+ spaceNamed: (name) => (name === SHARED ? this.#shared : this.#spaces.get(name)),
2193+ newerAt: (agent, version) => this.#newerFor(agent, version),
2194+ definitionCollisionsAt: (agent, newer, names, version) =>
2195+ this.#definitionCollisions(agent, newer, names, version),
2196+ setAt: (space, version) => this.#at(space, version),
2197+ collisionAt: (agent, pair, version) =>
2198+ this.#describe(pair, this.#agentView(agent), this.#viewAt(this.#spaceOf(agent), version), agent.space),
21132199 };
21142200 return this.#news;
21152201 }
Lines 2499–2507 at 318 (were 2413–2418 at 287)
24132499 pairs: (draft, against, settled) => this.#pairs(draft, against, settled),
24142500 describe: (pair, yoursView, theirsView, spaceName) => this.#describe(pair, yoursView, theirsView, spaceName),
24152501 definitionRule: () => this.#definitionRule,
2502+ // Only from a stored writer's kept rows, as keptPaths: a project in memory keeps none, and works them out.
2503+ changedSince: (space, from, to) =>
2504+ this.#writerStorage ? this.#paths.keptChangesSince(space, from, to) : undefined,
24162505 refuse: (agent, space, via, time, collisions, entries) =>
24172506 this.#refuse(agent, space, via, time, collisions, entries),
24182507 requireClosed: (tie, union) => this.#requireClosed(tie, union),
Lines 3061–3074 at 318 (were 2972–2984 at 287)
29723061 }
29733062
29743063 /** The space's atoms published after the agent's base, by others. */
2975− #newerFor(agent: AgentState): ReadonlySet<AtomId> {
3064+ /** `upTo`: the work published after the agent's base up to that version only (owed news, news.ts). */
3065+ #newerFor(agent: AgentState, upTo?: number): ReadonlySet<AtomId> {
29763066 const space = this.#spaceOf(agent);
29773067 const base = this.#at(space, agent.base);
2978− const current = this.#setOf(space);
3068+ const current = upTo === undefined ? this.#setOf(space) : this.#at(space, upTo);
29793069 const newer =
29803070 space.name === SHARED && space.membershipVersion
2981− ? new SharedAdditions(space, agent.base, base, current)
3071+ ? new SharedAdditions(space, agent.base, base, current, upTo ?? last(space))
29823072 : differenceSet(current, base);
29833073 return differenceSet(newer, new StableOverlaySet(agent.mine));
29843074 }
Lines 3208–3215 at 318 (were 3118–3123 at 287)
31183208 agent: AgentState,
31193209 newer: ReadonlySet<AtomId>,
31203210 names?: ReadonlySet<string>,
3211+ /** The space's version to compare against: its newest, or an owed publish's (news.ts). */
3212+ version?: number,
31213213 ): DefinitionCollision[] {
31223214 const draft = new Set(this.#draft(agent));
31233215 if (draft.size === 0 || newer.size === 0) return [];
Lines 3218–3236 at 318 (were 3126–3140 at 287)
31263218 const base = agent.mine.some((id) => at.has(id))
31273219 ? this.#view(differenceSet(at, new StableOverlaySet(agent.mine)))
31283220 : this.#viewAt(space, agent.base);
3221+ const to = version ?? last(space);
31293222 return this.#definitionRule.collisions(
31303223 draft,
31313224 this.#agentView(agent),
31323225 base,
3133− this.#viewAt(space, last(space)),
3226+ this.#viewAt(space, to),
31343227 newer,
31353228 space.name,
31363229 undefined,
31373230 names,
3231+ // Where the space changed since the agent's base, from each version's kept files on a stored writer, as land's
3232+ // (abso 714): walking every newer atom for them was 6.5 s of a publish 770 versions behind on abso.
3233+ () => (this.#writerStorage ? this.#paths.keptChangesSince(space, agent.base, to) : undefined),
31383234 );
31393235 }
31403236}
Lines 40–50 at 318 (were 40–45 at 287)
4040 indexVersion?: (version: Published) => void;
4141 /** Version of the selected membership event, independent of later publishes. */
4242 membershipVersion?: (atom: AtomId, version: number) => number | undefined;
43+ /**
44+ * membershipVersion reading the membership pages first, each page once (abso - Performance, 714): for a walk over
45+ * many atoms, such as SharedAdditions. Most atoms have one event, and the page says its version.
46+ */
47+ membershipVersions?: () => (atom: AtomId, version: number) => number | undefined;
4348 readonly name: string;
4449 readonly versions: Published[];
4550 /** Every atom published into this space (for shared, everything in it). */
Lines 63–75 at 318 (were 58–63 at 287)
5863 name,
5964 indexVersion: (version) => indexMembership(storage, prefix, version),
6065 membershipVersion: (atom, version) => membershipEvent(storage, prefix, atom, version)?.version,
66+ membershipVersions: () => {
67+ const pages = new PageReader(storage, prefix);
68+ return (atom, version) => {
69+ const known = pages.versionAt(atom, version);
70+ return known === null ? membershipEvent(storage, prefix, atom, version)?.version : known;
71+ };
72+ },
6173 versions: storedArray(storage, `${prefix}:versions`),
6274 own: new StoredSet(storage, `${prefix}:own`),
6375 publishedIn: new StoredMap(storage, `${prefix}:published`),
Lines 136–154 at 318 (were 124–129 at 287)
124136 }
125137 /** Whether atom is present at version, or undefined when its events must be read. */
126138 presentAt(atom: AtomId, version: number): boolean | undefined {
139+ const code = this.#code(atom);
140+ if (code === undefined || code === MIXED) return undefined;
141+ if (code === NONE) return false;
142+ return version >= code;
143+ }
144+ /** membershipVersion from the page: the version of its only event, or undefined; null when its events must be read. */
145+ versionAt(atom: AtomId, version: number): number | undefined | null {
146+ const code = this.#code(atom);
147+ if (code === undefined || code === MIXED) return null;
148+ if (code === NONE) return undefined;
149+ return version >= code ? code : undefined;
150+ }
151+ #code(atom: AtomId): number | undefined {
127152 this.#kept ??= this.#storage.read(`${this.#prefix}:pages:meta`, "kept") === 1;
128153 if (!this.#kept) return undefined;
129154 const seq = seqOf(atom);
Lines 160–166 at 318 (were 135–144 at 287)
135160 if (this.#pages.size >= 64) this.#pages.delete(this.#pages.keys().next().value!);
136161 this.#pages.set(index, page);
137162 }
138− const code = page[seq % PAGE] ?? NONE;
139− if (code === NONE) return false;
140− if (code === MIXED) return undefined;
141− return version >= code;
163+ return page[seq % PAGE] ?? NONE;
142164 }
143165}
144166
Lines 383–399 at 318 (were 361–370 at 287)
361383 readonly baseVersion: number;
362384 readonly base: ReadonlySet<AtomId>;
363385 readonly current: ReadonlySet<AtomId>;
364− constructor(space: Space, baseVersion: number, base: ReadonlySet<AtomId>, current: ReadonlySet<AtomId>) {
386+ /** `endVersion`: the version `current` is (the newest by default; an earlier one for owed news, news.ts). */
387+ constructor(
388+ space: Space,
389+ baseVersion: number,
390+ base: ReadonlySet<AtomId>,
391+ current: ReadonlySet<AtomId>,
392+ endVersion = last(space),
393+ ) {
365394 super();
366395 if (space.name !== SHARED || !space.membershipVersion) throw Error("shared additions require indexed shared space");
367− this.endVersion = last(space);
396+ this.endVersion = endVersion;
368397 this.space = space;
369398 this.baseVersion = baseVersion;
370399 this.base = base;
Lines 403–412 at 318 (were 374–382 at 287)
374403 return this.current.has(id) && !this.base.has(id);
375404 }
376405 *values(): SetIterator<AtomId> {
406+ const versionOf = this.space.membershipVersions?.() ?? this.space.membershipVersion!;
377407 for (let version = this.baseVersion + 1; version <= this.endVersion; version++) {
378408 for (const id of this.space.versions[version]!.atoms) {
379− if (this.space.membershipVersion!(id, this.endVersion) === version && this.has(id)) yield id;
409+ if (versionOf(id, this.endVersion) === version && this.has(id)) yield id;
380410 }
381411 }
382412 }
Lines 73–81 at 318 (were 73–79 at 287)
7373export function spellingOf(view: ReadView, path: string): string {
7474 if (view.hasFile(path)) return path;
7575 const key = pathKey(path);
76− // Known paths first, by key, then only those laid out (#46).
77− const twins = view.knownPaths().filter((p) => pathKey(p) === key && view.hasFile(p));
76+ // Every path the graph has ever had, by key, then only those the view has a file at (#46). Not the view's known paths
77+ // (abso Capacity, 714): those read every atom's membership and file list, 36,360 statements of a record on abso, as
78+ // clashIn found. A path the view never had has no file in it, so the answers are the same.
79+ const twins = [...view.graph.knownFiles()].filter((p) => pathKey(p) === key && view.hasFile(p));
7880 return twins.length === 1 ? twins[0]! : path;
7981}
new file, 55 lines
1+// Moves before laying out files (abso 714, piece 3): expressMoves looks at the draft's own written and deleted lines
2+// first, and lays out no file when none of its written lines with real content has a deleted line's text. moves.test.ts
3+// covers the moves themselves.
4+
5+import assert from "node:assert/strict";
6+import { test } from "node:test";
7+import type { Graph } from "../../../src/engine/index.ts";
8+import { type ExpressMovesHost, expressMoves } from "../express-moves.ts";
9+import type { AgentState } from "../project-types.ts";
11+/** A draft of two atoms: "del" deletes one line, "add" writes the others. Any view laid out throws. */
12+function host(deleted: string, written: string[]): ExpressMovesHost {
13+ const texts = [deleted, ...written];
14+ const graph = {
15+ deletedLines: (id: string) => (id === "del" ? ["line-0"] : []),
16+ *eachInsertedLine(id: string) {
17+ if (id === "add") for (let k = 1; k < texts.length; k++) yield `line-${k}`;
18+ },
19+ lineN: (line: string) => Number(line.slice("line-".length)),
20+ *textChunks(n: number) {
21+ yield texts[n]!;
22+ },
23+ textOf: (n: number) => texts[n]!,
24+ } as unknown as Graph;
25+ const laidOut = (): never => {
26+ throw new Error("laid out");
27+ };
28+ return {
29+ graph,
30+ draft: () => ["del", "add"],
31+ agentView: laidOut,
32+ beforeDraft: laidOut,
33+ view: laidOut,
34+ apply: laidOut,
35+ addDraft: laidOut,
36+ recordFile: laidOut,
37+ };
38+}
40+const agent = { name: "ann" } as AgentState;
42+test("an edit that only changes lines lays out no file", () => {
43+ expressMoves(host(" return pi * r * r;", [" return Math.PI * r * r;"]), agent, 1, []);
44+});
46+test("a deleted text written again with only brackets or blanks in common lays out no file", () => {
47+ expressMoves(host("}", [" const tree = parse(p);", "}", ""]), agent, 1, []);
48+});
50+test("a written line with real content that the draft also deleted goes on to the files", () => {
51+ assert.throws(
52+ () => expressMoves(host(" return pi * r * r;", ["", " return pi * r * r;"]), agent, 1, []),
53+ /laid out/,
54+ );
55+});
new file, 49 lines
1+// fileExactAt (version-log.ts, abso Capacity, 2026-10-17): the same answer as fileAt for exactly that spelling, at
2+// every version, read from the file's own lines without the version's list of files. abso's worker/test/
3+// project-files.test.ts checks it on the disk engine, where the list is what costs.
4+
5+import assert from "node:assert/strict";
6+import { test } from "node:test";
7+import { MemoryStore, Project } from "../project.ts";
8+
9+/** Files added, edited, emptied, made binary and taken out, beside others, over six versions. */
10+function history(): Project {
11+ const p = new Project(new MemoryStore(), { hasBlob: () => true });
12+ p.init({ "README.md": "hi\n", "abso.json": '{ "check": "true" }\n', "src/a.ts": "a\n" }, 0);
13+ p.record("ann", { "abso.yml": "pipelines:\n ci:\n on: [push]\n", "docs/abso.yml": "not this one\n" }, 1);
14+ p.publish("ann", "a pipeline", 2);
15+ p.record("ann", { "abso.json": '{ "check": "false" }\n', "empty.txt": "" }, 3, {}, { "abso.yaml": "b".repeat(64) });
16+ p.publish("ann", "a binary, and an empty file", 4);
17+ p.record("ann", { "abso.yml": null, "avcs.json": "{}\n", "src/a.ts": "" }, 5);
18+ p.publish("ann", "the pipeline gone, a file emptied", 6);
19+ return p;
20+}
22+const PATHS = [
23+ "abso.yml",
24+ "abso.yaml",
25+ "abso.json",
26+ "avcs.json",
27+ "docs/abso.yml",
28+ "empty.txt",
29+ "src/a.ts",
30+ "README.md",
31+ "never.txt",
32+];
34+test("fileExactAt answers what fileAt answers for the same spelling, at every version", () => {
35+ const p = history();
36+ const last = p.version;
37+ assert.ok(last >= 3);
38+ for (let v = 0; v <= last; v++)
39+ for (const path of PATHS) assert.deepEqual(p.fileExactAt(path, v), p.fileAt(path, v), `${path} at ${v}`);
40+});
42+test("a name nothing ever wrote is null, and another spelling is that spelling, not the stored one", () => {
43+ const p = history();
44+ const last = p.version;
45+ assert.deepEqual(p.fileExactAt("never.txt", last), { path: "never.txt", version: last, text: null });
46+ // fileAt reads the stored spelling for any spelling (#41); fileExactAt reads only the one asked.
47+ assert.equal((p.fileAt("ABSO.json", last) as { text: string | null }).text, '{ "check": "false" }\n');
48+ assert.deepEqual(p.fileExactAt("ABSO.json", last), { path: "ABSO.json", version: last, text: null });
49+});
Lines 105–124 at 318 (were 105–107 at 287)
105105 ] as const)
106106 assert.deepEqual(project.pathsAt(version).files, oracle.draftOf(agent)!.view.paths(), `paths at ${version}`);
107107});
109+test("an agent's files on a writer, from its base version's kept list when it has nothing of its own, as the in-memory project says", () => {
110+ // abso - Performance (abso 711): a status for an agent behind shared listed its files by laying out every known file.
111+ const oracle = new Project(new MemoryStore());
112+ const project = writer();
113+ history(oracle);
114+ history(project);
115+ // v0 and v1 are behind shared with nothing of their own, v2 is at shared, and bob, cy, dee and eve have drafts.
116+ for (const agent of ["v0", "v1", "v2", "bob", "cy", "dee", "eve"]) {
117+ assert.deepEqual(project.agentPaths(agent), oracle.agentPaths(agent), agent);
118+ assert.deepEqual(project.pathsOf(agent), oracle.pathsOf(agent), `${agent} for a reader`);
119+ }
120+ assert.deepEqual(project.agentPaths("v0").files, project.pathsAt(0).files);
121+ assert.equal(project.agentPaths("v0").files.includes("src/gone.ts"), true);
122+ assert.equal(project.agentPaths("v1").files.includes("src/gone.ts"), false);
123+ assert.equal(project.agentPaths("eve").files.includes("src/draft-new.ts"), true);
124+});
Lines 37–42 at 318 (were 37–43 at 287)
3737 );
3838 assert.equal(news[0]!.publisher, "lib");
3939 assert.equal(news[1]!.drafts, 1);
40− assert.equal(news[1]!.files, 1);
4140 assert.equal(news[1]!.changedNames, 1);
4241 assert.equal(news[1]!.news, 1);
4342});
new file, 56 lines
1+// A host learns each write's news as the write appends it (newsWritten), and can read an agent's waiting news without
2+// taking it (peekNews), so a listener can be woken for exactly the agents that got news and caught up on connect.
3+
4+import assert from "node:assert/strict";
5+import { test } from "node:test";
6+import { MemoryStore, type NewsWritten, Project } from "../project.ts";
7+
8+function setup() {
9+ const store = new MemoryStore();
10+ const written: NewsWritten[][] = [];
11+ const project = new Project(store, { newsWritten: (items) => written.push([...items]) });
12+ project.init({ "a.txt": "a\n" }, 0);
13+ for (const a of ["builder1", "builder2", "builder3"]) project.sync(a);
14+ written.length = 0;
15+ return { project, store, written };
16+}
18+test("a write's news is told once, per item, with its agent, text and place in the log", () => {
19+ const { project, store, written } = setup();
20+ project.announce("builder1", "Ship it", ["builder2", "builder3"], 1);
21+ assert.equal(written.length, 1, "one call for the write");
22+ const items = written[0]!;
23+ assert.deepEqual(
24+ items.map((i) => i.agent),
25+ ["builder2", "builder3"],
26+ );
27+ for (const item of items) {
28+ assert.match(item.text, /Announcement from builder1.*Ship it/);
29+ assert.equal(store.entries[item.seq]?.type, "news", "seq is the entry's place in the log");
30+ }
31+ assert.ok(items[1]!.seq > items[0]!.seq);
32+});
34+test("writes with no news, and taking news (heard), tell nothing", () => {
35+ const { project, written } = setup();
36+ project.announce("builder1", "Ship it", ["builder2"], 1);
37+ written.length = 0;
38+ project.news("builder2");
39+ project.sync("builder3");
40+ assert.deepEqual(written, []);
41+});
43+test("peekNews reads waiting news and takes nothing; hasAgent reads only", () => {
44+ const { project, store } = setup();
45+ project.announce("builder1", "Ship it", ["builder2"], 1);
46+ const length = store.entries.length;
47+ const peeked = project.peekNews("builder2");
48+ assert.equal(peeked.length, 1);
49+ assert.match(peeked[0]!.text, /Ship it/);
50+ assert.deepEqual(project.peekNews("builder2"), peeked, "still there");
51+ assert.deepEqual(project.peekNews("nobody"), [], "no agent: none, and none made");
52+ assert.equal(project.hasAgent("builder2"), true);
53+ assert.equal(project.hasAgent("nobody"), false);
54+ assert.equal(store.entries.length, length, "nothing written");
55+ assert.equal(project.news("builder2").news.length, 1, "the take still finds it");
56+});
new file, 190 lines
1+// Owed news (abso Capacity, 2026-10-15): with owesDefinitionNews set (abso's disk route sets it), a publish leaves its
2+// definition news for other agents for after its write. The same news, against the publish's version; told once; and
3+// the publisher's own answer as before. abso's worker/test/owed-news.test.ts covers the disk route's marker and alarm.
4+
5+import assert from "node:assert/strict";
6+import { test } from "node:test";
7+import { MemoryStore, Project } from "../project.ts";
8+
9+// abso-core's changed-definition.test.ts scenario: parse.ts defines parsePattern, match.ts imports it.
10+const START = {
11+ "src/parse.ts": [
12+ "export function parsePattern(text: string): Node {",
13+ ' return { kind: "lit", text };',
14+ "}",
15+ "",
16+ "export interface Node {",
17+ " kind: string;",
18+ " text: string;",
19+ "}",
20+ ].join("\n"),
21+ "src/match.ts": [
22+ 'import { parsePattern } from "./parse.ts";',
23+ "",
24+ "export function run(p: string) {",
25+ " return p;",
26+ "}",
27+ ].join("\n"),
28+ "README.md": "Uses parsePattern.\n",
29+};
31+/** bob's draft calls parsePattern; ann's draft changes its signature; cat's touches something else. Nothing published. */
32+function drafts(project: Project): void {
33+ project.init(START, 0);
34+ project.sync("bob");
35+ project.sync("ann");
36+ project.sync("cat");
37+ project.edit(
38+ "bob",
39+ { file: "src/match.ts", old: " return p;\n", new: " const tree = parsePattern(p);\n return tree;\n" },
40+ 1,
41+ );
42+ project.edit(
43+ "ann",
44+ {
45+ file: "src/parse.ts",
46+ old: "parsePattern(text: string): Node",
47+ new: "parsePattern(text: string, flags: string): Node",
48+ },
49+ 2,
50+ );
51+ project.edit("cat", { file: "README.md", old: "Uses parsePattern.", new: "Uses parsePattern, twice." }, 3);
52+}
54+const definitionNews = (news: readonly string[]) => news.filter((n) => /definition of parsePattern/.test(n)).sort();
56+test("the news owed is the news a publish would have told, and the publisher's own answer is the same", () => {
57+ const told = new Project(new MemoryStore());
58+ drafts(told);
59+ const toldAnswer = told.publish("ann", "parsePattern takes flags", 4);
60+ const expected = definitionNews(told.news("bob").news);
61+ assert.equal(expected.length, 1, "the scenario has a definition collision");
63+ const owing = new Project(new MemoryStore());
64+ owing.owesDefinitionNews = true;
65+ drafts(owing);
66+ assert.deepEqual(owing.publish("ann", "parsePattern takes flags", 4), toldAnswer, "the publisher's answer");
67+ const owed = owing.takeOwedDefinitionNews();
68+ assert.deepEqual(owed, [{ version: owing.version, space: owed[0]!.space, publisher: "ann", all: true }]);
69+ assert.deepEqual(owing.takeOwedDefinitionNews(), [], "handed over once");
70+ // Not told yet: bob's news holds no definition news until it's delivered.
71+ assert.deepEqual(definitionNews(owing.news("bob").news), []);
72+ const found = owing.definitionNewsOwed(owed[0]!);
73+ assert.deepEqual(
74+ found.map((f) => f.agent),
75+ ["bob"],
76+ );
77+ assert.ok(owing.deliverOwedNews(found) > 0);
78+ assert.deepEqual(definitionNews(owing.news("bob").news), expected);
79+ // Told twice adds nothing, and a run of the read after delivery finds nothing left.
80+ assert.equal(owing.deliverOwedNews(found), 0);
81+ assert.deepEqual(owing.definitionNewsOwed(owed[0]!), []);
82+});
84+test("worked out against the publish's version, though more was published before the news went out", () => {
85+ const told = new Project(new MemoryStore());
86+ drafts(told);
87+ told.publish("ann", "parsePattern takes flags", 4);
88+ const expected = definitionNews(told.news("bob").news);
90+ const owing = new Project(new MemoryStore());
91+ owing.owesDefinitionNews = true;
92+ drafts(owing);
93+ owing.publish("ann", "parsePattern takes flags", 4);
94+ const [first] = owing.takeOwedDefinitionNews();
95+ // Then parsePattern is removed, before the first publish's news is out: against the newest version the news
96+ // would say "removes"; against the first publish's, it says "changes", as told at publish time.
97+ owing.sync("ann");
98+ owing.edit(
99+ "ann",
100+ {
101+ file: "src/parse.ts",
102+ old: 'export function parsePattern(text: string, flags: string): Node {\n return { kind: "lit", text };\n}\n',
103+ new: "",
104+ },
105+ 5,
106+ );
107+ owing.publish("ann", "parsePattern goes", 6);
108+ assert.ok(owing.deliverOwedNews(owing.definitionNewsOwed(first!)) > 0);
109+ assert.deepEqual(definitionNews(owing.news("bob").news), expected, "the first publish's news, as it was");
110+});
112+test("an agent that synced past the version since isn't told it", () => {
113+ const owing = new Project(new MemoryStore());
114+ owing.owesDefinitionNews = true;
115+ drafts(owing);
116+ owing.publish("ann", "parsePattern takes flags", 4);
117+ const [owed] = owing.takeOwedDefinitionNews();
118+ owing.sync("bob");
119+ assert.deepEqual(owing.definitionNewsOwed(owed!), []);
120+});
122+test("the replay engine tells it at publish time, as before", () => {
123+ const told = new Project(new MemoryStore());
124+ drafts(told);
125+ told.publish("ann", "parsePattern takes flags", 4);
126+ assert.deepEqual(told.takeOwedDefinitionNews(), []);
127+ assert.equal(definitionNews(told.news("bob").news).length, 1);
128+});
130+test("owedAgents lists who may be owed, and the news one agent at a time adds up to the whole (abso 714)", () => {
131+ const owing = new Project(new MemoryStore());
132+ owing.owesDefinitionNews = true;
133+ drafts(owing);
134+ owing.publish("ann", "parsePattern takes flags", 4);
135+ const [owed] = owing.takeOwedDefinitionNews();
136+ assert.deepEqual(owing.owedAgents(owed!), ["bob", "cat"], "every other agent behind it with a draft");
137+ const whole = owing.definitionNewsOwed(owed!);
138+ assert.equal(whole.length, 1);
139+ assert.deepEqual(
140+ owing.owedAgents(owed!).flatMap((agent) => owing.definitionNewsOwed(owed!, [agent])),
141+ whole,
142+ );
143+ owing.sync("bob");
144+ assert.deepEqual(owing.owedAgents(owed!), ["cat"], "synced past it");
145+});
147+test("everything a publish tells other agents is owed and told after it, the same news (abso 714)", () => {
148+ // bob's draft calls parsePattern (definition news), dee's changes the line ann's publish changes (same-lines news),
149+ // and cat's touches nothing of it (no news).
150+ const scenario = (project: Project) => {
151+ drafts(project);
152+ project.sync("dee");
153+ project.edit(
154+ "dee",
155+ { file: "src/parse.ts", old: "parsePattern(text: string): Node", new: "parsePattern(input: string): Node" },
156+ 5,
157+ );
158+ };
159+ const told = new Project(new MemoryStore());
160+ scenario(told);
161+ const toldAnswer = told.publish("ann", "parsePattern takes flags", 6);
162+ const expected = Object.fromEntries(["bob", "cat", "dee"].map((a) => [a, told.news(a).news.toSorted()]));
163+ assert.ok(expected.bob!.length > 0 && expected.dee!.length > 0, "the scenario has both kinds of news");
165+ const owing = new Project(new MemoryStore());
166+ owing.owesDefinitionNews = true;
167+ scenario(owing);
168+ assert.deepEqual(owing.publish("ann", "parsePattern takes flags", 6), toldAnswer, "the publisher's answer");
169+ const [owed] = owing.takeOwedDefinitionNews();
170+ assert.equal(owed!.all, true);
171+ for (const a of ["bob", "cat", "dee"])
172+ assert.deepEqual(owing.news(a).news, [], `${a} is told nothing in the publish`);
173+ const names = owing.owedNewsNames(owed!);
174+ assert.deepEqual(names, ["parsePattern"]);
175+ // One agent at a time, as the host works it out.
176+ for (const agent of owing.owedAgents(owed!)) owing.deliverOwedNews(owing.newsOwed({ ...owed!, names }, [agent]));
177+ for (const a of ["bob", "cat", "dee"]) assert.deepEqual(owing.news(a).news.toSorted(), expected[a], a);
178+ // Twice tells nothing more.
179+ assert.deepEqual(owing.newsOwed({ ...owed!, names }), []);
180+});
182+test("a publish that no other draft can collide with owes nothing", () => {
183+ const owing = new Project(new MemoryStore());
184+ owing.owesDefinitionNews = true;
185+ owing.init({ "a.txt": "one\n" }, 0);
186+ owing.sync("ann");
187+ owing.edit("ann", { file: "a.txt", old: "one", new: "two" }, 1);
188+ owing.publish("ann", "alone", 2);
189+ assert.deepEqual(owing.takeOwedDefinitionNews(), []);
190+});
Lines 36–87 at 318 (were 36–38 at 287)
3636 storage.db.close();
3737 }
3838});
40+test("shared additions read each atom's version from the membership pages, and answer as its events do (abso - Performance, 714)", (t) => {
41+ const storage = new SqlState();
42+ try {
43+ const membership = new Membership(storage),
44+ space = membership.shared;
45+ const ids = (from: number, to: number) => Array.from({ length: to - from }, (_, i) => `a${from + i}`);
46+ const add = (atoms: string[], dropped: string[] = []) =>
47+ addVersion(space, { version: space.versions.length, agent: "test", message: "version", time: 0, atoms, dropped });
48+ // Three pages of atoms; a5 and a400 dropped and a5 back, a601 added and dropped: their events are read.
49+ add(ids(0, 300));
50+ add(ids(300, 600));
51+ add([], ["a5", "a400"]);
52+ add(["a5", "a600"]);
53+ add(["a601"]);
54+ add([], ["a601"]);
55+ const last = space.versions.length - 1;
56+ const { membershipVersions: _pages, ...eventsOnly } = space;
57+ const read = storage.read.bind(storage);
58+ let eventReads = 0;
59+ t.mock.method(storage, "read", (collection: string, key: string) => {
60+ if (collection.startsWith('membership:"":events:')) eventReads++;
61+ return read(collection, key);
62+ });
63+ const walk = (s: typeof space) => {
64+ eventReads = 0;
65+ const out: string[][] = [];
66+ for (let from = 0; from < last; from++)
67+ for (let to = from + 1; to <= last; to++)
68+ out.push([...new SharedAdditions(s, from, membership.at(s, from), membership.at(s, to), to)]);
69+ return { out, eventReads };
70+ };
71+ const paged = walk(space);
72+ const events = walk(eventsOnly);
73+ assert.deepEqual(paged.out, events.out);
74+ assert.ok(
75+ paged.eventReads < events.eventReads / 10,
76+ `${paged.eventReads} event reads against ${events.eventReads}`,
77+ );
78+ assert.deepEqual([...new SharedAdditions(space, 1, membership.at(space, 1), membership.at(space, 3), 3)], ["a600"]);
79+ assert.deepEqual(
80+ [...new SharedAdditions(space, 2, membership.at(space, 2), membership.at(space, 3), 3)],
81+ ["a5", "a600"],
82+ );
83+ assert.deepEqual([...new SharedAdditions(space, 3, membership.at(space, 3), membership.at(space, 5), 5)], []);
84+ } finally {
85+ storage.db.close();
86+ }
87+});
Lines 244–278 at 318 (were 244–249 at 287)
244244 };
245245}
246246
247+/**
248+ * fileAt for exactly this spelling, from the file's own lines (abso Capacity, 2026-10-17): no spelling lookup and no
249+ * list of the version's files. fileAt's hasFile answers from the version's whole path list, folded from version 0
250+ * when nothing's kept, and a spelling it doesn't find reads every known path. A name nothing ever wrote is one read.
251+ * The pipeline's project files (abso.yml and the like) are read this way on every tick.
252+ */
253+export function fileExactAt(
254+ host: LogHost,
255+ path: string,
256+ version: number,
257+ options: { draft?: string | null; agent?: string } = {},
258+): { path: string; version: number; text: string | null; blob?: string } {
259+ host.needInit();
260+ checkReadPath(path);
261+ const space = host.spaceFor(options);
262+ host.checkVersion(space, version);
263+ if (!host.graph.hasAtomsIn(path)) return { path, version, text: null };
264+ const view = host.viewAt(space, version);
265+ const attrs = view.attrs(path);
266+ // hasFile's own test, without its path list: kept while empty, a link, a binary, or a visible line.
267+ const exists = attrs.exists || attrs.link !== null || attrs.blob !== null || view.lines(path).length > 0;
268+ return {
269+ path,
270+ version,
271+ text: exists ? view.text(path) : null,
272+ ...(attrs.blob !== null ? { blob: attrs.blob } : {}),
273+ };
274+}
247276/** The files that may differ between two versions, and both views: compare's and compareSummary's ground. */
248277function compared(
249278 host: LogHost,
MCP
compare on this site's /mcp
CLI
abso diff 287 318 --json
JSON
/christopher/abso-core/compare/287..318?format=json