From 79aa85e883ebfcd1efd663631a2b80434ba61a8f Mon Sep 17 00:00:00 2001 From: Tyler Hallada Date: Tue, 17 Nov 2026 02:25:25 -0500 Subject: [PATCH] =?UTF-8?q?Several=20libraries=20on=20the=20server:=20one?= =?UTF-8?q?=20directory,=20store,=20notice=20stream,=20link=20index,=20pen?= =?UTF-8?q?ding=20links,=20reviewer=20and=20jobs=20each;=20/api/libraries?= =?UTF-8?q?=20and=20/api/l//=E2=80=A6;=20the=20page=20holds=20one=20li?= =?UTF-8?q?brary,=20named=20by=20its=20address,=20and=20switches=20by=20a?= =?UTF-8?q?=20page=20load?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The old single-library layout is not opened (the server says to run the migration, which comes next); the per-document migration, /recover and the old replicas check are gone. A server lock keeps two servers off one data directory. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab --- e2e/helpers.ts | 25 ++- e2e/libraries.spec.ts | 110 +++++++++++++ e2e/more.spec.ts | 2 +- e2e/nodes.spec.ts | 4 +- server/bundle.ts | 284 +++++++++++++++++++++++++++++++++ server/embed.ts | 5 + server/index.ts | 324 +++++++++++++------------------------- server/libraries.ts | 274 ++++++++++++++++++++++++++++++++ server/library.ts | 116 ++++---------- server/links/nodeIndex.ts | 8 + server/links/pending.ts | 10 +- server/lock.ts | 109 +++++++++++++ server/migrate.ts | 175 -------------------- src/ui/api.ts | 55 +++++++ src/ui/keys.ts | 3 +- src/ui/linker.ts | 7 +- src/ui/session.ts | 9 +- src/ui/store.ts | 198 +++++++++++++++-------- tests/libraries.test.ts | 235 +++++++++++++++++++++++++++ tests/migrate.test.ts | 175 -------------------- tests/scale.test.ts | 2 +- tests/store.test.ts | 97 ++++++++---- 22 files changed, 1468 insertions(+), 759 deletions(-) create mode 100644 e2e/libraries.spec.ts create mode 100644 server/bundle.ts create mode 100644 server/libraries.ts create mode 100644 server/lock.ts delete mode 100644 server/migrate.ts create mode 100644 src/ui/api.ts create mode 100644 tests/libraries.test.ts delete mode 100644 tests/migrate.test.ts diff --git a/e2e/helpers.ts b/e2e/helpers.ts index 72243bb..c26915a 100644 --- a/e2e/helpers.ts +++ b/e2e/helpers.ts @@ -42,9 +42,20 @@ export async function nodeAt(page: Page, ...path: string[]): Promise { return find(s, ...path); } -/** Go to the address of the section at these titles from the library root (none: the library, `/`), and wait for the page. */ +/** The id of the library the tests share: the server's first (what the unprefixed routes act on). */ +export async function libraryId(page: Page): Promise { + return (await (await page.request.get("/api/state")).json()).library; +} + +/** An address in the shared library: `/l/` for its root, then a path within it (`/n/`, `/w/en/Octopus`). */ +export async function libraryPath(page: Page, part = "/"): Promise { + const base = `/l/${await libraryId(page)}`; + return part === "/" ? base : base + part; +} + +/** Go to the address of the section at these titles from the library root (none: the library, `/l/`), and wait for the page. */ export async function openAt(page: Page, ...path: string[]) { - await page.goto(path.length ? `/n/${encodeURIComponent(await nodeAt(page, ...path))}` : "/"); + await page.goto(await libraryPath(page, path.length ? `/n/${encodeURIComponent(await nodeAt(page, ...path))}` : "/")); await page.waitForSelector("article"); } @@ -61,12 +72,12 @@ export async function openPage(page: Page, ...path: string[]) { } /** - * Go somewhere: an address as it is (`/`, `/w/en/Octopus`), or a top-level section by its title, - * opened as the page (openPage). Does not wait for the page. + * Go somewhere: an address in the shared library (`/` its root, `/w/en/Octopus`), or a top-level + * section by its title, opened as the page (openPage). Does not wait for the page. */ export async function visit(page: Page, where: string) { - if (where.startsWith("/")) return void (await page.goto(where)); - await page.goto(`/n/${encodeURIComponent(await nodeAt(page, where))}`); + if (where.startsWith("/")) return void (await page.goto(await libraryPath(page, where))); + await page.goto(await libraryPath(page, `/n/${encodeURIComponent(await nodeAt(page, where))}`)); await page.waitForFunction(() => (globalThis as any).__ie?.ready); await hoistHere(page); } @@ -77,7 +88,7 @@ export async function visit(page: Page, where: string) { * has the focus. */ export async function addTop(page: Page, title: string, text: string) { - await page.goto("/"); + await page.goto(await libraryPath(page)); await page.waitForFunction(() => (globalThis as any).__ie?.ready); await page.keyboard.press("a"); await page.keyboard.type(title); diff --git a/e2e/libraries.spec.ts b/e2e/libraries.spec.ts new file mode 100644 index 0000000..7e34a94 --- /dev/null +++ b/e2e/libraries.spec.ts @@ -0,0 +1,110 @@ +/** + * Several libraries, from the page: every address names its library (`/l/`), `/` opens the one + * last used, :/library lists, makes and opens them (a page load), a new library starts with its root + * alone, nothing of one library is found from another (the jump box, nearby and Related, a node's + * address), and each library keeps its own view. The panel that lists them is step 4's; these + * tests use the command and the API. They make their own libraries and delete them at the end: the + * other specs share the first. + */ +import { expect, test, type Page } from "@playwright/test"; +import { command, keys, libraryId, settle, state } from "./helpers"; + +const ready = (page: Page) => page.waitForFunction(() => (globalThis as any).__ie?.ready); +const status = (page: Page) => page.locator(".status .message"); +const lib = (page: Page) => state(page, (s) => s.library as string); + +test.describe.configure({ mode: "serial" }); +test.afterEach(({ page }) => settle(page)); + +test("a new library starts with its root alone, has an address of its own, and finds nothing of the first", async ({ page }) => { + const first = await libraryId(page); + await page.goto("/"); + await ready(page); + // `/` opens the first library in a browser that has used none, at its own address. + expect(await lib(page)).toBe(first); + await expect(page).toHaveURL(new RegExp(`/l/${first}$`)); + + await command(page, "/library new Work notes"); + await page.waitForURL((u) => /^\/l\/[0-9a-z]+$/.test(u.pathname) && !u.pathname.endsWith(first)); + await ready(page); + const work = await lib(page); + expect(work).not.toBe(first); + await expect(page.locator(".top h1")).toHaveText("Work notes"); + await expect(page.locator(".docbar .lib-name")).toHaveText("Work notes"); + // Its root alone: no seed, no starter trees. + expect(await state(page, (s) => s.snap.nodes[s.snap.root].children.length)).toBe(0); + + // A section with the same title as one in the first library, and text that mentions the first's titles. + await keys(page, "a"); + await page.keyboard.type("Fixed points"); + await page.keyboard.press("Enter"); + await page.waitForFunction(() => Object.values((globalThis as any).__ie.snap.nodes).some((n: any) => n.title === "Fixed points")); + await page.waitForFunction(() => (globalThis as any).__ie.synced()); + + // The jump box offers this library's nodes only. + await keys(page, "/"); + await page.keyboard.type("Amphidromes"); + await expect(page.locator(".jump li[data-hit]")).toHaveCount(0); + await page.keyboard.press("Escape"); + await keys(page, "/"); + await page.keyboard.type("Fixed points"); + await expect(page.locator(".jump li[data-hit]")).toHaveCount(1); + await page.keyboard.press("Escape"); + + // The server's routes for it hold only it. + const tree = await (await page.request.get(`/api/l/${work}/tree`)).json(); + expect(Object.values(tree.nodes).map((n: any) => n.title).sort()).toEqual(["Fixed points", "Work notes"]); + const firstTree = await (await page.request.get(`/api/l/${first}/tree`)).json(); + expect(Object.values(firstTree.nodes).some((n: any) => n.title === "Work notes")).toBe(false); + // Nearby and Related never come from the first library, though it has a "Fixed points" too. + const mine = Object.values(tree.nodes).find((n: any) => n.title === "Fixed points") as { id: string }; + const nearby = await (await page.request.get(`/api/l/${work}/links/nearby?node=${encodeURIComponent(mine.id)}`)).json(); + for (const n of nearby.nearby) expect(tree.nodes[n.handle]).toBeTruthy(); + const related = await (await page.request.get(`/api/l/${work}/links/related?node=${encodeURIComponent(mine.id)}`)).json(); + for (const r of related.related) expect(tree.nodes[r.node]).toBeTruthy(); + + // A node of the first library, at this library's address, is not found here. + const amph = Object.values(firstTree.nodes).find((n: any) => n.title === "Amphidromes") as { id: string }; + await page.goto(`/l/${work}/n/${encodeURIComponent(amph.id)}`); + await ready(page); + await expect(page.locator(".top h1")).toHaveText("Work notes"); + await expect(status(page)).toContainText(amph.id); + + // `/` now opens the library last used here. + await page.goto("/"); + await ready(page); + expect(await lib(page)).toBe(work); + // :/library with a name opens another, by a page load; each keeps its own view. + await command(page, "/library Library"); + await page.waitForURL(new RegExp(`/l/${first}`)); + await ready(page); + expect(await lib(page)).toBe(first); + await expect(page.locator(".top h1")).toHaveText("Library"); + const keysNow = await page.evaluate(() => Object.keys(localStorage).filter((k) => k.startsWith("ie:view:")).sort()); + expect(keysNow).toEqual(expect.arrayContaining([`ie:view:${first}:main`, `ie:view:${work}:main`])); +}); + +test("rename and delete over the API; an unknown library's address goes to the first; the last library cannot be deleted", async ({ page }) => { + const first = await libraryId(page); + const listed = (await (await page.request.get("/api/libraries")).json()).libraries as { id: string; title: string }[]; + const work = listed.find((l) => l.title === "Work notes")!; + expect(work).toBeTruthy(); + const renamed = await page.request.patch(`/api/libraries/${work.id}`, { data: { title: "Work, renamed" } }); + expect(renamed.ok()).toBe(true); + await page.goto(`/l/${work.id}`); + await ready(page); + await expect(page.locator(".top h1")).toHaveText("Work, renamed"); + // The page learns of its library's deletion and stops sending. + const gone = await page.request.delete(`/api/libraries/${work.id}`); + expect(gone.ok()).toBe(true); + expect((await gone.json()).movedTo).toContain(".deleted"); + await expect(status(page)).toContainText("This library has been deleted"); + // Its address now goes to the first library, saying so. + await page.goto(`/l/${work.id}`); + await page.waitForURL(new RegExp(`/l/${first}$`)); + await ready(page); + await expect(status(page)).toContainText(`There is no library ${work.id} here`); + // The first, now alone, cannot be deleted. + const last = await page.request.delete(`/api/libraries/${first}`); + expect(last.status()).toBe(409); +}); diff --git a/e2e/more.spec.ts b/e2e/more.spec.ts index 24d028b..0046d81 100644 --- a/e2e/more.spec.ts +++ b/e2e/more.spec.ts @@ -79,7 +79,7 @@ test("hoisting makes one node the whole page; Esc at its top steps out to its pa await expect(page).toHaveURL(/\/n\/[^/]+$/); // On the root itself, the address is the library's. await page.keyboard.press("O"); - await expect(page).toHaveURL(/\/$/); + await expect(page).toHaveURL(/\/l\/[0-9a-z]+$/); }); test("with speculation on, the focused sentence is already being written when it is asked for", async ({ page }) => { diff --git a/e2e/nodes.spec.ts b/e2e/nodes.spec.ts index 1607e87..5d59a62 100644 --- a/e2e/nodes.spec.ts +++ b/e2e/nodes.spec.ts @@ -68,10 +68,10 @@ test("the library root is the first page and a node like any other: its sections const first = await state(page, (s) => s.focus.node); await expect(page).toHaveURL(new RegExp(`/n/${encodeURIComponent(first)}$`)); await expect(page).toHaveTitle("Infinispand"); - // Back up onto the root itself: its address is /, and it is the node the keys act on. + // Back up onto the root itself: its address is the library's, /l/, and it is the node the keys act on. await keys(page, "h k"); expect(await state(page, (s) => s.focus.node === s.snap.root)).toBe(true); - await expect(page).toHaveURL(/\/$/); + await expect(page).toHaveURL(/\/l\/[0-9a-z]+$/); await expect(page).toHaveTitle("Library"); await keys(page, "D"); await expect(status(page)).toHaveText("The library itself cannot be deleted."); diff --git a/server/bundle.ts b/server/bundle.ts new file mode 100644 index 0000000..52bc14e --- /dev/null +++ b/server/bundle.ts @@ -0,0 +1,284 @@ +/** + * Everything the server keeps for one library, and the routes that act on it. Each library has its + * own store, notice stream, node index (vectors), pending links, link reviewer and background jobs, + * all bound to that library's database alone, so nothing one library holds can reach a request + * about another: a route finds its library first and is handed only that library's bundle. + * + * What is shared holds no library's content: the model, Wikipedia (and its cache) and the embedding + * model. + * + * Routes, after /api/l// (or after /api/ for the first library): + * + * GET state what the page needs to start + * GET events the library's notice stream (server-sent events) + * GET branch/, POST sync/ what replicas use + * GET tree[/], POST ops[/] the op API + * GET nodes//tree|export[/], POST nodes//import + * … links/* link discovery (links/routes.ts) + */ +import type { IncomingMessage, ServerResponse } from "node:http"; +import { join } from "node:path"; +import { VersionVector } from "loro-crdt"; +import { FormatError, serializeDoc } from "../src/core/format"; +import { Doc, OpError, descendants, type NodeId, type Op } from "../src/core/model"; +import { encodeVV, history } from "../src/core/repo"; +import { IMPORT_MAX, importTree } from "../src/core/seed"; +import { slugify } from "../src/core/text"; +import type { LLM } from "../src/llm/types"; +import type { Embedder } from "./embed"; +import { LibraryStore, validBranch } from "./library"; +import { Jobs } from "./links/jobs"; +import { NodeIndex } from "./links/nodeIndex"; +import { PendingStore } from "./links/pending"; +import { Reviewer } from "./links/review"; +import { linkRoutes } from "./links/routes"; +import { Linker } from "./links/scan"; +import { HttpError, readBody, readJson, sendJson as json } from "./util"; +import type { WikiClient } from "./wiki"; + +/** What every library's bundle is given: shared, and holding no library's content. */ +export interface Shared { + llm: () => LLM | null; + wiki: () => WikiClient | null; + embed: Embedder | null; + reviewCalls: number; + user: string; + /** What /state says besides the library's own part. */ + state: () => Record; +} + +/** Largest replica update a sync accepts. */ +const SYNC_MAX = 256 * 1024 * 1024; + +const vvHeader = (doc: Doc) => encodeVV(doc.loro.version().toJSON()); + +export class Bundle { + readonly listeners = new Set(); + readonly nodeIndex: NodeIndex; + readonly pending: PendingStore; + readonly reviewer: Reviewer; + readonly jobs: Jobs; + private linker: Linker | null = null; + private handleLinks: ReturnType; + + constructor( + readonly store: LibraryStore, + private shared: Shared, + ) { + const main = () => store.main; + // The embedding model is loaded on first use, in a worker thread shared by every library; each + // library's vectors are its own. Pending suggestions are derived data, kept beside the library. + this.nodeIndex = new NodeIndex(main, { file: join(store.dir, "vectors", "nodes"), embedder: shared.embed }); + this.nodeIndex.watch(store.main); + const getLinker = () => (this.linker ??= new Linker({ doc: main, wiki: shared.wiki, embedder: shared.embed, index: this.nodeIndex })); + this.pending = new PendingStore(join(store.dir, "links", "pending.json")); + // The link reviewer asks the configured model (no tools, structured verdicts); IE_REVIEW_CALLS caps a background job's calls. + this.reviewer = new Reviewer({ llm: shared.llm, wiki: shared.wiki, pending: this.pending, snap: () => store.main.snap() }); + this.jobs = new Jobs({ + snap: () => store.main.snap(), + linker: getLinker, + wiki: shared.wiki, + index: this.nodeIndex, + pending: this.pending, + announce: (state) => this.announce({ linkJob: state }), + reviewer: this.reviewer, + reviewCalls: shared.reviewCalls, + }); + this.handleLinks = linkRoutes({ main, linker: getLinker, index: this.nodeIndex, pending: this.pending, jobs: this.jobs, embedder: shared.embed, reviewer: this.reviewer, wrote: () => this.wrote("main") }); + } + + get id() { + return this.store.id; + } + + /** A notice to every page open on this library. */ + announce(message: Record) { + const line = `data: ${JSON.stringify(message)}\n\n`; + for (const res of this.listeners) res.write(line); + } + + /** A server-side write to a branch: saved shortly and announced to every replica. */ + wrote(branch: string) { + this.store.saveSoon(branch); + this.announce({ branch, from: "api" }); + } + + /** Write what is waiting, on the way out. */ + flush() { + this.store.flush(); + this.pending.flush(); + } + + /** The library is being moved aside: stop its job, write what is waiting, tell its pages, and write nothing more. */ + close() { + this.jobs.cancel(); + this.nodeIndex.close(); + this.pending.close(); + this.store.close(); + this.announce({ library: "deleted" }); + for (const res of this.listeners) res.end(); + this.listeners.clear(); + } + + /** A request about this library; `parts` is the path after its prefix, `url` rewritten to /api/. */ + async handle(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]): Promise { + const [a, b] = parts; + const method = req.method ?? "GET"; + if (a === "state" && method === "GET") { + const store = this.store; + json(res, 200, { + ...this.shared.state(), + library: store.id, + title: store.title, + branches: [...store.branches].map(([name, doc]) => ({ name, vv: vvHeader(doc) })), + linkJob: this.jobs.current, + }); + return true; + } + if (a === "nodes") return (await this.nodeApi(req, res, url, parts.slice(1)), true); + if (a && ["events", "branch", "sync", "tree", "ops"].includes(a)) return (await this.libraryApi(req, res, url, a, b), true); + if (a === "links") { + this.nodeIndex.activate(); + return this.handleLinks(req, res, url); + } + return false; + } + + /** The library as a whole: what replicas use, and the op API. */ + private async libraryApi(req: IncomingMessage, res: ServerResponse, url: URL, action: string, b: string | undefined) { + const method = req.method ?? "GET"; + const store = this.store; + const name = b || "main"; + if (!validBranch(name)) return json(res, 400, { error: "not a branch name" }); + + if (action === "events" && method === "GET") { + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" }); + res.write(": connected\n\n"); + this.listeners.add(res); + req.on("close", () => this.listeners.delete(res)); + return; + } + + // A replica fetches a branch whole. + if (action === "branch" && method === "GET") { + const doc = store.branches.get(name); + if (!doc) return json(res, 404, { error: `no such branch: ${name}` }); + res.writeHead(200, { "content-type": "application/octet-stream", "x-vv": vvHeader(doc), "x-library": store.id }); + return res.end(doc.snapshotBytes()); + } + + // A replica pushes what it has and gets back what it lacks. Request header x-vv is the + // replica's version; the response carries the server's. A replica must name the library it + // belongs to: bytes from another library (an old tab, a browser that outlived its data + // directory, a page of another library) would add a second root to this one. A beacon cannot + // send headers, so it names the library in the query. + if (action === "sync" && method === "POST") { + if ((req.headers["x-library"] ?? url.searchParams.get("library")) !== store.id) { + return json(res, 409, { error: "This page belongs to a different library than the server has here. Reload the page.", library: store.id }); + } + const bytes = await readBody(req, SYNC_MAX); + let doc = store.branches.get(name); + const before = doc ? vvHeader(doc) : ""; + if (!doc) { + if (!bytes.length) return json(res, 404, { error: `no such branch: ${name}` }); + doc = Doc.load(bytes, "server"); + if (doc.libraryId !== store.id) return json(res, 409, { error: "that branch is not of this library" }); + store.addBranch(name, doc); + } else if (bytes.length) { + doc.loro.import(bytes); + doc.touch(); + } + if (vvHeader(doc) !== before) { + store.saveSoon(name); + this.announce({ branch: name, from: String(req.headers["x-client"] ?? "") }); + } + const theirs = req.headers["x-vv"] ? new Map(JSON.parse(String(req.headers["x-vv"]))) : new Map(); + const update = doc.loro.export({ mode: "update", from: new VersionVector(theirs as never) }); + res.writeHead(200, { "content-type": "application/octet-stream", "x-vv": vvHeader(doc) }); + return res.end(update); + } + + // For outside agents: read the library as JSON… + if (action === "tree" && method === "GET") { + const doc = store.branches.get(name); + if (!doc) return json(res, 404, { error: `no such branch: ${name}` }); + return json(res, 200, { ...doc.snap(), library: store.id, conflicts: doc.conflicts(), history: history(doc).slice(0, 50) }); + } + + // …and write to it with the same ops everyone else uses. Node ids are the library's, so one + // batch can work anywhere in it (moving a node from one place to another is a move). + if (action === "ops" && method === "POST") return this.opsApi(req, res, name); + + json(res, 404, { error: "not found" }); + } + + private async opsApi(req: IncomingMessage, res: ServerResponse, name: string) { + const doc = this.store.branches.get(name); + if (!doc) return json(res, 404, { error: `no such branch: ${name}` }); + const input = await readJson<{ ops: Op[]; message?: string; author?: string; actor?: "human" | "llm" }>(req); + if (!Array.isArray(input.ops)) return json(res, 400, { error: "expected { ops: [...] }" }); + const author = typeof input.author === "string" ? input.author.slice(0, 100) : "api"; + try { + return json(res, 200, doc.as(author, () => doc.apply(input.ops, input.message ?? "Edit over HTTP", { actor: input.actor ?? "llm", tag: "api" }))); + } catch (err) { + if (err instanceof OpError) return json(res, 422, { error: err.message }); + throw err; + } finally { + this.wrote(name); + } + } + + /** + * One node and everything under it, by its id: the subtree as JSON with its conflicts, the text + * format as a download, or a file in the text format imported under it. An import is an ordinary + * commit on main; the browser makes the same commits in its own replica. + */ + private async nodeApi(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]) { + const method = req.method ?? "GET"; + const [id, action, branch] = parts as [NodeId, string | undefined, string | undefined]; + const name = branch || "main"; + if (!validBranch(name)) return json(res, 400, { error: "not a branch name" }); + const doc = this.store.branches.get(name); + if (!doc) return json(res, 404, { error: `no such branch: ${name}` }); + const snap = doc.snap(); + if (!id || !snap.nodes[id]) return json(res, 404, { error: `no such node: ${id ?? ""}` }); + + // GET nodes//tree[/]: the subtree, as tree returns the library. + if (action === "tree" && method === "GET") { + const ids = new Set([id, ...descendants(snap, id)]); + return json(res, 200, { root: id, nodes: Object.fromEntries([...ids].map((x) => [x, snap.nodes[x]])), conflicts: doc.conflicts().filter((c) => [c.node, c.parent].some((x) => x && ids.has(x))) }); + } + // GET nodes//export[/]: the text format, as a download. + if (action === "export" && method === "GET") { + const { text, skipped } = serializeDoc(snap, id); + res.writeHead(200, { + "content-type": "text/markdown; charset=utf-8", + "content-disposition": `attachment; filename="${slugify(snap.nodes[id].title) || "untitled"}${name === "main" ? "" : `-${encodeURIComponent(name)}`}.md"`, + "x-skipped": JSON.stringify(skipped), + }); + return res.end(text); + } + // POST nodes//import?name=file.md, with the file as the body: a new last child of the node (on main). + if (action === "import" && !branch && method === "POST") { + const file = (url.searchParams.get("name") ?? "").replace(/^.*[\\/]/, "").slice(0, 200) || "import.md"; + let text: string; + try { + text = (await readBody(req, IMPORT_MAX)).toString("utf8"); + } catch (err) { + if (err instanceof HttpError && err.status === 413) return json(res, 413, { error: `the file is too large to import (the limit is ${IMPORT_MAX / 1024 / 1024} MB)` }); + throw err; + } + const main = this.store.main; + if (!main.snap().nodes[id]) return json(res, 404, { error: `no such node on main: ${id}` }); + try { + const top = importTree(main, text, file, { creator: this.shared.user, parent: id }); + this.wrote("main"); + return json(res, 201, { node: top, title: main.snap().nodes[top].title }); + } catch (err) { + if (err instanceof FormatError) return json(res, 422, { error: err.message, problems: err.problems }); + throw err; + } + } + json(res, 404, { error: "not found" }); + } +} diff --git a/server/embed.ts b/server/embed.ts index 72e1d53..1809b63 100644 --- a/server/embed.ts +++ b/server/embed.ts @@ -394,6 +394,11 @@ export class VectorIndex { // -- persistence -- + /** Write nothing more (its directory is being moved aside). */ + detach() { + this.file = null; + } + save() { if (!this.file) return; const model = this.embedder?.spec.id ?? null; diff --git a/server/index.ts b/server/index.ts index 3a146b6..75e0b3e 100644 --- a/server/index.ts +++ b/server/index.ts @@ -1,42 +1,35 @@ /** * The local server. It does three small things: - * - relays library updates between replicas (tabs, people, agents) and keeps a copy on disk + * - relays each library's updates between replicas (tabs, people, agents) and keeps a copy on disk * - holds the API key and proxies model calls - * - exposes the op API over HTTP, so an outside agent can read and edit the tree + * - exposes the op API over HTTP, so an outside agent can read and edit a library * In development it also hosts Vite; in production it serves the built files. * - * The whole library is one database: /api/tree, /api/ops, /api/sync… act on all of it, and - * /api/nodes//… on one node and what is under it. See README.md for the list. + * There are several libraries, each a database of its own (libraries.ts): /api/libraries lists, + * makes, renames and deletes them, and /api/l//… acts on one of them (bundle.ts), the same + * routes without the prefix on the first. See README.md for the list. */ import { existsSync, mkdirSync, readFileSync } from "node:fs"; import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; import { userInfo } from "node:os"; import { extname, join, resolve } from "node:path"; -import { VersionVector } from "loro-crdt"; -import { Doc, OpError, descendants, type NodeId, type Op } from "../src/core/model"; -import { encodeVV, history } from "../src/core/repo"; -import { FormatError, serializeDoc } from "../src/core/format"; -import { IMPORT_MAX, importTree, writeSeed } from "../src/core/seed"; -import { slugify } from "../src/core/text"; +import { writeSeed } from "../src/core/seed"; import { mockLLM } from "../src/llm/mock"; import { LLMUnavailable, type JsonReq, type LLM, type Req, type TurnReq } from "../src/llm/types"; import { seed } from "../src/seed/tree"; +import { Bundle, type Shared } from "./bundle"; import { claudeLLM, describeError } from "./claude"; -import { LibraryStore, validBranch } from "./library"; +import { Libraries, NeedsMigration, importStarters } from "./libraries"; +import { lockHolder, takeLock } from "./lock"; import { SubscriptionError, queryPlanUsage, subscriptionLLM } from "./subscription"; import { usage, withMockUsage } from "./usage"; -import { HttpError, ROOT as root, abortOnClose, dataDir, readBody, readJson, sendJson as json } from "./util"; +import { HttpError, ROOT as root, abortOnClose, dataDir, readJson, sendJson as json } from "./util"; import { applyWebPolicy, webConfig } from "./web"; import { WikiClient, validContact, wiki, wikiLang } from "./wiki"; import { makeMockWikiFetch } from "./wikiMock"; import { wikiOff, wikiRoutes } from "./wikiRoutes"; import { embedder } from "./embed"; -import { Jobs } from "./links/jobs"; -import { NodeIndex } from "./links/nodeIndex"; -import { PendingStore } from "./links/pending"; -import { JOB_CALLS, Reviewer } from "./links/review"; -import { linkRoutes } from "./links/routes"; -import { Linker } from "./links/scan"; +import { JOB_CALLS } from "./links/review"; const PORT = Number(process.env.PORT ?? 4747); // Host names the dev server answers to besides localhost. Tailscale names are allowed so that @@ -103,89 +96,84 @@ const wikiState = { mode: wikiMode, lang: wikiLang(process.env.IE_WIKI_LANG), co /** A short reason for a failed model call, whichever provider made it. */ const explain = (err: unknown) => (err instanceof SubscriptionError ? { status: err.status, message: err.message } : describeError(err)); -// ---- the library on disk ---- +// ---- the libraries on disk ---- mkdirSync(DATA, { recursive: true }); const started = performance.now(); -const store = new LibraryStore(DATA).open(); -store.seedFirst((doc) => writeSeed(doc, readFileSync(join(root, "src/seed/prompt.txt"), "utf8"), seed)); -store.importLibrary(LIBRARY); -const startMs = Math.round(performance.now() - started); -// Writes are gathered before they go to disk; whatever is waiting goes on the way out. -process.on("exit", () => store.flush()); -for (const sig of ["SIGINT", "SIGTERM"] as const) process.on(sig, () => process.exit(0)); - -const vvHeader = (doc: Doc) => encodeVV(doc.loro.version().toJSON()); - -// ---- link discovery (server/links) ---- - -// The embedding model is loaded on first use, in a worker thread; IE_EMBED=off turns it off, and -// scanning then matches by text alone. Pending suggestions are derived data, kept beside the library. -const embed = process.env.IE_EMBED === "off" ? null : embedder(); -const nodeIndex = new NodeIndex(() => store.main, { file: join(DATA, "vectors", "nodes"), embedder: embed }); -nodeIndex.watch(store.main); -let linker: Linker | null = null; -const getLinker = () => (linker ??= new Linker({ doc: () => store.main, wiki: wikiClient, embedder: embed, index: nodeIndex })); -const pending = new PendingStore(join(DATA, "links", "pending.json")); -process.on("exit", () => pending.flush()); -// The link reviewer asks the configured model (no tools, structured verdicts); IE_REVIEW_CALLS caps a background job's calls. -const reviewer = new Reviewer({ llm: () => llm, wiki: wikiClient, pending, snap: () => store.main.snap() }); -const reviewCalls = Math.max(1, Number(process.env.IE_REVIEW_CALLS) || JOB_CALLS); -const jobs = new Jobs({ - snap: () => store.main.snap(), - linker: getLinker, - wiki: wikiClient, - index: nodeIndex, - pending, - announce: (state) => announce({ linkJob: state }), - reviewer, - reviewCalls, -}); -const handleLinks = linkRoutes({ main: () => store.main, linker: getLinker, index: nodeIndex, pending, jobs, embedder: embed, reviewer, wrote: () => wrote("main") }); - -// ---- live notifications ---- - -const listeners = new Set(); -function announce(message: Record) { - const line = `data: ${JSON.stringify(message)}\n\n`; - for (const res of listeners) res.write(line); +// A data directory in an older layout is never opened, nor migrated without being asked: the +// migration (npm run migrate) has a dry run and verifies what it writes. +const held = lockHolder(DATA); +if (held) { + console.error(`Another server (pid ${held.pid}${held.port ? `, port ${held.port}` : ""}) has ${DATA} open; stop it first, or set IE_DATA to another directory.`); + process.exit(1); } +const libraries = new Libraries(DATA); +try { + libraries.open((doc) => { + writeSeed(doc, readFileSync(join(root, "src/seed/prompt.txt"), "utf8"), seed); + console.log("seeded the first tree from src/seed"); + importStarters(doc, LIBRARY); + }); +} catch (err) { + if (!(err instanceof NeedsMigration)) throw err; + console.error(err.message); + process.exit(1); +} +takeLock(DATA, PORT); +const startMs = Math.round(performance.now() - started); + +// ---- each library's link discovery, notices and routes (server/bundle.ts) ---- + +// The embedding model is loaded on first use, in a worker thread shared by every library; +// IE_EMBED=off turns it off, and scanning then matches by text alone. +const embed = process.env.IE_EMBED === "off" ? null : embedder(); +const shared: Shared = { + llm: () => llm, + wiki: wikiClient, + embed, + reviewCalls: Math.max(1, Number(process.env.IE_REVIEW_CALLS) || JOB_CALLS), + user: USER, + state: () => ({ + user: USER, + llm: llm?.kind ?? "off", + model: llm?.model ?? null, + wiki: wikiState, + embed: embed ? (process.env.IE_EMBED === "fake" ? "fake" : "on") : "off", + web: { on: web.on, searches: web.searches, fetches: web.fetches }, + libraries: libraries.list(), + }), +}; +const bundles = new Map(); +for (const [id, store] of libraries.stores) bundles.set(id, new Bundle(store, shared)); +// Writes are gathered before they go to disk; whatever is waiting goes on the way out. +process.on("exit", () => { + for (const b of bundles.values()) b.flush(); +}); +for (const sig of ["SIGINT", "SIGTERM"] as const) process.on(sig, () => process.exit(0)); // ---- http plumbing ---- -/** Largest replica update a sync accepts. */ -const SYNC_MAX = 256 * 1024 * 1024; function needLLM(): LLM { if (!llm) throw new LLMUnavailable(); return llm; } -/** A server-side write to a branch: saved shortly and announced to every replica. */ -function wrote(branch: string) { - store.saveSoon(branch); - announce({ branch, from: "api" }); -} - async function api(req: IncomingMessage, res: ServerResponse, url: URL) { const parts = url.pathname.split("/").slice(2).map(decodeURIComponent); // after /api/ const [a, b] = parts; const method = req.method ?? "GET"; - if (a === "state" && method === "GET") { - return json(res, 200, { - user: USER, - llm: llm?.kind ?? "off", - model: llm?.model ?? null, - library: store.id, - branches: [...store.branches].map(([name, doc]) => ({ name, vv: vvHeader(doc) })), - migrated: store.migrated(), - wiki: wikiState, - embed: embed ? (process.env.IE_EMBED === "fake" ? "fake" : "on") : "off", - web: { on: web.on, searches: web.searches, fetches: web.fetches }, - linkJob: jobs.current, - }); + // One library: /api/l//…, everything that reads or writes a library's content. + if (a === "l") { + const bundle = b ? bundles.get(b) : undefined; + if (!bundle) return json(res, 404, { error: `no library ${b ?? ""}` }); + const rest = parts.slice(2); + if (await bundle.handle(req, res, rebased(url, rest), rest)) return; + return json(res, 404, { error: "not found" }); } + if (a === "libraries") return librariesApi(req, res, parts.slice(1)); + if (a === "usage" && method === "GET") return json(res, 200, usage.summary()); if (a === "llm" && method === "POST") { @@ -227,148 +215,56 @@ async function api(req: IncomingMessage, res: ServerResponse, url: URL) { } } - if (a === "nodes") return nodeApi(req, res, url, parts.slice(1)); - if (["events", "branch", "sync", "tree", "ops"].includes(a)) return libraryApi(req, res, url, a, b); if (await handleWiki(req, res, url)) return; - if (url.pathname.startsWith("/api/links/")) nodeIndex.activate(); - if (await handleLinks(req, res, url)) return; + + // Without a library named, the first one: so `curl /api/tree` still reads a library. + const first = bundles.get(libraries.first().id)!; + if (await first.handle(req, res, url, parts)) return; json(res, 404, { error: "not found" }); } -/** The library as a whole: what replicas use, and the op API. */ -async function libraryApi(req: IncomingMessage, res: ServerResponse, url: URL, action: string, b: string | undefined) { - const method = req.method ?? "GET"; - const name = b || "main"; - if (!validBranch(name)) return json(res, 400, { error: "not a branch name" }); - - if (action === "events" && method === "GET") { - res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" }); - res.write(": connected\n\n"); - listeners.add(res); - req.on("close", () => listeners.delete(res)); - return; - } - - // A replica fetches a branch whole. - if (action === "branch" && method === "GET") { - const doc = store.branches.get(name); - if (!doc) return json(res, 404, { error: `no such branch: ${name}` }); - res.writeHead(200, { "content-type": "application/octet-stream", "x-vv": vvHeader(doc), "x-library": store.id }); - return res.end(doc.snapshotBytes()); - } - - // A replica pushes what it has and gets back what it lacks. Request header x-vv is the - // replica's version; the response carries the server's. A replica must name the library it - // belongs to: bytes from another library (an old tab, a browser that outlived its data - // directory) would add a second root to this one. A beacon cannot send headers, so it names - // the library in the query. - if (action === "sync" && method === "POST") { - if ((req.headers["x-library"] ?? url.searchParams.get("library")) !== store.id) { - return json(res, 409, { error: "This page belongs to a different library than the server has now. Reload the page.", library: store.id }); - } - const bytes = await readBody(req, SYNC_MAX); - let doc = store.branches.get(name); - const before = doc ? vvHeader(doc) : ""; - if (!doc) { - if (!bytes.length) return json(res, 404, { error: `no such branch: ${name}` }); - doc = Doc.load(bytes, "server"); - if (doc.libraryId !== store.id) return json(res, 409, { error: "that branch is not of this library" }); - store.addBranch(name, doc); - } else if (bytes.length) { - doc.loro.import(bytes); - doc.touch(); - } - if (vvHeader(doc) !== before) { - store.saveSoon(name); - announce({ branch: name, from: String(req.headers["x-client"] ?? "") }); - } - const theirs = req.headers["x-vv"] ? new Map(JSON.parse(String(req.headers["x-vv"]))) : new Map(); - const update = doc.loro.export({ mode: "update", from: new VersionVector(theirs as never) }); - res.writeHead(200, { "content-type": "application/octet-stream", "x-vv": vvHeader(doc) }); - return res.end(update); - } - - // For outside agents: read the library as JSON… - if (action === "tree" && method === "GET") { - const doc = store.branches.get(name); - if (!doc) return json(res, 404, { error: `no such branch: ${name}` }); - return json(res, 200, { ...doc.snap(), conflicts: doc.conflicts(), history: history(doc).slice(0, 50) }); - } - - // …and write to it with the same ops everyone else uses. Node ids are the library's, so one - // batch can work anywhere in it (moving a node from one place to another is a move). - if (action === "ops" && method === "POST") return opsApi(req, res, name); - - json(res, 404, { error: "not found" }); -} - -async function opsApi(req: IncomingMessage, res: ServerResponse, name: string) { - const doc = store.branches.get(name); - if (!doc) return json(res, 404, { error: `no such branch: ${name}` }); - const input = await readJson<{ ops: Op[]; message?: string; author?: string; actor?: "human" | "llm" }>(req); - if (!Array.isArray(input.ops)) return json(res, 400, { error: "expected { ops: [...] }" }); - const author = typeof input.author === "string" ? input.author.slice(0, 100) : "api"; - try { - return json(res, 200, doc.as(author, () => doc.apply(input.ops, input.message ?? "Edit over HTTP", { actor: input.actor ?? "llm", tag: "api" }))); - } catch (err) { - if (err instanceof OpError) return json(res, 422, { error: err.message }); - throw err; - } finally { - wrote(name); - } +/** The URL a library's routes see: /api/, its query kept. */ +function rebased(url: URL, rest: string[]): URL { + const out = new URL(url); + out.pathname = `/api/${rest.map(encodeURIComponent).join("/")}`; + return out; } /** - * One node and everything under it, by its id: the subtree as JSON with its conflicts, the text - * format as a download, or a file in the text format imported under it. An import is an ordinary - * commit on main; the browser makes the same commits in its own replica. + * The libraries: + * GET /api/libraries → { libraries: [{ id, title, created, nodes, branches }] }, in order + * POST /api/libraries { title } → 201 { library }: a new library, its root alone, at the end + * PATCH /api/libraries/ { title } → { library }: renamed (a commit on its root's title) + * DELETE /api/libraries/ → { deleted, movedTo }: moved aside whole; never the last one */ -async function nodeApi(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]) { +async function librariesApi(req: IncomingMessage, res: ServerResponse, parts: string[]) { const method = req.method ?? "GET"; - const [id, action, branch] = parts as [NodeId, string | undefined, string | undefined]; - const name = branch || "main"; - if (!validBranch(name)) return json(res, 400, { error: "not a branch name" }); - const doc = store.branches.get(name); - if (!doc) return json(res, 404, { error: `no such branch: ${name}` }); - const snap = doc.snap(); - if (!id || !snap.nodes[id]) return json(res, 404, { error: `no such node: ${id ?? ""}` }); - - // GET /api/nodes//tree[/]: the subtree, as /api/tree returns the library. - if (action === "tree" && method === "GET") { - const ids = new Set([id, ...descendants(snap, id)]); - return json(res, 200, { root: id, nodes: Object.fromEntries([...ids].map((x) => [x, snap.nodes[x]])), conflicts: doc.conflicts().filter((c) => [c.node, c.parent].some((x) => x && ids.has(x))) }); + const [id] = parts; + const info = (lib: string) => libraries.list().find((l) => l.id === lib); + if (!id && method === "GET") return json(res, 200, { libraries: libraries.list() }); + if (!id && method === "POST") { + const input = await readJson<{ title?: unknown }>(req); + const store = libraries.create(input.title as string); + bundles.set(store.id, new Bundle(store, shared)); + console.log(`libraries: made “${store.title}” (${store.id})`); + return json(res, 201, { library: info(store.id) }); } - // GET /api/nodes//export[/]: the text format, as a download. - if (action === "export" && method === "GET") { - const { text, skipped } = serializeDoc(snap, id); - res.writeHead(200, { - "content-type": "text/markdown; charset=utf-8", - "content-disposition": `attachment; filename="${slugify(snap.nodes[id].title) || "untitled"}${name === "main" ? "" : `-${encodeURIComponent(name)}`}.md"`, - "x-skipped": JSON.stringify(skipped), - }); - return res.end(text); + if (id && parts.length === 1 && (method === "PATCH" || method === "POST")) { + const input = await readJson<{ title?: unknown }>(req); + const store = libraries.rename(id, input.title as string); + bundles.get(id)?.announce({ branch: "main", from: "api" }); + return json(res, 200, { library: info(store.id) }); } - // POST /api/nodes//import?name=file.md, with the file as the body: a new last child of the node (on main). - if (action === "import" && !branch && method === "POST") { - const file = (url.searchParams.get("name") ?? "").replace(/^.*[\\/]/, "").slice(0, 200) || "import.md"; - let text: string; - try { - text = (await readBody(req, IMPORT_MAX)).toString("utf8"); - } catch (err) { - if (err instanceof HttpError && err.status === 413) return json(res, 413, { error: `the file is too large to import (the limit is ${IMPORT_MAX / 1024 / 1024} MB)` }); - throw err; - } - const main = store.main; - if (!main.snap().nodes[id]) return json(res, 404, { error: `no such node on main: ${id}` }); - try { - const top = importTree(main, text, file, { creator: USER, parent: id }); - wrote("main"); - return json(res, 201, { node: top, title: main.snap().nodes[top].title }); - } catch (err) { - if (err instanceof FormatError) return json(res, 422, { error: err.message, problems: err.problems }); - throw err; - } + if (id && parts.length === 1 && method === "DELETE") { + const bundle = bundles.get(id); + if (!bundle) return json(res, 404, { error: `no library ${id}` }); + if (libraries.stores.size <= 1) return json(res, 409, { error: "the last library cannot be deleted" }); + bundle.close(); + const movedTo = libraries.remove(id); + bundles.delete(id); + console.log(`libraries: deleted ${id}; its files are in ${movedTo}`); + return json(res, 200, { deleted: id, movedTo }); } json(res, 404, { error: "not found" }); } @@ -438,9 +334,9 @@ createServer(async (req, res) => { serveStatic(res, path); } }).listen(PORT, "127.0.0.1", () => { - const nodes = Object.keys(store.main.snap().nodes).length; console.log(`Infinispand http://localhost:${PORT} model: ${llm ? `${llm.kind}${llm.model ? `: ${llm.model}` : ""}` : "off (set ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN to generate)"} data: ${DATA}`); - console.log(`library: ${store.titles().length} top-level sections, ${nodes} nodes, opened in ${startMs} ms`); + for (const l of libraries.list()) console.log(`library “${l.title}” (/l/${l.id}): ${libraries.get(l.id)!.titles().length} top-level sections, ${l.nodes} nodes`); + console.log(`${libraries.stores.size} librar${libraries.stores.size === 1 ? "y" : "ies"} opened in ${startMs} ms`); console.log(`web research: ${web.on ? `on (at most ${web.searches} searches and ${web.fetches} pages read per request)` : `off${web.why ? ` (${web.why})` : ""}`}`); console.log( `wikipedia: ${wikiMode === "live" ? `live (${wikiState.lang}.wikipedia.org, ${wikiState.contact ? "with" : "without"} a contact)` : wikiMode === "mock" ? "mock (fixtures, no network)" : "off"}`, diff --git a/server/libraries.ts b/server/libraries.ts new file mode 100644 index 0000000..e891dc8 --- /dev/null +++ b/server/libraries.ts @@ -0,0 +1,274 @@ +/** + * The libraries on disk. Each is a tree of its own, with its own history, and nothing in one refers + * to anything in another: a library is its own Loro database, with its own id, and what is derived + * from it (link suggestions, the reviewer's verdicts, vectors) is kept in its own directory. + * + * /libraries/index.json the libraries, in order: id, title, when made, whether deleted + * /libraries//.loro the library (library.ts) + * /libraries//links/pending.json link suggestions and the decisions about them (derived) + * /libraries//vectors/nodes.* its sections as vectors (derived) + * /libraries/.deleted/-