Name: Explicata, and EX_ for the environment variables

Infinispand becomes Explicata (Latin, "things unfolded") wherever the name
shows: the page title, README, package, prompts, seed title, Wikipedia
User-Agent and startup line. Every IE_* variable becomes EX_*. The browser's
IndexedDB name and the ie: storage keys stay, so settings and replicas
already stored are found; the migration fixtures keep the old seed title.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q6Kn9JiRmGKzPQMh7o
This commit is contained in:
thalladaandClaude Opus 5.5 committed 2026-11-17 18:03:49 -05:00
1 parent e6d71e84de
commit 60d26908d6
51 files changed
+256 -252

No files matched your search

+42 -41
View File
@@ -1,9 +1,10 @@
# Infinispand # Explicata
A tree of writing 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 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 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. by a model, and the tree is versioned like git. The name is Latin for "things unfolded" (*explicare*,
to unfold).
Everything is a node of a library: a single versioned tree whose root is the library itself. Everything is a node of a library: a single versioned tree whose root is the library itself.
Any node, with everything under it, can be moved under any other, copied, saved to a file, or Any node, with everything under it, can be moved under any other, copied, saved to a file, or
@@ -33,27 +34,27 @@ use on their own machine.
|---|---|---| |---|---|---|
| `ANTHROPIC_API_KEY` | unset | Enables generation. The key stays in the server process. | | `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. | | `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. | | `EX_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). | | `EX_LLM` | `claude` with a key, `subscription` with a token, else `off` | `mock`: a deterministic stand-in (the tests). |
| `IE_DATA` | `.data` | Where the libraries and their caches are kept. Delete it to start again from the seed and the starter trees. | | `EX_DATA` | `.data` | Where the libraries and their caches are kept. Delete it to start again from the seed and the starter trees. |
| `IE_LIBRARY` | `library` | Starter trees (`.md` files in the text format), written into the first library when `IE_DATA` is empty. | | `EX_LIBRARY` | `library` | Starter trees (`.md` files in the text format), written into the first library when `EX_DATA` is empty. |
| `IE_USER` | your login name | The name on commits the server makes for you (the page lets you change yours with `/user`). | | `EX_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. | | `EX_WIKI` | `live` | `mock`: built-in test articles, no network (the browser tests); `off`: every `/api/wiki/*` route answers 503. |
| `IE_HOSTS` | (none) | Extra host names the dev server answers to, comma-separated. `localhost` and `*.ts.net` (Tailscale) are always allowed. | | `EX_HOSTS` | (none) | Extra host names the dev server answers to, comma-separated. `localhost` and `*.ts.net` (Tailscale) are always allowed. |
| `IE_WIKI_LANG` | `en` | Which Wikipedia. | | `EX_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. | | `EX_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. | | `EX_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. | | `EX_WEB_SEARCHES`, `EX_WEB_FETCHES` | `5`, `5` | Searches and page reads one request to the editor may make. |
| `IE_REVIEW_CALLS` | `50` | Model calls the link reviewer may make in one `/linkhere` or `/linkall` (each call judges up to 60 links). What is left past the cap waits for you. | | `EX_REVIEW_CALLS` | `50` | Model calls the link reviewer may make in one `/linkhere` or `/linkall` (each call judges up to 60 links). What is left past the cap waits for you. |
| `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). | | `EX_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. | | `EX_EMBED_MODEL` | `Xenova/bge-small-en-v1.5` | Downloaded once into `EX_DATA/models/`. `Snowflake/snowflake-arctic-embed-xs` is a drop-in alternative. |
| `IE_EMBED_THREADS` | `4` | ONNX threads for the embedding model. | | `EX_EMBED_THREADS` | `4` | ONNX threads for the embedding model. |
| `IE_EMBED_OFFLINE` | unset | `1`: never download, use cached model files only. | | `EX_EMBED_OFFLINE` | unset | `1`: never download, use cached model files only. |
| `PORT` | `4747` | | | `PORT` | `4747` | |
For the tests: `IE_MOCK_DELAY` (ms per mock token), `IE_WIKI_MOCK_BULK_MS` (delay on background For the tests: `EX_MOCK_DELAY` (ms per mock token), `EX_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 Wikipedia requests), `EX_PROD=1` and `EX_DIST` (serve a build, and which one), `EX_E2E_PORT` and
`IE_E2E_DATA` (playwright.config.ts). `EX_E2E_DATA` (playwright.config.ts).
## Using it ## Using it
@@ -271,8 +272,8 @@ Press `?` for every key. The short version:
it rejects is kept, with its one-line reason, and not looked for again. The model gets no tools, it rejects is kept, with its one-line reason, and not looked for again. The model gets no tools,
only the candidates: each phrase's sentence, its section's title and path, and the target's title only the candidates: each phrase's sentence, its section's title and path, and the target's title
and description (or first sentence); many candidates go in one call, and nothing judged is sent and description (or first sentence); many candidates go in one call, and nothing judged is sent
twice. Without a model (`IE_LLM=off`), or when a call fails or a job reaches its cap twice. Without a model (`EX_LLM=off`), or when a call fails or a job reaches its cap
(`IE_REVIEW_CALLS`), nothing unreviewed is linked: the candidates are suggested instead, and the (`EX_REVIEW_CALLS`), nothing unreviewed is linked: the candidates are suggested instead, and the
status line says why. status line says why.
- A **suggestion** has a faint dashed underline. `Tab` reaches suggestions; `y` links one, `n` - 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 declines it (remembered in the node, on every replica). `/autolink suggest` leaves every
@@ -314,7 +315,7 @@ sources linked. `Esc` stops a run and keeps nothing of it (its edits were on its
Every claim taken from the web is linked (↗) to the page it came from, and only pages retrieved in 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 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 `EX_WEB_SEARCHES` searches and `EX_WEB_FETCHES` reads. Page text is treated as data, never
instructions. instructions.
What is sent where: What is sent where:
@@ -327,7 +328,7 @@ What is sent where:
page **from this machine** and a small model summarises it. A guard in the server refuses every 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 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. did not name, and anything past the caps.
- **With `IE_LLM=mock`** nothing leaves the machine. - **With `EX_LLM=mock`** nothing leaves the machine.
## How it works ## How it works
@@ -378,14 +379,14 @@ What is sent where:
On disk: On disk:
``` ```
IE_DATA/libraries/index.json the libraries, in order: id, title, when made, whether deleted EX_DATA/libraries/index.json the libraries, in order: id, title, when made, whether deleted
IE_DATA/libraries/<id>/<branch>.loro a library, one Loro snapshot per branch EX_DATA/libraries/<id>/<branch>.loro a library, one Loro snapshot per branch
IE_DATA/libraries/<id>/links/pending.json its link suggestions, the reviewer's verdicts and your decisions (derived) EX_DATA/libraries/<id>/links/pending.json its link suggestions, the reviewer's verdicts and your decisions (derived)
IE_DATA/libraries/<id>/vectors/nodes.* its sections as vectors (derived) EX_DATA/libraries/<id>/vectors/nodes.* its sections as vectors (derived)
IE_DATA/libraries/.deleted/<id>-<time>/ a deleted library, moved aside whole EX_DATA/libraries/.deleted/<id>-<time>/ a deleted library, moved aside whole
IE_DATA/wiki-cache/ Wikipedia answers (derived, shared) EX_DATA/wiki-cache/ Wikipedia answers (derived, shared)
IE_DATA/models/ the embedding model (shared) EX_DATA/models/ the embedding model (shared)
IE_DATA/server.lock the running server's pid EX_DATA/server.lock the running server's pid
``` ```
A library's id is its database's own id (base 36); its name is its root's title. Each library is a A library's id is its database's own id (base 36); its name is its root's title. Each library is a
@@ -404,21 +405,21 @@ history entry. An address that names nothing shows the library's root; one witho
(`/n/…`, `/doc/…`) is read in the library last used; a library the server does not have goes to (`/n/…`, `/doc/…`) is read in the library last used; a library the server does not have goes to
the first one. the first one.
When `IE_DATA` is empty, the first library is made with the seed and every `library/*.md`; a file When `EX_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. that does not parse is logged and skipped. A library made later starts with its root alone.
### Deleting a library ### Deleting a library
`D` in the libraries panel (or `DELETE /api/libraries/<id>`) moves the library's directory, whole `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` and unchanged, to `EX_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 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>/`, deletion. To bring one back: stop the server, move the directory back to `EX_DATA/libraries/<id>/`,
remove the `"deleted"` and `"movedTo"` fields from its entry in `IE_DATA/libraries/index.json`, and remove the `"deleted"` and `"movedTo"` fields from its entry in `EX_DATA/libraries/index.json`, and
start the server. Nothing ever empties `.deleted/`. start the server. Nothing ever empties `.deleted/`.
### From the single-library layout ### From the single-library layout
A data directory written before libraries (`IE_DATA/library/main.loro`) is not opened: the server A data directory written before libraries (`EX_DATA/library/main.loro`) is not opened: the server
says, in one line, to run the migration, which only ever runs when asked. Stop the server (and let says, in one line, to run the migration, which only ever runs when asked. Stop the server (and let
every open page say `saved` first: a page of the old library cannot send its edits to the new one), every open page say `saved` first: a page of the old library cannot send its edits to the new one),
then: then:
@@ -429,7 +430,7 @@ npm run migrate # the same, then writes it
``` ```
Both take another directory as an argument (`npm run migrate -- --check /path/to/data`); without Both take another directory as an argument (`npm run migrate -- --check /path/to/data`); without
one, `IE_DATA`, else `.data`. The migration copies the tree into a new library (a new id, a history one, `EX_DATA`, else `.data`. The migration copies the tree into a new library (a new id, a history
of one commit): titles, bodies, notes with their anchors, locks, authorship, targets, declined of one commit): titles, bodies, notes with their anchors, locks, authorship, targets, declined
phrases, the Wikipedia container with its articles' notes, the order of everything, and what each phrases, the Wikipedia container with its articles' notes, the order of everything, and what each
node was last reconciled with, so nothing turns stale. Every node target is rewritten to the new node was last reconciled with, so nothing turns stale. Every node target is rewritten to the new
@@ -439,10 +440,10 @@ when first needed. Before writing, it checks the copy node by node against the o
count, text, notes, anchors, flags, staleness, and every target that resolved resolving to the same count, text, notes, anchors, flags, staleness, and every target that resolved resolving to the same
node) and again from the file it wrote; any difference stops it with a report and leaves the node) and again from the file it wrote; any difference stops it with a report and leaves the
directory as it was. Then `libraries/` is put in place in one rename, and `library/`, directory as it was. Then `libraries/` is put in place in one rename, and `library/`,
`library.json`, `links/` and `vectors/` are moved, unchanged, to `IE_DATA/backup-<time>/`. History, `library.json`, `links/` and `vectors/` are moved, unchanged, to `EX_DATA/backup-<time>/`. History,
branches other than main (listed, and kept in the backup) and resolved conflicts are not carried. branches other than main (listed, and kept in the backup) and resolved conflicts are not carried.
It refuses while a server has the directory open, and a second run does nothing. A directory It refuses while a server has the directory open, and a second run does nothing. A directory
older still (`IE_DATA/docs/`) must first be opened once by a version from before libraries older still (`EX_DATA/docs/`) must first be opened once by a version from before libraries
(commit c4d6856). (commit c4d6856).
To go back: stop the server, move `libraries/` away and the backup's contents back, and check out To go back: stop the server, move `libraries/` away and the backup's contents back, and check out
+12 -12
View File
@@ -43,11 +43,11 @@ semicolon was throttled after about 500 requests; with the semicolon it ran 2,50
without a 429. Browser requests are limited by IP or user id, "not based on the user agent at all". 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 *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)` in opposite directions. With no contact, the default UA `Explicata/0.1 (personal knowledge tool)`
should be expected to fall in the 10/min "unidentified" tier. I did not provoke a 429 to check 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 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 `EX_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 `Explicata/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 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. the owner's real identity out of the UA.
@@ -152,7 +152,7 @@ What would make it necessary:
4. Needing to work offline for long periods. 4. Needing to work offline for long periods.
**Autocomplete without a contact.** At 6.5 s spacing, server-side autocomplete is slow: set **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" `EX_WIKI_CONTACT`. (Calling `search/title` from the browser would be the "unauthenticated browser"
tier, 200/min per IP; not done.) tier, 200/min per IP; not done.)
## 5. What makes a good candidate (from the demonstration) ## 5. What makes a good candidate (from the demonstration)
@@ -197,7 +197,7 @@ tier, 200/min per IP; not done.)
hits). hits).
- Embeddings: `Xenova/bge-small-en-v1.5`, q8 ONNX, **34 MB** on disk, 384 dimensions, MIT. Load - 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, 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**; `EX_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 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 embeds in about 15 s. `all-MiniLM-L6-v2` (Apache-2.0, 23 MB) is about 1.3× faster but separates
senses less clearly. senses less clearly.
@@ -210,12 +210,12 @@ considered and set aside:
- EmbeddingGemma-300m is under the Gemma terms and is 10× larger. - 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. - 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. `EX_EMBED_MODEL=Snowflake/snowflake-arctic-embed-xs` (Apache-2.0) is a drop-in alternative.
## 7. Caches ## 7. Caches
`<IE_DATA>/wiki-cache/<lang>/titles.json` (found 30 d, missing 3 d), `small.json` (summaries 14 d, `<EX_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, per library: `<IE_DATA>/libraries/<id>/vectors/<name>.json` senses 14 d, suggest and search 1 d), `articles/` (7 d). Vectors, per library: `<EX_DATA>/libraries/<id>/vectors/<name>.json`
and `.f32`. An expired entry is still served, marked `stale`, when the network is down. The 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. variables that configure all this are in the README.
@@ -353,7 +353,7 @@ another tree); each tree's heading lists what is already linked in it, and each
heading what is linked there. The model has no tools; it returns, by structured output, a verdict 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 (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 blind spot above as a reason to reject. Verdicts are stored with the suggestion in
`IE_DATA/libraries/<id>/links/pending.json` (each library its own), keyed by node, phrase and target rather than by offsets, so a `EX_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 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. are skipped by later scans of that node, as declined ones are.
@@ -366,11 +366,11 @@ list can say who decided.
**Cost.** A node scanned after an edit costs at most 2 calls (`SCAN_CALLS`), almost always 1, and **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 `/linkhere` or `/linkall` 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 candidates, at most `EX_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 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. model (`EX_MODEL`) at effort `low`: the app has no per-task model setting, and none was added.
**Falling back.** With no model (`IE_LLM=off`), when a call fails (a limit reached, the network **Falling back.** With no model (`EX_LLM=off`), when a call fails (a limit reached, the network
gone), or when a job reaches its cap, nothing unreviewed is applied: what is left stays pending, is gone), or when a job reaches its cap, nothing unreviewed is applied: what is left stays pending, is
drawn as suggestions and listed under *pending*, and the status line says why ("Not reviewed (the drawn as suggestions and listed under *pending*, and the status line says why ("Not reviewed (the
reviewer failed: …)"). reviewer failed: …)").
+2 -2
View File
@@ -113,8 +113,8 @@ test("every kind of pane's title rule is drawn by the curve into it, in the pane
test("a pane's colour is a function of the forest: unchanged by focus, a source scrolled out of sight, folding to a tab, or which way its rule is drawn", async ({ page }) => { test("a pane's colour is a function of the forest: unchanged by focus, a source scrolled out of sight, folding to a tab, or which way its rule is drawn", async ({ page }) => {
await library(page); await library(page);
for (const t of ["Infinispand", "Fixed points"]) await clickOpen(page, "Library", t); for (const t of ["Explicata", "Fixed points"]) await clickOpen(page, "Library", t);
await clickOpen(page, "Infinispand", "Expansion by depth"); await clickOpen(page, "Explicata", "Expansion by depth");
await clickOpen(page, "Fixed points", "The idea itself"); await clickOpen(page, "Fixed points", "The idea itself");
const colourOf = async () => Object.fromEntries((await lines(page)).map((l) => [l.to, { stroke: l.stroke, colour: l.colour, hue: l.paneHue }])); const colourOf = async () => Object.fromEntries((await lines(page)).map((l) => [l.to, { stroke: l.stroke, colour: l.colour, hue: l.paneHue }]));
const before = await colourOf(); const before = await colourOf();
+19 -19
View File
@@ -69,7 +69,7 @@ async function still(page: Page) {
} }
async function open(page: Page) { async function open(page: Page) {
await visit(page, "Infinispand"); await visit(page, "Explicata");
await page.waitForSelector(".strip .pane"); await page.waitForSelector(".strip .pane");
await page.evaluate(() => document.fonts.ready); await page.evaluate(() => document.fonts.ready);
await expect(page.locator(".strip .pane")).toHaveCount(2); await expect(page.locator(".strip .pane")).toHaveCount(2);
@@ -121,11 +121,11 @@ test("Enter on a section row opens its pane below in the next column; Shift+Ente
await keys(page, "l l l"); // Expansion by depth showing; the focus on its first row await keys(page, "l l l"); // Expansion by depth showing; the focus on its first row
// Nothing to the right yet: a plain trail is one pane per column. // Nothing to the right yet: a plain trail is one pane per column.
await keys(page, "Enter"); await keys(page, "Enter");
expect(await tree(page)).toEqual(["Infinispand", [["*", ["Expansion by depth", [["*", "Levels of a node"]]]]]]); expect(await tree(page)).toEqual(["Explicata", [["*", ["Expansion by depth", [["*", "Levels of a node"]]]]]]);
expect(await columns(page)).toEqual([["Infinispand"], ["Expansion by depth"], ["Levels of a node"]]); expect(await columns(page)).toEqual([["Explicata"], ["Expansion by depth"], ["Levels of a node"]]);
await keys(page, "j Enter"); await keys(page, "j Enter");
expect(await columns(page)).toEqual([["Infinispand"], ["Expansion by depth"], ["Levels of a node", "Pre-generated depth"]]); expect(await columns(page)).toEqual([["Explicata"], ["Expansion by depth"], ["Levels of a node", "Pre-generated depth"]]);
expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Pre-generated depth"]); expect(await trail(page)).toEqual(["Explicata", "Expansion by depth", "Pre-generated depth"]);
// They share the column's height, one above the other, beside the pane they came from. // They share the column's height, one above the other, beside the pane they came from.
const b = await boxes(page); const b = await boxes(page);
const [a, c, parent] = [b["Levels of a node"], b["Pre-generated depth"], b["Expansion by depth"]]; const [a, c, parent] = [b["Levels of a node"], b["Pre-generated depth"], b["Expansion by depth"]];
@@ -139,15 +139,15 @@ test("Enter on a section row opens its pane below in the next column; Shift+Ente
await expect(pane(page, "Expansion by depth").locator(".node.forked > .row")).toHaveText([/Levels of a node/]); await expect(pane(page, "Expansion by depth").locator(".node.forked > .row")).toHaveText([/Levels of a node/]);
// Shift+Enter opens in place of the focused one. // Shift+Enter opens in place of the focused one.
await keys(page, "j Shift+Enter"); await keys(page, "j Shift+Enter");
expect(await columns(page)).toEqual([["Infinispand"], ["Expansion by depth"], ["Levels of a node", "Generation on demand"]]); expect(await columns(page)).toEqual([["Explicata"], ["Expansion by depth"], ["Levels of a node", "Generation on demand"]]);
// Enter (or Shift+Enter) on the row of a pane already open focuses it: no second copy, and nothing closes. // Enter (or Shift+Enter) on the row of a pane already open focuses it: no second copy, and nothing closes.
await keys(page, "k k Enter"); await keys(page, "k k Enter");
expect(await columns(page)).toEqual([["Infinispand"], ["Expansion by depth"], ["Levels of a node", "Generation on demand"]]); expect(await columns(page)).toEqual([["Explicata"], ["Expansion by depth"], ["Levels of a node", "Generation on demand"]]);
expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Levels of a node"]); expect(await trail(page)).toEqual(["Explicata", "Expansion by depth", "Levels of a node"]);
await keys(page, "Enter"); await keys(page, "Enter");
expect(await columns(page)).toEqual([["Infinispand"], ["Expansion by depth"], ["Levels of a node", "Generation on demand"]]); expect(await columns(page)).toEqual([["Explicata"], ["Expansion by depth"], ["Levels of a node", "Generation on demand"]]);
await keys(page, "j j Shift+Enter"); await keys(page, "j j Shift+Enter");
expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Generation on demand"]); expect(await trail(page)).toEqual(["Explicata", "Expansion by depth", "Generation on demand"]);
}); });
test("a click, a Ctrl- and a middle click open beside; a Shift-click in place; a click in another fork makes it the focused one", async ({ page }) => { test("a click, a Ctrl- and a middle click open beside; a Shift-click in place; a click in another fork makes it the focused one", async ({ page }) => {
@@ -157,24 +157,24 @@ test("a click, a Ctrl- and a middle click open beside; a Shift-click in place; a
const row = (t: string) => page.locator(".pane .row", { hasText: t }).first(); const row = (t: string) => page.locator(".pane .row", { hasText: t }).first();
await row("Borrowed from Gwern").click(); await row("Borrowed from Gwern").click();
await row(kids[0]).click(); await row(kids[0]).click();
expect(await trail(page)).toEqual(["Infinispand", "Borrowed from Gwern", kids[0]]); expect(await trail(page)).toEqual(["Explicata", "Borrowed from Gwern", kids[0]]);
await row(kids[1]).click({ modifiers: ["Control"] }); await row(kids[1]).click({ modifiers: ["Control"] });
expect(await tree(page)).toEqual(["Infinispand", [["*", ["Borrowed from Gwern", [kids[0], ["*", kids[1]]]]]]]); expect(await tree(page)).toEqual(["Explicata", [["*", ["Borrowed from Gwern", [kids[0], ["*", kids[1]]]]]]]);
await row(kids[2]).click({ button: "middle" }); await row(kids[2]).click({ button: "middle" });
expect(await tree(page)).toEqual(["Infinispand", [["*", ["Borrowed from Gwern", [kids[0], kids[1], ["*", kids[2]]]]]]]); expect(await tree(page)).toEqual(["Explicata", [["*", ["Borrowed from Gwern", [kids[0], kids[1], ["*", kids[2]]]]]]]);
// A click on the first fork's heading focuses that fork, and makes that pane the active one. // A click on the first fork's heading focuses that fork, and makes that pane the active one.
await pane(page, kids[0]).locator(".pane-head").click(); await pane(page, kids[0]).locator(".pane-head").click();
expect(await trail(page)).toEqual(["Infinispand", "Borrowed from Gwern", kids[0]]); expect(await trail(page)).toEqual(["Explicata", "Borrowed from Gwern", kids[0]]);
expect(await focusedTitle(page)).toBe(kids[0]); expect(await focusedTitle(page)).toBe(kids[0]);
await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[0]); await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[0]);
// The first pane's rows too: beside, in the next column (above, as its row is above); and a click on a row already open keeps it. // The first pane's rows too: beside, in the next column (above, as its row is above); and a click on a row already open keeps it.
await row("Display forms").click(); await row("Display forms").click();
await expect.poll(() => columns(page)).toEqual([["Infinispand"], ["Display forms", "Borrowed from Gwern"], kids.slice(0, 3)]); await expect.poll(() => columns(page)).toEqual([["Explicata"], ["Display forms", "Borrowed from Gwern"], kids.slice(0, 3)]);
await row("Display forms").click(); await row("Display forms").click();
expect((await columns(page))[1]).toEqual(["Display forms", "Borrowed from Gwern"]); expect((await columns(page))[1]).toEqual(["Display forms", "Borrowed from Gwern"]);
// A Shift-click opens in place of the focused one (Display forms), and selects no text on the way. // A Shift-click opens in place of the focused one (Display forms), and selects no text on the way.
await row("Editing and regeneration").click({ modifiers: ["Shift"] }); await row("Editing and regeneration").click({ modifiers: ["Shift"] });
expect(await trail(page)).toEqual(["Infinispand", "Editing and regeneration"]); expect(await trail(page)).toEqual(["Explicata", "Editing and regeneration"]);
await expect.poll(async () => (await columns(page))[1]).toEqual(["Editing and regeneration", "Borrowed from Gwern"]); await expect.poll(async () => (await columns(page))[1]).toEqual(["Editing and regeneration", "Borrowed from Gwern"]);
expect(await page.evaluate(() => window.getSelection()?.isCollapsed ?? true)).toBe(true); expect(await page.evaluate(() => window.getSelection()?.isCollapsed ?? true)).toBe(true);
}); });
@@ -429,7 +429,7 @@ test("exactly one pane is active, under a heavy rule; the rest of the focused br
async function five(page: Page) { async function five(page: Page) {
await open(page); await open(page);
await keys(page, "j Enter j Enter j Enter j Enter j Enter"); await keys(page, "j Enter j Enter j Enter j Enter j Enter");
const kids = (await childTitles(page, "Infinispand")).slice(0, 5); const kids = (await childTitles(page, "Explicata")).slice(0, 5);
expect((await columns(page))[1]).toEqual(kids); expect((await columns(page))[1]).toEqual(kids);
await still(page); await still(page);
return kids; return kids;
@@ -458,7 +458,7 @@ test("a crowded column stacks its panes as the strip stacks columns: covered par
await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[4]); await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[4]);
const where = await focusedTitle(page); const where = await focusedTitle(page);
await keys(page, "["); await keys(page, "[");
expect(await trail(page)).toEqual(["Infinispand", kids[3]]); expect(await trail(page)).toEqual(["Explicata", kids[3]]);
await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[3]); await expect(page.locator(".pane.active .pane-head h2")).toHaveText(kids[3]);
b = await boxes(page); b = await boxes(page);
expect(b[kids[3]].whole).toBe(true); expect(b[kids[3]].whole).toBe(true);
@@ -726,7 +726,7 @@ test("a fork whose node is deleted closes, and the others stay", async ({ page,
const res = await request.post("/api/ops", { data: { author: "another", message: "Delete it", ops: [{ op: "delete", id }] } }); const res = await request.post("/api/ops", { data: { author: "another", message: "Delete it", ops: [{ op: "delete", id }] } });
expect(res.ok()).toBe(true); expect(res.ok()).toBe(true);
await expect.poll(async () => (await columns(page))[2]).toEqual(["Levels of a node"]); await expect.poll(async () => (await columns(page))[2]).toEqual(["Levels of a node"]);
expect(await trail(page)).toEqual(["Infinispand", "Expansion by depth", "Levels of a node"]); expect(await trail(page)).toEqual(["Explicata", "Expansion by depth", "Levels of a node"]);
}); });
test("a window too short to share a column stacks it at once: the focused pane whole, the other covered to its tab", async ({ page }) => { test("a window too short to share a column stacks it at once: the focused pane whole, the other covered to its tab", async ({ page }) => {
+2 -2
View File
@@ -15,7 +15,7 @@ const titlesUnder = (page: Page, title: string) =>
/** The first tree, opened in the column (hoisted, with the library one step out). */ /** The first tree, opened in the column (hoisted, with the library one step out). */
async function open(page: Page) { async function open(page: Page) {
await openPage(page, "Infinispand"); await openPage(page, "Explicata");
await page.evaluate(() => document.fonts.ready); await page.evaluate(() => document.fonts.ready);
} }
@@ -29,7 +29,7 @@ test("opens on an outline of ten titles with the prompt folded above it", async
await expect(page.locator("article > .outline > .node")).toHaveCount(10); await expect(page.locator("article > .outline > .node")).toHaveCount(10);
await expect(page.locator(".node.open")).toHaveCount(0); await expect(page.locator(".node.open")).toHaveCount(0);
await expect(page.locator(".abstract.seed.folded")).toBeVisible(); await expect(page.locator(".abstract.seed.folded")).toBeVisible();
await expect(page.locator("h1")).toHaveText("Infinispand"); await expect(page.locator("h1")).toHaveText("Explicata");
await page.keyboard.press("Enter"); await page.keyboard.press("Enter");
await expect(page.locator(".abstract.seed.folded")).toHaveCount(0); await expect(page.locator(".abstract.seed.folded")).toHaveCount(0);
await expect(page.locator(".abstract.seed")).toContainText("I think maybe we want something like CDRTs under the hood"); await expect(page.locator(".abstract.seed")).toContainText("I think maybe we want something like CDRTs under the hood");
+1 -1
View File
@@ -338,7 +338,7 @@ test("in the panes view the panel narrows the panes, and the curves follow it th
await page.goto("/"); await page.goto("/");
await page.waitForSelector(".strip .pane"); await page.waitForSelector(".strip .pane");
await page.evaluate(() => document.fonts.ready); await page.evaluate(() => document.fonts.ready);
await page.locator(".pane .row", { hasText: "Infinispand" }).first().dispatchEvent("click"); await page.locator(".pane .row", { hasText: "Explicata" }).first().dispatchEvent("click");
await page.locator(".pane .row", { hasText: "Expansion by depth" }).first().dispatchEvent("click"); await page.locator(".pane .row", { hasText: "Expansion by depth" }).first().dispatchEvent("click");
await expect(page.locator(".strip .pane")).toHaveCount(3); await expect(page.locator(".strip .pane")).toHaveCount(3);
await still(page); await still(page);
+3 -3
View File
@@ -1,5 +1,5 @@
/** /**
* Links and Wikipedia, keyboard only, against the mock Wikipedia (IE_WIKI=mock, server/wikiMock.ts) * Links and Wikipedia, keyboard only, against the mock Wikipedia (EX_WIKI=mock, server/wikiMock.ts)
* and the shared library with links written into it over the op API (e2e/helpers.ts). Nothing here * and the shared library with links written into it over the op API (e2e/helpers.ts). Nothing here
* touches the network: requests to wikipedia.org are refused, so a test that opens one only sees * touches the network: requests to wikipedia.org are refused, so a test that opens one only sees
* the address it would have gone to. * the address it would have gone to.
@@ -403,14 +403,14 @@ test("a disambiguation page lists its senses as rows; a missing article, an unre
await command(page, "/link w:Rate limited example"); await command(page, "/link w:Rate limited example");
await keys(page, "Enter"); await keys(page, "Enter");
await expect(page.locator(".wiki-pane.active").locator(".wiki-problem")).toContainText("fewer requests"); await expect(page.locator(".wiki-pane.active").locator(".wiki-problem")).toContainText("fewer requests");
await expect(page.locator(".status .message")).toContainText("IE_WIKI_CONTACT"); await expect(page.locator(".status .message")).toContainText("EX_WIKI_CONTACT");
expect(await page.evaluate(() => localStorage.getItem("ie:wiki-hint"))).toBe("true"); expect(await page.evaluate(() => localStorage.getItem("ie:wiki-hint"))).toBe("true");
await keys(page, "h h h"); await keys(page, "h h h");
await command(page, "/link w:Slow article"); await command(page, "/link w:Slow article");
await keys(page, "Enter"); await keys(page, "Enter");
await expect(page.locator(".wiki-pane.active").locator(".wiki-wait")).toContainText("Loading"); await expect(page.locator(".wiki-pane.active").locator(".wiki-wait")).toContainText("Loading");
await expect(page.locator(".wiki-pane.active").locator(".wiki-head h2")).toHaveText("Slow article", { timeout: 10_000 }); await expect(page.locator(".wiki-pane.active").locator(".wiki-head h2")).toHaveText("Slow article", { timeout: 10_000 });
await expect(page.locator(".status .message")).not.toContainText("IE_WIKI_CONTACT"); await expect(page.locator(".status .message")).not.toContainText("EX_WIKI_CONTACT");
await keys(page, "h h h"); await keys(page, "h h h");
await command(page, "/unlink"); await command(page, "/unlink");
}); });
+5 -5
View File
@@ -3,7 +3,7 @@ import { expect, test, type Page } from "@playwright/test";
import { command, idle, jump, keys, openPage, settle, state } from "./helpers"; import { command, idle, jump, keys, openPage, settle, state } from "./helpers";
/** The first tree as the page (hoisted), with the library one step out. */ /** The first tree as the page (hoisted), with the library one step out. */
const open = (page: Page) => openPage(page, "Infinispand"); const open = (page: Page) => openPage(page, "Explicata");
test.afterEach(({ page }) => settle(page)); test.afterEach(({ page }) => settle(page));
@@ -63,7 +63,7 @@ test("hoisting makes one node the whole page; Esc at its top steps out to its pa
await jump(page, "Semantic conflicts"); await jump(page, "Semantic conflicts");
await page.keyboard.press("z"); await page.keyboard.press("z");
await expect(page.locator("h1")).toHaveText("Semantic conflicts"); await expect(page.locator("h1")).toHaveText("Semantic conflicts");
await expect(page.locator(".crumbs")).toHaveText(/^Library › Infinispand › Versioning and merge ›/); await expect(page.locator(".crumbs")).toHaveText(/^Library › Explicata › Versioning and merge ›/);
await expect(page.locator("article > .outline > .node")).toHaveCount(3); await expect(page.locator("article > .outline > .node")).toHaveCount(3);
await page.keyboard.press("Escape"); await page.keyboard.press("Escape");
await expect(page.locator("h1")).toHaveText("Versioning and merge"); await expect(page.locator("h1")).toHaveText("Versioning and merge");
@@ -71,11 +71,11 @@ test("hoisting makes one node the whole page; Esc at its top steps out to its pa
expect(await state(page, (s) => s.snap.nodes[s.focus.node].title)).toBe("Semantic conflicts"); expect(await state(page, (s) => s.snap.nodes[s.focus.node].title)).toBe("Semantic conflicts");
await page.keyboard.press("O"); // collapse everything: the focus goes to the top await page.keyboard.press("O"); // collapse everything: the focus goes to the top
await page.keyboard.press("Escape"); await page.keyboard.press("Escape");
await expect(page.locator("h1")).toHaveText("Infinispand"); await expect(page.locator("h1")).toHaveText("Explicata");
await page.keyboard.press("O"); await page.keyboard.press("O");
await page.keyboard.press("Escape"); await page.keyboard.press("Escape");
await expect(page.locator("h1")).toHaveText("Library"); await expect(page.locator("h1")).toHaveText("Library");
expect(await state(page, (s) => s.snap.nodes[s.focus.node].title)).toBe("Infinispand"); expect(await state(page, (s) => s.snap.nodes[s.focus.node].title)).toBe("Explicata");
await expect(page).toHaveURL(/\/n\/[^/]+$/); await expect(page).toHaveURL(/\/n\/[^/]+$/);
// On the root itself, the address is the library's. // On the root itself, the address is the library's.
await page.keyboard.press("O"); await page.keyboard.press("O");
@@ -118,7 +118,7 @@ test("an outside agent edits over HTTP with the same ops, and the open page foll
await open(page); await open(page);
const tree = await (await request.get("/api/tree/main")).json(); const tree = await (await request.get("/api/tree/main")).json();
// The tree is the whole library; its top-level trees 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"); expect(Object.values<any>(tree.nodes).filter((n) => n.parent === tree.root).map((n) => n.title)).toContain("Explicata");
const target = Object.values<any>(tree.nodes).find((n) => n.title === "The first tree"); const target = Object.values<any>(tree.nodes).find((n) => n.title === "The first tree");
expect(target).toBeTruthy(); expect(target).toBeTruthy();
const res = await request.post("/api/ops/main", { const res = await request.post("/api/ops/main", {
+7 -7
View File
@@ -61,12 +61,12 @@ test("the library root is the first page and a node like any other: its sections
// The first top-level node opens in place, as any section does: the library stays the page. // The first top-level node opens in place, as any section does: the library stays the page.
await keys(page, "j l"); await keys(page, "j l");
await expect(page.locator(".top h1")).toHaveText("Library"); await expect(page.locator(".top h1")).toHaveText("Library");
await expect(page.locator("article > .outline > .node.open > .row .title")).toHaveText("Infinispand"); await expect(page.locator("article > .outline > .node.open > .row .title")).toHaveText("Explicata");
// Its text is a prompt its sections cite: folded there too. // Its text is a prompt its sections cite: folded there too.
await expect(page.locator("article > .outline > .node.open > .content > .abstract.seed.folded")).toBeVisible(); await expect(page.locator("article > .outline > .node.open > .content > .abstract.seed.folded")).toBeVisible();
const first = await state(page, (s) => s.focus.node); const first = await state(page, (s) => s.focus.node);
await expect(page).toHaveURL(new RegExp(`/n/${encodeURIComponent(first)}$`)); await expect(page).toHaveURL(new RegExp(`/n/${encodeURIComponent(first)}$`));
await expect(page).toHaveTitle("Infinispand"); await expect(page).toHaveTitle("Explicata");
// Back up onto the root itself: its address is the library's, /l/<id>, and it is the node the keys act on. // Back up onto the root itself: its address is the library's, /l/<id>, and it is the node the keys act on.
await keys(page, "h k"); await keys(page, "h k");
expect(await state(page, (s) => s.focus.node === s.snap.root)).toBe(true); expect(await state(page, (s) => s.focus.node === s.snap.root)).toBe(true);
@@ -90,12 +90,12 @@ test("the library root is the first page and a node like any other: its sections
await keys(page, "Escape"); await keys(page, "Escape");
// z makes a node the page; Esc at its top steps back out to the library, on its row. // z makes a node the page; Esc at its top steps back out to the library, on its row.
await keys(page, "j z"); await keys(page, "j z");
await expect(page.locator(".top h1")).toHaveText("Infinispand"); await expect(page.locator(".top h1")).toHaveText("Explicata");
await expect(page.locator(".crumbs")).toHaveText(/^Library ›/); await expect(page.locator(".crumbs")).toHaveText(/^Library ›/);
await expect(page.locator(".top .byline")).toContainText(/^\d+ sections · \d+ nodes/); await expect(page.locator(".top .byline")).toContainText(/^\d+ sections · \d+ nodes/);
await keys(page, "Escape"); await keys(page, "Escape");
await expect(page.locator(".top h1")).toHaveText("Library"); await expect(page.locator(".top h1")).toHaveText("Library");
expect(await focusedTitle(page)).toBe("Infinispand"); expect(await focusedTitle(page)).toBe("Explicata");
}); });
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 }) => { 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 }) => {
@@ -127,8 +127,8 @@ test("an address names a node by its id, and survives a reload, Back and Forward
}); });
test("the jump box searches the whole library, says where each match is, and goes there", async ({ page }) => { test("the jump box searches the whole library, says where each match is, and goes there", async ({ page }) => {
await openPage(page, "Infinispand"); await openPage(page, "Explicata");
await expect(page.locator(".top h1")).toHaveText("Infinispand"); await expect(page.locator(".top h1")).toHaveText("Explicata");
await page.keyboard.press("/"); await page.keyboard.press("/");
await page.keyboard.type("amphidromes"); await page.keyboard.type("amphidromes");
const hit = page.locator(".jump li").first(); const hit = page.locator(".jump li").first();
@@ -141,7 +141,7 @@ test("the jump box searches the whole library, says where each match is, and goe
// Back to where the jump started. // Back to where the jump started.
await page.goBack(); await page.goBack();
await ready(page); await ready(page);
await expect.poll(() => focusedTitle(page)).toBe("Infinispand"); await expect.poll(() => focusedTitle(page)).toBe("Explicata");
// A top-level node is found like any other, and says it is in the library. // A top-level node is found like any other, and says it is in the library.
await page.keyboard.press("/"); await page.keyboard.press("/");
await page.keyboard.type("Fixed points"); await page.keyboard.type("Fixed points");
+22 -22
View File
@@ -19,7 +19,7 @@ const paneTitles = async (page: Page) => (await panes(page)).map((p) => p.title)
const nodeId = (page: Page, title: string) => page.evaluate((t) => (Object.values((globalThis as any).__ie.snap.nodes) as any[]).find((n) => n.title === t).id as string, title); const nodeId = (page: Page, title: string) => page.evaluate((t) => (Object.values((globalThis as any).__ie.snap.nodes) as any[]).find((n) => n.title === t).id as string, title);
async function open(page: Page) { async function open(page: Page) {
await openAt(page, "Infinispand"); await openAt(page, "Explicata");
await page.waitForSelector(".strip .pane"); await page.waitForSelector(".strip .pane");
await page.evaluate(() => document.fonts.ready); await page.evaluate(() => document.fonts.ready);
// The library pane and the tree's; hoisting makes the tree's top the first. // The library pane and the tree's; hoisting makes the tree's top the first.
@@ -40,12 +40,12 @@ test("the library is the first pane, and any node of it opens in the next; reloa
expect(await paneTitles(page)).toEqual(["Library"]); expect(await paneTitles(page)).toEqual(["Library"]);
await expect(page.locator(".pane.root .rows > .node")).toHaveCount(await state(page, (s) => s.snap.nodes[s.snap.root].children.filter((c: string) => !s.snap.nodes[c].articles).length)); await expect(page.locator(".pane.root .rows > .node")).toHaveCount(await state(page, (s) => s.snap.nodes[s.snap.root].children.filter((c: string) => !s.snap.nodes[c].articles).length));
await keys(page, "j l"); // the first top-level node's row, then open it await keys(page, "j l"); // the first top-level node's row, then open it
expect(await paneTitles(page)).toEqual(["Library", "Infinispand"]); expect(await paneTitles(page)).toEqual(["Library", "Explicata"]);
// Its pane is headed like any other; its text, a prompt its sections cite, is folded. // Its pane is headed like any other; its text, a prompt its sections cite, is folded.
await expect(page.locator(".pane:not(.root) .pane-head h2")).toHaveText("Infinispand"); await expect(page.locator(".pane:not(.root) .pane-head h2")).toHaveText("Explicata");
await expect(page.locator(".pane:not(.root) .abstract.seed.folded")).toBeVisible(); await expect(page.locator(".pane:not(.root) .abstract.seed.folded")).toBeVisible();
await keys(page, "j l"); // the next one: its pane opens beside the first one's, below it in the same column await keys(page, "j l"); // the next one: its pane opens beside the first one's, below it in the same column
expect(await paneTitles(page)).toEqual(["Library", "Infinispand", "A mind made of text"]); expect(await paneTitles(page)).toEqual(["Library", "Explicata", "A mind made of text"]);
await keys(page, "l l"); // into its first section, and open that await keys(page, "l l"); // into its first section, and open that
const third = await paneTitles(page); const third = await paneTitles(page);
expect(third).toHaveLength(4); expect(third).toHaveLength(4);
@@ -68,13 +68,13 @@ test("the library is the first pane, and any node of it opens in the next; reloa
test("auto shows panes at 1920 px and on a laptop's 1366, the panes as pages on a phone or a narrow window; v and /view switch", async ({ page }) => { test("auto shows panes at 1920 px and on a laptop's 1366, the panes as pages on a phone or a narrow window; v and /view switch", async ({ page }) => {
await open(page); await open(page);
await expect(page.locator(".app.view-panes .strip .pane")).toHaveCount(1); await expect(page.locator(".app.view-panes .strip .pane")).toHaveCount(1);
await expect(page.locator(".strip .pane.root h1")).toHaveText("Infinispand"); await expect(page.locator(".strip .pane.root h1")).toHaveText("Explicata");
await page.setViewportSize({ width: 1366, height: 768 }); await page.setViewportSize({ width: 1366, height: 768 });
await expect(page.locator(".app.view-panes .strip .pane")).toHaveCount(1); await expect(page.locator(".app.view-panes .strip .pane")).toHaveCount(1);
for (const [width, height] of [[820, 900], [390, 800]]) { for (const [width, height] of [[820, 900], [390, 800]]) {
await page.setViewportSize({ width, height }); await page.setViewportSize({ width, height });
await expect(page.locator(".app.view-pages .panes[data-layout=pages] .strip .pane"), `${width}`).toHaveCount(1); await expect(page.locator(".app.view-pages .panes[data-layout=pages] .strip .pane"), `${width}`).toHaveCount(1);
await expect(page.locator(".trail .trail-step")).toHaveText(["Infinispand"]); await expect(page.locator(".trail .trail-step")).toHaveText(["Explicata"]);
} }
await page.setViewportSize({ width: 1920, height: 1080 }); await page.setViewportSize({ width: 1920, height: 1080 });
await expect(page.locator(".strip .pane")).toHaveCount(1); await expect(page.locator(".strip .pane")).toHaveCount(1);
@@ -101,7 +101,7 @@ test("opening three levels deep gives four panes left to right; h moves back lef
await keys(page, "l l l j j l l l"); await keys(page, "l l l j j l l l");
await expect(page.locator(".strip .pane")).toHaveCount(4); await expect(page.locator(".strip .pane")).toHaveCount(4);
const ps = await panes(page); const ps = await panes(page);
expect(ps.map((p) => p.title)).toEqual(["Infinispand", "Expansion by depth", "Generation on demand", "Deepening a leaf"]); expect(ps.map((p) => p.title)).toEqual(["Explicata", "Expansion by depth", "Generation on demand", "Deepening a leaf"]);
for (let i = 1; i < ps.length; i++) expect(ps[i].left).toBeGreaterThan(ps[i - 1].left); for (let i = 1; i < ps.length; i++) expect(ps[i].left).toBeGreaterThan(ps[i - 1].left);
// In each parent's list, the child whose pane is showing is marked. // In each parent's list, the child whose pane is showing is marked.
await expect(page.locator(".pane .node.showing > .row")).toHaveText(["Expansion by depth", "Generation on demand", "Deepening a leaf"].map((t) => new RegExp(t))); await expect(page.locator(".pane .node.showing > .row")).toHaveText(["Expansion by depth", "Generation on demand", "Deepening a leaf"].map((t) => new RegExp(t)));
@@ -111,7 +111,7 @@ test("opening three levels deep gives four panes left to right; h moves back lef
expect(await focusedTitle(page)).toBe("Generation on demand"); expect(await focusedTitle(page)).toBe("Generation on demand");
await keys(page, "h"); await keys(page, "h");
expect(await focusedTitle(page)).toBe("Expansion by depth"); expect(await focusedTitle(page)).toBe("Expansion by depth");
expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth", "Generation on demand", "Deepening a leaf"]); expect(await paneTitles(page)).toEqual(["Explicata", "Expansion by depth", "Generation on demand", "Deepening a leaf"]);
// And forward again along the same trail. // And forward again along the same trail.
await keys(page, "l"); await keys(page, "l");
expect(await focusedTitle(page)).toBe("Levels of a node"); expect(await focusedTitle(page)).toBe("Levels of a node");
@@ -121,14 +121,14 @@ test("opening three levels deep gives four panes left to right; h moves back lef
expect(await focusedTitle(page)).toBe("Deepening a leaf"); expect(await focusedTitle(page)).toBe("Deepening a leaf");
await expect(page.locator(".pane.active .pane-head h2")).toHaveText("Generation on demand"); await expect(page.locator(".pane.active .pane-head h2")).toHaveText("Generation on demand");
await keys(page, "q"); await keys(page, "q");
expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth"]); expect(await paneTitles(page)).toEqual(["Explicata", "Expansion by depth"]);
expect(await focusedTitle(page)).toBe("Generation on demand"); expect(await focusedTitle(page)).toBe("Generation on demand");
await keys(page, "q"); await keys(page, "q");
expect(await paneTitles(page)).toEqual(["Infinispand"]); expect(await paneTitles(page)).toEqual(["Explicata"]);
expect(await focusedTitle(page)).toBe("Expansion by depth"); expect(await focusedTitle(page)).toBe("Expansion by depth");
// The first pane stays. // The first pane stays.
await keys(page, "q"); await keys(page, "q");
expect(await paneTitles(page)).toEqual(["Infinispand"]); expect(await paneTitles(page)).toEqual(["Explicata"]);
await expect(page.locator(".status .message")).toContainText("first pane stays"); await expect(page.locator(".status .message")).toContainText("first pane stays");
}); });
@@ -141,19 +141,19 @@ test("j and k move among siblings, and the strip follows", async ({ page }) => {
await keys(page, "j"); await keys(page, "j");
expect(await focusedTitle(page)).toBe("Pre-generated depth"); expect(await focusedTitle(page)).toBe("Pre-generated depth");
await keys(page, "l"); // open it: its pane appears await keys(page, "l"); // open it: its pane appears
expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth", "Pre-generated depth"]); expect(await paneTitles(page)).toEqual(["Explicata", "Expansion by depth", "Pre-generated depth"]);
await keys(page, "j"); // a closed sibling: the open one's pane stays until something else is opened await keys(page, "j"); // a closed sibling: the open one's pane stays until something else is opened
expect(await focusedTitle(page)).toBe("Generation on demand"); expect(await focusedTitle(page)).toBe("Generation on demand");
expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth", "Pre-generated depth"]); expect(await paneTitles(page)).toEqual(["Explicata", "Expansion by depth", "Pre-generated depth"]);
await keys(page, "k"); await keys(page, "k");
expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth", "Pre-generated depth"]); expect(await paneTitles(page)).toEqual(["Explicata", "Expansion by depth", "Pre-generated depth"]);
await keys(page, "k k k k"); // stops at the first sibling, never wanders into other panes await keys(page, "k k k k"); // stops at the first sibling, never wanders into other panes
expect(await focusedTitle(page)).toBe("Levels of a node"); expect(await focusedTitle(page)).toBe("Levels of a node");
await keys(page, "j j j j j j"); await keys(page, "j j j j j j");
expect(await focusedTitle(page)).toBe("Deeper, not longer"); expect(await focusedTitle(page)).toBe("Deeper, not longer");
// A click on a row does what l does: focus it and show its pane, beside the one already open there. // A click on a row does what l does: focus it and show its pane, beside the one already open there.
await page.locator(".pane .row", { hasText: "Generation on demand" }).click(); await page.locator(".pane .row", { hasText: "Generation on demand" }).click();
expect(await paneTitles(page)).toEqual(["Infinispand", "Expansion by depth", "Pre-generated depth", "Generation on demand"]); expect(await paneTitles(page)).toEqual(["Explicata", "Expansion by depth", "Pre-generated depth", "Generation on demand"]);
expect(await focusedTitle(page)).toBe("Generation on demand"); expect(await focusedTitle(page)).toBe("Generation on demand");
}); });
@@ -177,9 +177,9 @@ test("a pre-generated note opened in a pane is set inside the pane", async ({ pa
test("in panes everything is reachable with the mouse: rows, headings, marked spans, a dragged selection", async ({ page }) => { test("in panes everything is reachable with the mouse: rows, headings, marked spans, a dragged selection", async ({ page }) => {
await open(page); await open(page);
await page.locator(".pane .row", { hasText: "Borrowed from Gwern" }).click(); await page.locator(".pane .row", { hasText: "Borrowed from Gwern" }).click();
expect(await paneTitles(page)).toEqual(["Infinispand", "Borrowed from Gwern"]); expect(await paneTitles(page)).toEqual(["Explicata", "Borrowed from Gwern"]);
await page.locator(".pane .row", { hasText: "Semantic zoom" }).click(); await page.locator(".pane .row", { hasText: "Semantic zoom" }).click();
expect(await paneTitles(page)).toEqual(["Infinispand", "Borrowed from Gwern", "Semantic zoom"]); expect(await paneTitles(page)).toEqual(["Explicata", "Borrowed from Gwern", "Semantic zoom"]);
// A marked span opens its note, and closes it again. // A marked span opens its note, and closes it again.
const anchor = page.locator(".pane .anchor", { hasText: "StretchText" }); const anchor = page.locator(".pane .anchor", { hasText: "StretchText" });
await anchor.click(); await anchor.click();
@@ -189,11 +189,11 @@ test("in panes everything is reachable with the mouse: rows, headings, marked sp
// A pane's heading focuses its node, leaving the trail as it is; a click on the focused row whose pane is showing keeps it; its x closes it. // A pane's heading focuses its node, leaving the trail as it is; a click on the focused row whose pane is showing keeps it; its x closes it.
await page.locator(".pane-head", { hasText: "Borrowed from Gwern" }).click(); await page.locator(".pane-head", { hasText: "Borrowed from Gwern" }).click();
expect(await focusedTitle(page)).toBe("Borrowed from Gwern"); expect(await focusedTitle(page)).toBe("Borrowed from Gwern");
expect(await paneTitles(page)).toEqual(["Infinispand", "Borrowed from Gwern", "Semantic zoom"]); expect(await paneTitles(page)).toEqual(["Explicata", "Borrowed from Gwern", "Semantic zoom"]);
await page.locator(".pane .row", { hasText: "Borrowed from Gwern" }).click(); await page.locator(".pane .row", { hasText: "Borrowed from Gwern" }).click();
expect(await paneTitles(page)).toEqual(["Infinispand", "Borrowed from Gwern", "Semantic zoom"]); expect(await paneTitles(page)).toEqual(["Explicata", "Borrowed from Gwern", "Semantic zoom"]);
await page.locator('.pane[data-pane-index="1"] .pane-ctl .pane-btn.close').click(); await page.locator('.pane[data-pane-index="1"] .pane-ctl .pane-btn.close').click();
expect(await paneTitles(page)).toEqual(["Infinispand"]); expect(await paneTitles(page)).toEqual(["Explicata"]);
await page.locator(".pane .row", { hasText: "Borrowed from Gwern" }).click(); await page.locator(".pane .row", { hasText: "Borrowed from Gwern" }).click();
await page.locator(".pane .row", { hasText: "Typography" }).click(); await page.locator(".pane .row", { hasText: "Typography" }).click();
// Dragging across a pane's text makes that range the focus. // Dragging across a pane's text makes that range the focus.
@@ -223,14 +223,14 @@ test("past the viewport, earlier panes become spines; a click on one brings it b
expect(await strip.evaluate((el) => el.scrollWidth > el.clientWidth)).toBe(true); expect(await strip.evaluate((el) => el.scrollWidth > el.clientWidth)).toBe(true);
// The root has slid under the rest and shows as a spine, its title set vertically. // The root has slid under the rest and shows as a spine, its title set vertically.
const spine = page.locator('.col[data-covered] .spine').first(); const spine = page.locator('.col[data-covered] .spine').first();
await expect(spine).toHaveText("Infinispand"); await expect(spine).toHaveText("Explicata");
await expect.poll(() => spine.evaluate((el) => getComputedStyle(el).opacity)).toBe("1"); await expect.poll(() => spine.evaluate((el) => getComputedStyle(el).opacity)).toBe("1");
expect(await spine.locator(".spine-title").evaluate((el) => getComputedStyle(el).writingMode)).toBe("vertical-rl"); expect(await spine.locator(".spine-title").evaluate((el) => getComputedStyle(el).writingMode)).toBe("vertical-rl");
const box = (await spine.boundingBox())!; const box = (await spine.boundingBox())!;
expect(box.x).toBeGreaterThanOrEqual(0); expect(box.x).toBeGreaterThanOrEqual(0);
expect(box.width).toBeLessThan(60); expect(box.width).toBeLessThan(60);
await spine.click(); await spine.click();
expect(await focusedTitle(page)).toBe("Infinispand"); expect(await focusedTitle(page)).toBe("Explicata");
// The trail stays; the strip slides back to show the first pane whole. // The trail stays; the strip slides back to show the first pane whole.
await expect(page.locator(".strip .pane")).toHaveCount(4); await expect(page.locator(".strip .pane")).toHaveCount(4);
await expect.poll(async () => (await panes(page))[0].left).toBe(0); await expect.poll(async () => (await panes(page))[0].left).toBe(0);
+15 -15
View File
@@ -27,14 +27,14 @@ test.afterEach(({ page }) => settle(page));
test("a column's panes stand in the order of their sources: opened from a row higher up, a pane stands higher", async ({ page }) => { test("a column's panes stand in the order of their sources: opened from a row higher up, a pane stands higher", async ({ page }) => {
await library(page); await library(page);
await clickOpen(page, "Library", "Octopus minds"); await clickOpen(page, "Library", "Octopus minds");
await clickOpen(page, "Library", "Infinispand"); await clickOpen(page, "Library", "Explicata");
await expect.poll(() => colTitles(page, 1)).toEqual(["Infinispand", "Octopus minds"]); await expect.poll(() => colTitles(page, 1)).toEqual(["Explicata", "Octopus minds"]);
await clickOpen(page, "Library", "Fixed points"); await clickOpen(page, "Library", "Fixed points");
await expect.poll(() => colTitles(page, 1)).toEqual(["Infinispand", "Fixed points", "Octopus minds"]); await expect.poll(() => colTitles(page, 1)).toEqual(["Explicata", "Fixed points", "Octopus minds"]);
// Kept with the view. // Kept with the view.
await page.reload(); await page.reload();
await page.waitForSelector(".strip .pane"); await page.waitForSelector(".strip .pane");
expect(await colTitles(page, 1)).toEqual(["Infinispand", "Fixed points", "Octopus minds"]); expect(await colTitles(page, 1)).toEqual(["Explicata", "Fixed points", "Octopus minds"]);
await noFaults(page, "after a reload"); await noFaults(page, "after a reload");
}); });
@@ -98,12 +98,12 @@ test("a click anywhere in a pane that is not text, a row or a link makes that pa
test("every pane of a crowded column shows at least its tab, above or below the one looked at; tabs line up with the active rule; curves stay on their sources and lines", async ({ page }) => { test("every pane of a crowded column shows at least its tab, above or below the one looked at; tabs line up with the active rule; curves stay on their sources and lines", async ({ page }) => {
await page.setViewportSize({ width: 1920, height: 700 }); await page.setViewportSize({ width: 1920, height: 700 });
await library(page); await library(page);
for (const t of ["Octopus minds", "Infinispand", "The tides", "Fixed points", "What a proof is"]) await clickOpen(page, "Library", t); for (const t of ["Octopus minds", "Explicata", "The tides", "Fixed points", "What a proof is"]) await clickOpen(page, "Library", t);
// The one looked at near the top: those below it stack at the column's foot. // The one looked at near the top: those below it stack at the column's foot.
await pane(page, "Infinispand").locator(".pane-head h2").dispatchEvent("click"); await pane(page, "Explicata").locator(".pane-head h2").dispatchEvent("click");
await still(page); await still(page);
for (const first of ["Infinispand", "What a proof is"]) { for (const first of ["Explicata", "What a proof is"]) {
if (first !== "Infinispand") { if (first !== "Explicata") {
await pane(page, first).locator(".pane-head h2").dispatchEvent("click"); await pane(page, first).locator(".pane-head h2").dispatchEvent("click");
await still(page); await still(page);
} }
@@ -145,7 +145,7 @@ test("every pane of a crowded column shows at least its tab, above or below the
test("a pane cut off for any reason peeks out whole, across and down, and the curves follow it: covered from below or above, by its share, by the column's foot, beside a pinned pane, and with its column covered", async ({ page }) => { test("a pane cut off for any reason peeks out whole, across and down, and the curves follow it: covered from below or above, by its share, by the column's foot, beside a pinned pane, and with its column covered", async ({ page }) => {
await page.setViewportSize({ width: 1920, height: 700 }); await page.setViewportSize({ width: 1920, height: 700 });
await library(page); await library(page);
for (const t of ["Octopus minds", "Infinispand", "The tides", "Fixed points"]) await clickOpen(page, "Library", t); for (const t of ["Octopus minds", "Explicata", "The tides", "Fixed points"]) await clickOpen(page, "Library", t);
/** Hover each pane of the top-level trees' 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 sweep = async (label: string, across: boolean) => {
const col = page.locator(".strip > .col").nth(1); const col = page.locator(".strip > .col").nth(1);
@@ -190,7 +190,7 @@ test("a pane cut off for any reason peeks out whole, across and down, and the cu
return peeked; return peeked;
}; };
// Covered from below (the one looked at near the top) and from above (near the foot). // Covered from below (the one looked at near the top) and from above (near the foot).
await pane(page, "Infinispand").locator(".pane-head h2").dispatchEvent("click"); await pane(page, "Explicata").locator(".pane-head h2").dispatchEvent("click");
await still(page); await still(page);
expect(await sweep("top looked at", false)).toBeGreaterThan(0); expect(await sweep("top looked at", false)).toBeGreaterThan(0);
await pane(page, "Octopus minds").locator(".pane-head h2").dispatchEvent("click"); await pane(page, "Octopus minds").locator(".pane-head h2").dispatchEvent("click");
@@ -214,7 +214,7 @@ test("a pane cut off for any reason peeks out whole, across and down, and the cu
await page.setViewportSize({ width: 1920, height: 1080 }); 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 page.evaluate(() => Object.keys(localStorage).filter((k) => k.startsWith("ie:view:")).forEach((k) => localStorage.removeItem(k)));
await library(page); await library(page);
await clickOpen(page, "Library", "Infinispand"); await clickOpen(page, "Library", "Explicata");
await clickOpen(page, "Library", "Octopus minds"); await clickOpen(page, "Library", "Octopus minds");
await pane(page, "Octopus minds").locator(".pane-head h2").dispatchEvent("click"); await pane(page, "Octopus minds").locator(".pane-head h2").dispatchEvent("click");
await still(page); await still(page);
@@ -224,7 +224,7 @@ test("a pane cut off for any reason peeks out whole, across and down, and the cu
test("the curves keep to their sources and landing lines through every kind of layout change: scrolls, a resize, folding, a drag, an article arriving, a sticky tab", async ({ page }) => { test("the curves keep to their sources and landing lines through every kind of layout change: scrolls, a resize, folding, a drag, an article arriving, a sticky tab", async ({ page }) => {
await library(page); await library(page);
for (const t of ["Infinispand", "Fixed points"]) await clickOpen(page, "Library", t); for (const t of ["Explicata", "Fixed points"]) await clickOpen(page, "Library", t);
await clickOpen(page, "Fixed points", "Recursion without names"); await clickOpen(page, "Fixed points", "Recursion without names");
await noFaults(page, "opened"); await noFaults(page, "opened");
await clickOpen(page, "Recursion without names", "fixed-point combinator", ".lnk, .anchor"); await clickOpen(page, "Recursion without names", "fixed-point combinator", ".lnk, .anchor");
@@ -304,7 +304,7 @@ test("a dotted curve to a source out of sight in its pane turns, at its end, tow
test("Alt with h j k l moves between panes from a node, a selection or an article; left then right comes back; [ ] still go up and down", async ({ page }) => { test("Alt with h j k l moves between panes from a node, a selection or an article; left then right comes back; [ ] still go up and down", async ({ page }) => {
await library(page); await library(page);
await clickOpen(page, "Library", "Infinispand"); await clickOpen(page, "Library", "Explicata");
await clickOpen(page, "Library", "Fixed points"); await clickOpen(page, "Library", "Fixed points");
await clickOpen(page, "Fixed points", "Recursion without names"); await clickOpen(page, "Fixed points", "Recursion without names");
await pane(page, "Recursion without names").locator(".pane-head h2").dispatchEvent("click"); await pane(page, "Recursion without names").locator(".pane-head h2").dispatchEvent("click");
@@ -316,11 +316,11 @@ test("Alt with h j k l moves between panes from a node, a selection or an articl
await expect.poll(() => activeTitle(page)).toBe("Recursion without names"); await expect.poll(() => activeTitle(page)).toBe("Recursion without names");
await page.keyboard.press("Alt+h"); await page.keyboard.press("Alt+h");
await page.keyboard.press("Alt+k"); await page.keyboard.press("Alt+k");
await expect.poll(() => activeTitle(page)).toBe("Infinispand"); await expect.poll(() => activeTitle(page)).toBe("Explicata");
await page.keyboard.press("Alt+j"); await page.keyboard.press("Alt+j");
await expect.poll(() => activeTitle(page)).toBe("Fixed points"); await expect.poll(() => activeTitle(page)).toBe("Fixed points");
await page.keyboard.press("Alt+ArrowUp"); await page.keyboard.press("Alt+ArrowUp");
await expect.poll(() => activeTitle(page)).toBe("Infinispand"); await expect.poll(() => activeTitle(page)).toBe("Explicata");
await keys(page, "]"); await keys(page, "]");
await expect.poll(() => activeTitle(page)).toBe("Fixed points"); await expect.poll(() => activeTitle(page)).toBe("Fixed points");
await page.keyboard.press("Alt+h"); await page.keyboard.press("Alt+h");
+2 -2
View File
@@ -27,8 +27,8 @@ async function forest(page: Page) {
await open(page, "Library", "Octopus minds"); await open(page, "Library", "Octopus minds");
await open(page, "Octopus minds", "A separate experiment"); await open(page, "Octopus minds", "A separate experiment");
await open(page, "A separate experiment", "The common ancestor"); await open(page, "A separate experiment", "The common ancestor");
await open(page, "Library", "Infinispand"); await open(page, "Library", "Explicata");
await open(page, /Infinispand/, "Expansion by depth"); await open(page, /Explicata/, "Expansion by depth");
await open(page, "Expansion by depth", "Levels of a node"); await open(page, "Expansion by depth", "Levels of a node");
await open(page, "Expansion by depth", "Generation on demand"); await open(page, "Expansion by depth", "Generation on demand");
await open(page, "Library", "The tides"); await open(page, "Library", "The tides");
+1 -1
View File
@@ -12,7 +12,7 @@ async function open(page: Page) {
(globalThis as any).__opened = []; (globalThis as any).__opened = [];
window.open = ((url: string) => ((globalThis as any).__opened.push(String(url)), null)) as typeof window.open; window.open = ((url: string) => ((globalThis as any).__opened.push(String(url)), null)) as typeof window.open;
}); });
await openPage(page, "Infinispand"); await openPage(page, "Explicata");
} }
test.describe.configure({ mode: "serial" }); test.describe.configure({ mode: "serial" });
+1 -1
View File
@@ -4,7 +4,7 @@
* bare [[marks]] resolved on save, model-written text with its marks taken out and checked, the * bare [[marks]] resolved on save, model-written text with its marks taken out and checked, the
* Related list, /linkhere and /linkall with progress and a cancel, the /autolink modes, and latency. Against the * Related list, /linkhere and /linkall with progress and a cancel, the /autolink modes, and latency. Against the
* mock model, the mock Wikipedia (Octopus, Cephalopod, Fred Hoyle, Hoyle state, Carbon-12, Lambda * mock model, the mock Wikipedia (Octopus, Cephalopod, Fred Hoyle, Hoyle state, Carbon-12, Lambda
* calculus, …) and the hashed-words embedder (IE_EMBED=fake). * calculus, …) and the hashed-words embedder (EX_EMBED=fake).
*/ */
import { expect, test, type Page } from "@playwright/test"; import { expect, test, type Page } from "@playwright/test";
import { addTop, autoLayout, command, idle, jump, keys, linksHere, paced, selected, settle, state, visit, writeReport } from "./helpers"; import { addTop, autoLayout, command, idle, jump, keys, linksHere, paced, selected, settle, state, visit, writeReport } from "./helpers";
+2 -2
View File
@@ -8,12 +8,12 @@
* term of several words and not a single lower-case word, and fails on a sentence that says * term of several words and not a single lower-case word, and fails on a sentence that says
* "mockfail" (src/llm/mock.ts). * "mockfail" (src/llm/mock.ts).
* *
* IE_SHOTS=<dir> also saves the links list with each filter, light and dark, into that directory. * EX_SHOTS=<dir> also saves the links list with each filter, light and dark, into that directory.
*/ */
import { expect, test, type Page } from "@playwright/test"; import { expect, test, type Page } from "@playwright/test";
import { addTop, command, idle, keys, linksHere, selected, settle, state, visit } from "./helpers"; import { addTop, command, idle, keys, linksHere, selected, settle, state, visit } from "./helpers";
const SHOTS = process.env.IE_SHOTS; const SHOTS = process.env.EX_SHOTS;
const nolink = (page: Page) => state(page, (s) => (s.snap.nodes[s.focus.node].nolink ?? []) as string[]); const nolink = (page: Page) => state(page, (s) => (s.snap.nodes[s.focus.node].nolink ?? []) as string[]);
const panel = (page: Page) => page.locator("[data-links-panel]"); const panel = (page: Page) => page.locator("[data-links-panel]");
+1 -1
View File
@@ -3,7 +3,7 @@
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content" /> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content" />
<title>Infinispand</title> <title>Explicata</title>
</head> </head>
<body> <body>
<div id="app"></div> <div id="app"></div>
+2 -2
View File
@@ -1,11 +1,11 @@
{ {
"name": "infinispand", "name": "explicata",
"version": "1.0.0", "version": "1.0.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "infinispand", "name": "explicata",
"version": "1.0.0", "version": "1.0.0",
"dependencies": { "dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.3.325", "@anthropic-ai/claude-agent-sdk": "^0.3.325",
+2 -2
View File
@@ -1,5 +1,5 @@
{ {
"name": "infinispand", "name": "explicata",
"version": "1.0.0", "version": "1.0.0",
"private": true, "private": true,
"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.", "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.",
@@ -8,7 +8,7 @@
"test": "vitest run", "test": "vitest run",
"dev": "tsx server/index.ts", "dev": "tsx server/index.ts",
"build": "vite build", "build": "vite build",
"start": "IE_PROD=1 tsx server/index.ts", "start": "EX_PROD=1 tsx server/index.ts",
"e2e": "playwright test", "e2e": "playwright test",
"check": "tsc --noEmit", "check": "tsc --noEmit",
"verify": "tsx scripts/verify.ts", "verify": "tsx scripts/verify.ts",
+5 -5
View File
@@ -3,11 +3,11 @@ import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { defineConfig } from "@playwright/test"; import { defineConfig } from "@playwright/test";
// IE_E2E_PORT lets two runs go side by side. // EX_E2E_PORT lets two runs go side by side.
const PORT = Number(process.env.IE_E2E_PORT ?? 4760); const PORT = Number(process.env.EX_E2E_PORT ?? 4760);
// Each run gets an empty data directory, so it starts from a freshly seeded library. // Each run gets an empty data directory, so it starts from a freshly seeded library.
const data = process.env.IE_E2E_DATA ?? mkdtempSync(join(tmpdir(), "ie-e2e-")); const data = process.env.EX_E2E_DATA ?? mkdtempSync(join(tmpdir(), "ie-e2e-"));
process.env.IE_E2E_DATA = data; process.env.EX_E2E_DATA = data;
export default defineConfig({ export default defineConfig({
testDir: "e2e", testDir: "e2e",
@@ -27,7 +27,7 @@ export default defineConfig({
// Each port builds into its own directory: two runs side by side must not rebuild the files the // Each port builds into its own directory: two runs side by side must not rebuild the files the
// other is serving. // other is serving.
command: `npx vite build --outDir dist-e2e-${PORT} --emptyOutDir && npx tsx server/index.ts`, command: `npx vite build --outDir dist-e2e-${PORT} --emptyOutDir && npx tsx server/index.ts`,
env: { IE_DIST: `dist-e2e-${PORT}`, IE_PROD: "1", IE_LLM: "mock", IE_MOCK_DELAY: "10", IE_DATA: data, PORT: String(PORT), IE_USER: "tester", IE_WIKI: "mock", IE_EMBED: "fake", IE_WIKI_MOCK_BULK_MS: "60" }, env: { EX_DIST: `dist-e2e-${PORT}`, EX_PROD: "1", EX_LLM: "mock", EX_MOCK_DELAY: "10", EX_DATA: data, PORT: String(PORT), EX_USER: "tester", EX_WIKI: "mock", EX_EMBED: "fake", EX_WIKI_MOCK_BULK_MS: "60" },
url: `http://localhost:${PORT}/api/state`, url: `http://localhost:${PORT}/api/state`,
reuseExistingServer: false, reuseExistingServer: false,
timeout: 60_000, timeout: 60_000,
+1 -1
View File
@@ -25,7 +25,7 @@ interface Fixture {
} }
function base() { function base() {
const doc = Doc.create("alice", "Infinispand", "A document that expands without limit."); const doc = Doc.create("alice", "Explicata", "A document that expands without limit.");
const root = doc.snap().root; const root = doc.snap().root;
const { created } = doc.apply( const { created } = doc.apply(
[ [
+16 -16
View File
@@ -1,18 +1,18 @@
/** /**
* Evaluate the link scanner (server/links/scan.ts) on the starter library against hand labels. * 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 [files…] live: fill the Wikipedia cache for the * EX_DATA=/tmp/x npx tsx scripts/linkEval.ts warm [files…] live: fill the Wikipedia cache for the
* sampled sections, write their traces * sampled sections, write their traces
* IE_DATA=/tmp/x npx tsx scripts/linkEval.ts eval [files…] offline (cache only): precision and * EX_DATA=/tmp/x npx tsx scripts/linkEval.ts eval [files…] offline (cache only): precision and
* recall against the labels * recall against the labels
* IE_DATA=/tmp/x npx tsx scripts/linkEval.ts trace [files…] offline: the traces, for labelling * EX_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 * 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 * named file's tree (by file name, without .md) 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. * 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 * `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 * of requests (EX_EVAL_BUDGET, default 380); nothing but candidate phrases is sent. The embedding
* model is the real one unless IE_EMBED says otherwise. * model is the real one unless EX_EMBED says otherwise.
*/ */
import { readFileSync, readdirSync, writeFileSync } from "node:fs"; import { readFileSync, readdirSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path"; import { join, resolve } from "node:path";
@@ -25,10 +25,10 @@ import { Linker, type TraceRow, type Tuning } from "../server/links/scan";
import { WikiClient } from "../server/wiki"; import { WikiClient } from "../server/wiki";
const [mode = "eval", ...rest] = process.argv.slice(2); const [mode = "eval", ...rest] = process.argv.slice(2);
const DATA = resolve(process.env.IE_DATA ?? ""); const DATA = resolve(process.env.EX_DATA ?? "");
if (!process.env.IE_DATA) throw new Error("set IE_DATA to a scratch directory"); if (!process.env.EX_DATA) throw new Error("set EX_DATA to a scratch directory");
const SAMPLE = Number(process.env.IE_EVAL_SAMPLE ?? 12); const SAMPLE = Number(process.env.EX_EVAL_SAMPLE ?? 12);
const BUDGET = Number(process.env.IE_EVAL_BUDGET ?? 380); const BUDGET = Number(process.env.EX_EVAL_BUDGET ?? 380);
const FILES = 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"); const LABELS = resolve("tests/fixtures/link-labels.json");
@@ -68,7 +68,7 @@ const wiki = new WikiClient({
...(live ? {} : { fetch: (async () => { throw new TypeError("offline (eval)"); }) as typeof fetch, offlineHoldMs: 0, spacingMs: 0 }), ...(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 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 tuning: Partial<Tuning> = JSON.parse(process.env.EX_EVAL_TUNING ?? "{}");
const linker = new Linker({ doc: () => doc, wiki: () => wiki, embedder: embedder(), index, tuning }); const linker = new Linker({ doc: () => doc, wiki: () => wiki, embedder: embedder(), index, tuning });
const t0 = performance.now(); const t0 = performance.now();
@@ -140,7 +140,7 @@ if (mode === "heldout") {
for (const r of chosen.filter((r) => r.tier === "auto" && !ok(r))) console.log(fmt(r)); for (const r of chosen.filter((r) => r.tier === "auto" && !ok(r))) console.log(fmt(r));
console.log("\nauto right:"); console.log("\nauto right:");
for (const r of chosen.filter((r) => r.tier === "auto" && ok(r))) console.log(fmt(r)); for (const r of chosen.filter((r) => r.tier === "auto" && ok(r))) console.log(fmt(r));
if (process.env.IE_EVAL_SUGGEST) { if (process.env.EX_EVAL_SUGGEST) {
console.log("\nsuggest errors:"); console.log("\nsuggest errors:");
for (const r of chosen.filter((r) => r.tier === "suggest" && !ok(r))) console.log(fmt(r)); for (const r of chosen.filter((r) => r.tier === "suggest" && !ok(r))) console.log(fmt(r));
} }
@@ -191,18 +191,18 @@ const show = (title: string, list: Row[]) => {
const wrong = chosen.filter((r) => find(r) && !correct(r)); const wrong = chosen.filter((r) => find(r) && !correct(r));
show("wrong (chosen, label disagrees):", wrong); 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))); 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) { if (missed.length && process.env.EX_EVAL_MISSES) {
console.log("\nmissed (worth linking, not chosen or wrong target):"); console.log("\nmissed (worth linking, not chosen or wrong target):");
for (const l of missed) { for (const l of missed) {
const r = rows.find((x) => x.doc === l.doc && x.node === l.node && x.key === l.key); 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)"}`); 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)); if (process.env.EX_EVAL_RIGHT) show("right:", chosen.filter(correct));
// Every labelled row with what judge() saw, for tuning (IE_EVAL_DUMP=file). // Every labelled row with what judge() saw, for tuning (EX_EVAL_DUMP=file).
if (process.env.IE_EVAL_DUMP) { if (process.env.EX_EVAL_DUMP) {
const dump = rows.map((r) => ({ ...r, label: find(r)?.label ?? null, labelTarget: find(r)?.target ?? null, right: correct(r) })); 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)); writeFileSync(process.env.EX_EVAL_DUMP, JSON.stringify(dump, null, 1));
} }
// The embedding worker is unref'd, but a script is done here whatever is still open. // The embedding worker is unref'd, but a script is done here whatever is still open.
process.exit(0); process.exit(0);
+1 -1
View File
@@ -72,7 +72,7 @@ export class Bundle {
this.nodeIndex.watch(store.main); this.nodeIndex.watch(store.main);
const getLinker = () => (this.linker ??= new Linker({ doc: main, wiki: shared.wiki, embedder: shared.embed, index: this.nodeIndex })); const getLinker = () => (this.linker ??= new Linker({ doc: main, wiki: shared.wiki, embedder: shared.embed, index: this.nodeIndex }));
this.pending = new PendingStore(join(store.dir, "links", "pending.json")); this.pending = new PendingStore(join(store.dir, "links", "pending.json"));
// The link reviewer asks the configured model (no tools, structured verdicts); IE_REVIEW_CALLS caps a background job's calls. // The link reviewer asks the configured model (no tools, structured verdicts); EX_REVIEW_CALLS caps a background job's calls.
this.reviewer = new Reviewer({ llm: shared.llm, wiki: shared.wiki, pending: this.pending, snap: () => store.main.snap() }); this.reviewer = new Reviewer({ llm: shared.llm, wiki: shared.wiki, pending: this.pending, snap: () => store.main.snap() });
this.jobs = new Jobs({ this.jobs = new Jobs({
snap: () => store.main.snap(), snap: () => store.main.snap(),
+10 -10
View File
@@ -4,15 +4,15 @@
* *
* Node text never leaves the machine: the model runs in a worker thread of this process * Node text never leaves the machine: the model runs in a worker thread of this process
* (transformers.js on onnxruntime-node, server/embedWorker.mjs). It is loaded on first use; its * (transformers.js on onnxruntime-node, server/embedWorker.mjs). It is loaded on first use; its
* files are downloaded once from the Hugging Face hub into <IE_DATA>/models/. If that fails * files are downloaded once from the Hugging Face hub into <EX_DATA>/models/. If that fails
* (offline, no native runtime), embed() returns null and callers fall back to text search. * (offline, no native runtime), embed() returns null and callers fall back to text search.
* *
* embedder.embed(texts) Float32Array[] (unit length) or null * embedder.embed(texts) Float32Array[] (unit length) or null
* new VectorIndex(file).upsert() re-embeds only entries whose text hash changed * new VectorIndex(file).upsert() re-embeds only entries whose text hash changed
* index.search / textSearch / hybrid cosine top-k, BM25, and the two fused * index.search / textSearch / hybrid cosine top-k, BM25, and the two fused
* *
* IE_EMBED_MODEL picks the model (default Xenova/bge-small-en-v1.5, MIT, 384 dimensions); * EX_EMBED_MODEL picks the model (default Xenova/bge-small-en-v1.5, MIT, 384 dimensions);
* IE_EMBED=off turns embeddings off, IE_EMBED=fake uses hashed words (the tests). * EX_EMBED=off turns embeddings off, EX_EMBED=fake uses hashed words (the tests).
*/ */
import { createHash } from "node:crypto"; import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync } from "node:fs"; import { existsSync, mkdirSync, readFileSync } from "node:fs";
@@ -46,15 +46,15 @@ export type Loader = (spec: ModelSpec, cacheDir: string) => Promise<EmbedFn>;
/** /**
* The model with transformers.js, in a worker thread: loading it and every batch run off the main * The model with transformers.js, in a worker thread: loading it and every batch run off the main
* thread, so the server keeps answering while a library is being embedded. A few threads are * thread, so the server keeps answering while a library is being embedded. A few threads are
* nearly as fast as all of them and leave the machine usable (IE_EMBED_THREADS, default 4); * nearly as fast as all of them and leave the machine usable (EX_EMBED_THREADS, default 4);
* IE_EMBED_OFFLINE=1 reads only files downloaded before. * EX_EMBED_OFFLINE=1 reads only files downloaded before.
*/ */
const workerLoader: Loader = (spec, cacheDir) => const workerLoader: Loader = (spec, cacheDir) =>
new Promise((resolveLoad, rejectLoad) => { new Promise((resolveLoad, rejectLoad) => {
// execArgv: [] keeps a TypeScript loader (tsx) out of the worker, which is plain JavaScript. // execArgv: [] keeps a TypeScript loader (tsx) out of the worker, which is plain JavaScript.
const worker = new Worker(new URL("./embedWorker.mjs", import.meta.url), { const worker = new Worker(new URL("./embedWorker.mjs", import.meta.url), {
execArgv: [], execArgv: [],
workerData: { id: spec.id, pooling: spec.pooling, cacheDir, offline: process.env.IE_EMBED_OFFLINE === "1", threads: Number(process.env.IE_EMBED_THREADS) || 4 }, workerData: { id: spec.id, pooling: spec.pooling, cacheDir, offline: process.env.EX_EMBED_OFFLINE === "1", threads: Number(process.env.EX_EMBED_THREADS) || 4 },
}); });
// The worker must not keep a script alive that is otherwise done. // The worker must not keep a script alive that is otherwise done.
worker.unref(); worker.unref();
@@ -90,7 +90,7 @@ const workerLoader: Loader = (spec, cacheDir) =>
}); });
/** /**
* A stand-in model for tests and offline runs (IE_EMBED=fake): a bag of hashed words, normalised, * A stand-in model for tests and offline runs (EX_EMBED=fake): a bag of hashed words, normalised,
* so texts sharing words are near each other. It needs no download and separates nothing subtle. * so texts sharing words are near each other. It needs no download and separates nothing subtle.
*/ */
export function fakeVector(text: string, dim = 384): Float32Array { export function fakeVector(text: string, dim = 384): Float32Array {
@@ -176,10 +176,10 @@ export class Embedder {
} }
let shared: Embedder | null = null; let shared: Embedder | null = null;
/** The server's embedder, configured from IE_DATA, IE_EMBED_MODEL and IE_EMBED. */ /** The server's embedder, configured from EX_DATA, EX_EMBED_MODEL and EX_EMBED. */
export function embedder(): Embedder { export function embedder(): Embedder {
const mode = process.env.IE_EMBED; const mode = process.env.EX_EMBED;
shared ??= new Embedder({ model: mode === "fake" ? "fake" : process.env.IE_EMBED_MODEL, off: mode === "off", loader: mode === "fake" ? fakeLoader : workerLoader }); shared ??= new Embedder({ model: mode === "fake" ? "fake" : process.env.EX_EMBED_MODEL, off: mode === "off", loader: mode === "fake" ? fakeLoader : workerLoader });
return shared; return shared;
} }
+24 -24
View File
@@ -33,13 +33,13 @@ import { JOB_CALLS } from "./links/review";
const PORT = Number(process.env.PORT ?? 4747); const PORT = Number(process.env.PORT ?? 4747);
// Host names the dev server answers to besides localhost. Tailscale names are allowed so that // Host names the dev server answers to besides localhost. Tailscale names are allowed so that
// `tailscale serve` works; IE_HOSTS adds more (comma-separated; a leading dot matches subdomains). // `tailscale serve` works; EX_HOSTS adds more (comma-separated; a leading dot matches subdomains).
const ALLOWED_HOSTS = [".ts.net", ...(process.env.IE_HOSTS ?? "").split(",").map((h) => h.trim()).filter(Boolean)]; const ALLOWED_HOSTS = [".ts.net", ...(process.env.EX_HOSTS ?? "").split(",").map((h) => h.trim()).filter(Boolean)];
const DATA = dataDir(); const DATA = dataDir();
const PROD = process.env.IE_PROD === "1"; const PROD = process.env.EX_PROD === "1";
const MODEL = process.env.IE_MODEL ?? "claude-opus-5-5"; const MODEL = process.env.EX_MODEL ?? "claude-opus-5-5";
const USER = process.env.IE_USER ?? userInfo().username; const USER = process.env.EX_USER ?? userInfo().username;
const LIBRARY = resolve(process.env.IE_LIBRARY ?? join(root, "library")); const LIBRARY = resolve(process.env.EX_LIBRARY ?? join(root, "library"));
// ---- model ---- // ---- model ----
@@ -52,11 +52,11 @@ if (process.env.ANTHROPIC_API_KEY?.startsWith("sk-ant-oat")) {
console.log("ANTHROPIC_API_KEY holds a subscription token; using it as CLAUDE_CODE_OAUTH_TOKEN instead."); console.log("ANTHROPIC_API_KEY holds a subscription token; using it as CLAUDE_CODE_OAUTH_TOKEN instead.");
} }
const apiKey = Boolean(process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN); const apiKey = Boolean(process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN);
const wanted = process.env.IE_LLM ?? (apiKey ? "claude" : process.env.CLAUDE_CODE_OAUTH_TOKEN ? "subscription" : "off"); const wanted = process.env.EX_LLM ?? (apiKey ? "claude" : process.env.CLAUDE_CODE_OAUTH_TOKEN ? "subscription" : "off");
const llm: LLM | null = const llm: LLM | null =
wanted === "claude" ? claudeLLM(MODEL) wanted === "claude" ? claudeLLM(MODEL)
: wanted === "subscription" ? subscriptionLLM(MODEL) : wanted === "subscription" ? subscriptionLLM(MODEL)
: wanted === "mock" ? withMockUsage(mockLLM({ delay: Number(process.env.IE_MOCK_DELAY ?? 12) })) : wanted === "mock" ? withMockUsage(mockLLM({ delay: Number(process.env.EX_MOCK_DELAY ?? 12) }))
: null; : null;
// Usage: every provider reports into one tracker (server/usage.ts), served at GET /api/usage. // Usage: every provider reports into one tracker (server/usage.ts), served at GET /api/usage.
@@ -71,27 +71,27 @@ if (wanted === "subscription") {
// ---- web research for the editor agent ---- // ---- web research for the editor agent ----
// IE_WEB=off takes web search and fetch away from the agent entirely; IE_WEB_SEARCHES and // EX_WEB=off takes web search and fetch away from the agent entirely; EX_WEB_SEARCHES and
// IE_WEB_FETCHES cap each run (default 5 and 5). The browser asks for research; this decides. // EX_WEB_FETCHES cap each run (default 5 and 5). The browser asks for research; this decides.
const web = webConfig(process.env, Boolean(llm)); const web = webConfig(process.env, Boolean(llm));
if (process.env.IE_WEB && !web.on && web.why) console.warn(`web research is off: ${web.why}.`); if (process.env.EX_WEB && !web.on && web.why) console.warn(`web research is off: ${web.why}.`);
// ---- Wikipedia ---- // ---- Wikipedia ----
// IE_WIKI picks where /api/wiki/* gets its answers: the real Wikipedia (live), the fixtures in // EX_WIKI picks where /api/wiki/* gets its answers: the real Wikipedia (live), the fixtures in
// server/wikiMock.ts (mock: tests and offline work, no network at all), or nowhere (off). An // server/wikiMock.ts (mock: tests and offline work, no network at all), or nowhere (off). An
// unrecognised value is treated as off, so a typo never sends requests nobody asked for. // unrecognised value is treated as off, so a typo never sends requests nobody asked for.
type WikiMode = "live" | "mock" | "off"; type WikiMode = "live" | "mock" | "off";
const wikiWanted = process.env.IE_WIKI ?? "live"; const wikiWanted = process.env.EX_WIKI ?? "live";
const wikiMode: WikiMode = wikiWanted === "live" || wikiWanted === "mock" ? wikiWanted : "off"; const wikiMode: WikiMode = wikiWanted === "live" || wikiWanted === "mock" ? wikiWanted : "off";
if (wikiMode !== wikiWanted) console.warn(`IE_WIKI=${wikiWanted} is not live, mock or off; Wikipedia is off.`); if (wikiMode !== wikiWanted) console.warn(`EX_WIKI=${wikiWanted} is not live, mock or off; Wikipedia is off.`);
// The mock keeps nothing on disk and never holds itself offline, so one test's "offline" title // The mock keeps nothing on disk and never holds itself offline, so one test's "offline" title
// does not leak into the next. // does not leak into the next.
const mockWiki = wikiMode === "mock" ? new WikiClient({ lang: process.env.IE_WIKI_LANG, fetch: makeMockWikiFetch(undefined, Number(process.env.IE_WIKI_MOCK_BULK_MS) || 0), spacingMs: 0, persist: false, offlineHoldMs: 0 }) : null; const mockWiki = wikiMode === "mock" ? new WikiClient({ lang: process.env.EX_WIKI_LANG, fetch: makeMockWikiFetch(undefined, Number(process.env.EX_WIKI_MOCK_BULK_MS) || 0), spacingMs: 0, persist: false, offlineHoldMs: 0 }) : null;
const wikiClient = () => (wikiMode === "off" ? null : (mockWiki ?? wiki())); const wikiClient = () => (wikiMode === "off" ? null : (mockWiki ?? wiki()));
const handleWiki = wikiMode === "off" ? wikiOff : wikiRoutes(() => wikiClient()!); const handleWiki = wikiMode === "off" ? wikiOff : wikiRoutes(() => wikiClient()!);
/** What the UI may know: the mode, the language, and whether a contact is set (never the contact). */ /** What the UI may know: the mode, the language, and whether a contact is set (never the contact). */
const wikiState = { mode: wikiMode, lang: wikiLang(process.env.IE_WIKI_LANG), contact: validContact(process.env.IE_WIKI_CONTACT) !== null }; const wikiState = { mode: wikiMode, lang: wikiLang(process.env.EX_WIKI_LANG), contact: validContact(process.env.EX_WIKI_CONTACT) !== null };
/** A short reason for a failed model call, whichever provider made it. */ /** A short reason for a failed model call, whichever provider made it. */
const explain = (err: unknown) => (err instanceof SubscriptionError ? { status: err.status, message: err.message } : describeError(err)); const explain = (err: unknown) => (err instanceof SubscriptionError ? { status: err.status, message: err.message } : describeError(err));
@@ -104,7 +104,7 @@ const started = performance.now();
// migration (npm run migrate) has a dry run and verifies what it writes. // migration (npm run migrate) has a dry run and verifies what it writes.
const held = lockHolder(DATA); const held = lockHolder(DATA);
if (held) { if (held) {
console.error(`Another server (pid ${held.pid}${held.port ? `, port ${held.port}` : ""}) has ${DATA} open; stop it first, or set IE_DATA to another directory.`); console.error(`Another server (pid ${held.pid}${held.port ? `, port ${held.port}` : ""}) has ${DATA} open; stop it first, or set EX_DATA to another directory.`);
process.exit(1); process.exit(1);
} }
const libraries = new Libraries(DATA); const libraries = new Libraries(DATA);
@@ -125,20 +125,20 @@ const startMs = Math.round(performance.now() - started);
// ---- each library's link discovery, notices and routes (server/bundle.ts) ---- // ---- each library's link discovery, notices and routes (server/bundle.ts) ----
// The embedding model is loaded on first use, in a worker thread shared by every library; // The embedding model is loaded on first use, in a worker thread shared by every library;
// IE_EMBED=off turns it off, and scanning then matches by text alone. // EX_EMBED=off turns it off, and scanning then matches by text alone.
const embed = process.env.IE_EMBED === "off" ? null : embedder(); const embed = process.env.EX_EMBED === "off" ? null : embedder();
const shared: Shared = { const shared: Shared = {
llm: () => llm, llm: () => llm,
wiki: wikiClient, wiki: wikiClient,
embed, embed,
reviewCalls: Math.max(1, Number(process.env.IE_REVIEW_CALLS) || JOB_CALLS), reviewCalls: Math.max(1, Number(process.env.EX_REVIEW_CALLS) || JOB_CALLS),
user: USER, user: USER,
state: () => ({ state: () => ({
user: USER, user: USER,
llm: llm?.kind ?? "off", llm: llm?.kind ?? "off",
model: llm?.model ?? null, model: llm?.model ?? null,
wiki: wikiState, wiki: wikiState,
embed: embed ? (process.env.IE_EMBED === "fake" ? "fake" : "on") : "off", embed: embed ? (process.env.EX_EMBED === "fake" ? "fake" : "on") : "off",
web: { on: web.on, searches: web.searches, fetches: web.fetches }, web: { on: web.on, searches: web.searches, fetches: web.fetches },
libraries: libraries.list(), libraries: libraries.list(),
}), }),
@@ -295,8 +295,8 @@ const CSP = [
].join("; "); ].join("; ");
function serveStatic(res: ServerResponse, path: string) { function serveStatic(res: ServerResponse, path: string) {
// IE_DIST: another build to serve (the browser tests build one per port, so runs side by side do not collide). // EX_DIST: another build to serve (the browser tests build one per port, so runs side by side do not collide).
const dist = resolve(root, process.env.IE_DIST ?? "dist"); const dist = resolve(root, process.env.EX_DIST ?? "dist");
let file = resolve(dist, "." + path); let file = resolve(dist, "." + path);
if (!file.startsWith(dist) || !existsSync(file) || path === "/") file = join(dist, "index.html"); if (!file.startsWith(dist) || !existsSync(file) || path === "/") file = join(dist, "index.html");
res.writeHead(200, { res.writeHead(200, {
@@ -334,7 +334,7 @@ createServer(async (req, res) => {
serveStatic(res, path); serveStatic(res, path);
} }
}).listen(PORT, "127.0.0.1", () => { }).listen(PORT, "127.0.0.1", () => {
console.log(`Infinispand http://localhost:${PORT} model: ${llm ? `${llm.kind}${llm.model ? `: ${llm.model}` : ""}` : "off (set ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN to generate)"} data: ${DATA}`); console.log(`Explicata http://localhost:${PORT} model: ${llm ? `${llm.kind}${llm.model ? `: ${llm.model}` : ""}` : "off (set ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN to generate)"} data: ${DATA}`);
for (const l of libraries.list()) console.log(`library “${l.title}” (/l/${l.id}): ${libraries.get(l.id)!.titles().length} top-level sections, ${l.nodes} nodes`); for (const l of libraries.list()) console.log(`library “${l.title}” (/l/${l.id}): ${libraries.get(l.id)!.titles().length} top-level sections, ${l.nodes} nodes`);
console.log(`${libraries.stores.size} librar${libraries.stores.size === 1 ? "y" : "ies"} opened in ${startMs} ms`); console.log(`${libraries.stores.size} librar${libraries.stores.size === 1 ? "y" : "ies"} opened in ${startMs} ms`);
console.log(`web research: ${web.on ? `on (at most ${web.searches} searches and ${web.fetches} pages read per request)` : `off${web.why ? ` (${web.why})` : ""}`}`); console.log(`web research: ${web.on ? `on (at most ${web.searches} searches and ${web.fetches} pages read per request)` : `off${web.why ? ` (${web.why})` : ""}`}`);
+2 -2
View File
@@ -32,7 +32,7 @@ export interface JobState {
finishedAt?: number; finishedAt?: number;
/** Seconds left, estimated from the requests still to make and the client's spacing. */ /** Seconds left, estimated from the requests still to make and the client's spacing. */
etaSec: number | null; etaSec: number | null;
/** The client is spacing requests for want of a contact (IE_WIKI_CONTACT). */ /** The client is spacing requests for want of a contact (EX_WIKI_CONTACT). */
slow: boolean; slow: boolean;
message?: string; message?: string;
/** The reviewer's part, for a job started with review: verdicts so far, calls made of those allowed, and why it stopped early if it did. */ /** The reviewer's part, for a job started with review: verdicts so far, calls made of those allowed, and why it stopped early if it did. */
@@ -55,7 +55,7 @@ export class Jobs {
pending: PendingStore; pending: PendingStore;
announce: (state: JobState) => void; announce: (state: JobState) => void;
reviewer?: Reviewer; reviewer?: Reviewer;
/** Calls a job's review may make (IE_REVIEW_CALLS). */ /** Calls a job's review may make (EX_REVIEW_CALLS). */
reviewCalls?: number; reviewCalls?: number;
}, },
) {} ) {}
+1 -1
View File
@@ -1,6 +1,6 @@
/** /**
* Suggestions and what was decided about them. Derived data, so they live on the server under * Suggestions and what was decided about them. Derived data, so they live on the server under
* <IE_DATA>/libraries/<id>/links/pending.json, one file per library, and never in the library. * <EX_DATA>/libraries/<id>/links/pending.json, one file per library, and never in the library.
* *
* A scan replaces what was pending for its node, but what was decided is kept: the model * A scan replaces what was pending for its node, but what was decided is kept: the model
* reviewer's verdict (link or not, and why), a person's decision, and when an approved link was * reviewer's verdict (link or not, and why), a person's decision, and when an approved link was
+1 -1
View File
@@ -22,7 +22,7 @@ import type { Suggestion } from "./scan";
/** Proposals per call. */ /** Proposals per call. */
export const BATCH = 60; export const BATCH = 60;
/** Calls a background job may make, unless IE_REVIEW_CALLS says otherwise. */ /** Calls a background job may make, unless EX_REVIEW_CALLS says otherwise. */
export const JOB_CALLS = 50; export const JOB_CALLS = 50;
/** Calls the scan after one edit may make. */ /** Calls the scan after one edit may make. */
export const SCAN_CALLS = 2; export const SCAN_CALLS = 2;
+1 -1
View File
@@ -20,7 +20,7 @@
* or POST { node, text, title, ancestors } * or POST { node, text, title, ancestors }
* POST /api/links/jobs { scope: "node" | "library", node?, review? } → the job's state (node: a node's id, scanned with * POST /api/links/jobs { scope: "node" | "library", node?, review? } → the job's state (node: a node's id, scanned with
* everything under it; on the library root, the whole library); it runs in the background * everything under it; on the library root, the whole library); it runs in the background
* (with review, the model reviewer judges what it finds, within IE_REVIEW_CALLS calls) * (with review, the model reviewer judges what it finds, within EX_REVIEW_CALLS calls)
* GET /api/links/jobs → { job } (the current or last one) * GET /api/links/jobs → { job } (the current or last one)
* DELETE /api/links/jobs → cancel the running job * DELETE /api/links/jobs → cancel the running job
* GET /api/links/status → embeddings, the node index, the pending count, the job * GET /api/links/status → embeddings, the node index, the pending count, the job
+1 -1
View File
@@ -177,7 +177,7 @@ export const TUNING: Tuning = {
}; };
/** /**
* Per-model adjustments. The test model (IE_EMBED=fake: hashed words) gives a 7-word description * Per-model adjustments. The test model (EX_EMBED=fake: hashed words) gives a 7-word description
* and a paragraph a cosine of 0.1–0.3 when they share a word and 0 when they share none. * and a paragraph a cosine of 0.1–0.3 when they share a word and 0 when they share none.
*/ */
const PROFILES: Record<string, Partial<Tuning>> = { const PROFILES: Record<string, Partial<Tuning>> = {
+2 -2
View File
@@ -1,7 +1,7 @@
/** /**
* From the single-library layout to the libraries layout (libraries.ts), once, when asked: * From the single-library layout to the libraries layout (libraries.ts), once, when asked:
* *
* npm run migrate migrate IE_DATA (or .data) * npm run migrate migrate EX_DATA (or .data)
* npm run migrate -- --check a dry run: build, verify and report, writing nothing * npm run migrate -- --check a dry run: build, verify and report, writing nothing
* npm run migrate -- [--check] DIR another data directory * npm run migrate -- [--check] DIR another data directory
* *
@@ -402,7 +402,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolvePath(process.arg
const unknown = args.filter((a) => a.startsWith("-") && a !== "--check"); const unknown = args.filter((a) => a.startsWith("-") && a !== "--check");
const dirs = args.filter((a) => !a.startsWith("-")); const dirs = args.filter((a) => !a.startsWith("-"));
if (unknown.length || dirs.length > 1) { if (unknown.length || dirs.length > 1) {
console.error("usage: npm run migrate [-- [--check] [DATA_DIR]] (DATA_DIR defaults to IE_DATA, else .data)"); console.error("usage: npm run migrate [-- [--check] [DATA_DIR]] (DATA_DIR defaults to EX_DATA, else .data)");
process.exit(2); process.exit(2);
} }
const r = migrateLibraries(dirs[0] ?? dataDir(), { check }); const r = migrateLibraries(dirs[0] ?? dataDir(), { check });
+1 -1
View File
@@ -73,7 +73,7 @@ const INHERITED = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_EFFORT|CLAUDE_CODE_(ENTRYPOINT
* OAuth token inside Claude Code, so neither is ever passed on. * OAuth token inside Claude Code, so neither is ever passed on.
*/ */
function childEnv(): Record<string, string | undefined> { function childEnv(): Record<string, string | undefined> {
const env: Record<string, string | undefined> = { ...process.env, CLAUDE_AGENT_SDK_CLIENT_APP: "infinispand/1.0.0" }; const env: Record<string, string | undefined> = { ...process.env, CLAUDE_AGENT_SDK_CLIENT_APP: "explicata/1.0.0" };
for (const k of Object.keys(env)) if (k === "ANTHROPIC_API_KEY" || k === "ANTHROPIC_AUTH_TOKEN" || INHERITED.test(k)) delete env[k]; for (const k of Object.keys(env)) if (k === "ANTHROPIC_API_KEY" || k === "ANTHROPIC_AUTH_TOKEN" || INHERITED.test(k)) delete env[k];
return env; return env;
} }
+2 -2
View File
@@ -7,8 +7,8 @@ import { fileURLToPath } from "node:url";
/** The checkout's root directory. */ /** The checkout's root directory. */
export const ROOT = resolve(fileURLToPath(new URL(".", import.meta.url)), ".."); export const ROOT = resolve(fileURLToPath(new URL(".", import.meta.url)), "..");
/** Where the library and everything derived from it are kept: IE_DATA, or .data in the checkout. */ /** Where the library and everything derived from it are kept: EX_DATA, or .data in the checkout. */
export const dataDir = () => resolve(process.env.IE_DATA ?? join(ROOT, ".data")); export const dataDir = () => resolve(process.env.EX_DATA ?? join(ROOT, ".data"));
/** A failure with the HTTP status it should be answered with. */ /** A failure with the HTTP status it should be answered with. */
export class HttpError extends Error { export class HttpError extends Error {
+9 -9
View File
@@ -1,8 +1,8 @@
/** /**
* Web research on the server: whether it is on (IE_WEB), the per-run caps (IE_WEB_SEARCHES, * Web research on the server: whether it is on (EX_WEB), the per-run caps (EX_WEB_SEARCHES,
* IE_WEB_FETCHES), and the Messages API's web tools as the API-key route declares them. * EX_WEB_FETCHES), and the Messages API's web tools as the API-key route declares them.
* *
* The browser asks for research on an agent turn; what it gets is decided here. With IE_WEB=off a * The browser asks for research on an agent turn; what it gets is decided here. With EX_WEB=off a
* turn never carries web tools, whatever the browser asked, and the caps the browser sends are * turn never carries web tools, whatever the browser asked, and the caps the browser sends are
* replaced by the server's. * replaced by the server's.
*/ */
@@ -23,14 +23,14 @@ const count = (v: string | undefined, d: number) => {
return v !== undefined && v !== "" && Number.isInteger(n) && n >= 0 && n <= 50 ? n : d; return v !== undefined && v !== "" && Number.isInteger(n) && n >= 0 && n <= 50 ? n : d;
}; };
/** IE_WEB is on or off (default on, when there is a model at all); anything else is off, said once. */ /** EX_WEB is on or off (default on, when there is a model at all); anything else is off, said once. */
export function webConfig(env: Record<string, string | undefined>, hasModel: boolean): WebConfig { export function webConfig(env: Record<string, string | undefined>, hasModel: boolean): WebConfig {
const caps = { searches: count(env.IE_WEB_SEARCHES, DEFAULT_LIMITS.searches), fetches: count(env.IE_WEB_FETCHES, DEFAULT_LIMITS.fetches) }; const caps = { searches: count(env.EX_WEB_SEARCHES, DEFAULT_LIMITS.searches), fetches: count(env.EX_WEB_FETCHES, DEFAULT_LIMITS.fetches) };
const wanted = env.IE_WEB ?? "on"; const wanted = env.EX_WEB ?? "on";
if (!hasModel) return { on: false, ...caps, why: "no model is configured" }; if (!hasModel) return { on: false, ...caps, why: "no model is configured" };
if (wanted === "off") return { on: false, ...caps, why: "IE_WEB=off" }; if (wanted === "off") return { on: false, ...caps, why: "EX_WEB=off" };
if (wanted !== "on") return { on: false, ...caps, why: `IE_WEB=${wanted} is not on or off` }; if (wanted !== "on") return { on: false, ...caps, why: `EX_WEB=${wanted} is not on or off` };
if (caps.searches === 0 && caps.fetches === 0) return { on: false, ...caps, why: "IE_WEB_SEARCHES and IE_WEB_FETCHES are both 0" }; if (caps.searches === 0 && caps.fetches === 0) return { on: false, ...caps, why: "EX_WEB_SEARCHES and EX_WEB_FETCHES are both 0" };
return { on: true, ...caps }; return { on: true, ...caps };
} }
+6 -6
View File
@@ -15,7 +15,7 @@
* *
* Every request goes through one serial queue with a minimum spacing, priority for interactive * Every request goes through one serial queue with a minimum spacing, priority for interactive
* calls, Retry-After / 429 / 503 / maxlag handling, and a descriptive User-Agent. Results are * calls, Retry-After / 429 / 503 / maxlag handling, and a descriptive User-Agent. Results are
* cached on disk under <IE_DATA>/wiki-cache/, so scanning the same text twice costs nothing. * cached on disk under <EX_DATA>/wiki-cache/, so scanning the same text twice costs nothing.
* Nothing here throws into a caller: failures come back as { ok: false, reason }. * Nothing here throws into a caller: failures come back as { ok: false, reason }.
* *
* Only the candidate phrase or the search query itself is ever sent, never surrounding text. * Only the candidate phrase or the search query itself is ever sent, never surrounding text.
@@ -207,7 +207,7 @@ export function validContact(contact: string | undefined): string | null {
/** The User-Agent: generic by default; never the owner's name, host or paths unless they supply a contact. */ /** The User-Agent: generic by default; never the owner's name, host or paths unless they supply a contact. */
export function userAgent(contact: string | null): string { export function userAgent(contact: string | null): string {
return contact ? `Infinispand/0.1 (${contact})` : "Infinispand/0.1 (personal knowledge tool)"; return contact ? `Explicata/0.1 (${contact})` : "Explicata/0.1 (personal knowledge tool)";
} }
interface WikiOptions { interface WikiOptions {
@@ -930,12 +930,12 @@ export class WikiClient {
const MODIFIED = "Adapted: references, navigation boxes, infoboxes, edit links and images removed."; const MODIFIED = "Adapted: references, navigation boxes, infoboxes, edit links and images removed.";
let shared: WikiClient | null = null; let shared: WikiClient | null = null;
/** The server's client, configured from IE_DATA, IE_WIKI_LANG and IE_WIKI_CONTACT. */ /** The server's client, configured from EX_DATA, EX_WIKI_LANG and EX_WIKI_CONTACT. */
export function wiki(): WikiClient { export function wiki(): WikiClient {
if (!shared) { if (!shared) {
shared = new WikiClient({ lang: process.env.IE_WIKI_LANG, contact: process.env.IE_WIKI_CONTACT }); shared = new WikiClient({ lang: process.env.EX_WIKI_LANG, contact: process.env.EX_WIKI_CONTACT });
if (process.env.IE_WIKI_CONTACT && !shared.contact) { if (process.env.EX_WIKI_CONTACT && !shared.contact) {
console.warn("IE_WIKI_CONTACT is not an email address, an http(s) URL or User:Name; sending the generic User-Agent."); console.warn("EX_WIKI_CONTACT is not an email address, an http(s) URL or User:Name; sending the generic User-Agent.");
} }
process.once("exit", () => shared?.flush()); process.once("exit", () => shared?.flush());
} }
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* A stand-in Wikipedia for tests and offline work (IE_WIKI=mock). `mockWikiFetch` answers every * A stand-in Wikipedia for tests and offline work (EX_WIKI=mock). `mockWikiFetch` answers every
* URL server/wiki.ts builds, in the shapes the real APIs return (docs/wikipedia.md §2), from a * URL server/wiki.ts builds, in the shapes the real APIs return (docs/wikipedia.md §2), from a
* few short articles written for the purpose. The HTML imitates action=parse output, junk * few short articles written for the purpose. The HTML imitates action=parse output, junk
* included (reference markers, infoboxes, navboxes, hatnotes, TemplateStyles), so the real * included (reference markers, infoboxes, navboxes, hatnotes, TemplateStyles), so the real
+3 -3
View File
@@ -16,7 +16,7 @@
* Answers: 200 { ok: true, ... }; 400 bad input; 404 { ok: false, reason: "missing" }; * Answers: 200 { ok: true, ... }; 400 bad input; 404 { ok: false, reason: "missing" };
* 503 { ok: false, reason, retryAfter } when Wikipedia is unreachable or asked us to wait. * 503 { ok: false, reason, retryAfter } when Wikipedia is unreachable or asked us to wait.
* A request the browser abandons (a superseded keystroke) is dropped from the queue unsent. * A request the browser abandons (a superseded keystroke) is dropped from the queue unsent.
* With IE_WIKI=off the server wires in wikiOff instead: every route answers 503 reason "off". * With EX_WIKI=off the server wires in wikiOff instead: every route answers 503 reason "off".
*/ */
import type { IncomingMessage, ServerResponse } from "node:http"; import type { IncomingMessage, ServerResponse } from "node:http";
import { HttpError, abortOnClose, sendJson as send } from "./util"; import { HttpError, abortOnClose, sendJson as send } from "./util";
@@ -125,9 +125,9 @@ export function wikiRoutes(client: () => WikiClient) {
}; };
} }
/** IE_WIKI=off: the routes exist, so the UI can tell "turned off" from "unreachable", but none works. */ /** EX_WIKI=off: the routes exist, so the UI can tell "turned off" from "unreachable", but none works. */
export async function wikiOff(_req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> { export async function wikiOff(_req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
if (!url.pathname.startsWith("/api/wiki/")) return false; if (!url.pathname.startsWith("/api/wiki/")) return false;
send(res, 503, { ok: false, reason: "off", message: "Wikipedia is turned off on this server (IE_WIKI=off)." }); send(res, 503, { ok: false, reason: "off", message: "Wikipedia is turned off on this server (EX_WIKI=off)." });
return true; return true;
} }
+1 -1
View File
@@ -10,7 +10,7 @@ import type { SeedNode, SeedNote } from "../seed/types";
import { parseDoc } from "./format"; import { parseDoc } from "./format";
import { clip } from "./text"; import { clip } from "./text";
export const SEED_TITLE = "Infinispand"; export const SEED_TITLE = "Explicata";
export interface BuildOptions { export interface BuildOptions {
/** Name on the commit that creates the tree's top ("seed" by default, as on the commits under it). */ /** Name on the commit that creates the tree's top ("seed" by default, as on the commits under it). */
+2 -2
View File
@@ -2,7 +2,7 @@
import { ancestors, ancestorsBelowRoot, label, sections, topOf, tops, type NodeId, type Snap } from "../core/model"; import { ancestors, ancestorsBelowRoot, label, sections, topOf, tops, type NodeId, type Snap } from "../core/model";
import { paragraphs, plain, type Form } from "../core/text"; import { paragraphs, plain, type Form } from "../core/text";
export const SYSTEM = `You are the writing engine inside Infinispand, a library of text that a reader can expand without limit. export const SYSTEM = `You are the writing engine inside Explicata, a library of text that a reader can expand without limit.
The library is a tree. Every node has a title and a body. A reader starts from an outline of titles, opens a node to read its body, and can then open its subsections or select any sentence, phrase or word and ask for more. What they get back is a new node: either subsections, or a note anchored to the words they selected. You write those nodes, and you keep existing nodes consistent with each other when one of them is edited. The library is a tree. Every node has a title and a body. A reader starts from an outline of titles, opens a node to read its body, and can then open its subsections or select any sentence, phrase or word and ask for more. What they get back is a new node: either subsections, or a note anchored to the words they selected. You write those nodes, and you keep existing nodes consistent with each other when one of them is edited.
@@ -15,7 +15,7 @@ How to write here:
Reply with the requested text and nothing else.`; Reply with the requested text and nothing else.`;
export const AGENT_SYSTEM = `You are the editor inside Infinispand, a library of text stored as one tree of nodes. A person has asked you to change it, and you make the change yourself with the tools you are given: the same create, update, replace, delete and move operations the person has from the keyboard. export const AGENT_SYSTEM = `You are the editor inside Explicata, a library of text stored as one tree of nodes. A person has asked you to change it, and you make the change yourself with the tools you are given: the same create, update, replace, delete and move operations the person has from the keyboard.
About the tree: About the tree:
- Every node has an id, a title and a body. A "section" is a structural child listed under its parent. A "note" is an expansion anchored to a quote from its parent's body, shown beside that text. - Every node has an id, a title and a body. A "section" is a structural child listed under its parent. A "note" is an expansion anchored to a quote from its parent's body, shown beside that text.
+1 -1
View File
@@ -10,7 +10,7 @@
*/ */
import { hostOf } from "../core/ref"; import { hostOf } from "../core/ref";
/** Per-run caps on searches and fetches. Defaults; the server's IE_WEB_SEARCHES / IE_WEB_FETCHES win. */ /** Per-run caps on searches and fetches. Defaults; the server's EX_WEB_SEARCHES / EX_WEB_FETCHES win. */
export const DEFAULT_LIMITS = { searches: 5, fetches: 5 } as const; export const DEFAULT_LIMITS = { searches: 5, fetches: 5 } as const;
export interface Research { export interface Research {
+1 -1
View File
@@ -1,7 +1,7 @@
import type { SeedNode } from "./types"; import type { SeedNode } from "./types";
/** /**
* The pre-generated tree: Infinispand describing itself. * The pre-generated tree: Explicata describing itself.
* The root's body is src/seed/prompt.txt, verbatim; each top-level section's * The root's body is src/seed/prompt.txt, verbatim; each top-level section's
* `src` lists the prompt sentences it traces back to. * `src` lists the prompt sentences it traces back to.
*/ */
+1 -1
View File
@@ -4,7 +4,7 @@ let dbp: Promise<IDBDatabase> | null = null;
function db(): Promise<IDBDatabase> { function db(): Promise<IDBDatabase> {
return (dbp ??= new Promise((resolve, reject) => { return (dbp ??= new Promise((resolve, reject) => {
// The project's former name: kept, so replicas already stored in a browser are found. // The project's first name (infinite-expand): kept, so replicas already stored in a browser are found.
const req = indexedDB.open("infinite-expand", 1); const req = indexedDB.open("infinite-expand", 1);
req.onupgradeneeded = () => req.result.createObjectStore("kv"); req.onupgradeneeded = () => req.result.createObjectStore("kv");
req.onsuccess = () => resolve(req.result); req.onsuccess = () => resolve(req.result);
+6 -4
View File
@@ -147,6 +147,8 @@ export interface Sample {
// ---- store ---- // ---- store ----
const clientId = Math.random().toString(36).slice(2); const clientId = Math.random().toString(36).slice(2);
// Browser keys keep the prefix `ie:` from the project's first name (infinite-expand), so settings
// already stored in a browser are found.
const lsGet = <T>(k: string, d: T): T => { const lsGet = <T>(k: string, d: T): T => {
try { try {
const v = localStorage.getItem(k); const v = localStorage.getItem(k);
@@ -1184,7 +1186,7 @@ class Store {
// Once per browser: why Wikipedia is slow, and what makes it fast. // Once per browser: why Wikipedia is slow, and what makes it fast.
if (lsGet("ie:wiki-hint", false)) return; if (lsGet("ie:wiki-hint", false)) return;
lsSet("ie:wiki-hint", true); lsSet("ie:wiki-hint", true);
this.say("Wikipedia is answering slowly: without a contact address the server may only ask it a few times a minute. Start the server with IE_WIKI_CONTACT set (an email address, an https:// URL or User:Name) to lift that."); this.say("Wikipedia is answering slowly: without a contact address the server may only ask it a few times a minute. Start the server with EX_WIKI_CONTACT set (an email address, an https:// URL or User:Name) to lift that.");
}); });
this.user = lsGet("ie:user", state?.user ?? "you"); this.user = lsGet("ie:user", state?.user ?? "you");
if (state) this.llm = refreshAfterCalls(remoteLLM(state.llm, state.model ?? undefined)); if (state) this.llm = refreshAfterCalls(remoteLLM(state.llm, state.model ?? undefined));
@@ -1459,7 +1461,7 @@ class Store {
/** The window's title: the article on the column's article page, else the node the reader is on. */ /** The window's title: the article on the column's article page, else the node the reader is on. */
private setTitle() { private setTitle() {
document.title = this.colWiki ? `${this.colWiki.title} · Wikipedia` : label(this.snap, this.activeNode) || "Infinispand"; document.title = this.colWiki ? `${this.colWiki.title} · Wikipedia` : label(this.snap, this.activeNode) || "Explicata";
} }
/** Every edit is saved as it is made; this says whether the server has it yet. */ /** Every edit is saved as it is made; this says whether the server has it yet. */
@@ -3130,7 +3132,7 @@ class Store {
if (!this.writable()) return; if (!this.writable()) return;
if (!this.generating) return this.say("No model configured, so there is no editor to ask."); if (!this.generating) return this.say("No model configured, so there is no editor to ask.");
if (opts.research && !instruction.trim()) return this.say("Say what to research: /research <question>. The editor writes what it finds into the focused node."); if (opts.research && !instruction.trim()) return this.say("Say what to research: /research <question>. The editor writes what it finds into the focused node.");
if (opts.research && !this.web.on) return this.say("Web research is off on this server (IE_WEB=off). : on a node still asks the editor, without the web."); if (opts.research && !this.web.on) return this.say("Web research is off on this server (EX_WEB=off). : on a node still asks the editor, without the web.");
if (this.agentRun?.running) return this.say("The editor is still working: Esc stops it."); if (this.agentRun?.running) return this.say("The editor is still working: Esc stops it.");
const research = (opts.research ?? wantsResearch(instruction)) && this.web.on; const research = (opts.research ?? wantsResearch(instruction)) && this.web.on;
const focus = this.focus.node; const focus = this.focus.node;
@@ -3433,7 +3435,7 @@ class Store {
/** The status line's account of a job; `made`, once it is over, the links the reviewer approved that this page made. */ /** The status line's account of a job; `made`, once it is over, the links the reviewer approved that this page made. */
jobText(j: JobState, made?: number): string { jobText(j: JobState, made?: number): string {
const eta = j.etaSec ? ` · about ${j.etaSec < 90 ? `${j.etaSec} s` : `${Math.round(j.etaSec / 60)} min`} left` : ""; const eta = j.etaSec ? ` · about ${j.etaSec < 90 ? `${j.etaSec} s` : `${Math.round(j.etaSec / 60)} min`} left` : "";
const slow = j.slow && j.state === "running" ? " · Wikipedia is asked once every 6.5 s without a contact: start the server with IE_WIKI_CONTACT (an email, https:// URL or User:Name) for about 6× faster" : ""; const slow = j.slow && j.state === "running" ? " · Wikipedia is asked once every 6.5 s without a contact: start the server with EX_WIKI_CONTACT (an email, https:// URL or User:Name) for about 6× faster" : "";
const r = j.review; const r = j.review;
const fell = r?.fallback ? ` · ${this.links.fallbackText(r.fallback)}: ${r.left} left for you` : ""; const fell = r?.fallback ? ` · ${this.links.fallbackText(r.fallback)}: ${r.left} left for you` : "";
if (j.state === "running") { if (j.state === "running") {
+1 -1
View File
@@ -51,7 +51,7 @@ const senses = new Map<string, Loadable<Sense[]>>();
const SLOW_MS = 2000; const SLOW_MS = 2000;
async function get<T>(path: string, key: string, signal?: AbortSignal): Promise<{ ok: true; value: T; stale?: boolean } | ({ ok: false } & Problem)> { async function get<T>(path: string, key: string, signal?: AbortSignal): Promise<{ ok: true; value: T; stale?: boolean } | ({ ok: false } & Problem)> {
if (config.mode === "off") return { ok: false, reason: "off", message: "Wikipedia is turned off on this server (IE_WIKI=off)." }; if (config.mode === "off") return { ok: false, reason: "off", message: "Wikipedia is turned off on this server (EX_WIKI=off)." };
const slow = setTimeout(() => slowOnce(), SLOW_MS); const slow = setTimeout(() => slowOnce(), SLOW_MS);
try { try {
const res = await fetch(path, { signal }); const res = await fetch(path, { signal });
+1 -1
View File
@@ -64,7 +64,7 @@ describe("actions", () => {
it("the selection menu puts Copy first, then what the words carry, then the lenses, linking and Related", () => { it("the selection menu puts Copy first, then what the words carry, then the lenses, linking and Related", () => {
const { act, calls } = recorder(); const { act, calls } = recorder();
const plain = selectionEntries(sel({ related: [{ title: "Expansion by depth", where: "Infinispand" }, { title: "Nodes" }] }), act); const plain = selectionEntries(sel({ related: [{ title: "Expansion by depth", where: "Explicata" }, { title: "Nodes" }] }), act);
expect(labels(plain)).toEqual([ expect(labels(plain)).toEqual([
"# “a probability for each possible next piece”", "# “a probability for each possible next piece”",
"Copy", "Copy",
+1 -1
View File
@@ -164,7 +164,7 @@ describe("convergence", () => {
} }
} }
}), }),
{ numRuns: Number(process.env.IE_RUNS ?? 200) }, { numRuns: Number(process.env.EX_RUNS ?? 200) },
); );
}, 300_000); }, 300_000);
}); });
+2 -2
View File
@@ -86,7 +86,7 @@ function serve(data: string, library: string, port = PORT): { child: ChildProces
const out: string[] = []; const out: string[] = [];
const child = spawn(process.execPath, ["--import", "tsx", "server/index.ts"], { const child = spawn(process.execPath, ["--import", "tsx", "server/index.ts"], {
cwd: ROOT, cwd: ROOT,
env: { ...process.env, IE_PROD: "1", IE_LLM: "mock", IE_MOCK_DELAY: "0", IE_WIKI: "mock", IE_EMBED: "fake", IE_DATA: data, IE_LIBRARY: library, PORT: String(port), IE_USER: "tester" }, env: { ...process.env, EX_PROD: "1", EX_LLM: "mock", EX_MOCK_DELAY: "0", EX_WIKI: "mock", EX_EMBED: "fake", EX_DATA: data, EX_LIBRARY: library, PORT: String(port), EX_USER: "tester" },
stdio: ["ignore", "pipe", "pipe"], stdio: ["ignore", "pipe", "pipe"],
}); });
servers.push(child); servers.push(child);
@@ -140,7 +140,7 @@ describe("the server with several libraries", () => {
expect(a.title).toBe("Library"); expect(a.title).toBe("Library");
const treeA = await get(`/api/l/${a.id}/tree`); const treeA = await get(`/api/l/${a.id}/tree`);
const topsA = treeA.nodes[treeA.root].children.map((c: string) => treeA.nodes[c].title); const topsA = treeA.nodes[treeA.root].children.map((c: string) => treeA.nodes[c].title);
expect(topsA).toEqual(["Infinispand", "Tides"]); expect(topsA).toEqual(["Explicata", "Tides"]);
// The unprefixed routes are the first library's. // The unprefixed routes are the first library's.
expect((await get("/api/tree")).library).toBe(a.id); expect((await get("/api/tree")).library).toBe(a.id);
expect((await get("/api/state")).library).toBe(a.id); expect((await get("/api/state")).library).toBe(a.id);
+1 -1
View File
@@ -2,7 +2,7 @@
* Link discovery (server/links): the extractor, the tiering rule, density and first mention, * Link discovery (server/links): the extractor, the tiering rule, density and first mention,
* self and ancestor exclusion, declined phrases, marks, degraded text-only mode, the incremental * self and ancestor exclusion, declined phrases, marks, degraded text-only mode, the incremental
* node index, background jobs, and accept/reject. Offline: the mock Wikipedia and the hashed-words * node index, background jobs, and accept/reject. Offline: the mock Wikipedia and the hashed-words
* embedder (IE_EMBED=fake). * embedder (EX_EMBED=fake).
*/ */
import { createServer, type Server } from "node:http"; import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net"; import type { AddressInfo } from "node:net";
+1
View File
@@ -173,6 +173,7 @@ describe.each(["pre", "main", "mixed"])("migrating data written by %s", (name) =
const rootNote = root.children.map((c) => b.nodes[c]).find((n) => n.kind === "note")!; const rootNote = root.children.map((c) => b.nodes[c]).find((n) => n.kind === "note")!;
expect(rootNote.anchors.map((x) => x.text)).toEqual(["Root words"]); expect(rootNote.anchors.map((x) => x.text)).toEqual(["Root words"]);
expect(rootNote.body).toBe("A note on the library root itself."); expect(rootNote.body).toBe("A note on the library root itself.");
// The fixtures were written when the project was called Infinispand.
expect(b.nodes[root.children[0]].title).toBe("Infinispand"); expect(b.nodes[root.children[0]].title).toBe("Infinispand");
expect(b.nodes[root.children[1]].title).toBe("Migration notes"); expect(b.nodes[root.children[1]].title).toBe("Migration notes");
// Locks: set on a model's node, taken off a person's. // Locks: set on a model's node, taken off a person's.
+6 -6
View File
@@ -1,6 +1,6 @@
/** /**
* Web research for the editor agent, with no network: the mock's fake search and fetch, the URL * Web research for the editor agent, with no network: the mock's fake search and fetch, the URL
* rule in the tool executor, pause_turn, caps, IE_WEB, the subscription route's option object, and * rule in the tool executor, pause_turn, caps, EX_WEB, the subscription route's option object, and
* the API-key route's request and stream against a local stand-in for the API. * the API-key route's request and stream against a local stand-in for the API.
*/ */
import { createServer, type IncomingMessage, type Server } from "node:http"; import { createServer, type IncomingMessage, type Server } from "node:http";
@@ -223,22 +223,22 @@ describe("caps", () => {
}); });
it("the server's caps replace the browser's, and are the API tools' max_uses", () => { it("the server's caps replace the browser's, and are the API tools' max_uses", () => {
const cfg = webConfig({ IE_WEB_SEARCHES: "3", IE_WEB_FETCHES: "2" }, true); const cfg = webConfig({ EX_WEB_SEARCHES: "3", EX_WEB_FETCHES: "2" }, true);
expect(cfg).toEqual({ on: true, searches: 3, fetches: 2 }); expect(cfg).toEqual({ on: true, searches: 3, fetches: 2 });
const req = applyWebPolicy({ system: "", context: "", messages: [], research: { searches: 99, fetches: 99, used: { searches: 1, fetches: 0 } } }, cfg); const req = applyWebPolicy({ system: "", context: "", messages: [], research: { searches: 99, fetches: 99, used: { searches: 1, fetches: 0 } } }, cfg);
expect(req.research).toMatchObject({ searches: 3, fetches: 2, used: { searches: 1, fetches: 0 } }); expect(req.research).toMatchObject({ searches: 3, fetches: 2, used: { searches: 1, fetches: 0 } });
const tools = apiWebTools("claude-opus-5-5", req.research!); const tools = apiWebTools("claude-opus-5-5", req.research!);
expect(tools.map((t) => [t.type, (t as { max_uses?: number }).max_uses])).toEqual([["web_search_20260209", 3], ["web_fetch_20260209", 2]]); expect(tools.map((t) => [t.type, (t as { max_uses?: number }).max_uses])).toEqual([["web_search_20260209", 3], ["web_fetch_20260209", 2]]);
expect(webConfig({}, true)).toEqual({ on: true, searches: 5, fetches: 5 }); expect(webConfig({}, true)).toEqual({ on: true, searches: 5, fetches: 5 });
expect(webConfig({ IE_WEB_SEARCHES: "lots" }, true).searches).toBe(5); expect(webConfig({ EX_WEB_SEARCHES: "lots" }, true).searches).toBe(5);
}); });
}); });
describe("IE_WEB", () => { describe("EX_WEB", () => {
it("off: research is taken out of every turn, whatever the browser asked", async () => { it("off: research is taken out of every turn, whatever the browser asked", async () => {
const cfg = webConfig({ IE_WEB: "off" }, true); const cfg = webConfig({ EX_WEB: "off" }, true);
expect(cfg.on).toBe(false); expect(cfg.on).toBe(false);
expect(webConfig({ IE_WEB: "maybe" }, true).on).toBe(false); expect(webConfig({ EX_WEB: "maybe" }, true).on).toBe(false);
expect(webConfig({}, false).on).toBe(false); expect(webConfig({}, false).on).toBe(false);
// The mock behind the server's policy, as the server runs it. // The mock behind the server's policy, as the server runs it.
const base = mockLLM(); const base = mockLLM();
+2 -2
View File
@@ -236,7 +236,7 @@ describe("queue", () => {
await w.lookup(["Page 1"]); await w.lookup(["Page 1"]);
await w.lookup(["Page 2"]); await w.lookup(["Page 2"]);
expect(slept).toEqual([1000]); expect(slept).toEqual([1000]);
expect(calls[0].headers["user-agent"]).toBe("Infinispand/0.1 (personal knowledge tool)"); expect(calls[0].headers["user-agent"]).toBe("Explicata/0.1 (personal knowledge tool)");
}); });
it("drops a queued request whose caller aborted, without sending it", async () => { it("drops a queued request whose caller aborted, without sending it", async () => {
@@ -258,7 +258,7 @@ describe("user agent and contact", () => {
expect(validContact("https://example.org/me")).toBe("https://example.org/me"); expect(validContact("https://example.org/me")).toBe("https://example.org/me");
expect(validContact("Jane Doe")).toBeNull(); expect(validContact("Jane Doe")).toBeNull();
expect(validContact("a@b.c; rm")).toBeNull(); expect(validContact("a@b.c; rm")).toBeNull();
expect(userAgent("me@example.org")).toBe("Infinispand/0.1 (me@example.org)"); expect(userAgent("me@example.org")).toBe("Explicata/0.1 (me@example.org)");
}); });
}); });
+1 -1
View File
@@ -139,7 +139,7 @@ describe("/api/wiki over the mock provider", () => {
for (const path of ["/api/wiki/summary?title=Octopus", "/api/wiki/lookup", "/api/wiki/anything"]) { for (const path of ["/api/wiki/summary?title=Octopus", "/api/wiki/lookup", "/api/wiki/anything"]) {
expect(await get(off.base, path)).toEqual({ expect(await get(off.base, path)).toEqual({
status: 503, status: 503,
body: { ok: false, reason: "off", message: "Wikipedia is turned off on this server (IE_WIKI=off)." }, body: { ok: false, reason: "off", message: "Wikipedia is turned off on this server (EX_WIKI=off)." },
}); });
} }
expect((await fetch(`${off.base}/api/state`)).status).toBe(418); expect((await fetch(`${off.base}/api/state`)).status).toBe(418);