Docs: the libraries panel and deleting (and restoring) a library in the README; no documents left: the seed's description of itself, docs/wikipedia.md (top-level trees, per-library paths), the tagline, comments, test names and the link evaluation script

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
thalladaandClaude Opus 5.5 committed 2026-11-17 03:07:02 -05:00
1 parent 146437a01a
commit fc7c222407
26 files changed
+167 -145

No files matched your search

+34 -14
View File
@@ -1,6 +1,6 @@
# Infinispand
A document you can expand without limit. It opens as an outline of titles; every node, sentence,
A tree of writing you can expand without limit. It opens as an outline of titles; every node, sentence,
phrase and word can be opened further. The first levels are written ahead of time and open
instantly; past them, a model writes the expansion on request. Everything is editable, by you or
by a model, and the tree is versioned like git.
@@ -90,21 +90,31 @@ Press `?` for every key. The short version:
on words, a row, a link, a note or a pane opens what can be done with it, Copy first (Shift+right-
click is the browser's own menu); so does the `⋯` beside a row, a pane's pin, a page's byline or a
note, shown only when pointed at, and a stale flag. The top bar, which stays at the top, has
`undo`, `redo` when there is something to redo, and `menu` (jump, history, links, layout and
settings); on its left, the library's name. Keys named in the status line or a panel's head are buttons. On a phone the
bar sits at the foot of the screen and menus rise from it. Every item acts by pressing its key
`undo`, `redo` when there is something to redo, and `menu` (libraries, jump, history, links,
layout and settings); on its left, the library's name, which opens the libraries panel. Keys
named in the status line or a panel's head are buttons. On a phone the selection bar sits at the
foot of the screen and menus rise from it. Every item acts by pressing its key
(`src/ui/press.ts`), so a click and a key cannot do different things. The first visit says, once,
in the status line, that a click on a sentence offers actions and `?` lists the keys. Left to the
keys: stepping by grain (`j` `k` `i`; a click or a drag goes straight there), `Tab` from mark to
mark, `[` `]` up and down a column (a click on a pane does it), and the commands typed at `:`
that no menu lists (`/branch`, `/switch`, `/merge`, `/user`, `/link`, …), which the menu's
Command line… opens for typing.
- **Libraries.** `:/library` lists the libraries, `:/library name` opens one and `:/library new
name` makes one (its root alone) and opens it. Each library is a page of its own, at its own
address (`/l/<id>`); opening another loads the page. `/` opens the library last used in this
browser. A library's name is its root's title (`r` on the root renames it). Nothing crosses
between libraries: links, the jump box, Related, the link scanner and reviewer, and the editor
agent see only the library they are in; export then import carries a tree across.
- **Libraries.** `m`, or a click on the library's name at the top left, opens the libraries panel
on the left: every library, with how many nodes it holds, ● the one open here. `j` `k` move,
`Enter` (or a click on a row) opens one, `n` names a new one (its root alone) and opens it, `r`
renames one, `D` deletes one after a `y` (`n` keeps it; the last library cannot be deleted, and
where a deleted one goes is below); `Esc`, `m`, the name again or a press outside closes the
panel. A row's `⋯`, or a right-click on it, offers the same. Beside the panel the column moves
over and the panes narrow; on a phone it covers the page. Each library is a page of its own, at
its own address (`/l/<id>`); opening another loads the page, where you left it in this browser.
`/` opens the library last used in this browser. A library's name is its root's title (`r` on
the root renames it too). Nothing crosses between libraries: links, the jump box, Related, the
link scanner and reviewer, and the editor agent see only the library they are in; export then
import carries a tree across. A page whose library is deleted, by another page or while it was
away, stops sending, says so (`deleted · not saved` in the top bar) and opens the panel on the
others. On the command line, `:/library name` opens a library by name and `:/library new name`
makes one.
- On a window 900 px wide or more, a laptop's too, the page opens as panes side by side, after
Andy Matuschak's notes: the library, then each open node in a pane of its own. `v` switches between
panes and the single column, `/view auto|column|panes` sets it.
@@ -219,7 +229,7 @@ Press `?` for every key. The short version:
- A **suggestion** has a faint dashed underline. `Tab` reaches suggestions; `y` links one, `n`
declines it (remembered in the node, on every replica). `/autolink suggest` leaves every
candidate to you; `/autolink on` makes the scanner's surest links unreviewed (they measured 0.84
precision on unseen documents); `/autolink off` scans nothing by itself.
precision on unseen trees); `/autolink off` scans nothing by itself.
- `S` opens the **links list** of the node you are on and everything under it (on the library
root, of the whole library), beside the text: every link found or made, what
was rejected and what waits, each with who decided (the reviewer or you) and the reviewer's
@@ -306,7 +316,8 @@ What is sent where:
- **`src/ui/`** The browser's replica of the library (`session.ts`, kept in IndexedDB), the store
and keymap, and the page. The mouse acts through the keymap: `actions.ts` builds what the
selection bar and the menus offer for each kind of target, every item pressing its key
(`press.ts`); `Mouse.tsx` draws the one menu, the bar and the key hints. The panes view's panes are a forest of forks (`forks.ts`, pure functions;
(`press.ts`); `Mouse.tsx` draws the one menu, the bar and the key hints; `Menu.tsx` the top bar
and the libraries panel (its state in `libraries.ts`). The panes view's panes are a forest of forks (`forks.ts`, pure functions;
the store's `trail` is its focused branch); `stack.ts` is the stacking shared by the strip and its
columns, `lanes.ts` orders the curves' lanes.
@@ -344,6 +355,15 @@ the first one.
When `IE_DATA` is empty, the first library is made with the seed and every `library/*.md`; a file
that does not parse is logged and skipped. A library made later starts with its root alone.
### Deleting a library
`D` in the libraries panel (or `DELETE /api/libraries/<id>`) moves the library's directory, whole
and unchanged, to `IE_DATA/libraries/.deleted/<id>-<time>/` and marks its entry in `index.json`
deleted; the page says where it went. The last library cannot be deleted, and `u` cannot undo a
deletion. To bring one back: stop the server, move the directory back to `IE_DATA/libraries/<id>/`,
remove the `"deleted"` and `"movedTo"` fields from its entry in `IE_DATA/libraries/index.json`, and
start the server. Nothing ever empties `.deleted/`.
### From the single-library layout
A data directory written before libraries (`IE_DATA/library/main.loro`) is not opened: the server
@@ -430,10 +450,10 @@ Node ids are the library's, so one batch of ops can work anywhere in it.
| | |
|---|---|
| `GET /api/libraries` | `{ libraries: [{ id, title, created, nodes, branches }] }`, in order |
| `GET /api/libraries` | `{ libraries: [{ id, title, created, nodes, branches }] }`, in order; `nodes` counts what is under the root (not the root, nor the Wikipedia container) |
| `POST /api/libraries` `{ title }` | a new library, its root alone, at the end: 201 `{ library }` |
| `PATCH /api/libraries/<id>` `{ title }` | rename it (a commit on its root's title) |
| `DELETE /api/libraries/<id>` | move it aside whole to `libraries/.deleted/`; 409 for the last one |
| `DELETE /api/libraries/<id>` | `{ deleted, movedTo }`: moved aside whole to `libraries/.deleted/` (see Deleting a library); 409 for the last one |
| `GET /api/l/<id>/tree[/<branch>]` | the whole library as JSON, with conflicts and recent history |
| `POST /api/l/<id>/ops[/<branch>]` | `{ ops, message?, author?, actor? }`, applied as one commit. `create` and `update` take `ref`: `{ "kind": "wiki", "title", "lang" }`, `{ "kind": "node", "id", "path" }` or `{ "kind": "url", "url", "title" }`; `"ref": null` removes it |
| `GET /api/l/<id>/nodes/<node>/tree[/<branch>]` | one node and everything under it, with their conflicts |
+22 -22
View File
@@ -111,7 +111,7 @@ When text is shown in the app it must carry:
modified". We remove references, boxes and images, so `article()` and `section()` return
`attribution.modified` and an `attribution.text` that says so.
- **Share-alike** applies to modified article text that is redistributed. If a node quotes or adapts
article text and the document is exported or shared, that part is CC BY-SA. Linking to an
article text and that text is exported or shared, that part is CC BY-SA. Linking to an
article and writing your own prose about it is not affected.
- **Images** each have their own licence and need their own credit. This is why they are dropped.
@@ -215,7 +215,7 @@ considered and set aside:
## 7. Caches
`<IE_DATA>/wiki-cache/<lang>/titles.json` (found 30 d, missing 3 d), `small.json` (summaries 14 d,
senses 14 d, suggest and search 1 d), `articles/` (7 d). Vectors: `<IE_DATA>/vectors/<name>.json`
senses 14 d, suggest and search 1 d), `articles/` (7 d). Vectors, per library: `<IE_DATA>/libraries/<id>/vectors/<name>.json`
and `.f32`. An expired entry is still served, marked `stale`, when the network is down. The
variables that configure all this are in the README.
@@ -240,17 +240,17 @@ memory for the page's life only, never in IndexedDB.
16 distinct phrases per section on average (986 for 60 sections), so one lookup request per
node scanned alone, a third of one when a job batches nodes together.
2. **Library titles**: a phrase equal (normalised: case, plurals, hyphens, a leading article) to a
section's title of up to four words, never the node itself or an ancestor; other documents
preferred.
section's title of up to four words, never the node itself or an ancestor; sections in other
top-level trees preferred.
3. **Meaning**: the library's sections in a vector index, re-embedded only when their text hash
changes (patches only mark nodes; the embedding runs later, off any request). Sections of other
documents at cosine ≥ 0.78 become a link only where a phrase here names them; otherwise they are
changes (patches only mark nodes; the embedding runs later, off any request). Sections in other
top-level trees at cosine ≥ 0.78 become a link only where a phrase here names them; otherwise they are
the derived **Related** list.
4. **Wikipedia**: through the client's serial queue in its own lane: a person's requests (an
article, a preview) first, background jobs next, the scans that follow edits last (a scan that
has waited 30 s goes ahead of a job). One batched lookup; at most two disambiguation pages a scan resolved by fit, at
most one title search for a multi-word miss; every hit scored by cosine between the node in its
document and "Title: description".
top-level tree and "Title: description".
5. **Tiers** (`judge()` in `scan.ts`): each kind of phrase has its own bar, and `auto` needs the
phrase's form to vouch for it as well as the fit:
@@ -259,8 +259,8 @@ memory for the page's life only, never in IndexedDB.
| term (several words) | exact title, one word ranked ≥ 6,000, fit ≥ 0.55 | fit ≥ 0.60 (0.65 for a redirect) |
| name | exact title, not an ordinary word (rank < 1,000 is dropped), a single word only if unlisted; fit ≥ 0.55 (0.60 single) | fit ≥ 0.60 |
| one word | rank ≥ 15,000, exact title, fit ≥ 0.70 | rank ≥ 8,000, fit ≥ 0.64 |
| library title | a title of several words, fit (node to node) ≥ 0.72 | same document ≥ 0.64 (any title); another document only a multi-word or rare title |
| never auto | a sense chosen by fit (suggested for names and terms with a 0.04 margin), a searched title, a one-word section title ("The comma"), a concept already mentioned in an earlier section of the document (applied once per document, where it first appears; later mentions only suggested), a concept central to the document (in its title or in 30 % of its sections: linked once, at its first mention, suggested) | |
| library title | a title of several words, fit (node to node) ≥ 0.72 | same top-level tree ≥ 0.64 (any title); another tree only a multi-word or rare title |
| never auto | a sense chosen by fit (suggested for names and terms with a 0.04 margin), a searched title, a one-word section title ("The comma"), a concept already mentioned in an earlier section of the same top-level tree (applied once per tree, where it first appears; later mentions only suggested), a concept central to the tree (in its title or in 30 % of its sections: linked once, at its first mention, suggested) | |
| dropped | countries, surname and list pages, articles about a film, album, band… | |
With a phrase matching both a section and an article, the section wins. Then first mention per
@@ -274,12 +274,12 @@ come from* and *The invention of writing* (64 sections; 444 labelled phrases, 16
13 of them to a different target than the scanner found), plus 12 sections of *Tuning and
temperament*, first used as a held-out set and then looked at, so no longer held out. Every
phrase the scanner resolved was labelled by hand as a careful Wikipedia editor would link
(MOS:LINK: no everyday words, no countries, a document's own subject once).
(MOS:LINK: no everyday words, no countries, a tree's own subject once).
Fresh held-out set (`tests/fixtures/link-labels-heldout.json`): 16 sections each of *The
Antikythera mechanism*, *The one merger* (the eukaryotic cell), *The tides* and *What a proof is*
(64 sections). It was labelled from the text alone, by a forked copy of the agent, before the
scanner had ever run on those documents: an exhaustive list of the 165 phrases worth linking, each
scanner had ever run on those trees: an exhaustive list of the 165 phrases worth linking, each
with its acceptable targets, so a link not on the list counts as wrong (closed-world scoring;
`linkEval.ts heldout`). The rule was frozen before it was scored, and was scored once.
@@ -287,17 +287,17 @@ Live requests: 299 in all, serial, 6.5 s apart (no contact), no 429s.
| | auto: precision | recall | auto + suggest: precision | recall |
|---|---|---|---|---|
| tuning sample (4 documents), first rule | 0.962 (50/52) | 0.303 | 0.809 (89/110) | 0.539 |
| tuning sample (4 trees), first rule | 0.962 (50/52) | 0.303 | 0.809 (89/110) | 0.539 |
| *Tuning and temperament*, first rule | 0.818 (9/11) | 0.321 | 0.650 (13/20) | 0.464 |
| tuning sample, final rule | 1.000 (32/32) | 0.194 | 0.826 (90/109) | 0.545 |
| *Tuning and temperament*, final rule (looked at before) | 1.000 (5/5) | 0.179 | 0.700 (14/20) | 0.500 |
| **fresh held-out set (4 documents), final rule** | **0.844 (27/32)** | **0.164** | **0.577 (56/97)** | **0.339** |
| **fresh held-out set (4 trees), final rule** | **0.844 (27/32)** | **0.164** | **0.577 (56/97)** | **0.339** |
The final rule adds two form rules that the errors pointed to: a concept is applied unasked only
where it is first mentioned in its document (later mentions are suggested), and a one-word
where it is first mentioned in its top-level tree (later mentions are suggested), and a one-word
section title is only ever suggested. A word already linked inside a longer phrase is no longer
linked again on its own (the "beryllium" beside "beryllium-8" error). On the fresh set the five
wrong autos were: "front dial" → the section *The front dial* (a real same-document section the
wrong autos were: "front dial" → the section *The front dial* (a real section of the same tree the
labeller did not list); "linear chromosomes" → *Linear chromosome* (label: *Chromosome*);
"complex traits" → *Complex traits* (a genetics article for an ordinary phrase); "Asgard archaea"
→ *Asgard archaea* (label: *Asgard (archaea)*; arguably right); "northern hemisphere" →
@@ -310,7 +310,7 @@ Representative decisions of the first rule (tuning sample unless marked):
- right, auto: "fixed-point theorems" → *Fixed-point theorem* (fit 0.81); "Cephalopod eyes" →
*Cephalopod eye* (0.81); "cuttlefish" → *Cuttlefish* (0.73); "Uruk" → *Uruk* (0.70); "white dwarf"
→ *White dwarf* (0.71); "tablets" → the section *The tablet* in the same document (0.81);
→ *White dwarf* (0.71); "tablets" → the section *The tablet* in the same tree (0.81);
*Tuning and temperament*: "Andreas Werckmeister" → *Andreas Werckmeister* (0.71), "syntonic comma" → *Syntonic
comma* (0.73).
- right, suggest: "incompleteness theorem" → *Gödel's incompleteness theorems* (redirect, 0.76);
@@ -341,19 +341,19 @@ owner's library, accepted about 64 % of `auto` and 17 % of `suggest` candidates,
the scanner's known blind spots: a parent linked to its own child or sibling, a second mention of
something linked nearby, everyday words and household names, a fragment of a longer name, the wrong
sense or the wrong person of the same name, a library section matched on its title alone, and the
document's own quoted prompt. That reviewer is now built in (`server/links/review.ts`), and
first tree's own quoted prompt. That reviewer is now built in (`server/links/review.ts`), and
**`/autolink review`** is the default whenever a model is configured.
**Flow.** After a scan (an edit saved, `/linkhere`, `/linkall`) the candidates nobody has judged
go to the configured model in batches of up to 60, grouped by document and section. Each proposal
go to the configured model in batches of up to 60, grouped by top-level tree and section. Each proposal
carries its sentence, the section's title and path, the target's title and short description (and
the first sentence of its summary when the cache has one, never a new request), and for a library
target how it stands to the section (subsection, parent, sibling, elsewhere in the document,
another document); each document heading lists what is already linked in it, and each section
target how it stands to the section (subsection, parent, sibling, elsewhere in its tree, in
another tree); each tree's heading lists what is already linked in it, and each section
heading what is linked there. The model has no tools; it returns, by structured output, a verdict
(link or not) and a reason of at most twelve words per proposal. The system prompt names each
blind spot above as a reason to reject. Verdicts are stored with the suggestion in
`IE_DATA/links/pending.json`, keyed by node, phrase and target rather than by offsets, so a
`IE_DATA/libraries/<id>/links/pending.json` (each library its own), keyed by node, phrase and target rather than by offsets, so a
suggestion found again by a later scan keeps its verdict and is never sent twice. Rejected phrases
are skipped by later scans of that node, as declined ones are.
@@ -365,7 +365,7 @@ library as before (a link, or the phrase in the node's `nolink`) and on the serv
list can say who decided.
**Cost.** A node scanned after an edit costs at most 2 calls (`SCAN_CALLS`), almost always 1, and
none when nothing new was found. A document or library job costs ⌈N / 60⌉ calls for N new
none when nothing new was found. A `/linkhere` or `/linkall` job costs ⌈N / 60⌉ calls for N new
candidates, at most `IE_REVIEW_CALLS` (default 50, so 3,000 candidates); the status line counts
them, and a second run asks nothing about what the first judged. Every call uses the configured
model (`IE_MODEL`) at effort `low`: the app has no per-task model setting, and none was added.
+2 -2
View File
@@ -288,7 +288,7 @@ test("a pane covered across and down peeks out whole on both axes; the wheel scr
await open(page, "Recursion without names", "fixed-point combinator", ".lnk, .anchor");
await expect(pane(page, "Fixed-point combinator").locator(".wrow").first()).toBeVisible();
await still(page);
// The documents' column is covered to spines, and folded down: hover the spine of a folded pane in it.
// The top-level trees' column is covered to spines, and folded down: hover the spine of a folded pane in it.
const col = pane(page, "The tides").locator("xpath=..");
expect(await col.evaluate((c) => c.hasAttribute("data-covered") || !!c.nextElementSibling?.hasAttribute("data-over"))).toBe(true);
const tides = pane(page, "The tides");
@@ -334,7 +334,7 @@ test("a pane covered across and down peeks out whole on both axes; the wheel scr
const b = (await bar.boundingBox())!;
const at = { x: b.x + b.width / 2, y: b.y + b.height / 2 };
expect(await page.evaluate(({ x, y }) => !!document.elementFromPoint(x, y)?.closest(".selbar"), at)).toBe(true);
// Peek the documents' column (to the left, covered): it slides out over the pane with the bar.
// Peek the top-level trees' column (to the left, covered): it slides out over the pane with the bar.
await page.mouse.move(sp.x + sp.width / 2, sp.y + 60);
await expect(col).toHaveAttribute("data-peek", "");
const over = await page.evaluate(({ x, y }) => {
+3 -3
View File
@@ -5,7 +5,7 @@
* own height among them; when they do not fit it stacks them as the strip stacks columns, covering
* all but the pane looked at, partly and then down to a tab. Curves run from where each pane was opened to its title; panes close (q, ×)
* and pin (P, pin). Same build, mock model, mock Wikipedia and shared library as the other specs;
* the documents are hoisted to (z) as in panes.spec.ts.
* the top-level trees are hoisted to (z) as in panes.spec.ts.
*/
import { expect, test, type Page } from "@playwright/test";
import { autoLayout, command, focusedTitle, jump, keys, seedLinks, selected, settle, state, visit } from "./helpers";
@@ -398,7 +398,7 @@ test("curves down one gutter take lanes of their own, side by side, up to as man
await page.goto("/");
await page.waitForSelector(".strip .pane");
await page.evaluate(() => document.fonts.ready);
// Ten documents opened from the library: ten curves down the gutter into column 1.
// Ten top-level trees opened from the library: ten curves down the gutter into column 1.
for (let i = 0; i < 10; i++) await keys(page, "j Enter");
await still(page);
const runs = await page.evaluate(() =>
@@ -676,7 +676,7 @@ test("q on an article opened from an article in a fork closes that article only
await page.waitForSelector(".strip .pane");
await page.evaluate(() => document.fonts.ready);
await jump(page, "Recursion without names");
// A fork beside it from the document's pane: Recursion without names starts a fork.
// A fork beside it from the top's pane: Recursion without names starts a fork.
await keys(page, "k Enter j Enter");
expect((await trail(page)).at(-1)).toBe("Recursion without names");
await tabTo(page, "fixed-point combinator");
+1 -1
View File
@@ -64,7 +64,7 @@ const hoistHere = (page: Page) => state(page, (s) => void (!s.panes && s.setHois
/**
* The section at these titles as the page: in the column hoisted to it (as z does), with the
* library one step out; in panes, in its own pane beside the library's. What `/doc/<name>` used to open.
* library one step out; in panes, in its own pane beside the library's.
*/
export async function openPage(page: Page, ...path: string[]) {
await openAt(page, ...path);
+1 -1
View File
@@ -264,7 +264,7 @@ test("branches merge; a conflict in meaning is found, resolved by the model, and
await expect(page.locator(".verdict")).toContainText("Verified");
});
test("two people editing at once converge, and the document survives a reload", async ({ browser }) => {
test("two people editing at once converge, and the library survives a reload", async ({ browser }) => {
const a = await (await browser.newContext()).newPage();
const b = await (await browser.newContext()).newPage();
await open(a);
+7 -7
View File
@@ -65,7 +65,7 @@ test("each kind of link has its mark; a note that also links keeps its dotted un
await expect(wiki).toBeVisible();
expect(await wiki.evaluate((el) => getComputedStyle(el).textDecorationLine)).toContain("underline");
await expect(sec.locator(".lmark.l-wiki").first()).toHaveText("W");
// Another note in the library: §, with the document in its tooltip.
// Another note in the library: §, with its top in its tooltip.
await expect(sec.locator(".lnk.l-node", { hasText: "Y combinator" })).toBeVisible();
const nodeMark = sec.locator(".lmark.l-node").first();
await expect(nodeMark).toHaveText("§");
@@ -101,7 +101,7 @@ test("hovering a link shows its preview and leaving or a key takes it away; focu
await page.mouse.move(5, 5);
await page.waitForTimeout(700);
await expect(page.locator(".popup")).toHaveCount(0);
// The node link's preview names its document and shows its first lines.
// The node link's preview names its top and shows its first lines.
await page.locator(".lnk.l-node", { hasText: "Y combinator" }).hover();
await expect(popup).toContainText("Fixed points");
await expect(popup).toContainText("How Y works");
@@ -309,7 +309,7 @@ test("Linked from and Mentioned in list what links here, reachable by j and Ente
await expect(back.locator("li.focused")).toHaveCount(1);
await keys(page, "Enter");
expect(await selected(page)).toBe("Several of the leading systems");
// Lambda calculus is linked from two documents: its pane lists both, and either leads back.
// Lambda calculus is linked from two top-level trees: its pane lists both, and either leads back.
await inPane(page, "Recursion without names", "lambda calculus");
await keys(page, "Enter j l");
const art = page.locator(".wiki-pane").last();
@@ -333,13 +333,13 @@ test("linking by hand: the picker links to the library, to Wikipedia and to an a
const s = (globalThis as any).__ie.snap;
return s.nodes[d].children.map((c: string) => s.nodes[c]).filter((n: any) => n.ref).map((n: any) => `${n.anchors[0].text}|${n.ref.kind}|${n.ref.title ?? n.ref.url ?? n.ref.path?.join("/")}`);
}, doc);
// A word in the document's text: i i selects it; w opens the picker filled with it.
// A word in the page's text: i i selects it; w opens the picker filled with it.
await keys(page, "i i");
const word = await selected(page);
await keys(page, "w");
const picker = page.locator(".picker");
await expect(picker.locator("input")).toHaveValue(word);
// Library: a document by title.
// Library: a top-level node by title.
await page.keyboard.press("Control+a");
await page.keyboard.type("Octopus minds");
await expect(picker.locator(".choice.selected .t")).toHaveText("Octopus minds");
@@ -368,7 +368,7 @@ test("linking by hand: the picker links to the library, to Wikipedia and to an a
await expect(picker.locator(".choice.selected")).toContainText("example.org");
await keys(page, "Enter");
expect(await linkCount()).toEqual([`${word}|wiki|Octopus`, `${second}|url|https://example.org/tides`]);
// /link with a target in the text form, on the node itself: the document is about something.
// /link with a target in the text form, on the node itself: the node is about something.
await keys(page, "Escape Escape");
await command(page, "/link w:Tide");
expect(await state(page, (s) => s.snap.nodes[s.focus.node].ref)).toEqual({ kind: "wiki", title: "Tide", lang: "en" });
@@ -536,7 +536,7 @@ test("keypress → paint stays within one frame budget through links and article
const warm = await measure(3);
report[view] = { cold, warm };
// One frame for nearly every key; a rare second frame (a preview appearing, the column's
// article page giving way to the document) is allowed, as the other latency tests allow it.
// article page giving way to the node's page) is allowed, as the other latency tests allow it.
expect(warm.keystrokes).toBeGreaterThan(30);
expect(warm.median).toBeLessThan(17.5);
expect(warm.p95).toBeLessThan(34);
+2 -2
View File
@@ -125,9 +125,9 @@ test("deleting the words a note is about orphans the note, visibly", async ({ pa
test("an outside agent edits over HTTP with the same ops, and the open page follows", async ({ page, request }) => {
await open(page);
const tree = await (await request.get("/api/tree/main")).json();
// The tree is the whole library; its documents are the root's sections.
// The tree is the whole library; its top-level trees are the root's sections.
expect(Object.values<any>(tree.nodes).filter((n) => n.parent === tree.root).map((n) => n.title)).toContain("Infinispand");
const target = Object.values<any>(tree.nodes).find((n) => n.title === "The first document");
const target = Object.values<any>(tree.nodes).find((n) => n.title === "The first tree");
expect(target).toBeTruthy();
const res = await request.post("/api/ops/main", {
data: { author: "outside-agent", message: "Add a remark", ops: [{ op: "create", parent: target.id, title: "Written over HTTP", body: "By an agent that is not the browser." }] },
+1 -1
View File
@@ -99,7 +99,7 @@ test("the library root is the first page and a node like any other: its sections
expect(await focusTitle(page)).toBe("Infinispand");
});
test("an address names a node by its id, and survives a reload, Back and Forward; an old document address shows the library", async ({ page }) => {
test("an address names a node by its id, and survives a reload, Back and Forward; an old /doc/ address shows the library", async ({ page }) => {
await openAt(page);
await jump(page, "Amphidromes");
const amph = await state(page, (s) => s.focus.node);
+4 -4
View File
@@ -173,7 +173,7 @@ test("a pane cut off for any reason peeks out whole, across and down, and the cu
await page.setViewportSize({ width: 1920, height: 700 });
await library(page);
for (const t of ["Octopus minds", "Infinispand", "The tides", "Fixed points"]) await open(page, "Library", t);
/** Hover each pane of the documents' column that is cut off, and check it comes out whole, and the curves with it. */
/** Hover each pane of the top-level trees' column that is cut off, and check it comes out whole, and the curves with it. */
const sweep = async (label: string, across: boolean) => {
const col = page.locator(".strip > .col").nth(1);
const n = await col.locator(":scope > .pane").count();
@@ -237,7 +237,7 @@ test("a pane cut off for any reason peeks out whole, across and down, and the cu
expect(await col.evaluate((c) => c.hasAttribute("data-covered") || !!c.nextElementSibling?.hasAttribute("data-over"))).toBe(true);
expect(await sweep("column covered", true)).toBeGreaterThan(0);
// By its share of a column that is not crowded: a tall window, two documents, one longer than its share.
// By its share of a column that is not crowded: a tall window, two top-level trees, one longer than its share.
await page.setViewportSize({ width: 1920, height: 1080 });
await page.evaluate(() => Object.keys(localStorage).filter((k) => k.startsWith("ie:view:")).forEach((k) => localStorage.removeItem(k)));
await library(page);
@@ -264,14 +264,14 @@ test("the curves keep to their sources and landing lines through every kind of l
await noFaults(page, "scrolled back");
await page.locator(".strip").evaluate((el) => (el.scrollLeft = Math.max(0, el.scrollLeft - 300)));
await noFaults(page, "the strip scrolled");
// A resize that folds the documents' column, and back.
// A resize that folds the top-level trees' column, and back.
await page.setViewportSize({ width: 1920, height: 520 });
await noFaults(page, "folded");
await page.setViewportSize({ width: 1600, height: 900 });
await noFaults(page, "resized");
await page.setViewportSize({ width: 1920, height: 1080 });
await noFaults(page, "unfolded");
// A drag down the documents' column.
// A drag down the top-level trees' column.
await page.evaluate(() => {
const ie = (globalThis as any).__ie;
const col = ie.paneColumns.get(1);
+1 -1
View File
@@ -22,7 +22,7 @@ async function still(page: Page) {
await frames(page);
}
async function open(page: Page, inPane: string | RegExp, text: string | RegExp, sel = ".row") {
// A row by its exact title (the shared library has documents whose titles start the same).
// A row by its exact title (the shared library has top-level nodes whose titles start the same).
const it = sel === ".row" && typeof text === "string" ? pane(page, inPane).locator(".row", { has: page.locator(`.title:text-is("${text}")`) }) : pane(page, inPane).locator(sel, { hasText: text });
await it.first().dispatchEvent("click");
await still(page);
+1 -1
View File
@@ -49,7 +49,7 @@ test("/research shows its searches and pages, writes a section, and links its cl
await expect(page.locator(".status .message")).toContainText("sources: How tides work (example.org)");
await idle(page);
// The section is in the document, with the phrase linked to the page: a web link, marked ↗.
// The section is in the library, with the phrase linked to the page: a web link, marked ↗.
const link = await state(page, (s) => {
const snap = s.snap;
const sec = Object.values(snap.nodes).find((n: any) => n.title === "On how tides work") as any;
+12 -12
View File
@@ -1,7 +1,7 @@
/**
* A large library in the browser: 100 more documents of 50 nodes each (over 5,000 nodes in all),
* A large library in the browser: 100 more top-level trees of 50 nodes each (over 5,000 nodes in all),
* written over the op API. Keypress → paint is measured as in the other specs, while moving
* through the library page, inside documents and across them, in the column and in panes, and
* through the library page, inside those trees and across them, in the column and in panes, and
* between four forks of the library pane, each three panes deep; a body edit is timed from the
* store call to the painted frame. Runs last: it fills the shared library.
*/
@@ -49,12 +49,12 @@ const keySamples = async (page: Page) => (await state(page, (s) => s.samples as
test.describe.configure({ mode: "serial" });
test.setTimeout(300_000);
test("a library of over 5,000 nodes in 100 more documents: keypress → paint and a body edit, in the column and in panes", async ({ page, request }) => {
// Write the documents, one commit each, as an outside agent would.
test("a library of over 5,000 nodes in 100 more top-level trees: keypress → paint and a body edit, in the column and in panes", async ({ page, request }) => {
// Write the trees, one commit each, as an outside agent would.
const tree = await (await request.get("/api/tree")).json();
let t = Date.now();
for (let d = 0; d < 100; d++) {
const ops: any[] = [{ op: "create", parent: tree.root, title: `Scale document ${d}`, body: SENTENCE.repeat(3) }];
const ops: any[] = [{ op: "create", parent: tree.root, title: `Scale tree ${d}`, body: SENTENCE.repeat(3) }];
let n = 1;
for (let s = 0; s < 7; s++) {
const sec = n++;
@@ -63,7 +63,7 @@ test("a library of over 5,000 nodes in 100 more documents: keypress → paint an
}
ops.push({ op: "create", parent: "$0", kind: "note", quote: "something that matters", body: "A note." });
for (let i = 0; i < n; i++) ops.push({ op: "bless", id: `$${i}` });
const res = await request.post("/api/ops", { data: { author: "scale", message: `Scale document ${d}`, ops } });
const res = await request.post("/api/ops", { data: { author: "scale", message: `Scale tree ${d}`, ops } });
expect(res.ok()).toBe(true);
}
const written = Date.now() - t;
@@ -85,13 +85,13 @@ test("a library of over 5,000 nodes in 100 more documents: keypress → paint an
// ---- the column ----
await page.evaluate(() => ((globalThis as any).__ie.samples.length = 0));
// Down the library page's 113 rows, into documents and out, across to the next.
// Down the library page's 113 rows, into trees and out, across to the next.
for (let i = 0; i < 40; i++) await paced(page, "j");
for (let i = 0; i < 6; i++) await paced(page, "l j l j l i j Escape h h h j");
await paced(page, "O");
const column = stats(await keySamples(page));
// A body edit inside a document deep in the library.
await visit(page, "Scale document 97");
// A body edit inside a tree deep in the library.
await visit(page, "Scale tree 97");
await ready(page);
await paced(page, "j l j");
const columnEdit = stats(await editTimes(page, 15));
@@ -110,7 +110,7 @@ test("a library of over 5,000 nodes in 100 more documents: keypress → paint an
// ---- forks: four documents opened side by side from the library pane, each three panes deep (document, part, leaf) ----
// A fresh view: the panes opened above stay open (opens go beside), and would be restored here.
await page.evaluate(() => localStorage.clear());
await visit(page, "Scale document 90");
await visit(page, "Scale tree 90");
await ready(page);
await paced(page, "l l l l");
for (let d = 1; d < 4; d++) await paced(page, "h h j Enter l l l l");
@@ -126,12 +126,12 @@ test("a library of over 5,000 nodes in 100 more documents: keypress → paint an
await page.evaluate(() => ((globalThis as any).__ie.samples.length = 0));
for (let i = 0; i < 8; i++) await paced(page, "[ [ [ ] ] ]");
const forks = stats(await keySamples(page));
await visit(page, "Scale document 98");
await visit(page, "Scale tree 98");
await ready(page);
await paced(page, "l l j");
const panesEdit = stats(await editTimes(page, 15));
const report = { nodes, documents: await state(page, (s) => s.snap.nodes[s.snap.root].children.length), writtenMs: written, bootFreshMs: bootFresh, bootStoredMs: bootStored, column, columnEdit, panes, panesEdit, forks };
const report = { nodes, tops: await state(page, (s) => s.snap.nodes[s.snap.root].children.length), writtenMs: written, bootFreshMs: bootFresh, bootStoredMs: bootStored, column, columnEdit, panes, panesEdit, forks };
console.log("large library:", JSON.stringify(report));
writeReport("scale", report);
for (const r of [column, panes]) {
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "infinispand",
"version": "1.0.0",
"private": true,
"description": "A document you can expand without limit: an outline whose every node, sentence and word opens further, written ahead or by a model, versioned like git.",
"description": "A tree of writing you can expand without limit: an outline whose every node, sentence and word opens further, written ahead or by a model, versioned like git.",
"type": "module",
"scripts": {
"test": "vitest run",
+19 -18
View File
@@ -1,11 +1,11 @@
/**
* Evaluate the link scanner (server/links/scan.ts) on the starter library against hand labels.
*
* IE_DATA=/tmp/x npx tsx scripts/linkEval.ts warm [docs…] live: fill the Wikipedia cache for the
* IE_DATA=/tmp/x npx tsx scripts/linkEval.ts warm [files…] live: fill the Wikipedia cache for the
* sampled sections, write their traces
* IE_DATA=/tmp/x npx tsx scripts/linkEval.ts eval [docs…] offline (cache only): precision and
* IE_DATA=/tmp/x npx tsx scripts/linkEval.ts eval [files…] offline (cache only): precision and
* recall against the labels
* IE_DATA=/tmp/x npx tsx scripts/linkEval.ts trace [docs…] offline: the traces, for labelling
* IE_DATA=/tmp/x npx tsx scripts/linkEval.ts trace [files…] offline: the traces, for labelling
*
* The sample is the first SAMPLE sections (in reading order, the top's own text included) of each
* named file's tree (by file name, without .md) that have at least 40 words. Labels: tests/fixtures/link-labels.json, one entry per
@@ -29,7 +29,7 @@ const DATA = resolve(process.env.IE_DATA ?? "");
if (!process.env.IE_DATA) throw new Error("set IE_DATA to a scratch directory");
const SAMPLE = Number(process.env.IE_EVAL_SAMPLE ?? 12);
const BUDGET = Number(process.env.IE_EVAL_BUDGET ?? 380);
const DOCS = rest.length ? rest : ["octopus-minds", "fixed-points", "origin-of-the-elements", "invention-of-writing"];
const FILES = rest.length ? rest : ["octopus-minds", "fixed-points", "origin-of-the-elements", "invention-of-writing"];
const LABELS = resolve("tests/fixtures/link-labels.json");
// The whole starter library, so that titles under other tops can be matched as they would be.
@@ -39,9 +39,9 @@ for (const f of readdirSync("library").filter((x) => x.endsWith(".md")).sort())
const snap = doc.snap();
const words = (s: string) => s.split(/\s+/).filter(Boolean).length;
function sample(snap: Snap, slug: string): NodeId[] {
const d = byFile.get(slug);
if (!d) throw new Error(`no file library/${slug}.md`);
function sample(snap: Snap, name: string): NodeId[] {
const d = byFile.get(name);
if (!d) throw new Error(`no file library/${name}.md`);
const out: NodeId[] = [];
const visit = (id: NodeId) => {
if (out.length < SAMPLE && words(snap.nodes[id].body) >= 40) out.push(id);
@@ -54,8 +54,8 @@ const pathOf = (id: NodeId) => [...ancestorsBelowRoot(snap, id).reverse().slice(
// `sample`: the sampled sections' texts only, for labelling before the scanner has seen them.
if (mode === "sample") {
const out = DOCS.flatMap((slug) => sample(snap, slug).map((id) => ({ doc: slug, node: pathOf(id), text: snap.nodes[id].body })));
const file = join(DATA, `sample-${DOCS.join("+")}.json`);
const out = FILES.flatMap((name) => sample(snap, name).map((id) => ({ doc: name, node: pathOf(id), text: snap.nodes[id].body })));
const file = join(DATA, `sample-${FILES.join("+")}.json`);
writeFileSync(file, JSON.stringify(out, null, 1));
console.error(`${out.length} sections → ${file}`);
process.exit(0);
@@ -76,7 +76,7 @@ await index.refresh();
const indexMs = Math.round(performance.now() - t0);
console.error(`index: ${index.vectors.size} sections in ${indexMs} ms${index.degraded ? " (no model: degraded)" : ""}`);
const nodes = DOCS.flatMap((slug) => sample(snap, slug).map((id) => ({ slug, id })));
const nodes = FILES.flatMap((name) => sample(snap, name).map((id) => ({ name, id })));
if (live) {
// One deduplicated lookup of every candidate of every sampled section first: 50 phrases a request.
@@ -87,10 +87,11 @@ if (live) {
console.error(`lookups done: ${wiki.requests} requests`);
}
/** `doc` (here and in the label files) is the starter file's name, without .md. */
type Row = TraceRow & { doc: string; node: string; sentence?: string };
const rows: Row[] = [];
const perNode: { node: string; ms: number; requests: number }[] = [];
for (const { slug, id } of nodes) {
for (const { name, id } of nodes) {
if (live && wiki.requests >= BUDGET) {
console.error(`budget of ${BUDGET} requests reached; stopping before ${pathOf(id)}`);
break;
@@ -102,15 +103,15 @@ for (const { slug, id } of nodes) {
for (const t of trace) {
const from = Math.max(body.lastIndexOf(". ", t.start) + 2, body.lastIndexOf("\n", t.start) + 1, 0);
const to = body.indexOf(". ", t.start);
rows.push({ ...t, doc: slug, node: pathOf(id), sentence: body.slice(from, to < 0 ? body.length : to + 1) });
rows.push({ ...t, doc: name, node: pathOf(id), sentence: body.slice(from, to < 0 ? body.length : to + 1) });
}
if (live) wiki.flush();
if (live) console.error(`${slug} › ${pathOf(id)}: ${r.stats.candidates} candidates, ${r.suggestions.length} chosen, ${r.stats.requests} requests (total ${wiki.requests})`);
if (live) console.error(`${name} › ${pathOf(id)}: ${r.stats.candidates} candidates, ${r.suggestions.length} chosen, ${r.stats.requests} requests (total ${wiki.requests})`);
}
wiki.flush();
if (mode === "warm" || mode === "trace") {
const file = join(DATA, `trace-${DOCS.join("+")}.json`);
const file = join(DATA, `trace-${FILES.join("+")}.json`);
writeFileSync(file, JSON.stringify(rows, null, 1));
console.error(`${rows.length} traced phrases → ${file}; ${wiki.requests} requests`);
const ms = perNode.map((p) => p.ms).sort((a, b) => a - b);
@@ -123,7 +124,7 @@ if (mode === "warm" || mode === "trace") {
if (mode === "heldout") {
// tests/fixtures/link-labels-heldout.json lists, per section, every phrase worth a link and the
// acceptable targets, written from the text before the scanner ran. A link not on it is wrong.
const held: { doc: string; node: string; key: string; phrase: string; targets: string[] }[] = JSON.parse(readFileSync(resolve("tests/fixtures/link-labels-heldout.json"), "utf8")).labels.filter((l: { doc: string }) => DOCS.includes(l.doc));
const held: { doc: string; node: string; key: string; phrase: string; targets: string[] }[] = JSON.parse(readFileSync(resolve("tests/fixtures/link-labels-heldout.json"), "utf8")).labels.filter((l: { doc: string }) => FILES.includes(l.doc));
const label = (r: Row) => held.find((l) => l.doc === r.doc && l.node === r.node && l.key === r.key);
const ok = (r: Row) => !!label(r)?.targets.includes(r.target);
const chosen = rows.filter((r) => r.chosen);
@@ -131,7 +132,7 @@ if (mode === "heldout") {
const right = set.filter(ok).length;
console.log(`${name.padEnd(16)} ${String(set.length).padStart(4)} chosen ${String(right).padStart(4)} right precision ${(set.length ? right / set.length : 1).toFixed(3)} recall ${(right / held.length).toFixed(3)}`);
};
console.log(`documents: ${DOCS.join(", ")}; ${nodes.length} sections; ${held.length} phrases worth linking`);
console.log(`files: ${FILES.join(", ")}; ${nodes.length} sections; ${held.length} phrases worth linking`);
line("auto", chosen.filter((r) => r.tier === "auto"));
line("auto + suggest", chosen);
const fmt = (r: Row) => ` [${r.tier} fit ${r.fit ?? "-"}] ${r.doc} | ${r.node} | “${r.phrase}” → ${r.target}${label(r) ? ` (label: ${label(r)!.targets.join(" or ")})` : " (not on the list)"} — ${r.sentence?.trim().slice(0, 140)}`;
@@ -159,7 +160,7 @@ interface Label {
note?: string;
}
const labels: Label[] = JSON.parse(readFileSync(LABELS, "utf8")).labels;
const mine = labels.filter((l) => DOCS.includes(l.doc));
const mine = labels.filter((l) => FILES.includes(l.doc));
const find = (r: Row) => mine.find((l) => l.doc === r.doc && l.node === r.node && l.key === r.key);
const chosen = rows.filter((r) => r.chosen);
const unlabelled = chosen.filter((r) => !find(r));
@@ -175,7 +176,7 @@ const report = (name: string, set: Row[]) => {
const rcl = yes ? right / yes : 0;
console.log(`${name.padEnd(16)} ${String(set.length).padStart(4)} chosen ${String(right).padStart(4)} right precision ${p.toFixed(3)} recall ${rcl.toFixed(3)}`);
};
console.log(`documents: ${DOCS.join(", ")}; ${nodes.length} sections; ${mine.length} labelled phrases (${yes} worth linking)`);
console.log(`files: ${FILES.join(", ")}; ${nodes.length} sections; ${mine.length} labelled phrases (${yes} worth linking)`);
report("auto", chosen.filter((r) => r.tier === "auto"));
report("auto + suggest", chosen);
if (unlabelled.length) console.log(`unlabelled chosen: ${unlabelled.length}\n${unlabelled.map((r) => ` ${r.doc} | ${r.node} | ${r.key} → ${r.target} [${r.tier}]`).join("\n")}`);
+2 -2
View File
@@ -215,9 +215,9 @@ export class Doc {
const loro = new LoroDoc();
loro.setPeerId(randomPeer());
const doc = new Doc(loro, author);
doc.begin("Create document", actor);
doc.begin("Create the tree", actor);
initRoot(loro.getTree("tree").createNode(), title, body, actor);
doc.commit("Create document", actor);
doc.commit("Create the tree", actor);
return doc;
}
+1 -1
View File
@@ -136,7 +136,7 @@ export function clip(s: string, n: number): string {
return s.length <= n ? s : s.slice(0, n - 1).trimEnd() + "…";
}
/** A file name or title as a document's slug: lowercase letters, digits and single hyphens. */
/** A title or file name as a safe file name (an export's): lowercase letters, digits and single hyphens. */
export function slugify(s: string): string {
return (
s
+17 -17
View File
@@ -24,7 +24,7 @@ export const seed: SeedNode[] = [
"This would be necessary for user selections that weren’t covered by the pre-generations like highlighting certain sentences, phrases, or words.",
"In general level of detail expands further but the length of the text generated at a deeper level isn’t necessarily deeper.",
],
body: "A document opens as an outline of titles. Opening a node shows its body and the titles of its children, and each level down is a step denser than the one above. The first levels are written ahead of time and open instantly; past them, or on any selection of text, the model generates the expansion on request. Going deeper makes the text more specific, not longer.",
body: "A tree opens as an outline of titles. Opening a node shows its body and the titles of its children, and each level down is a step denser than the one above. The first levels are written ahead of time and open instantly; past them, or on any selection of text, the model generates the expansion on request. Going deeper makes the text more specific, not longer.",
notes: [
{
quote: "a step denser",
@@ -90,7 +90,7 @@ export const seed: SeedNode[] = [
children: [
{
title: "Deepening a leaf",
body: "A leaf is a section with no child sections. Pressing `e` on one asks the LLM to write them: a handful of titled children, each a step denser than the leaf's own body. They are committed to the tree like any other edit, so the next reader finds them already there. This is the sense in which the document has no bottom; every leaf is one keystroke from not being a leaf.",
body: "A leaf is a section with no child sections. Pressing `e` on one asks the LLM to write them: a handful of titled children, each a step denser than the leaf's own body. They are committed to the tree like any other edit, so the next reader finds them already there. This is the sense in which the tree has no bottom; every leaf is one keystroke from not being a leaf.",
notes: [
{
quote: "no bottom",
@@ -114,13 +114,13 @@ export const seed: SeedNode[] = [
quote: "challenge",
form: "note",
lens: "elaborate",
body: "Challenge asks for the strongest objection to the selected claim. It is the lens most likely to change the document instead of lengthening it.",
body: "Challenge asks for the strongest objection to the selected claim. It is the lens most likely to change the text instead of lengthening it.",
},
],
},
{
title: "Context and latency",
body: "Generated text streams into place as it is produced, with a budget of under one second to the first token. Each request carries the ancestor path, root to node, together with the outline of the whole document, sent as cached context so that repeated requests in the same region do not pay for it twice. Speculative generation is optional: when enabled, focusing a sentence starts generating its expansion before it is asked for.",
body: "Generated text streams into place as it is produced, with a budget of under one second to the first token. Each request carries the ancestor path, root to node, together with the outline of the top-level tree it is in, sent as cached context so that repeated requests in the same region do not pay for it twice. Speculative generation is optional: when enabled, focusing a sentence starts generating its expansion before it is asked for.",
notes: [
{
quote: "sent as cached context",
@@ -147,7 +147,7 @@ export const seed: SeedNode[] = [
form: "passage",
lens: "elaborate",
body: P(
"The failure this guards against is the expansion that grows by padding: the same claim restated with more adjectives, then again with an example nobody asked for. A reader who descends three levels into such a document has read the first level three times.",
"The failure this guards against is the expansion that grows by padding: the same claim restated with more adjectives, then again with an example nobody asked for. A reader who descends three levels into such a tree has read the first level three times.",
"The alternative is to treat each level like a map at a larger scale. The sheet of paper stays the same size; the territory it covers shrinks, and the detail that was below the threshold at the previous scale appears.",
),
notes: [
@@ -331,7 +331,7 @@ export const seed: SeedNode[] = [
},
{
title: "The editor agent",
body: "At node grain the command bar takes an instruction instead of a question: tighten this, add a section on that, split this node in two. The instruction goes to an LLM editor agent that works on a fork of the document under its own peer id, using the same operations as the user. When it finishes, its fork is merged back. The user can keep editing in the meantime, because the two sets of changes meet as an ordinary merge.",
body: "At node grain the command bar takes an instruction instead of a question: tighten this, add a section on that, split this node in two. The instruction goes to an LLM editor agent that works on a fork of the library under its own peer id, using the same operations as the user. When it finishes, its fork is merged back. The user can keep editing in the meantime, because the two sets of changes meet as an ordinary merge.",
notes: [
{
quote: "peer id",
@@ -470,7 +470,7 @@ export const seed: SeedNode[] = [
"Another key element to this is that users can actually add, modify, or delete a “node” to the tree.",
"I think maybe we want something like CDRTs under the hood that would instead use LLMs to resolve logical conflicts.",
],
body: "A document is a tree of nodes held in a CRDT. Each node has a title, a body, a kind and a provenance, and a note is tied to its parent's text by anchors that survive editing. Every browser holds a full replica, and a small local server relays changes and keeps the API key.",
body: "A library is a tree of nodes held in a CRDT, its root the library itself; there can be several, each a tree of its own. Each node has a title, a body, a kind and a provenance, and a note is tied to its parent's text by anchors that survive editing. Every browser holds a full replica, and a small local server relays changes and keeps the API key.",
notes: [
{
quote: "CRDT",
@@ -482,7 +482,7 @@ export const seed: SeedNode[] = [
children: [
{
title: "Nodes",
body: "The document lives in a Loro CRDT, using its movable tree for structure and its text type for bodies. A node has a title and a body. It has a kind: a section is a structural child, listed in the outline under its parent, and a note is an expansion anchored to a span of its parent's body. And it has a provenance: whether it was written by a human or by an LLM, and whether it is pinned.",
body: "A library lives in a Loro CRDT of its own, using its movable tree for structure and its text type for bodies. A node has a title and a body. It has a kind: a section is a structural child, listed in the outline under its parent, and a note is an expansion anchored to a span of its parent's body. And it has a provenance: whether it was written by a human or by an LLM, and whether it is pinned.",
notes: [
{
quote: "movable tree",
@@ -515,7 +515,7 @@ export const seed: SeedNode[] = [
},
{
title: "Local-first",
body: "Each browser holds a full replica of the document in IndexedDB and can read and edit without a connection. A small local server does three things: it relays updates between tabs, people and agents; it persists the document to disk; and it is the only holder of the API key, so the key never reaches a browser.",
body: "Each browser holds a full replica of the library in IndexedDB and can read and edit without a connection. A small local server does three things: it relays updates between tabs, people and agents; it persists each library to disk; and it is the only holder of the API key, so the key never reaches a browser.",
notes: [
{
quote: "full replica",
@@ -557,7 +557,7 @@ export const seed: SeedNode[] = [
},
{
title: "History operations",
body: "Four operations work on history. Time travel checks out an earlier commit read-only. Revert returns the tree to an earlier state by adding a new commit, so the reverted work stays in history. A branch is a named fork of the document. Merge brings one branch's changes into another. All four are reached from the history view, opened with g.",
body: "Four operations work on history. Time travel checks out an earlier commit read-only. Revert returns the tree to an earlier state by adding a new commit, so the reverted work stays in history. A branch is a named fork of the library. Merge brings one branch's changes into another. All four are reached from the history view, opened with g.",
notes: [
{
quote: "by adding a new commit",
@@ -581,7 +581,7 @@ export const seed: SeedNode[] = [
},
{
title: "Semantic conflicts",
body: "Some conflicts are invisible to the CRDT because the merged result is well-formed. There are three kinds. They are found by comparing both sides against the merge base, with an LLM scanning for contradictions, and written into the document as conflict records. An LLM then proposes a resolution as an explicit commit that can be reviewed and reverted, never silently; without an LLM the conflict stays open for a person.",
body: "Some conflicts are invisible to the CRDT because the merged result is well-formed. There are three kinds. They are found by comparing both sides against the merge base, with an LLM scanning for contradictions, and written into the library as conflict records. An LLM then proposes a resolution as an explicit commit that can be reviewed and reverted, never silently; without an LLM the conflict stays open for a person.",
children: [
{
title: "Three kinds",
@@ -608,7 +608,7 @@ export const seed: SeedNode[] = [
},
{
title: "Detection",
body: "At a merge, each node is compared three ways: its state at the merge base, on one side, and on the other. A field changed differently on both sides, or changed on one and deleted on the other, is a conflict. Contradictions between different nodes cannot be found by comparison, so an LLM scans the two sets of changes for them. Every conflict found is recorded in the document itself as a conflict record, which means it is replicated and versioned like everything else.",
body: "At a merge, each node is compared three ways: its state at the merge base, on one side, and on the other. A field changed differently on both sides, or changed on one and deleted on the other, is a conflict. Contradictions between different nodes cannot be found by comparison, so an LLM scans the two sets of changes for them. Every conflict found is recorded in the library itself as a conflict record, which means it is replicated and versioned like everything else.",
notes: [
{
quote: "merge base",
@@ -710,7 +710,7 @@ export const seed: SeedNode[] = [
"The first example we should use in the editor/explorer should be meta: this project itself.",
"Break what I have outlined here down into an initial tree we can explore together.",
],
body: "The tree is a working memory shared by a person and a model. The person steers by attention, the model fills in at the resolution asked for, and either can restructure what is there. The first document is this one.",
body: "The tree is a working memory shared by a person and a model. The person steers by attention, the model fills in at the resolution asked for, and either can restructure what is there. The first tree in the library is this one.",
notes: [
{
quote: "working memory",
@@ -737,11 +737,11 @@ export const seed: SeedNode[] = [
},
{
title: "Either can restructure",
body: "The tree is a shared working memory in the plain sense that both parties read it and both write it. Neither is confined to filling in. The person can add, move, rewrite and delete nodes, and so can the model, through the same operations; the document can grow in directions that neither started with. What a person writes is kept as written.",
body: "The tree is a shared working memory in the plain sense that both parties read it and both write it. Neither is confined to filling in. The person can add, move, rewrite and delete nodes, and so can the model, through the same operations; the tree can grow in directions that neither started with. What a person writes is kept as written.",
},
{
title: "The first document",
body: "The first document is this one. Its root holds the prompt that began the project, verbatim, and each top-level section is tied to the sentences of the prompt it came from, so the description of the tool can be read, questioned and corrected with the tool.",
title: "The first tree",
body: "The first tree is this one. Its top node holds the prompt that began the project, verbatim, and each section under it is tied to the sentences of the prompt it came from, so the description of the tool can be read, questioned and corrected with the tool.",
},
],
},
@@ -781,7 +781,7 @@ export const seed: SeedNode[] = [
},
{
title: "Interface",
body: "One check covers the interface. A script drives the application through this document using only the keyboard, and records two latencies against their budgets: keypress to paint for pre-generated expansions, under 50 ms, and time to first token for generated ones, under 1 s.",
body: "One check covers the interface. A script drives the application through this tree using only the keyboard, and records two latencies against their budgets: keypress to paint for pre-generated expansions, under 50 ms, and time to first token for generated ones, under 1 s.",
},
],
},
+4 -3
View File
@@ -2,9 +2,10 @@
* Application state for the browser: the library's replicas, sync with the server, the focus
* model, and every action the keyboard, the mouse or the command bar can take.
*
* There is one library, a tree of nodes, and every node in it is reachable from anywhere: the
* library root is the first page, and any node can be made the whole page (hoisted, in the column)
* or shown in the next pane. Nothing is closed to open something else, so model work carries on
* The page holds one library (its address names it; another is opened by a page load from the
* libraries panel), a tree of nodes, and every node in it is reachable from anywhere: the library
* root is the first page, and any node can be made the whole page (hoisted, in the column) or
* shown in the next pane. Nothing is closed to open something else, so model work carries on
* wherever the reader goes, and writes into the node it was asked about.
*/
import { UndoManager } from "loro-crdt";
+3 -3
View File
@@ -1,6 +1,6 @@
/**
* Convergence: replicas of a library that apply random concurrent ops through the op API (moving
* and copying nodes between its documents among them) and exchange updates in random order must
* and copying nodes between its top-level trees among them) and exchange updates in random order must
* end in identical state, with a history that still verifies. Along the way every snapshot, which
* is patched node by node after each change, must equal one read from scratch.
*/
@@ -39,8 +39,8 @@ function base(): Doc {
{ op: "create", parent: "$0" as NodeId, title: "Two", body: "The second child." },
{ op: "create", parent: "$1" as NodeId, title: "Deep", body: "A grandchild." },
{ op: "create", parent: "$0" as NodeId, kind: "note", quote: "Beta", form: "gloss", body: "second letter" },
{ op: "create", parent: lib, title: "Doc B", body: "Another document entirely." },
{ op: "create", parent: "$5" as NodeId, title: "Three", body: "A section of the second document." },
{ op: "create", parent: lib, title: "Doc B", body: "Another tree entirely." },
{ op: "create", parent: "$5" as NodeId, title: "Three", body: "A section of the second tree." },
],
"Base",
);
+15 -15
View File
@@ -134,7 +134,7 @@ describe("history", () => {
doc.apply([{ op: "delete", id: one }], "Delete one");
doc.apply([{ op: "update", id: root, title: "Root!" }], "Rename");
const h = history(doc);
expect(h.map((c) => c.message)).toEqual(["Rename", "Delete one", "Edit one", "Add children", "Create document"]);
expect(h.map((c) => c.message)).toEqual(["Rename", "Delete one", "Edit one", "Add children", "Create the tree"]);
expect(verifyHistory(doc)).toEqual({ checked: 5, unhashed: 0, mismatches: [] });
expect(at(doc, h[2]).canonical()).toBe(states[0]);
revertTo(doc, h[2]);
@@ -282,26 +282,26 @@ function library() {
const staleIds = (doc: Doc) => Object.keys(doc.snap().nodes).filter((id) => isStale(doc.snap(), id as NodeId));
describe("library", () => {
it("the root is never stale, and an edit inside a document marks neither the root nor the other documents", () => {
it("the root is never stale, and an edit inside a top-level tree marks neither the root nor the other trees", () => {
const { doc, lib, a, aPart, aLeaf, aNote, b } = library();
expect(staleIds(doc)).toEqual([]);
doc.apply([{ op: "update", id: a, body: "Alpha is now about something else." }], "Edit a document's text");
doc.apply([{ op: "update", id: a, body: "Alpha is now about something else." }], "Edit a top's text");
// Its own sections now elaborate text that changed; nothing outside it does.
expect(staleIds(doc)).toEqual([aPart]);
doc.apply([{ op: "bless", id: aPart }], "Accept");
doc.apply([{ op: "update", id: aLeaf, body: "A rewritten leaf." }], "Edit a leaf");
expect(staleIds(doc)).toEqual([aPart]);
doc.apply([{ op: "update", id: aPart, body: "A rewritten part." }], "Edit the part");
// Up to its document, which now summarises a changed part; down to its leaf and the note whose words went.
// Up to its top, which now summarises a changed part; down to its leaf and the note whose words went.
const inAlpha = [a, aLeaf, aNote].sort();
expect(staleIds(doc).sort()).toEqual(inAlpha);
// Renaming, adding and deleting documents changes the library's sections, which it does not summarise.
// Renaming, adding and deleting top-level nodes changes the library's sections, which it does not summarise.
doc.apply(retitleOps(doc.snap(), b, "Beta renamed"), "Rename");
doc.apply([{ op: "create", parent: lib, title: "Gamma", body: "New." }], "New document");
doc.apply([{ op: "delete", id: b }], "Delete a document");
doc.apply([{ op: "create", parent: lib, title: "Gamma", body: "New." }], "New top");
doc.apply([{ op: "delete", id: b }], "Delete a top");
expect(staleIds(doc).sort()).toEqual(inAlpha);
expect(staleness(doc.snap(), lib)).toEqual({ up: false, down: false, orphan: false });
// The library's own text is the reader's; editing it marks no document.
// The library's own text is the reader's; editing it marks no top.
doc.apply([{ op: "update", id: lib, body: "My library." }], "Write the library's text");
expect(staleIds(doc).sort()).toEqual(inAlpha);
expect(topOf(doc.snap(), lib)).toBeNull();
@@ -309,7 +309,7 @@ describe("library", () => {
expect(ancestorsBelowRoot(doc.snap(), aLeaf)).toEqual([doc.snap().nodes[aLeaf].parent, a]);
});
it("moves a node from one document to another with an ordinary move; its notes keep their anchors and undo moves it back", () => {
it("moves a node from one top-level tree to another with an ordinary move; its notes keep their anchors and undo moves it back", () => {
const { doc, a, aPart, aNote, b } = library();
const undo = new UndoManager(doc.loro, { mergeInterval: 0, excludeOriginPrefixes: [SYSTEM_ORIGIN] });
doc.group = { start: () => undo.groupStart(), end: () => undo.groupEnd() };
@@ -319,7 +319,7 @@ describe("library", () => {
expect(topOf(snap, aPart)).toBe(b);
expect(snap.nodes[aNote].anchors[0].text).toBe("a phrase worth a note");
expect(sections(snap, a)).toEqual([]);
// Both documents' summaries are now out of date, as with any move.
// Both tops' summaries are now out of date, as with any move.
expect(staleness(snap, a).up && staleness(snap, b).up).toBe(true);
expect(verifyHistory(doc).mismatches).toEqual([]);
expect(undo.undo()).toBe(true);
@@ -333,9 +333,9 @@ describe("library", () => {
expect(tops(doc.snap())).toEqual([a, b, aPart]);
});
it("loads a library whose nodes still carry slugs (and node targets a document slug), ignoring them", () => {
it("loads a library whose nodes still carry slugs from before step 1 (and node targets naming one), ignoring them", () => {
const { doc, a, aLeaf, b } = library();
// As an older version wrote them: a slug on each top, and a target naming its document.
// As an older version wrote them: a slug on each top, and a target naming its top by that slug.
const old = doc.fork();
old.apply([{ op: "create", parent: b, kind: "note", quote: "Beta", ref: { kind: "node", id: aLeaf, path: ["Alpha part"] } }], "Link");
const link = notesOf(old.snap(), b)[0];
@@ -367,13 +367,13 @@ describe("library", () => {
expect(snap.nodes[note].anchors[0].text).toBe("a phrase worth a note");
});
it("reverts one document to a commit and leaves the others as they are now", () => {
it("reverts one top-level tree to a commit and leaves the others as they are now", () => {
const { doc, a, aPart, aLeaf, b, bLeaf } = library();
const mark = history(doc)[0];
doc.apply([{ op: "update", id: aLeaf, body: "Changed later." }], "Change a leaf");
doc.apply([{ op: "delete", id: aPart }], "Delete a part");
doc.apply([{ op: "create", parent: a, title: "Added later" }], "Add a section");
doc.apply([{ op: "update", id: bLeaf, body: "Beta changed later too." }], "Change the other document");
doc.apply([{ op: "update", id: bLeaf, body: "Beta changed later too." }], "Change the other top");
const beta = doc.shape(doc.snap(), b);
revertSubtreeTo(doc, mark, a);
const snap = doc.snap();
@@ -384,7 +384,7 @@ describe("library", () => {
expect(verifyHistory(doc).mismatches).toEqual([]);
});
it("names the nodes a commit wrote, and syncs edits in different documents without comparing whole states", () => {
it("names the nodes a commit wrote, and syncs edits in different top-level trees without comparing whole states", () => {
const { doc, aLeaf, bLeaf } = library();
doc.apply([{ op: "update", id: aLeaf, body: "Edited." }], "Edit");
expect([...touched(doc, history(doc)[0].spans).nodes]).toContain(aLeaf);
+2 -2
View File
@@ -130,7 +130,7 @@ describe("parsing", () => {
expect(problems("")).toEqual([`doc.md: no "# Title" heading`]);
});
it("makes slugs from titles and file names", () => {
it("makes safe file names from titles and file names", () => {
expect(slugify("Tuning & Temperament")).toBe("tuning-temperament");
expect(slugify("Ça va? Déjà vu!")).toBe("ca-va-deja-vu");
expect(slugify("../../etc/passwd")).toBe("etc-passwd");
@@ -280,7 +280,7 @@ describe("export and import", () => {
expect(canonBody(" one \n two\n\n\n\nthree \n \n")).toBe("one\ntwo\n\nthree");
});
it("exports the first document without losing a note", () => {
it("exports the first tree without losing a note", () => {
const prompt = readFileSync(new URL("../src/seed/prompt.txt", import.meta.url), "utf8");
const doc = Doc.library("test");
const first = writeSeed(doc, prompt, seed);
+1 -1
View File
@@ -81,7 +81,7 @@ describe("the hash and history", () => {
it("a tree without targets hashes as it did before targets existed", () => {
// The row of a node with no target is unchanged, so old commits still verify: the first
// document's seed commits are checked by the seed tests; here, a slug-only row.
// tree's seed commits are checked by the seed tests; here, a library made now.
const { doc } = library();
expect(verifyHistory(doc).mismatches).toEqual([]);
});
+2 -2
View File
@@ -89,7 +89,7 @@ describe("a research run with the mock", () => {
expect(seen[0].messages[0].content).toContain("Web research is on for this request");
});
it("is stopped by its signal, and nothing it did reaches the document", async () => {
it("is stopped by its signal, and nothing it did reaches the library", async () => {
const { doc, tides } = fixture();
const ac = new AbortController();
const before = doc.snap().nodes[tides].children.length;
@@ -106,7 +106,7 @@ describe("citing only what was retrieved", () => {
const result = await runAgent(mockLLM(), doc, "tides, unretrieved", tides, (e) => events.push(e), undefined, {}, research);
const error = events.find((e) => e.kind === "error")!;
expect(error.text).toMatch(/not among the search results or pages read in this run/);
// It corrected itself to a page it did retrieve; the rejected address is nowhere in the document.
// It corrected itself to a page it did retrieve; the rejected address is nowhere in the library.
expect(result.sources.map((s) => s.url)).toEqual([MOCK_RESULTS[0].url]);
expect(Object.values(doc.snap().nodes).some((n) => n.ref?.kind === "url" && n.ref.url === MOCK_UNRETRIEVED)).toBe(false);
});
+8 -8
View File
@@ -1,5 +1,5 @@
/**
* A library of about 5,000 nodes in 100 documents: an edit must cost what it touches, not the size
* A library of about 5,000 nodes in 100 top-level trees: an edit must cost what it touches, not the size
* of the library. Timings are printed; the assertions are budgets well inside one 16 ms frame for
* the work a keystroke does, and a comparison with a library a tenth the size.
*/
@@ -14,12 +14,12 @@ import { renderContext } from "../src/llm/prompts";
const SENTENCE = "This sentence is about something that matters here. Another follows it, with a few more words. ";
/** `docs` documents of 50 nodes each: 7 sections of 6 leaves, and a note. */
/** `docs` top-level trees of 50 nodes each: 7 sections of 6 leaves, and a note. */
function synthetic(docs: number): Doc {
const doc = Doc.library("scale");
const lib = doc.snap().root;
for (let d = 0; d < docs; d++) {
const ops: Op[] = [{ op: "create", parent: lib, title: `Document ${d}`, body: SENTENCE.repeat(3) }];
const ops: Op[] = [{ op: "create", parent: lib, title: `Tree ${d}`, body: SENTENCE.repeat(3) }];
let n = 1;
for (let s = 0; s < 7; s++) {
const sec = n++;
@@ -27,10 +27,10 @@ function synthetic(docs: number): Doc {
for (let k = 0; k < 6; k++, n++) ops.push({ op: "create", parent: `$${sec}` as NodeId, title: `Leaf ${d}.${s}.${k}`, body: SENTENCE.repeat(2) });
}
ops.push({ op: "create", parent: "$0" as NodeId, kind: "note", quote: "something that matters", body: "A note." });
// And a link to an article, shared by every tenth document, for the backlinks index to follow.
// And a link to an article, shared by every tenth tree, for the backlinks index to follow.
ops.push({ op: "create", parent: "$0" as NodeId, kind: "note", quote: "Another follows", ref: { kind: "wiki", title: `Topic ${d % 10}`, lang: "en" } });
for (let i = 0; i < n; i++) ops.push({ op: "bless", id: `$${i}` as NodeId });
doc.apply(ops, `Document ${d}`, { actor: "llm" });
doc.apply(ops, `Tree ${d}`, { actor: "llm" });
}
return doc;
}
@@ -55,7 +55,7 @@ function editCost(doc: Doc, rounds = 25) {
}
describe("a large library", () => {
it("costs what an edit touches: 5,000 nodes in 100 documents", () => {
it("costs what an edit touches: 5,000 nodes in 100 top-level trees", () => {
let t = performance.now();
const big = synthetic(100);
const built = performance.now() - t;
@@ -80,7 +80,7 @@ describe("a large library", () => {
const reread = (performance.now() - t) / 1000;
expect(loaded.snap()).toBe(first);
// Server start: open the stored library and list its documents, as server/index.ts does.
// Server start: open the stored library and list its top-level nodes, as the server does.
const data = mkdtempSync(join(tmpdir(), "ie-scale-"));
mkdirSync(join(data, "library"));
writeFileSync(join(data, "library", "main.loro"), bytes);
@@ -98,7 +98,7 @@ describe("a large library", () => {
expect(ix.mentions("en", "Topic 3")).toHaveLength(10);
const small = editCost(Doc.load(synthetic(10).snapshotBytes(), "reader"));
console.log(
`scale: ${nodes} nodes, ${(bytes.length / 1024).toFixed(0)} KB · built in ${built.toFixed(0)} ms · loaded and read in ${boot.toFixed(0)} ms · first state hash ${firstHash.toFixed(0)} ms · server store opened and listed in ${serverStart.toFixed(0)} ms · cached snapshot ${(reread * 1000).toFixed(1)} µs · backlinks index built in ${indexed.toFixed(1)} ms · body edit (op, commit, snapshot, staleness, context) median ${edit.toFixed(2)} ms at 100 documents, ${small.toFixed(2)} ms at 10`,
`scale: ${nodes} nodes, ${(bytes.length / 1024).toFixed(0)} KB · built in ${built.toFixed(0)} ms · loaded and read in ${boot.toFixed(0)} ms · first state hash ${firstHash.toFixed(0)} ms · server store opened and listed in ${serverStart.toFixed(0)} ms · cached snapshot ${(reread * 1000).toFixed(1)} µs · backlinks index built in ${indexed.toFixed(1)} ms · body edit (op, commit, snapshot, staleness, context) median ${edit.toFixed(2)} ms at 100 trees, ${small.toFixed(2)} ms at 10`,
);
expect(edit).toBeLessThan(8);
// An edit at a tenth of the size costs about the same: nothing it does walks the whole library.
+1 -1
View File
@@ -124,7 +124,7 @@ describe("a node and everything under it, wherever it is", () => {
lib.apply([{ op: "move", id: one, parent: b }, { op: "update", id: one, title: "Renamed" }], "move and rename");
expect(address(lib.snap(), one)).toBe(`/n/${encodeURIComponent(one)}`);
expect(resolve(lib.snap(), `/n/${encodeURIComponent(one)}`)).toEqual({ node: one });
// What names nothing says so (the page then shows the library): a gone node, an old document address, anything else.
// What names nothing says so (the page then shows the library): a gone node, an old `/doc/…` address, anything else.
expect(resolve(lib.snap(), "/n/999%40999")).toEqual({ missing: "no node 999@999" });
expect(resolve(lib.snap(), "/doc/tides")).toEqual({ missing: "no page /doc/tides" });
expect(resolve(lib.snap(), "/n/%E0%A4%A")).toMatchObject({ missing: expect.any(String) });