From 8923ba95f948639982ff829dc519aaf068990194 Mon Sep 17 00:00:00 2001 From: Tyler Hallada Date: Sun, 15 Nov 2026 14:30:50 -0500 Subject: [PATCH] Scripts and docs Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab --- README.md | 333 ++++++++++++++++++++++++++++++++++++++++++++ docs/wikipedia.md | 326 +++++++++++++++++++++++++++++++++++++++++++ scripts/fixtures.ts | 205 +++++++++++++++++++++++++++ scripts/linkEval.ts | 206 +++++++++++++++++++++++++++ scripts/verify.ts | 51 +++++++ 5 files changed, 1121 insertions(+) create mode 100644 README.md create mode 100644 docs/wikipedia.md create mode 100644 scripts/fixtures.ts create mode 100644 scripts/linkEval.ts create mode 100644 scripts/verify.ts diff --git a/README.md b/README.md new file mode 100644 index 0000000..e667982 --- /dev/null +++ b/README.md @@ -0,0 +1,333 @@ +# Infinispand + +A document 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. + +All documents live in one library: a single versioned tree whose root is the library and whose +sections are the documents, so a node can move from one document to another and reading goes from +one to the next without closing anything. The first document is this project describing itself, +grown from the prompt that started it; a set of starter documents (`library/*.md`) comes with it. + +## Run it + +```sh +npm install +npm run dev # http://localhost:4747 +``` + +Without credentials the library is fully explorable and editable, and anything that needs a model +says so. To turn generation on, start the server with `ANTHROPIC_API_KEY=sk-ant-…`, or, to run on +your own Claude subscription, with the token `claude setup-token` prints: +`CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat… npm run dev`. Subscription calls go through the Claude Agent +SDK, count against your plan's limits and start a little slower; that route is for the owner's own +use on their own machine. + +`npm run build && npm start` serves the production build. + +| Variable | Default | | +|---|---|---| +| `ANTHROPIC_API_KEY` | unset | Enables generation. The key stays in the server process. | +| `CLAUDE_CODE_OAUTH_TOKEN` | unset | A subscription token, used when no API key is set. A token put in `ANTHROPIC_API_KEY` by mistake is moved here. | +| `IE_MODEL` | `claude-opus-5-5` | Model for every call. | +| `IE_LLM` | `claude` with a key, `subscription` with a token, else `off` | `mock`: a deterministic stand-in (the tests). | +| `IE_DATA` | `.data` | Where the library and its caches are kept. Delete it to start again from the seed and the starter documents. | +| `IE_LIBRARY` | `library` | Starter documents, each imported once. | +| `IE_USER` | your login name | The name on commits the server makes for you (the page lets you change yours with `/user`). | +| `IE_WIKI` | `live` | `mock`: built-in test articles, no network (the browser tests); `off`: every `/api/wiki/*` route answers 503. | +| `IE_WIKI_LANG` | `en` | Which Wikipedia. | +| `IE_WIKI_CONTACT` | unset | An email address, an `https://` URL or `User:Name` for the User-Agent of Wikipedia requests. Without it requests are spaced 6.5 s apart (the page says so once, the first time it is slow); with it, 1 s. Nothing else about you is sent. | +| `IE_WEB` | `on` when a model is configured | `off` takes web search and fetch away from the editor agent, whatever the page asks. | +| `IE_WEB_SEARCHES`, `IE_WEB_FETCHES` | `5`, `5` | Searches and page reads one request to the editor may make. | +| `IE_EMBED` | on | Local embeddings for link discovery (bge-small, loaded on first use in a worker thread, about 560 MB of memory). `off`: links are found by text alone. `fake`: hashed words, no download (the tests). | +| `IE_EMBED_MODEL` | `Xenova/bge-small-en-v1.5` | Downloaded once into `IE_DATA/models/`. `Snowflake/snowflake-arctic-embed-xs` is a drop-in alternative. | +| `IE_EMBED_THREADS` | `4` | ONNX threads for the embedding model. | +| `IE_EMBED_OFFLINE` | unset | `1`: never download, use cached model files only. | +| `PORT` | `4747` | | + +For the tests: `IE_MOCK_DELAY` (ms per mock token), `IE_WIKI_MOCK_BULK_MS` (delay on background +Wikipedia requests), `IE_PROD=1` and `IE_DIST` (serve a build, and which one), `IE_E2E_PORT` and +`IE_E2E_DATA` (playwright.config.ts). + +## Using it + +Press `?` for every key. The short version: + +- Focus is a **node** and a **grain**. `j` `k` move, `l` opens, `h` closes. `i` narrows the grain + (node → sentence → word), `Esc` widens it. +- `e` goes deeper on whatever is focused. Text with a dotted underline already has an expansion; + anything else is written on request. `d` `y` `x` `c` ask for a definition, a reason, an example, + an objection; `:` asks your own question. The size of the selection decides the form: a word or + two gets an inline gloss, a sentence a margin note, several sentences an inset passage, a node + child sections. +- `c` edits, `r` renames, `a` adds, `D` deletes, `u` undoes (the last edit made in this tab, + wherever it was). On a node, `:` hands an instruction to the editor agent; `Esc` stops it. +- `g` opens history: commits, branches, conflicts. `f` shows only what touched the current + document; `r` reverts the current document to a commit, leaving the rest of the library alone. +- The library is the first page. `l` or `Enter` opens a document in place; `h` or `Esc` at its top + steps back out. `/` jumps to any section in any document. +- `m` (or a click on the title) opens the documents menu: type to filter, `Enter` opens. `Esc` + moves to the list, where `n` makes a document, `r` renames, `s` duplicates, `D` deletes (`u` + brings it back), `x` saves it as a `.md` file and `i` imports one (dropping a file on the menu + works too). From the command bar: `/new`, `/open`, `/rename`, `/duplicate`, `/export`, + `/import`. All of these are ordinary edits of the library, made in the browser's replica. +- Edits are saved as they are made; the top bar says `saved` once the server has them all. +- On a window 1600 px wide or more the page opens as panes side by side, after Andy Matuschak's + notes: the library, the open document, its open sections. Following a link opens its target in + the next pane; moving back left with `h` closes nothing; `q` closes panes. `v` switches between + panes and the single column, `/view auto|column|panes` sets it. + +### Links and Wikipedia + +- A node can have a **target**: a Wikipedia article, another node in the library, or a web page. + A note with a target and no text of its own is a **link**. Linked words get a thin underline and + a mark after them, after gwern.net: **W** Wikipedia, **§** a node in this library, **↗** the web. + A note that also links keeps its dotted underline and gets the mark. +- Hovering linked words, or landing on them with `Tab`, previews the target. `Enter` opens it: in + panes in the next pane; in the column a preview first, then the node (Back returns) or the + article as a page of its own. `L` opens a node's own target; a web page opens in a new tab. +- An article is shown as a tree, so the same keys work: its sections are rows, `Tab` walks its + links, `Enter` opens one. A disambiguation page lists its senses. `W` opens the article on + wikipedia.org. Article text is set apart (sans-serif, tinted, under a W) and carries its licence + line. +- Under an open node, **Linked from** lists what links to it; under an article, **Mentioned in** + lists the library's nodes that link to it. +- To link by hand, select words (`i`, widen with `H` `L`) and press `w`: the picker offers library + sections and notes, Wikipedia articles and, for a pasted address, the web page. `w` on a link + retargets it, `D` removes it; `:/link target` and `:/unlink` do the same. +- A link to a deleted node stays in the text, marked broken, with the document and section titles + it pointed to, so undoing the delete finds it again. + +### Links found for you + +- Whenever text is written (an edit saved, text a model wrote, a file imported) the server scans it + in the background: phrases that are another section's title, sections of other documents close in + meaning, and Wikipedia articles, each checked against the text. These scans ask Wikipedia only + after anything a person is waiting for. +- What is found is **suggested** (a faint dashed underline). `Tab` reaches suggestions; `y` links + one, `n` declines it (remembered in the node, on every replica). `S` reviews a document's + suggestions one by one. `/autolink on` also makes the surest at once, as one commit (`u` takes it + back); it is opt-in because that tier measured 0.84 precision on unseen documents. + `/autolink off` scans nothing by itself. +- In the body editor `[[` opens a completer (library titles, then Wikipedia). A bare `[[term]]` + left in the text is looked up on save. +- Under the node being read, **Related** lists sections of other documents close in meaning. + `1`–`5` with words selected links them to that row; on the node, goes there. +- `/linkdoc` and `/linkall` scan the document or the library in the background, with progress in + the status line (`/linkcancel` stops). +- A model writing a note or sections is given a few nearby library nodes and may mark phrases + `[[phrase]]`; the marks never show and each is checked before it becomes a link. The editor + agent has a `suggest_links` tool. + +How the rule was tuned and measured: [docs/wikipedia.md](docs/wikipedia.md). + +### Web research + +The editor agent can search the web and read pages, and nothing else, only when asked: by +`:/research question` on a node, or by a request that plainly asks for it ("look up", "search the +web", "find sources", "cite sources", "fact-check"; a fixed rule, not a model's guess). A panel +above the status line lists each search, page and edit as it happens, then a summary and the +sources linked. `Esc` stops a run and keeps nothing of it (its edits were on its own copy). + +Every claim taken from the web is linked (↗) to the page it came from, and only pages retrieved in +that run may be cited; any other address is refused. Each request may make at most +`IE_WEB_SEARCHES` searches and `IE_WEB_FETCHES` reads. Page text is treated as data, never +instructions. + +What is sent where: + +- **With an API key**, searches and fetches are Anthropic's server tools, run by Anthropic during + the call (pages are fetched from Anthropic's servers). Fetch may only read addresses from the + request, the document sent with it, or an earlier search or fetch of the run; dynamic filtering + (which runs code) is off. +- **On a subscription**, Claude Code is given exactly WebSearch and WebFetch. WebFetch fetches the + page **from this machine** and a small model summarises it. A guard in the server refuses every + other tool, any non-public address, any page the run's searches did not return and the request + did not name, and anything past the caps. +- **With `IE_LLM=mock`** nothing leaves the machine. + +## How it works + +- **`src/core/model.ts`** The library is a tree of nodes in a [Loro](https://loro.dev) CRDT. A node + is a section (listed under its parent) or a note (anchored to a span of its parent's text by CRDT + cursors). One op API, `create / update / replace / delete / move / copy / bless`, is used by every + writer: the keyboard, the editor agent and `POST /api/ops`. +- **Staleness is computed, not stored.** Each node remembers a hash of the children and of the + parent text it was last reconciled with; a mismatch makes it stale in that direction. A person's + edits pin a node: flagged when stale, never rewritten. The library and its documents are not + reconciled with each other. +- **Snapshots are patched, not rebuilt**: a change re-reads only the nodes it wrote, so an edit + costs what it touches, whatever the size of the library. +- **`src/core/repo.ts`** Every commit records the SHA-256 of the tree, so any checkout can be + verified. Merging is structural (the CRDT) and then semantic: base, ours and theirs are compared + node by node and what a character merge cannot see becomes a conflict record. +- **`src/llm/`** Prompts and the tasks built on them: expand a selection, deepen a leaf, cascade + after an edit (a resolver decides how far up), resolve conflicts, and the editor agent, which + works on a fork and merges back. A prompt carries the focused node's document only. +- **`src/core/ref.ts`, `src/core/links.ts`** Targets, the backlinks index, finding a node target + again, and `applyLinks`, which links a batch of spans in one commit. +- **`src/core/format.ts`, `seed.ts`, `library.ts`** The text format, writing a parsed tree into the + library, and the document operations and addresses. +- **`server/`** Relays updates between replicas and persists them (`library.ts`), proxies model + calls (`claude.ts`, `subscription.ts`, `usage.ts`, `web.ts`), Wikipedia (`wiki.ts`, `wikiHtml.ts`, + `wikiRoutes.ts`, `wikiMock.ts`), local embeddings (`embed.ts`), link discovery (`links/`), and + migrates data from older layouts (`migrate.ts`). +- **`src/ui/`** The browser's replica of the library (`session.ts`, kept in IndexedDB), the store + and keymap, and the page. + +## The library + +On disk: + +``` +IE_DATA/library/.loro the library, one Loro snapshot per branch +IE_DATA/library.json starter documents already imported +IE_DATA/links/pending.json link suggestions waiting for a writer (derived) +IE_DATA/vectors/nodes.* the library's sections as vectors (derived) +IE_DATA/wiki-cache/ Wikipedia answers (derived) +IE_DATA/models/ the embedding model +``` + +Each document has a slug, made from its title when it is created and kept on rename, and a title. + +| | | +|---|---| +| `/` | the library | +| `/doc/` | a document | +| `/doc//` | a node in it (the id is what counts: a moved node is still found) | +| `/n/` | any node | +| `/w//` | a Wikipedia article as a page of its own (the column) | + +The address follows the focus; opening a document or jumping makes a history entry. + +On startup every `library/*.md` whose slug (its file name) has not been imported before is +imported at the end of the library, so a starter document you delete stays deleted. A file that +does not parse is logged and skipped. + +A data directory from an older layout (one database per document under `IE_DATA/docs/`, or a +single document at `IE_DATA/*.loro`) is migrated into one library, histories kept, on the first +start that finds no `IE_DATA/library/`; the old files are moved aside unchanged. If a browser still +holds edits to such a document that never reached the server, the page says so and `:/recover` +saves each as a `.md` file. + +### The text format + +Used for the starter library and for export and import. + +``` +# Document title + +Root text: paragraphs separated by blank lines. Inline markup is only *emphasis* and `code`. + +## A section heading depth is tree depth + +Its text. + +^ "exact words from the text above" gloss define: a few words shown inline +^ "other words" note why: one to three sentences in the margin. +^ "more words" passage: the first paragraph of an inset note. + + A further paragraph of that note, indented two spaces. + ^ "further paragraph" note: a note on the note, anchored in its text. + +## A section about something -> w:Fixed-point combinator + +^ "words" link -> w:Octopus a link: a target and no text +^ "other words" note why -> w:Hoyle state: a note that also has a target +^ "a phrase" link -> /fixed-points/Recursion without names/How Y works +^ "nearby" link -> ./A section about something +^ "a quote" link -> /octopus-minds/Arms that decide ^"tastes what it touches" +^ "the web" link -> https://example.org/page "Its title" +``` + +A `^` line is a note on the section above it, or, indented, on the note above: `^ "quote" form +[lens]: text`, where form is `gloss`, `note` or `passage` and the lens is `elaborate` (default), +`define`, `why`, `example`, `challenge` or any question. The quote must be exact words of the +parent's text (the first occurrence is anchored); a missing quote is an error naming the file, +line, section and quote. A target is `w:Title` (`w.fr:Titre` for another language), a node by its +document's slug and section titles (`./Section` in the same document, `^"quote"` for a note there), +or an `http(s)` address with an optional title. A target containing `: ` is quoted; in a path `\/`, +`\^` and `\\` escape a slash, a caret and a backslash. Wrapped lines join with a space; a line +ending in `\` keeps its break; a text line starting with `#`, `^` or `\` is written with a `\` in +front. Imported documents are written as the model, all reconciled, so nothing starts stale. + +Export writes each note with the current text of its anchor; orphaned notes and sections under a +note have no place in the format and are left out and counted. Export then import gives back the +same tree. + +### HTTP API + +`<branch>` defaults to `main`. Node ids are the library's, so one batch of ops can span documents. + +| | | +|---|---| +| `GET /api/tree[/<branch>]` | the whole library as JSON, with conflicts and recent history | +| `POST /api/ops[/<branch>]` | `{ ops, message?, author?, actor? }`, applied as one commit. `create` and `update` take `ref`: `{ "kind": "wiki", "title", "lang" }`, `{ "kind": "node", "id", "doc", "path" }` or `{ "kind": "url", "url", "title" }`; `"ref": null` removes it | +| `GET /api/docs` | the documents, in library order: `{ node, slug, title, excerpt }` | +| `POST /api/docs` `{ title }` | a new blank document | +| `POST /api/docs/import?name=file.md` | body: the file (2 MB at most); 422 with `problems` if it does not parse | +| `GET` / `PATCH {title}` / `DELETE /api/docs/<slug>` | read, rename, delete (undoable) | +| `POST /api/docs/<slug>/duplicate` `{ title }` | a copy of the document | +| `GET /api/docs/<slug>/export[/<branch>]` | the text format; header `x-skipped` counts what was left out | +| `GET /api/docs/<slug>/tree[/<branch>]`, `POST /api/docs/<slug>/ops[/<branch>]` | one document's subtree with its conflicts; ops as above | +| `GET /api/wiki/…` | Wikipedia through the server's cache: `summary`, `article` (`&full=1` for every section), `section`, `senses`, `suggest`, `search`, `lookup` (server/wikiRoutes.ts) | +| `POST /api/links/scan` `{ node }` | scan a node and record what is found as pending | +| `GET /api/links/pending?doc=<slug>&tier=auto\|suggest` | pending suggestions with the context a reviewer needs | +| `POST /api/links/accept` / `reject` `{ ids, author? }` | link them in one commit, or record them as declined | +| `POST` / `GET` / `DELETE /api/links/jobs` `{ scope: "doc" \| "library", doc? }` | a background scan: start, progress, cancel | +| `GET /api/links/related?node=`, `/nearby?node=`, `/status` | the Related list, the nearby list a model is given, the scanner's state | +| `GET /api/state`, `/api/usage`, `/api/events`, `/api/branch/<b>`, `POST /api/sync/<b>`, `POST /api/llm/…` | what the page uses | + +An outside agent reads and writes with the same ops the keyboard uses: + +```sh +curl localhost:4747/api/docs/tides/tree +curl localhost:4747/api/ops -H 'content-type: application/json' -d '{ + "author": "my-agent", "message": "Add a remark", + "ops": [{ "op": "create", "parent": "<node id>", "title": "A remark", "body": "Text." }] +}' +curl localhost:4747/api/links/jobs -H 'content-type: application/json' -d '{"scope":"library"}' +curl 'localhost:4747/api/links/pending?doc=tides' +curl localhost:4747/api/links/accept -H 'content-type: application/json' -d '{"ids":["…"],"author":"reviewer"}' +``` + +## Checks + +```sh +npm test # unit tests, and a convergence property test (random concurrent ops, 3 replicas) +npm run e2e # the page driven from the keyboard in a real browser, with latency measurements +npm run check # type check +npm run verify # every prompt sentence traced to a section; every seed commit re-hashed +npm run fixtures render DIR && npm run fixtures check DIR + # seeded semantic conflicts with known answers (scripts/fixtures.ts) +``` + +`scripts/linkEval.ts` measures the link scanner against the hand labels in `tests/fixtures/`. + +## Known limits + +- There is no access control: the server binds to localhost and trusts whoever can reach it. +- Undoing or reverting a deletion re-creates nodes under new ids: content, anchors and links that + carry a path are restored; anything else that referred to the old ids is not. +- Semantic conflicts are detected on every sync but resolved by a model only after an explicit + merge, and only within a document. Two replicas resolving one conflict at once conflict again. + Two replicas pointing one link at different targets is left to a person (`1` `2` in history). +- Export cannot hold a note's title, sections under a note, or the prompt sentences the first + document's sections cite. +- Two replicas creating documents with the same slug at once both keep it; the first in the library + wins the address. Two replicas linking the same words both keep their link. +- In history, the documents a commit touched are placed by where its nodes are now: a commit that + only deleted names none. +- Articles are shown without images, references or infoboxes. +- Web research: that queries never carry the document's text rests on the agent's instructions, + not a check, and a cited source is checked to have been retrieved, not to say what was written. + +## Third-party material + +- `server/links/words.txt`: the first 20,000 words of FrequencyWords `en_50k` (2018, from + OpenSubtitles) by Hermit Dave, https://github.com/hermitdave/FrequencyWords, filtered to plain + lower-case words, under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). +- Wikipedia text shown in the page is fetched at run time and shown with its attribution, under + CC BY-SA 4.0. The test articles in `server/wikiMock.ts` were written for the tests. +- The embedding model (bge-small-en-v1.5, MIT) is downloaded at run time, not bundled. diff --git a/docs/wikipedia.md b/docs/wikipedia.md new file mode 100644 index 0000000..35dc596 --- /dev/null +++ b/docs/wikipedia.md @@ -0,0 +1,326 @@ +# Wikipedia and local semantic search + +The findings and decisions behind `server/wiki.ts`, `server/embed.ts` and `server/links/`. Sources +were read on 14 November 2026. The Wikimedia rate limits are new this year and its own page calls +them "subject to experimentation and change", so check the links again before relying on the +numbers. + +## 1. What an unauthenticated client may do + +**Rate limits.** [Wikimedia APIs/Rate limits](https://www.mediawiki.org/wiki/Wikimedia_APIs/Rate_limits) +(last edited 8 Nov 2026). The limits apply per user across the Action API and the REST APIs: + +| Client | Requests per minute | +|---|---| +| Unidentified ("no identifying traits beyond IP address") | 10 | +| Unauthenticated browser requests | 200 | +| Unauthenticated bots with a compliant User-Agent | 200 | +| Authenticated, new account or few edits | 200 | +| Authenticated, established editor | 2000 | +| Bot-flagged accounts, Toolforge with compliant UA, granted exemptions | exempt (robot policy still applies) | + +The same page says to "limit concurrency to 3 or fewer requests" and to "respect the Retry-After +header on 429 responses". 429 and 503 "typically include Retry-After"; without one, "wait at least +five seconds or use exponential back-off". It mentions no headers that report remaining quota, +and the live responses had none. The limits are not split by endpoint family: one budget covers +the Action API and REST together. The [changelog](https://www.mediawiki.org/wiki/Wikimedia_APIs/Changelog) +dates the rollout: Phase 1 enforcement from 12 Mar 2026, Phase 2 for identified requests from the +week of 28 Apr 2026, and the API Portal (api.wikimedia.org) sunset in June 2026. + +**The User-Agent is parsed by machine, and the contact in it decides the tier.** +[User-Agent policy](https://foundation.wikimedia.org/wiki/Policy:Wikimedia_Foundation_User-Agent_Policy) +(edited 27 Mar 2026): a client should identify itself "in a way that isn't going to be confused +with many other bots, and supplying some way of contacting you, the operator". The format is +`<client name>/<version> (<contact information>) <library>/<version>`, and the contact is "an +email address, a website, or a wiki user", e.g. `(wikipedia:de; User:DuesenBot)`. On the +[rate-limit talk page](https://www.mediawiki.org/wiki/Talk:Wikimedia_APIs/Rate_limits) WMF staff +explain how it is enforced. A contact the gateway did not recognise "dropped you to the lowest rate +limit tier". The contact must match "the regex used for extracting the contact info", which reads +the parenthesised part as a semicolon-separated list with no spaces inside an element, and only +the last element is used (15 Apr 2026). A client that sent `(wikipedia:en User:Name)` without the +semicolon was throttled after about 500 requests; with the semicolon it ran 2,500 requests at 1/s +without a 429. Browser requests are limited by IP or user id, "not based on the user agent at all". + +*Consequence for this app.* The privacy rule (no name, email or host in the UA) and the policy pull +in opposite directions. With no contact, the default UA `Infinispand/0.1 (personal knowledge tool)` +should be expected to fall in the 10/min "unidentified" tier. I did not provoke a 429 to check +this. The client therefore spaces requests 6.5 s apart when there is no contact. If the owner sets +`IE_WIKI_CONTACT` to an email address, an `https://` URL or `User:Name`, the UA becomes +`Infinispand/0.1 (<contact>)` and the spacing drops to 1 s, a third of the 200/min budget. The +policy does expect a contact. A throwaway address or a wiki user page is enough, and either keeps +the owner's real identity out of the UA. + +**maxlag.** [Manual:Maxlag parameter](https://www.mediawiki.org/wiki/Manual:Maxlag_parameter): +`maxlag=5` is the recommended value on Wikimedia wikis. It applies to any `api.php` request: +"Interactive tasks … may omit it. Noninteractive tasks should always use it." A lag error comes +back as HTTP 200 with `error.code = "maxlag"` and a `Retry-After` header. The client sends it on +bulk work only. + +**Serial requests and batching.** [API:Etiquette](https://www.mediawiki.org/wiki/API:Etiquette) +(edited 13 May 2026) asks for requests "in series rather than in parallel", says "there is no hard +speed limit on read requests", and recommends `Accept-Encoding: gzip`, the pipe (`titles=A|B|C`) +"whenever possible", and caching. + +**Authentication** only raises a new account to the same 200/min a compliant UA already gets (the +2000/min tier needs an established editor account), and Wikimedia Enterprise is overkill for one +user, so neither is used. + +## 2. Endpoints used, and why + +| Need | Request | Notes | +|---|---|---| +| Batch title check | `GET /w/api.php?action=query&format=json&formatversion=2&redirects=1&prop=pageprops\|description&ppprop=disambiguation&titles=A\|B\|…` | "limited to 50 titles per query, or 500 for those with the `apihighlimits` right" ([API:Query](https://www.mediawiki.org/wiki/API:Query)). The answer has `normalized`, `redirects` (with `tofragment`), and `pages` with `missing`/`invalid`. A disambiguation page carries `pageprops.disambiguation`. The short description is in `description`. Pages are not returned in request order, so inputs are mapped back through normalized → redirects. | +| Senses of a disambiguation page | same, with `generator=links&gplnamespace=0&gpllimit=max` on the one title | One request gives every linked article with its description. "Set" returned 73. | +| Title autocomplete | `GET /w/rest.php/v1/search/title?q=…&limit=…` | Documented for this: "a typeahead search that automatically suggests relevant pages by title" ([REST reference](https://www.mediawiki.org/wiki/API:REST_API/Reference)). Returns title, description and thumbnail, limit 1–100. `action=opensearch` returns empty descriptions on Wikimedia wikis ([API:Opensearch](https://www.mediawiki.org/wiki/API:Opensearch)). `list=prefixsearch` gives titles only. The completion index is "updated once a day" ([Help:CirrusSearch](https://www.mediawiki.org/wiki/Help:CirrusSearch)). | +| Full-text search | `GET /w/rest.php/v1/search/page?q=…&limit=…` | Excerpt with `<span class="searchmatch">`, plus description and thumbnail, in one call. `q` takes CirrusSearch syntax: `morelike:Title` (pipe for several), `intitle:`, quotes. There is no parameter for passing context, and no text can be sent other than the query. `list=search` is equivalent (`srlimit` ≤ 500). | +| Preview | `GET /api/rest_v1/page/summary/{title}?redirect=true` | Extract, description, thumbnail, `revision`, `type: "disambiguation"`. Edge-cached (`s-maxage=1209600`), so it is cheap for Wikimedia. rest_v1 is RESTBase, which is being retired: there is no date for `page/summary` ([RESTBase/deprecation](https://www.mediawiki.org/wiki/RESTBase/deprecation)). The client falls back to `prop=extracts\|pageimages\|description\|info` if it disappears. | +| Article by section | `GET /w/api.php?action=parse&page=…&redirects=1&prop=text\|tocdata\|revid\|displaytitle\|properties&disableeditsection=1&disablelimitreport=1&disabletoc=1` | One request for the whole page (Octopus: 480 KB raw, 69 KB after sanitising), split on the server at `div.mw-heading` boundaries and cached for 7 days. A section then costs nothing. `prop=sections` now warns "deprecated … use prop=tocdata". With `section=N`, both come back empty, so the section list cannot be had alongside one section's text. REST `/page/{title}/html` (Parsoid, with `<section>` wrappers) also works; the splitter flattens either. | + +Two route parameters (`server/wikiRoutes.ts`) shape the answers for the UI. `article?full=1` +returns every section's sanitised HTML along with the section list and the `disambiguation` +flag (read from `prop=properties`), so a whole article costs the browser one request and the +server at most one. `summary?cached=1` answers from the server's cache only, fresh or expired, +and never waits on Wikipedia: 404 `reason: "uncached"` when nothing is cached. The UI uses it to +put a summary in a model prompt without delaying the prompt. + +What gets stripped (seen in real output): inline `<style>` (TemplateStyles), `sup.reference` +markers, the reference list, COinS spans (`Z3988`), navboxes, infoboxes, sidebars, hatnotes, +clade tables, the hidden short description, edit links, maintenance boxes and `noprint`. Images +are dropped: each file has its own licence, and the browser would load them from +upload.wikimedia.org. MathML is kept, because the parser now emits native MathML and browsers +render it. + +**Services not used.** The Link Recommendation API ("Add a link") takes an existing article, not +arbitrary text, and is scheduled for deprecation from July 2026; its underlying idea (anchor +dictionary and link probability) is the right one, see §4. CirrusSearch's semantic search is an +internal, undocumented path. The Wikidata Embedding Project searches Wikidata items, is in alpha, +and would send node text off the machine. `wbsearchentities` adds nothing over `search/title`. + +## 3. Licence and attribution + +Article text is CC BY-SA 4.0 (and GFDL where applicable) +([Reusing Wikipedia content](https://en.wikipedia.org/wiki/Wikipedia:Reusing_Wikipedia_content)). +When text is shown in the app it must carry: + +- **Credit**: "a hyperlink or URL to the page(s) being reused" is acceptable. The client gives the + article URL and a permanent link to the revision shown (`oldid`). +- **Licence notice**: name the licence and link to it + (https://creativecommons.org/licenses/by-sa/4.0/). +- **Modifications**: one "must indicate in a reasonable fashion that the original work has been + 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 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. + +The UI must show `attribution.text`, with its links, next to every pane of article text, and next +to summary extracts too. + +## 4. Decision: live API with a disk cache; no local title index + +Measured on two real nodes from `library/` (§6): **2 lookup requests per node of 80–100 +candidates**, about 25 % of them found. Arithmetic, with spacing 1 s (contact set) or 6.5 s (none): + +| Work | Requests | Time with contact | Time without | +|---|---|---|---| +| One edited node, cold: ≤ 100 phrases → 2 batches, plus 0–4 `senses` | 2–6 | 2–6 s | 13–40 s | +| Same node rescanned | 0 | 0 | 0 | +| Autocomplete while typing a link (debounced, superseded requests aborted unsent) | 3–6 per link | ≤ 1/s | unusable, see below | +| Open an article (whole page, then sections free) | 1 | 1 s | 6.5 s | +| Bulk pass, 600 nodes × 60 phrases = 36,000; assume half unique → 18,000 → 360 batches, plus ~600 `senses` | ~1,000 | ~17 min | ~1.8 h | +| Bulk pass, 5,000 nodes (unique phrases grow sub-linearly; say 120,000) → 2,400 batches, plus ~3,000 `senses` | ~5,400 | ~1.5 h | ~10 h | + +At 1 request a second the client uses 30 % of the 200/min budget, serially, with interactive calls +jumping ahead of bulk ones. A local title index is not needed for these volumes. The +`all-titles-in-ns0` dump is 110 MB gzipped, and it has no redirect targets, disambiguation flags or +descriptions: for those you also need `page_props` (486 MB) and `redirect`. Building one would +replace a few hundred cached requests with a gigabyte of downloads and a weekly refresh. + +What would make it necessary: + +1. The client stays in the 10/min tier (no contact can be given) and bulk passes over thousands of + nodes must finish in minutes. +2. Matching every n-gram of every node, rather than an extracted list of candidates: that means + 10⁵–10⁶ lookups per pass. +3. Link-worthiness statistics, which the API does not provide: how often a phrase is used as link + text on Wikipedia (keyphraseness or link probability), and which target it usually points to + (commonness). That is the real case for a local dataset: an anchor-text dictionary built from + the pagelinks/linktarget dumps (7.2 GB and 1.5 GB gzipped), or the "Add a link" model's anchor + tables. It would replace most of the per-phrase checking, not just speed it up. +4. Needing to work offline for long periods. + +**Autocomplete without a contact.** At 6.5 s spacing, server-side autocomplete is slow: set +`IE_WIKI_CONTACT`. (Calling `search/title` from the browser would be the "unauthenticated browser" +tier, 200/min per IP; not done.) + +## 5. What makes a good candidate (from the demonstration) + +- **Batching makes candidates almost free, but most raw n-grams miss.** 57 of 80 and 75 of 80 in the + first run. Every candidate checked costs 1/50 of a request, so over-generating is fine, but a + per-node cap of 80 crowded out the single nouns that mattered (*octopus*, *cephalopod*, + *nautilus*). The extractor should rank noun phrases above arbitrary trigrams. +- **Single common words resolve to junk or to disambiguation pages.** "itself" → *Reflexive + pronoun*, "repeated" → *Rerun*, "twice" → *Twice (South Korean girl group)*, "quickly" → + *Quickly (Bubble tea chain)*. 38 of 95 hits in the second run were disambiguation pages, nearly + all of them ordinary words ("small", "clever", "split"). +- **Case matters past the first letter.** Titles are case-sensitive after the first character: + "Y combinator" is a disambiguation page, while "Y Combinator" is the company. Keep the text's own + casing, and use `search/title` (case-insensitive) as a second try for multi-word misses. +- **Plurals mostly resolve through redirects**: "fixed-point theorems" → *Fixed-point theorem*, + "cephalopods" → *Cephalopod*. Trying a singular form is a cheap extra candidate. +- **Embedding fit separates senses well.** Each candidate was scored by the cosine between the + node text and "Title: short description" (bge-small): + - *Fixed point* senses: *Fixed point (mathematics)* 0.83, then *Fixed-point arithmetic* 0.65 and + *Triple point* 0.62. + - *Y combinator*: *Fixed-point combinator* 0.75 against *Y Combinator* (the company) 0.50. + - "set" in a maths sentence: *Set (mathematics)* 0.66, tied with *Category of sets*; *Set + (deity)* ranked 55th of 73 at 0.48. + - Among direct hits in the octopus node, right senses scored 0.60–0.74 (*Octopus*, *Cephalopod*, + *Squid*, *Nautilus*, *Neuron*). Wrong ones scored 0.34–0.51 (*Fat fetishism* for "gaining", + *Twice*, *Quickly*, *Arriving* the album). + + A threshold near 0.6 for this model separates most of them. Junk such as "therefore" → *Logical + consequence* (0.52) sits just below it, so fit alone does not decide whether something is worth + linking. Combine it with a link-worthiness prior (§4.3) or a rule of noun phrases only. + +## 6. Measured on this machine + +24 live requests in total: 6 raw probes, and 18 through the client with the generic UA, serial, +6.5 s apart. There were no 429s. + +- Node *fixed-points* (201 words, 80 candidates): 2 requests, 23 found, 12 of them disambiguation + pages. Node *octopus-minds* (145 words, 80 candidates): 2 requests, 5 found. A second extraction + (326 words, 100 candidates, single words first): 2 requests, 95 found. +- Repeat scan of both nodes, plus a repeat summary, article and suggest: **0 requests** (196 cache + hits). +- Embeddings: `Xenova/bge-small-en-v1.5`, q8 ONNX, **34 MB** on disk, 384 dimensions, MIT. Load + 0.6 s from cache, 1.5 s including the download. With 4 threads (the default, + `IE_EMBED_THREADS`): **43 paragraphs/s** for ~110-word paragraphs and **450 short strings/s**; + with 8 threads, 61/s and 575/s. Process RSS is about 560 MB once loaded. The 600-node library + embeds in about 15 s. `all-MiniLM-L6-v2` (Apache-2.0, 23 MB) is about 1.3× faster but separates + senses less clearly. + +**Choice of model.** bge-small-en-v1.5 is MIT-licensed, has a 512-token window, has a good MTEB +score for its 33M parameters, and is a first-class transformers.js model. Larger models were +considered and set aside: + +- `jina-embeddings-v5-text-small` (Feb 2026, MTEB-en 71.7) is **CC BY-NC 4.0** and 0.6B parameters. +- EmbeddingGemma-300m is under the Gemma terms and is 10× larger. +- Qwen3-Embedding-0.6B is Apache, but has about 18× the parameters; its CPU speed was not measured. + +`IE_EMBED_MODEL=Snowflake/snowflake-arctic-embed-xs` (Apache-2.0) is a drop-in alternative. + +## 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` +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. + +## 8. Link discovery as built + +`server/links/` (README "Links found for you" says what the writer sees). A scan of one node: + +1. **Candidates** (`extract.ts`). Runs of content words, cut at punctuation, function words, a + possessive, `code` and existing links; every span of one to four words of a run, in the text's + own casing, with a singular variant. Proper names (capitalised away from a sentence's start, or + capitalised again elsewhere in the text, or followed by another capital) and multi-word spans + are always candidates; a single lower-case word only when its rank in the bundled frequency list + (`words.txt`, 20,000 words from FrequencyWords/OpenSubtitles, CC BY-SA 4.0) is past 6,000. A + phrase may not end on a verb form. `[[marks]]` are forced candidates. Measured on the sample: + 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. +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 + 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". +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: + + | | auto (applied unasked) | suggest | + |---|---|---| + | 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) | | + | 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 + node, no overlaps, three links a paragraph counting existing ones, the strongest kept, and a word + already linked inside a longer phrase in the node ("beryllium" beside "beryllium-8") not again. + Without embeddings nothing is applied unasked; the strongest are suggested. + +**Evaluation** (`scripts/linkEval.ts`). Tuning sample (`tests/fixtures/link-labels.json`): the +first 16 sections with 40 words or more of *Octopus minds*, *Fixed points*, *Where the elements +come from* and *The invention of writing* (64 sections; 444 labelled phrases, 165 worth linking, +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). + +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 +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. + +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 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** | + +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 +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 +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" → +*Northern Hemisphere* (well known, not listed). With 32 decisions the precision estimate is +loose, but it is under 0.95, so the default is now **`/autolink suggest`**: nothing is written +without the writer's say; `/autolink on` is an opt-in. The rule was not tuned against the fresh +set. + +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); + *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); + "helium nuclei" → *Alpha particle* (0.67); "Shang" → *Shang dynasty* (0.70). +- wrong, auto: "fixed-point theorem" in a later section of *Fixed points* (labelled not worth a + second link); "beryllium" in a section that also links "beryllium-8"; *Tuning and temperament*: "Pythagorean" → + the section *Pythagorean*. +- wrong, suggest: "mammal" → *Mammal*, "joints" → *Joint*, "pigment" → *Pigment* (ordinary words + that fit the text); "unprovable" → *Independence (mathematical logic)*; "Arabic" → *Arabic* where + the label wanted *Arabic alphabet*. +- rightly dropped: "Bang" → *Explosion* (a sense; "Big Bang" was linked); "Sun" (rank 830); + "Iraq" (a country); "Hoyle" → a surname page; "concealment" → *Oecophoridae* (moths), fit 0.59. + +**Cost.** A node scanned alone, cold: one lookup plus 0–3 sense or search requests (median 2 on +the sample), so 1–4 requests: 7–26 s without a contact, 1–4 s with one. Warm (cached): 0 requests, +46 ms median, 580 ms max per section with the real model (scan time includes embedding the +context and any new "Title: description" strings). Embedding the 252 sections of the starter +library: 3.8 s in the evaluation script; in the server on a first start, 318 sections in 6.8 s on +the worker thread, while `/api/state` kept answering in about 1 ms. A bulk pass over the owner's ~600 nodes should take +about 10,000 phrases → ~200 lookups plus ~1 sense or search per node, ~800 requests: ~85 min +without a contact, ~14 min with one (estimated from the sample, not run). diff --git a/scripts/fixtures.ts b/scripts/fixtures.ts new file mode 100644 index 0000000..0ff4e6e --- /dev/null +++ b/scripts/fixtures.ts @@ -0,0 +1,205 @@ +/** + * Seeded semantic-conflict fixtures: hand-made pairs of concurrent edits whose correct outcome + * is known. The detection half is deterministic and is asserted here directly. The resolution + * half needs a model, so it runs in two steps that work with any model, with or without an API key: + * + * tsx scripts/fixtures.ts render DIR write the exact prompts the app would send, as DIR/<name>.prompt.txt + * tsx scripts/fixtures.ts check DIR read DIR/<name>.response.json, apply it through the app's + * own code path, and check the result against what is known + */ +import { mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs"; +import { join } from "node:path"; +import { Doc, setPeerSource, type NodeId } from "../src/core/model"; +import { mergeBranch, verifyHistory, type MergeReport } from "../src/core/repo"; +import { resolveConflicts, scanContradictions } from "../src/llm/tasks"; +import type { JsonReq, LLM } from "../src/llm/types"; + +interface Fixture { + name: string; + about: string; + build(): { doc: Doc; other: Doc; ids: Record<string, NodeId> }; + /** What the structural merge must report, before any model is involved. */ + detect(report: MergeReport, doc: Doc): string[]; + /** What must be true once the model's answer has been applied. Returns failures. */ + check(doc: Doc, ids: Record<string, NodeId>): string[]; +} + +function base() { + const doc = Doc.create("alice", "Infinispand", "A document that expands without limit."); + const root = doc.snap().root; + const { created } = doc.apply( + [ + { op: "create", parent: root, title: "Latency budget", body: "Pre-generated expansions must paint within 50 ms of the keypress. Generated expansions must show a first token within one second." }, + { op: "create", parent: root, title: "Undo", body: "Every edit is a commit and can be undone." }, + { op: "create", parent: root, title: "Sidenotes", body: "A note of one to three sentences is shown in the margin beside the line it is about." }, + { op: "create", parent: root, title: "Speculation", body: "With speculation on, the expansion of the focused sentence starts before it is asked for." }, + { op: "create", parent: root, title: "Hoisting", body: "Any node can be hoisted to fill the page." }, + { op: "bless", id: root }, + ], + "Base", + { actor: "llm" }, + ); + const [latency, undo, sidenotes, speculation, hoisting] = created; + return { doc, ids: { root, latency, undo, sidenotes, speculation, hoisting } }; +} + +const has = (text: string, ...needles: (string | RegExp)[]) => needles.every((n) => (typeof n === "string" ? text.toLowerCase().includes(n.toLowerCase()) : n.test(text))); + +const fixtures: Fixture[] = [ + { + name: "compatible-additions", + about: "Both sides added a different, compatible clause to the same sentence. The right answer keeps both.", + build() { + const { doc, ids } = base(); + const other = doc.fork("bob"); + doc.apply([{ op: "update", id: ids.sidenotes, body: "A note of one to three sentences is shown in the margin beside the line it is about, and is pushed down if it would overlap the note above it." }], "A: overlap rule"); + other.apply([{ op: "update", id: ids.sidenotes, body: "A note of one to three sentences is shown in the margin beside the line it is about; on screens too narrow for a margin it is set into the column instead." }], "B: narrow screens"); + return { doc, other, ids }; + }, + detect: (r) => (r.conflicts.length === 1 && r.conflicts[0].type === "edit-edit" ? [] : [`expected one edit-edit conflict, got ${JSON.stringify(r.conflicts.map((c) => c.type))}`]), + check(doc, ids) { + const body = doc.snap().nodes[ids.sidenotes].body; + const out: string[] = []; + if (!has(body, "overlap")) out.push("lost side A's overlap rule"); + if (!has(body, "narrow")) out.push("lost side B's narrow-screen rule"); + if (!has(body, "margin")) out.push("lost the original claim"); + return out; + }, + }, + { + name: "incompatible-numbers", + about: "The two sides give different numbers for the same budget. They cannot be blended; the rest of the document says 50 ms.", + build() { + const { doc, ids } = base(); + // Elsewhere in the document, the 50 ms figure is relied on. This is what should decide it. + doc.apply([{ op: "create", parent: ids.root, title: "How we know it works", body: "A scripted keyboard run measures keypress to paint and fails if the 95th percentile exceeds the 50 ms budget." }], "Verification", { actor: "llm" }); + const other = doc.fork("bob"); + doc.apply([{ op: "update", id: ids.latency, body: "Pre-generated expansions must paint within 50 ms of the keypress, measured at the 95th percentile. Generated expansions must show a first token within one second." }], "A: percentile"); + other.apply([{ op: "update", id: ids.latency, body: "Pre-generated expansions must paint within 200 ms of the keypress. Generated expansions must show a first token within one second." }], "B: relax to 200"); + return { doc, other, ids }; + }, + detect: (r) => (r.conflicts.length === 1 && r.conflicts[0].type === "edit-edit" ? [] : ["expected one edit-edit conflict"]), + check(doc, ids) { + const body = doc.snap().nodes[ids.latency].body; + const c = doc.conflicts()[0]; + const out: string[] = []; + if (!has(body, "50 ms")) out.push("did not keep the 50 ms budget the rest of the document relies on"); + if (has(body, "200")) out.push("kept or blended in the contradicting 200 ms figure"); + if (/(\d+)\s*[-–]\s*(\d+)\s*ms|between 50 and 200/i.test(body)) out.push("blended the two numbers into a range neither side wrote"); + if (!c.rationale || c.rationale.length < 20) out.push("gave no usable rationale for a human to overrule"); + return out; + }, + }, + { + name: "edit-vs-delete", + about: "One side deleted a section; the other had just rewritten it with substantial new content. The edit should come back.", + build() { + const { doc, ids } = base(); + const other = doc.fork("bob"); + doc.apply([{ op: "delete", id: ids.speculation }], "A: delete speculation"); + other.apply([{ op: "update", id: ids.speculation, body: "With speculation on, the expansion of the focused sentence starts 350 ms after focus settles, before it is asked for. If the reader then presses e, the stream already in flight is adopted, so the first words appear at once. It is off by default because it spends tokens on expansions that may never be read." }], "B: explain speculation"); + return { doc, other, ids }; + }, + detect: (r, doc) => { + const out: string[] = []; + if (r.conflicts.length !== 1 || r.conflicts[0].type !== "edit-delete") out.push("expected one edit-delete conflict"); + if (Object.values(doc.snap().nodes).some((n) => n.title === "Speculation")) out.push("the structural merge should let the deletion win"); + return out; + }, + check(doc) { + const restored = Object.values(doc.snap().nodes).find((n) => n.title === "Speculation"); + if (!restored) return ["let the deletion stand, discarding the other side's new work"]; + return has(restored.body, "350") ? [] : ["restored the section but lost the new content"]; + }, + }, + { + name: "cross-node-contradiction", + about: "The edits touch different nodes, so the merge is clean, but one side's new claim contradicts the other's. A second pair of edits is unrelated and must not be reported.", + build() { + const { doc, ids } = base(); + const other = doc.fork("bob"); + doc.apply([{ op: "update", id: ids.undo, body: "Every edit is a commit and can be undone. Undo history is unlimited: every step back to the creation of the document is kept." }], "A: unlimited undo"); + doc.apply([{ op: "update", id: ids.hoisting, body: "Any node can be hoisted to fill the page, and a breadcrumb leads back up." }], "A: breadcrumb"); + other.apply([{ op: "create", parent: ids.root, title: "Memory limits", body: "To bound memory, the editor keeps only the last 20 undo steps; older steps are discarded and cannot be undone." }], "B: undo cap"); + other.apply([{ op: "update", id: ids.sidenotes, body: "A note of one to three sentences is shown in the right margin beside the line it is about." }], "B: right margin"); + return { doc, other, ids }; + }, + detect: (r) => (r.kind === "merge" && r.conflicts.length === 0 ? [] : ["expected a clean structural merge with no conflicts"]), + check(doc, ids) { + const found = doc.conflicts().filter((c) => c.type === "contradiction"); + const out: string[] = []; + if (found.length !== 1) return [`expected exactly one contradiction, got ${found.length}`]; + const snap = doc.snap(); + const titles = [found[0].node, found[0].other!].map((id) => snap.nodes[id]?.title).sort(); + if (titles.join("|") !== "Memory limits|Undo") out.push(`reported the wrong pair: ${titles.join(" / ")}`); + const undo = snap.nodes[ids.undo].body; + const limits = Object.values(snap.nodes).find((n) => n.title === "Memory limits")!.body; + if (has(undo, "unlimited") && has(limits, "last 20")) out.push("the two nodes still contradict after the resolution"); + if (!has(snap.nodes[ids.hoisting].body, "breadcrumb") || !has(snap.nodes[ids.sidenotes].body, "right margin")) out.push("disturbed the unrelated edits"); + return out; + }, + }, +]; + +/** A provider that records the request, or answers from a file. */ +function scripted(dir: string, name: string, mode: "render" | "check"): LLM { + const refuse = () => Promise.reject(new Error("not used")); + return { + kind: "mock", + stream: refuse, + turn: refuse, + async json<T>(req: JsonReq): Promise<T> { + const file = join(dir, `${name}.response.json`); + if (mode === "render") { + const shape = + req.schema === "resolve" + ? '{"resolutions": [{"id": "<conflict id>", "text": "<the text the node should have>", "rationale": "<one or two sentences>"}]}' + : '{"contradictions": [{"node": "<id of the first node>", "other": "<id of the second node>", "explanation": "<one sentence>", "text": "<revised body for the second node>"}]}'; + writeFileSync( + join(dir, `${name}.prompt.txt`), + `=== SYSTEM ===\n${req.system}\n\n=== USER (context) ===\n${req.context}\n\n=== USER (request) ===\n${req.prompt}\n\n=== REPLY FORMAT ===\nReply with a single JSON object of exactly this shape and nothing else:\n${shape}\n`, + ); + throw new Rendered(); + } + if (!existsSync(file)) throw new Error(`missing ${file}`); + return JSON.parse(readFileSync(file, "utf8")) as T; + }, + }; +} +class Rendered extends Error {} + +const [mode, dir] = process.argv.slice(2) as ["render" | "check", string]; +if (!["render", "check"].includes(mode) || !dir) { + console.error("usage: tsx scripts/fixtures.ts render|check DIR"); + process.exit(2); +} +mkdirSync(dir, { recursive: true }); +let failed = 0; +for (const f of fixtures) { + // Fixed peer ids, so node and conflict ids are the same when rendering and when checking. + let peer = 1000n; + setPeerSource(() => peer++); + const { doc, other, ids } = f.build(); + const report = mergeBranch(doc, other, "bob"); + const detection = f.detect(report, doc); + const llm = scripted(dir, f.name, mode); + try { + if (f.name === "cross-node-contradiction") await scanContradictions(llm, doc, report); + else await resolveConflicts(llm, doc); + } catch (err) { + if (!(err instanceof Rendered)) throw err; + } + if (mode === "render") { + console.log(`${detection.length ? "FAIL" : "ok "} detect ${f.name}${detection.length ? ": " + detection.join("; ") : ""}`); + failed += detection.length ? 1 : 0; + continue; + } + const problems = [...detection, ...f.check(doc, ids)]; + const history = verifyHistory(doc); + if (history.mismatches.length || history.unhashed) problems.push("history no longer verifies"); + console.log(`${problems.length ? "FAIL" : "pass"} ${f.name}: ${f.about}`); + for (const p of problems) console.log(` - ${p}`); + failed += problems.length ? 1 : 0; +} +console.log(mode === "render" ? `\nprompts written to ${dir}` : `\n${fixtures.length - failed} of ${fixtures.length} fixtures pass`); +process.exit(failed ? 1 : 0); diff --git a/scripts/linkEval.ts b/scripts/linkEval.ts new file mode 100644 index 0000000..f8f9f46 --- /dev/null +++ b/scripts/linkEval.ts @@ -0,0 +1,206 @@ +/** + * 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 + * sampled sections, write their traces + * IE_DATA=/tmp/x npx tsx scripts/linkEval.ts eval [docs…] 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 + * + * The sample is the first SAMPLE sections (in reading order, document text included) of each named + * document that have at least 40 words. Labels: tests/fixtures/link-labels.json, one entry per + * phrase (by its normalised key) per section, saying whether it is worth linking and to what. + * `warm` goes to Wikipedia through the client (serial, spaced as it enforces) and stops at a budget + * of requests (IE_EVAL_BUDGET, default 380); nothing but candidate phrases is sent. The embedding + * model is the real one unless IE_EMBED says otherwise. + */ +import { readFileSync, readdirSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { importDoc } from "../src/core/library"; +import { Doc, ancestorsInDoc, documents, sections, type NodeId, type Snap } from "../src/core/model"; +import { embedder } from "../server/embed"; +import { extract } from "../server/links/extract"; +import { NodeIndex } from "../server/links/nodeIndex"; +import { Linker, type TraceRow, type Tuning } from "../server/links/scan"; +import { WikiClient } from "../server/wiki"; + +const [mode = "eval", ...rest] = process.argv.slice(2); +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 LABELS = resolve("tests/fixtures/link-labels.json"); + +// The whole starter library, so that titles in other documents can be matched as they would be. +const doc = Doc.library("eval"); +for (const f of readdirSync("library").filter((x) => x.endsWith(".md")).sort()) importDoc(doc, readFileSync(join("library", f), "utf8"), f, { creator: "eval", slug: f.replace(/\.md$/, "") }); +const snap = doc.snap(); + +const words = (s: string) => s.split(/\s+/).filter(Boolean).length; +function sample(snap: Snap, slug: string): NodeId[] { + const d = documents(snap).find((x) => snap.nodes[x].slug === slug); + if (!d) throw new Error(`no document ${slug}`); + const out: NodeId[] = []; + const visit = (id: NodeId) => { + if (out.length < SAMPLE && words(snap.nodes[id].body) >= 40) out.push(id); + sections(snap, id).forEach(visit); + }; + visit(d); + return out; +} +const pathOf = (id: NodeId) => [...ancestorsInDoc(snap, id).reverse().slice(1), id].map((x) => snap.nodes[x].title).join(" › ") || snap.nodes[id].title; + +// `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`); + writeFileSync(file, JSON.stringify(out, null, 1)); + console.error(`${out.length} sections → ${file}`); + process.exit(0); +} + +const live = mode === "warm"; +const wiki = new WikiClient({ + dataDir: DATA, + // Offline modes answer from the cache alone: anything uncached is "unavailable", never fetched. + ...(live ? {} : { fetch: (async () => { throw new TypeError("offline (eval)"); }) as typeof fetch, offlineHoldMs: 0, spacingMs: 0 }), +}); +const index = new NodeIndex(() => doc, { file: join(DATA, "vectors", "eval-nodes"), embedder: embedder(), delayMs: 0 }); +const tuning: Partial<Tuning> = JSON.parse(process.env.IE_EVAL_TUNING ?? "{}"); +const linker = new Linker({ doc: () => doc, wiki: () => wiki, embedder: embedder(), index, tuning }); + +const t0 = performance.now(); +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 }))); + +if (live) { + // One deduplicated lookup of every candidate of every sampled section first: 50 phrases a request. + const variants = [...new Set(nodes.flatMap(({ id }) => extract(snap.nodes[id].body, { skip: new Set() }).flatMap((c) => c.variants)))]; + console.error(`${nodes.length} sections, ${variants.length} distinct phrases to look up`); + await wiki.lookup(variants, { priority: "bulk" }); + wiki.flush(); + console.error(`lookups done: ${wiki.requests} requests`); +} + +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) { + if (live && wiki.requests >= BUDGET) { + console.error(`budget of ${BUDGET} requests reached; stopping before ${pathOf(id)}`); + break; + } + const trace: TraceRow[] = []; + const r = await linker.scan({ node: id, priority: live ? "bulk" : "interactive", trace }); + perNode.push({ node: pathOf(id), ms: r.stats.ms, requests: r.stats.requests }); + const body = snap.nodes[id].body; + 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) }); + } + 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})`); +} +wiki.flush(); + +if (mode === "warm" || mode === "trace") { + const file = join(DATA, `trace-${DOCS.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); + console.error(`scan time per section: median ${ms[ms.length >> 1]} ms, max ${ms[ms.length - 1]} ms; requests per section: ${(perNode.reduce((a, p) => a + p.requests, 0) / Math.max(1, perNode.length)).toFixed(2)}`); + process.exit(0); +} + +// ---- heldout: closed-world scoring against a list of everything worth linking ---- + +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 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); + const line = (name: string, set: Row[]) => { + 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`); + 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)}`; + console.log("\nauto errors:"); + for (const r of chosen.filter((r) => r.tier === "auto" && !ok(r))) console.log(fmt(r)); + console.log("\nauto right:"); + for (const r of chosen.filter((r) => r.tier === "auto" && ok(r))) console.log(fmt(r)); + if (process.env.IE_EVAL_SUGGEST) { + console.log("\nsuggest errors:"); + for (const r of chosen.filter((r) => r.tier === "suggest" && !ok(r))) console.log(fmt(r)); + } + process.exit(0); +} + +// ---- eval ---- + +interface Label { + doc: string; + node: string; + key: string; + phrase: string; + /** yes: worth linking, to `target`. no: not worth linking. */ + label: "yes" | "no"; + target?: string; + note?: string; +} +const labels: Label[] = JSON.parse(readFileSync(LABELS, "utf8")).labels; +const mine = labels.filter((l) => DOCS.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)); +const correct = (r: Row) => { + const l = find(r); + return !!l && l.label === "yes" && l.target === r.target; +}; +const yes = mine.filter((l) => l.label === "yes").length; +const report = (name: string, set: Row[]) => { + const labelled = set.filter(find); + const right = labelled.filter(correct).length; + const p = labelled.length ? right / labelled.length : 1; + 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)`); +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")}`); +const show = (title: string, list: Row[]) => { + if (!list.length) return; + console.log(`\n${title}`); + for (const r of list) { + const l = find(r); + console.log(` [${r.tier ?? "drop"} ${r.score.toFixed(3)} fit ${r.fit ?? "-"}] “${r.phrase}” → ${r.target}${l ? ` label: ${l.label}${l.target && l.target !== r.target ? ` (${l.target})` : ""}` : ""} (${r.why})`); + } +}; +const wrong = chosen.filter((r) => find(r) && !correct(r)); +show("wrong (chosen, label disagrees):", wrong); +const missed = mine.filter((l) => l.label === "yes" && !chosen.some((r) => r.doc === l.doc && r.node === l.node && r.key === l.key && correct(r))); +if (missed.length && process.env.IE_EVAL_MISSES) { + console.log("\nmissed (worth linking, not chosen or wrong target):"); + for (const l of missed) { + const r = rows.find((x) => x.doc === l.doc && x.node === l.node && x.key === l.key); + console.log(` ${l.doc} | ${l.node} | “${l.phrase}” → ${l.target}${r ? ` scanner: ${r.target} [${r.tier ?? "drop"} ${r.score} fit ${r.fit}] ${r.why}` : " (never resolved)"}`); + } +} +if (process.env.IE_EVAL_RIGHT) show("right:", chosen.filter(correct)); +// Every labelled row with what judge() saw, for tuning (IE_EVAL_DUMP=file). +if (process.env.IE_EVAL_DUMP) { + const dump = rows.map((r) => ({ ...r, label: find(r)?.label ?? null, labelTarget: find(r)?.target ?? null, right: correct(r) })); + writeFileSync(process.env.IE_EVAL_DUMP, JSON.stringify(dump, null, 1)); +} +// The embedding worker is unref'd, but a script is done here whatever is still open. +process.exit(0); diff --git a/scripts/verify.ts b/scripts/verify.ts new file mode 100644 index 0000000..ec165f7 --- /dev/null +++ b/scripts/verify.ts @@ -0,0 +1,51 @@ +/** + * Checks on the seed document that do not need a browser. + * + * tsx scripts/verify.ts coverage of the prompt + history verification + * tsx scripts/verify.ts entail F write the parent/children pairs to F, for a fresh model to judge + */ +import { readFileSync, writeFileSync } from "node:fs"; +import { Doc, descendants, sections } from "../src/core/model"; +import { verifyHistory } from "../src/core/repo"; +import { writeSeed } from "../src/core/seed"; +import { overlaps, plain, sentences } from "../src/core/text"; +import { seed } from "../src/seed/tree"; + +const prompt = readFileSync(new URL("../src/seed/prompt.txt", import.meta.url), "utf8"); +const doc = Doc.library("seed"); +const first = writeSeed(doc, prompt, seed); +const snap = doc.snap(); +const root = snap.nodes[first]; + +if (process.argv[2] === "entail") { + // Each node that has sections, with those sections: the claim is that the first is a + // summary supported by the rest. The document itself is excluded: it is the prompt, not a summary. + const pairs = descendants(snap, first) + .map((id) => snap.nodes[id]) + .filter((n) => n.kind === "section" && sections(snap, n.id).length) + .map((n) => ({ + id: n.id, + title: n.title, + summary: plain(n.body), + sections: sections(snap, n.id).map((c) => ({ title: snap.nodes[c].title, body: plain(snap.nodes[c].body) })), + })); + writeFileSync(process.argv[3], JSON.stringify(pairs, null, 2)); + console.log(`wrote ${pairs.length} parent/children pairs to ${process.argv[3]}`); +} else { + const tops = sections(snap, first); + const all = sentences(root.body); + let uncovered = 0; + for (const s of all) { + const by = tops.filter((id) => snap.nodes[id].anchors.some((a) => overlaps(s, [a.start, a.end]))); + if (!by.length) { + uncovered++; + console.log(`UNCOVERED: ${root.body.slice(s[0], s[1])}`); + } + } + const nodes = descendants(snap, first).map((id) => snap.nodes[id]); + console.log(`prompt sentences: ${all.length}, traced to a section: ${all.length - uncovered}, untraced: ${uncovered}`); + console.log(`tree: ${nodes.filter((n) => n.kind === "section").length} sections, ${nodes.filter((n) => n.kind === "note").length} notes`); + const v = verifyHistory(doc); + console.log(`history: ${v.checked} commits re-hashed after checkout, ${v.mismatches.length} mismatches, ${v.unhashed} without a hash`); + process.exit(uncovered || v.mismatches.length ? 1 : 0); +}