Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
spaces: page aliases and unlinked mentions (replaces #439) (#659)
nyblnet76f338fb887b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 84253e29..03a6e65a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -280,6 +280,16 @@ jobs:# rows. Needs the shell built above; a skip in CI is a failure.run: node scripts/test-spaces-chrome.ts+ - name: spaces aliases and unlinked mentions+ # The assertions that matter in this one are the NEGATIVES: a page+ # title found inside a code block, an existing link, a bare URL or the+ # middle of a longer word must all produce NO mention, and a title full+ # of regex metacharacters must not throw. It also asserts that a name+ # surrounded by kana matches, which a `\b`-style boundary silently+ # never does — a rule built for English is a total failure in ja,+ # zh-Hans and zh-Hant rather than a partial one.+ run: node scripts/test-spaces-mentions.ts+- name: Mermaid flowchart ⇄ diagram rig# spaces/src/diagram/: our own Mermaid flowchart parser and layered# layout (the mermaid library is megabytes and nothing is fetched atdiff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 1e31e638..67483b3a 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -6804,6 +6804,71 @@ none. The builders zip x, y, z, colour and size by index; project one and notanother and the plot pairs the wrong height with the wrong position, plausibly.+## 2026-09-10 — aliases resolve at LINK time; a word-boundary rule built for English is not a degradation in Japanese, it is a zero++bento/spaces gained page **aliases** and **unlinked mentions** (`spaces/src/mentions.ts`).+Four things were settled that a later session could otherwise contradict.++**An alias is resolved where a name becomes a page id, and nowhere else.**+`Page.aliases` is read by exactly one function — `nameIndex` — which the+`[[…]]` resolver, ⌘K and the `[[` page picker all call. What gets written into+the file is an ordinary `#p/<id>` href, so `buildIndex`'s backlinks, the graph,+export, print and the CRDT never learn that aliases exist. The alternative,+resolving at render time, would give every one of those a second way to name a+page, and they would drift. If a future feature wants alias-aware behaviour,+the answer is to call `nameIndex`, not to teach another module about the field.++**All three surfaces or none.** An alias that reaches the resolver but not+search is worse than no alias: you file something under the name you use for+it, and then cannot find it by that name — which reads as the search being+broken. Half an alias was the shape this nearly shipped in.++**Collisions are reported, never repaired.** Two pages can claim one name+because a file arrives already written. `nameIndex` settles it identically in+every replica — a TITLE always beats an alias, then document order — and+`validate()` reports `alias-collision` naming the page a `[[link]]` will+actually reach. Repairing it would rename something the author wrote; saying+nothing would leave a link landing somewhere nobody chose. This is the one+place the app tells you about a clash it resolved on your behalf.++**The word-boundary rule is the CJK decision, and it is not a tuning+parameter.** Unlinked mentions match a page's names against every other page's+prose, so a boundary rule is what keeps "Roadmap" out of "Roadmaps". The+obvious spelling is `\b`, or its Unicode equivalent `(?<![\p{L}\p{N}_])`.+Applied to Japanese that does not find fewer mentions — it finds NONE, ever,+because every kana beside a name is a letter and the assertion never opens.+This app ships ja, zh-Hans and zh-Hant; a rule with that property is a silent+total failure in three of its nine locales, and it passes every test written in+English.++So a boundary is required only where the NAME's own edge character is a word+character in a script that separates words, and the minimum scannable length is+three code points for such a name and two for one containing Han, kana or+Hangul. The stated cost, because it is real and someone will find it: a Han+name also matches inside a longer Han compound (京都 inside 東京都). That is+what every CJK-aware substring search in the world does, it is visible, and it+is bounded; the alternative is a feature that does not exist for a third of the+supported languages. `scripts/test-spaces-mentions.ts` asserts both halves.++Two mechanical notes worth not rediscovering. The `v` regex flag expresses this+boundary as one set difference and is NOT used: `v` is Safari 17 while this+app's floor is Safari 16.4 (`DecompressionStream`, which the shell's own loader+needs), and a regex the engine cannot COMPILE throws at construction — the cost+of being wrong is a panel that throws on every page open, not a missing match.+Measured, all four spellings of the boundary run within noise of each other, so+the choice is the floor and nothing else. And the run-splitting scanner+separates skipped regions with U+0000 rather than a space: with a space,+`New<a>x</a>York` collapses to `New York` and the scanner reports a mention+nobody wrote.++**It is not the quadratic thing it sounds like.** "Every page's title against+every page's text" is N×M; the reader's panel never computes that. Opening a+page scans the document once for THAT page's names, so the cost is the size of+the space and not the number of pages in it. Measured on a synthetic 1000-page,+2.5MB space: 6.5ms to open a page, against 1.9ms for the backlink index the app+already builds on every commit. The all-pairs answer exists for the agent+surface (`bento.mentions()`) at ~1s on the same space, and is not on any paint+path.## 2026-09-13 — Broadcast is a special case of collaboration: the relay half**Decision.** A live show is not a second transport. An audience member is adiff --git a/docs/spaces-agents.md b/docs/spaces-agents.mdindex 6dbbb953..178f3b57 100644--- a/docs/spaces-agents.md+++ b/docs/spaces-agents.md@@ -322,6 +322,12 @@ notifications, automation. The file is the team boundary and the capability.it lists the linker, with no maintenance. A space where pages only link *down*the tree wastes the one thing this format does that a folder of files cannot.+**Give a page `aliases` when people call it more than one thing.** `aliases:+["NYC", "the Big Apple"]` on a page titled New York makes all three names reach+it from a `[[wikilink]]`, from ⌘K and from the `[[` picker — and makes prose+that says "NYC" show up as an unlinked mention on that page. It costs one array+and it is the cheapest way to make a space find things for its reader.+## `window.bento````js@@ -331,6 +337,7 @@ bento.pages() // [{id, title, parent, archived, blobento.getPage(id) // one page, with its blocksbento.search(q) // [{pageId, title, blockId}]bento.outline() // the whole space as a tree+bento.mentions(pageId?) // where a page is named but not linkedbento.validate() // what is wrong or suspectbento.stats() // pages, blocks, words, bytes, biggest assetsbento.comments(query?) // review threads, flat, with a typed anchor@@ -435,6 +442,31 @@ In sidebar order (depth-first). Headings carry their **block id**, so what comesback can be handed straight to `updateBlock` or `moveBlock`. `links` is whatthat page points at, which is the other half of the backlinks a reader sees.+### `bento.mentions()`++```js+bento.mentions('p-abc') // that page's unlinked mentions+bento.mentions() // every page's, as { pageId: Mention[] }+// Mention: { pageId, fromPage, fromBlock, matched, htmlStart, htmlEnd, snippet }+```++Where a page's **title or aliases** appear as plain words in some other page+without a link. `matched` is the text as it was actually written, and+`htmlStart`/`htmlEnd` are offsets into `fromBlock`'s `html`, so a link can be+spliced in exactly where the words are rather than found again by string search+— which would hit the wrong occurrence when the name appears twice.++It never reports a name inside a code block, a code span, a link that already+exists, a URL or a mail address; nor in a block that already links to the+target; nor in the page's own text; nor as part of a longer word. Names under+three characters (two, for a name written in Han, kana or Hangul) are not+scanned for at all.++**READ ONLY on purpose.** Deciding that a sentence meant *that* page is a+judgement, and an agent that rewrote a hundred blocks on a guess would be+unreviewable. Link the ones you are sure of with `updateBlock`, and leave the+rest to the panel, where a person can see the sentence before deciding.+### `bento.stats()````jsdiff --git a/scripts/test-spaces-mentions.ts b/scripts/test-spaces-mentions.tsnew file mode 100644index 00000000..a3922414--- /dev/null+++ b/scripts/test-spaces-mentions.ts@@ -0,0 +1,291 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// bento/spaces — aliases and unlinked mentions.+//+// node scripts/test-spaces-mentions.ts+//+// THE ASSERTIONS THAT MATTER HERE ARE THE NEGATIVES. A mention engine that+// finds things is easy; one that does not find a title inside a code block, an+// existing link, a URL or the middle of a longer word is the whole feature.+// Each of those is checked, and each was sabotage-verified — the guard was+// removed, this rig went red, the guard was restored.+//+// It also MEASURES. "Every page's title against every page's text" is the+// quadratic shape this feature has to avoid, so the cost of both the per-page+// path (what the reader's panel calls) and the all-pairs path is timed on a+// synthetic space and printed. A number nobody prints is a number nobody+// checks.++import {+ aliasesOf, namesOf, nameIndex, nameKey, scannable, escapeRe,+ scanRuns, compileNames, mentionsOf, mentionIndex, linkMention,+} from '../spaces/src/mentions.ts'+import { buildIndex, type SpacesDoc, type Page, type Block } from '../spaces/src/model.ts'++let failed = 0+let ran = 0+const ok = (cond: unknown, what: string) => {+ ran+++ if (cond) return+ failed+++ console.error(` FAIL ${what}`)+}+const eq = (a: unknown, b: unknown, what: string) =>+ ok(JSON.stringify(a) === JSON.stringify(b), `${what}\n got ${JSON.stringify(a)}\n want ${JSON.stringify(b)}`)++const blk = (html: string, extra: Partial<Block> = {}): Block =>+ ({ id: `b${Math.random().toString(36).slice(2, 9)}`, type: 'p', html, ...extra })++const pg = (id: string, title: string, blocks: Block[] = [], extra: Partial<Page> = {}): Page =>+ ({ id, title, blocks, ...extra })++const doc = (pages: Page[]): SpacesDoc => ({+ format: 'bento/spaces' as SpacesDoc['format'], version: 1, docId: 'd1',+ title: 'T', pages, theme: { background: '#fff', color: '#000', accent: '#07f', fontFamily: 'x' },+})++const mentions = (pages: Page[], target: string) => {+ const d = doc(pages)+ return mentionsOf(d, buildIndex(d), target)+}++// ---------------------------------------------------------------------------+console.log('names and aliases')+// ---------------------------------------------------------------------------+{+ eq(aliasesOf(pg('p1', 'X')), [], 'no aliases key = no aliases')+ eq(aliasesOf(pg('p1', 'X', [], { aliases: 'NYC' as unknown as string[] })), [],+ 'aliases: a bare string is not an array and yields none')+ eq(aliasesOf(pg('p1', 'X', [], { aliases: ['NYC', '', ' ', 42 as unknown as string, 'nyc', 'New York'] })),+ ['NYC', 'New York'], 'aliases: blanks, non-strings and case-dupes dropped')+ eq(namesOf(pg('p1', 'New York', [], { aliases: ['NYC', 'new york'] })), ['New York', 'NYC'],+ 'namesOf: title first, an alias equal to the title is not repeated')++ ok(!scannable('It'), '"It" is under the Latin minimum')+ ok(scannable('API'), '"API" is exactly the Latin minimum')+ ok(scannable('東京'), 'two Han characters are scannable')+ ok(!scannable('都'), 'one Han character is not')+ ok(!scannable(' '), 'whitespace is not a name')++ eq(nameKey(' NYC '), 'nyc', 'nameKey trims and folds case')+}++// ---------------------------------------------------------------------------+console.log('nameIndex — resolution and collisions')+// ---------------------------------------------------------------------------+{+ const ix = nameIndex(doc([+ pg('p1', 'New York', [], { aliases: ['NYC', 'The Big Apple'] }),+ pg('p2', 'Projects'),+ pg('p3', 'Archive', [], { aliases: ['Projects'] }),+ ]))+ eq(ix.byName.get('nyc'), 'p1', 'an alias resolves to its page')+ eq(ix.byName.get('new york'), 'p1', 'so does the title')+ eq(ix.byName.get('projects'), 'p2',+ 'a TITLE beats an alias claiming the same name, whatever the page order')+ eq([...(ix.collisions.get('projects') ?? [])].sort(), ['p2', 'p3'],+ 'the clash is reported, not hidden')+ ok(!ix.collisions.has('nyc'), 'an uncontested alias is not a collision')++ // pages before them in the array must not change the answer+ const flipped = nameIndex(doc([+ pg('p3', 'Archive', [], { aliases: ['Projects'] }),+ pg('p2', 'Projects'),+ ]))+ eq(flipped.byName.get('projects'), 'p2', 'title-before-alias holds when the alias page comes first')+}++// ---------------------------------------------------------------------------+console.log('eligible text — the NEGATIVES')+// ---------------------------------------------------------------------------+{+ const target = pg('t', 'Roadmap')++ const has = (html: string) => mentions([target, pg('s', 'Source', [blk(html)])], 't')++ eq(has('We should read the Roadmap today').length, 1, 'plain prose IS a mention')+ eq(has('We should read the Roadmap today')[0].matched, 'Roadmap', 'the matched text is reported')++ // --- NEGATIVE: inside a code span+ eq(has('run <code>Roadmap --now</code> please').length, 0,+ 'NEGATIVE: a title inside a code span is not a mention')+ // --- NEGATIVE: a code BLOCK+ eq(mentions([target, pg('s', 'Source', [blk('Roadmap', { type: 'code' })])], 't').length, 0,+ 'NEGATIVE: a title inside a code block is not a mention')+ // --- NEGATIVE: inside an existing link+ eq(has('see <a href="https://x.example/">Roadmap</a>').length, 0,+ 'NEGATIVE: a title inside an existing link is not a mention')+ // --- NEGATIVE: inside a URL+ eq(has('see https://example.com/Roadmap/2026 for more').length, 0,+ 'NEGATIVE: a title inside a bare URL is not a mention')+ eq(has('mail [email protected] about it').length, 0,+ 'NEGATIVE: a title inside a mail address is not a mention')+ // --- NEGATIVE: a substring of a longer word+ eq(has('the Roadmaps are ready').length, 0,+ 'NEGATIVE: a title that is a prefix of a longer word is not a mention')+ eq(has('the preRoadmap plan').length, 0,+ 'NEGATIVE: a title that is a suffix of a longer word is not a mention')+ eq(has('the pre-Roadmap plan').length, 1,+ 'a hyphen IS a boundary — "pre-Roadmap" mentions Roadmap')+ // --- NEGATIVE: the page's own text+ eq(mentions([pg('t', 'Roadmap', [blk('Roadmap is this page')])], 't').length, 0,+ "NEGATIVE: a page never mentions itself")+ // --- NEGATIVE: a block that already links there+ eq(has('the <a href="#p/t">Roadmap</a> and the Roadmap again').length, 0,+ 'NEGATIVE: a block that already links to the target offers no mention')+ // --- NEGATIVE: a skipped region cannot be spliced into a name+ eq(mentions([pg('t', 'New York'), pg('s', 'S', [blk('New<a href="#p/z">x</a>York')])], 't').length, 0,+ 'NEGATIVE: a name cannot be assembled across a skipped region')++ // --- attack: regex metacharacters in a title+ const nasty = pg('t2', 'C++ (v2) [beta] .*')+ let threw = false+ let found = -1+ try {+ found = mentions([nasty, pg('s', 'S', [blk('we shipped C++ (v2) [beta] .* last week')])], 't2').length+ } catch { threw = true }+ ok(!threw, 'a title full of regex metacharacters does not throw')+ eq(found, 1, 'and it matches LITERALLY, not as a pattern')+ eq(mentions([nasty, pg('s', 'S', [blk('we shipped Cxx v2 beta zzz last week')])], 't2').length, 0,+ 'a metacharacter title does not match what its pattern would have')+ eq(escapeRe('a(b'), 'a\\(b', 'escapeRe escapes')++ // --- case+ eq(has('read the roadmap').length, 1, 'matching is case-insensitive')+ eq(has('read the ROADMAP').length, 1, 'in both directions')++ // --- aliases are mentioned too+ const aliased = pg('t3', 'New York', [], { aliases: ['NYC'] })+ const viaAlias = mentions([aliased, pg('s', 'S', [blk('I moved to NYC last year')])], 't3')+ eq(viaAlias.length, 1, 'an ALIAS is mentioned as well as the title')+ eq(viaAlias[0].matched, 'NYC', 'and the alias is what is reported as matched')++ // --- longest first+ const two = mentions([pg('t4', 'New York City'), pg('o', 'New York')], 't4')+ void two+ const both = doc([+ pg('a', 'New'), pg('b', 'New York'),+ pg('s', 'S', [blk('I live in New York now')]),+ ])+ const ix = mentionIndex(both)+ eq((ix.get('b') ?? []).length, 1, 'the LONGER name wins the overlap')+ eq((ix.get('a') ?? []).length, 0, 'the shorter one does not steal it')+}++// ---------------------------------------------------------------------------+console.log('CJK')+// ---------------------------------------------------------------------------+{+ const tokyo = pg('t', '東京')+ const m = mentions([tokyo, pg('s', 'S', [blk('私は東京に住んでいます。')])], 't')+ eq(m.length, 1, 'ja: a name surrounded by kana IS a mention (a \\b rule finds ZERO here)')+ eq(m[0].matched, '東京', 'ja: the matched text is the name')++ const hans = pg('t2', '北京')+ eq(mentions([hans, pg('s', 'S', [blk('他去了北京开会')])], 't2').length, 1,+ 'zh-Hans: a name inside unspaced Han text is a mention')++ const hant = pg('t3', '臺灣')+ eq(mentions([hant, pg('s', 'S', [blk('這是臺灣的資料')])], 't3').length, 1,+ 'zh-Hant: likewise')++ // the KNOWN cost of the substring rule, asserted so nobody thinks it a bug+ eq(mentions([pg('t4', '京都'), pg('s', 'S', [blk('東京都に行く')])], 't4').length, 1,+ 'documented cost: a Han name matches inside a longer Han compound')++ // mixed script: a Latin edge still gets its boundary+ eq(mentions([pg('t5', 'Bento日本'), pg('s', 'S', [blk('これはBento日本です')])], 't5').length, 1,+ 'a mixed name whose edges are Han/Latin matches where each edge allows')++ // CJK inside a code span is still skipped+ eq(mentions([tokyo, pg('s', 'S', [blk('<code>東京</code>')])], 't').length, 0,+ 'NEGATIVE: the code-span rule holds for CJK too')+}++// ---------------------------------------------------------------------------+console.log('offsets and linkMention')+// ---------------------------------------------------------------------------+{+ const target = pg('t', 'Roadmap')+ const html = 'read the <b>Roadmap</b> and the Roadmap again'+ const found = mentions([target, pg('s', 'S', [blk(html)])], 't')+ eq(found.length, 2, 'both occurrences are found')+ eq(html.slice(found[0].htmlStart, found[0].htmlEnd), 'Roadmap', 'first offset lands on the html')+ eq(html.slice(found[1].htmlStart, found[1].htmlEnd), 'Roadmap', 'second offset lands on the SECOND one')+ eq(linkMention(html, found[1], 't'),+ 'read the <b>Roadmap</b> and the <a href="#p/t">Roadmap</a> again',+ 'linkMention wraps exactly the occurrence that matched')++ // entities do not shift the offsets+ const ent = 'the R&D Team met'+ const rd = mentions([pg('t2', 'R&D Team'), pg('s', 'S', [blk(ent)])], 't2')+ eq(rd.length, 1, 'a name spanning an entity is found')+ eq(linkMention(ent, rd[0], 't2'), 'the <a href="#p/t2">R&D Team</a> met',+ 'and linking it keeps the entity intact')++ // a stale offset writes nothing+ ok(linkMention('completely different text', found[0], 't') === null,+ 'linkMention refuses offsets that no longer describe the html')+ ok(linkMention(html, found[0], '../evil') === null || !String(linkMention(html, found[0], '../evil')).includes('../'),+ 'a target id is scrubbed before it becomes an href')++ eq(scanRuns('a<code>b</code>c').text.replace(/ /g, '|'), 'a|c', 'scanRuns drops skipped regions')+ eq(compileNames(['It', 'a']).length, 0, 'nothing scannable compiles to no regex at all')+}++// ---------------------------------------------------------------------------+console.log('cost')+// ---------------------------------------------------------------------------+{+ // A synthetic space in the shape the header claims to survive: many pages,+ // each with real prose, some of which genuinely mentions others.+ const WORDS = ('the quick brown fox jumps over a lazy dog while the roadmap ' ++ 'and the design review wait for nobody in particular today').split(' ')+ const build = (n: number): SpacesDoc => {+ const pages: Page[] = []+ for (let i = 0; i < n; i++) {+ const blocks: Block[] = []+ for (let j = 0; j < 12; j++) {+ const words: string[] = []+ for (let k = 0; k < 40; k++) words.push(WORDS[(i * 7 + j * 3 + k) % WORDS.length])+ // one in six paragraphs names another page outright+ if ((i + j) % 6 === 0) words.splice(10, 0, `Page ${(i * 13 + j) % n}`)+ blocks.push(blk(words.join(' ')))+ }+ pages.push(pg(`p${i}`, `Page ${i}`, blocks, i % 5 === 0 ? { aliases: [`Alias ${i}`] } : {}))+ }+ return doc(pages)+ }++ for (const n of [100, 500, 1000]) {+ const d = build(n)+ const ix = buildIndex(d)+ const chars = d.pages.reduce((s, p) => s + p.blocks.reduce((t, b) => t + (b.html ?? '').length, 0), 0)++ const t0 = performance.now()+ for (const p of d.pages.slice(0, 20)) mentionsOf(d, ix, p.id)+ const perPage = (performance.now() - t0) / 20++ const t1 = performance.now()+ const all = mentionIndex(d)+ const allPairs = performance.now() - t1++ const t2 = performance.now()+ buildIndex(d)+ const bi = performance.now() - t2++ let total = 0+ for (const list of all.values()) total += list.length+ console.log(` ${String(n).padStart(4)} pages, ${(chars / 1024).toFixed(0)}KB text` ++ ` · buildIndex ${bi.toFixed(1)}ms` ++ ` · one page's mentions ${perPage.toFixed(2)}ms` ++ ` · all pairs ${allPairs.toFixed(0)}ms (${total} mentions)`)++ ok(perPage < 200, `per-page mentions on ${n} pages stays under 200ms (was ${perPage.toFixed(1)})`)+ }+}++console.log(failed ? `\n${failed} of ${ran} FAILED` : `\nall ${ran} assertions pass`)+process.exit(failed ? 1 : 0)diff --git a/scripts/test-spaces.mjs b/scripts/test-spaces.mjsindex 774820fb..56511e78 100755--- a/scripts/test-spaces.mjs+++ b/scripts/test-spaces.mjs@@ -52,6 +52,7 @@ const RIGS = [{ name: 'roundtrip', file: 'scripts/test-spaces-roundtrip.ts', bundle: true },{ name: 'md-strict', file: 'scripts/test-spaces-md-strict.ts', bundle: true },{ name: 'restore-gate', file: 'scripts/test-spaces-restore-gate.ts', bundle: true },+ { name: 'mentions', file: 'scripts/test-spaces-mentions.ts' },{ name: 'size', file: 'scripts/test-spaces-size.mjs' },// Revision tracking has no timezone dependency; the browser rig needs the// built spaces shell and Playwright/Chrome (the CI browser job provides both).diff --git a/spaces/CHANGELOG.md b/spaces/CHANGELOG.mdindex 92bc1ca9..137de05b 100644--- a/spaces/CHANGELOG.md+++ b/spaces/CHANGELOG.md@@ -814,6 +814,53 @@ Versions follow `0.MINOR.PATCH` while pre-1.0.- The labels hide on a narrower window as slides' do. On a phone, thewhole group is in ⋯, under captions. The `/` menu lists the same familiesin the same order, with the same captions.+- **A page can answer to more than one name.** "Also known as" in the page+ panel takes a comma-separated list — "NYC, the Big Apple" on a page titled+ New York — and every one of those names reaches the page from a+ `[[wikilink]]`, from ⌘K search, and from the `[[` page picker. All three, on+ purpose: an alias that links but cannot be searched means you file something+ under the name you use for it and then cannot find it by that name, which+ reads as the search being broken rather than the alias being half-built.++ The alias is resolved where a name becomes a page id, so what gets written+ into the file is an ordinary `#p/<id>` link — backlinks, the graph, export,+ print and collaboration never learn that aliases exist. `aliases` is a new,+ absent-by-default key; clearing the last one deletes it again, so a page that+ had an alias and lost it is byte-identical to one that never had one, and an+ older build round-trips the array untouched.++ Two pages can claim one name, because a file arrives already written. The+ resolver settles it the same way in every copy — a title always beats an+ alias, then document order — and `bento.validate()` reports it as+ `alias-collision`, naming which page a `[[link]]` will actually reach. It is+ the one place this app tells you about a clash it resolved on your behalf.++- **Unlinked mentions: "this page is named in six others you never linked."**+ Under the backlinks, every place this page's title or aliases appear as plain+ words somewhere else, each with the sentence it appears in and a button that+ turns those exact words into a link.++ Most of the work is in what it refuses to find. A title inside a code block+ or a code span, inside a link you already made, inside a URL or a mail+ address, or in the middle of a longer word is not a mention; nor is a block+ that already links here; nor is the page's own text. Names shorter than three+ characters are not scanned for at all, because a page called "It" mentions+ everything.++ **CJK was designed for, not discovered.** A word-boundary rule built for+ English does not degrade in Japanese, it returns exactly zero — every kana+ beside a name is a letter, so the boundary never opens. So a boundary is+ required only where the name's own edge is a word character in a script that+ separates words, and two Han characters count as a whole name where three+ Latin ones are the floor. 私は東京に住んでいます mentions 東京. The cost of+ that rule, stated because it is real: a Han name also matches inside a longer+ Han compound.++ And it is not the quadratic thing it sounds like. Reading a page scans the+ document ONCE for that page's names, so the cost is the size of the space and+ not the number of pages in it: measured on a synthetic 1000-page, 2.5MB+ space, 6.5ms per page open, against 1.9ms for the backlink index the app+ already built. A 100-page space is 1.3ms.## [0.1.0] — 2026-08-03diff --git a/spaces/README.md b/spaces/README.mdindex 35e49b90..4517dc2f 100644--- a/spaces/README.md+++ b/spaces/README.md@@ -69,6 +69,7 @@ load contract and format additivity.| File | What it owns ||---|---|| `src/model.ts` | the format, `buildIndex()` (tree, backlinks), id repair |+| `src/mentions.ts` | page **aliases** (the one place a name becomes a page id) and **unlinked mentions** — the matching rule, and everything it refuses to match || `src/sanitize.ts` | the inline allowlist — the only thing between a file someone mailed you and script execution || `src/store.ts` | undo, and the **typing run** || `src/journal.ts` | daily notes — the date is `page.journal`, never the title |diff --git a/spaces/src/agent.ts b/spaces/src/agent.tsindex a688784e..504e884c 100644--- a/spaces/src/agent.ts+++ b/spaces/src/agent.ts@@ -32,6 +32,7 @@import { type SpacesDoc, type Page, type Block, buildIndex, isRemote, newBlock, newPage, uid, descendantsOf, linkCard, commentsOn, pageAssetKeys } from './model.ts'import { SPECS, SPEC } from './blocks.ts'+import { aliasesOf, nameKey } from './mentions.ts'import { sanitizeInline, textOf, inertBody, esc, UNWRAP } from './sanitize.ts'import { orphanAssets, humanBytes } from './assets.ts'import { danglingRefs, orphanNotes, LABEL_OK } from './footnotes.ts'@@ -259,6 +260,47 @@ export function validateDoc(doc: SpacesDoc): ValidateResult {fix: 'Set home to a real page id. Readers land on the first page instead, which may not be the one you wrote to be landed on.' })}+ // ---- names and aliases ---------------------------------------------------+ // TWO PAGES CLAIMING ONE NAME is not an error and is not repaired: a file+ // arrives already written, and the resolver has a deterministic answer for+ // it (mentions.ts nameIndex — titles before aliases, then document order).+ // But the answer is invisible from the outside, so `[[Projects]]` lands+ // somewhere the author did not choose and nothing anywhere says why. This is+ // that report: the one place this app tells you about a clash it resolved on+ // your behalf.+ //+ // A page ALIASED to its own title is silently fine — `namesOf` de-duplicates+ // it — so it is not reported. Two pages simply TITLED the same thing is also+ // not reported: that is ordinary and the ids keep them apart everywhere+ // except a `[[wikilink]]`, which is the one case worth a line.+ {+ const claims = new Map<string, Array<{ id: string; title: string; alias: boolean }>>()+ for (const kind of [false, true]) {+ for (const p of pages) {+ if (!p || typeof p.id !== 'string') continue+ const names = kind ? aliasesOf(p) : [String(p.title ?? '')]+ for (const n of names) {+ const k = nameKey(n)+ if (!k) continue+ const list = claims.get(k)+ if (list) { if (!list.some((c) => c.id === p.id)) list.push({ id: p.id, title: String(p.title ?? ''), alias: kind }) }+ else claims.set(k, [{ id: p.id, title: String(p.title ?? ''), alias: kind }])+ }+ }+ }+ for (const [k, list] of claims) {+ if (list.length < 2 || !list.some((c) => c.alias)) continue+ const winner = list[0]+ for (const loser of list.slice(1)) {+ add({+ page: loser.id, code: 'alias-collision', severity: 'warning', path: 'aliases',+ message: `More than one page answers to the name "${k}": ${list.map((c) => `"${c.title}"${c.alias ? ' (alias)' : ' (title)'}`).join(', ')}. A [[${k}]] link resolves to "${winner.title}".`,+ fix: `Rename the alias on "${loser.title}", or remove it. A title always wins over an alias, and among aliases the first page in doc.pages wins — so the page an author meant is not necessarily the page they get.`,+ })+ }+ }+ }+// ---- the field schema ----------------------------------------------------// Only a DECLARED `doc.fields` can be wrong; a document without one gets// DEFAULT_FIELDS, which is code.diff --git a/spaces/src/editor.ts b/spaces/src/editor.tsindex 8e1c9a7e..cf532491 100644--- a/spaces/src/editor.ts+++ b/spaces/src/editor.ts@@ -56,6 +56,9 @@ import '../../kernel/src/ui/dialog.css'import { createPanel, type Panel } from '../../kernel/src/ui/panel.ts'import '../../kernel/src/ui/panel.css'import { PropsPanel } from './props'+import {+ nameIndex, namesOf, mentionsOf, linkMention, type Mention,+} from './mentions.ts'import {internAsset, prepareImage, humanBytes, IMAGE_EMBED_BUDGET, MEDIA_EMBED_BUDGET, blobToDataUri,} from './assets'@@ -1173,6 +1176,10 @@ export class Editor {this.main.append(view)this.wire(view)view.querySelector('.sp-page-inner')?.append(this.backlinks(page.id))+ // Unlinked mentions sit BESIDE the backlinks and below them: "what links+ // here" is a fact about the space, "what could have" is a suggestion, and+ // a suggestion above a fact reads as one.+ view.querySelector('.sp-page-inner')?.append(this.unlinked(page.id))// Comments are EDITOR-ONLY. The gate is here rather than in comments.ts// because this is the object that knows which view it is in — and the// renderer, which print and the reading view share, has never heard of@@ -2985,6 +2992,78 @@ export class Editor {return box}+ /**+ * WHAT COULD LINK HERE — this page's names, found as plain words elsewhere.+ *+ * Derived at paint like the backlinks above it, never stored: a count+ * written into the file goes stale in somebody else's copy the moment they+ * type. `mentionsOf` makes ONE pass over the document for THIS page's names,+ * so the cost does not grow with the number of pages — see mentions.ts.+ *+ * A reader with nothing to link gets nothing at all: an empty "Unlinked+ * mentions (0)" heading on every page is chrome that only ever says no.+ */+ private unlinked(pageId: string): HTMLElement {+ const s = this.store+ const box = el('section', 'sp-mentions')+ let found: Mention[]+ // A malformed page (a title that is somehow not a string, an `aliases`+ // shape nobody anticipated) must cost the reader a panel, never the page.+ try { found = mentionsOf(s.doc, s.index, pageId) } catch { return box }+ if (!found.length) return box++ box.append(el('h2', 'sp-backlinks-h', t('Unlinked mentions')))+ const ul = el('ul', 'sp-backlink-list')+ for (const m of found) {+ const from = s.index.page.get(m.fromPage)+ if (!from) continue+ const li = document.createElement('li')+ const a = document.createElement('a')+ a.href = `#p/${from.id}`+ a.textContent = from.title || t('Untitled')+ a.addEventListener('click', (e) => { e.preventDefault(); s.goToPage(from.id) })+ li.append(a, el('span', 'sp-snippet', m.snippet))+ // The whole point of the panel: one click turns the words into the link+ // somebody meant to make. Hidden in a locked/reader copy, where the+ // mentions are still worth SEEING and the button would only fail.+ if (!(this.store.readOnly || this.reading)) {+ const btn = document.createElement('button')+ btn.className = 'sp-btn sp-mention-link'+ btn.type = 'button'+ btn.textContent = t('Link')+ btn.title = t('Turn these words into a link to this page')+ btn.addEventListener('click', () => this.linkMentionNow(m, pageId))+ li.append(btn)+ }+ ul.append(li)+ }+ box.append(ul)+ return box+ }++ /**+ * Turn one unlinked mention into a real link.+ *+ * The offsets were computed when the panel was painted, and the document may+ * have moved since — a collaborator's op, an undo, an edit in another tab.+ * `linkMention` returns null rather than splicing into a stale offset, and+ * this repaints instead of writing, which re-derives the mention from the+ * text as it now is. Silently writing the wrong span would corrupt a block.+ */+ private linkMentionNow(m: Mention, targetId: string): void {+ const s = this.store+ if (s.readOnly) return+ const found = s.index.block.get(m.fromBlock)+ const next = found ? linkMention(String(found.block.html ?? ''), m, targetId) : null+ if (next === null) {+ this.status(t('That text has changed — nothing was linked'))+ this.paintPage()+ return+ }+ s.commit(() => { const b = s.block(m.fromBlock); if (b) b.html = sanitizeInline(next) })+ this.paintPage()+ }+// ---- editing ------------------------------------------------------------private blockAt(node: Node | null): { id: string; host: HTMLElement } | null {const host = (node instanceof HTMLElement ? node : node?.parentElement)?.closest<HTMLElement>('[data-edit]')@@ -3623,6 +3702,13 @@ export class Editor {for (const p of s.doc.pages) {const hits: string[] = []if (p.title.toLowerCase().includes(q)) hits.push(p.title)+ // ⌘K FINDS A PAGE BY ITS ALIASES. An alias that reaches the `[[…]]`+ // resolver but not search is worse than no alias: you can link to+ // the page by the name you use for it and then cannot find it by+ // that name, which reads as the search being broken.+ for (const alias of namesOf(p).slice(1)) {+ if (alias.toLowerCase().includes(q)) hits.push(t('also called “{name}”', { name: alias }))+ }for (const b of p.blocks) {const text = textOf(b.html)if (text.toLowerCase().includes(q)) hits.push(text)@@ -3911,14 +3997,22 @@ export class Editor {const q = input.value.trim().toLowerCase()list.innerHTML = ''for (const p of s.doc.pages) {- if (q && !p.title.toLowerCase().includes(q)) continue+ // `[[` FINDS A PAGE BY ITS ALIASES TOO — the third of the three+ // places an alias has to reach (the resolver, ⌘K, here). Typing+ // `[[NYC` must offer the page titled "New York", or the alias only+ // works for text somebody imported and never for text you type.+ const names = namesOf(p)+ const alias = q ? names.slice(1).find((n) => n.toLowerCase().includes(q)) : undefined+ if (q && !p.title.toLowerCase().includes(q) && !alias) continueconst li = document.createElement('li')const b = document.createElement('button')b.className = 'sp-result'b.type = 'button'b.innerHTML =`<span class="sp-result-ico">${ICONS.page}</span>` +- `<span class="sp-result-txt"><strong>${escapeHtml(p.title || t('Untitled'))}</strong></span>`+ `<span class="sp-result-txt"><strong>${escapeHtml(p.title || t('Untitled'))}</strong>` ++ (alias ? `<span>${escapeHtml(t('also called “{name}”', { name: alias }))}</span>` : '') ++ `</span>`b.addEventListener('click', () => choose(p.id, p.title || t('Untitled')))li.append(b)list.append(li)@@ -4760,12 +4854,12 @@ export class Editor {return}- // pages this space already has, so an incremental import links INTO it- const existing = new Map<string, string>()- for (const page of s.doc.pages) {- const key = page.title.trim().toLowerCase()- if (key && !existing.has(key)) existing.set(key, page.id)- }+ // Pages this space already has, so an incremental import links INTO it —+ // BY EVERY NAME they answer to. `nameIndex` carries titles and aliases and+ // settles the ties, which is what makes `[[NYC]]` in an imported vault+ // land on the page already titled "New York": aliases have to reach the+ // resolver or they are an alias in name only.+ const existing = nameIndex(s.doc).byNameconst plan = planImport(files, {rootTitle: t('Imported notes'),resolveExisting: (target) => existing.get(target),diff --git a/spaces/src/i18n/de.ts b/spaces/src/i18n/de.tsindex 08de3ad6..b3e7a15f 100644--- a/spaces/src/i18n/de.ts+++ b/spaces/src/i18n/de.ts@@ -248,6 +248,13 @@ export const de: Catalog = {"Link — ⌘K": "Link — ⌘K","Linked": "Verknüpft","Linked from": "Verlinkt von",+ "Unlinked mentions": "Nicht verlinkte Erwähnungen",+ "Turn these words into a link to this page": "Diese Wörter in einen Link auf diese Seite verwandeln",+ "That text has changed — nothing was linked": "Dieser Text hat sich geändert – es wurde nichts verlinkt",+ "also called “{name}”": "auch „{name}“ genannt",+ "NYC, the Big Apple": "NYC, Big Apple",+ "Names that also reach this page from [[links]], search and the page picker": "Namen, die auch aus [[Links]], der Suche und der Seitenauswahl auf diese Seite führen",+ "Also known as": "Auch bekannt als","Links to it become dead": "Links darauf laufen ins Leere","List": "Liste","Live": "Live",diff --git a/spaces/src/i18n/es.ts b/spaces/src/i18n/es.tsindex cf14ad8b..a447f9b9 100644--- a/spaces/src/i18n/es.ts+++ b/spaces/src/i18n/es.ts@@ -248,6 +248,13 @@ export const es: Catalog = {"Link — ⌘K": "Enlace — ⌘K","Linked": "Enlazado","Linked from": "Enlazado desde",+ "Unlinked mentions": "Menciones sin enlazar",+ "Turn these words into a link to this page": "Convertir estas palabras en un enlace a esta página",+ "That text has changed — nothing was linked": "Ese texto ha cambiado: no se enlazó nada",+ "also called “{name}”": "también llamada «{name}»",+ "NYC, the Big Apple": "NYC, la Gran Manzana",+ "Names that also reach this page from [[links]], search and the page picker": "Nombres que también llegan a esta página desde [[enlaces]], la búsqueda y el selector de páginas",+ "Also known as": "También conocida como","Links to it become dead": "Los enlaces a ella dejan de funcionar","List": "Lista","Live": "En vivo",diff --git a/spaces/src/i18n/fr.ts b/spaces/src/i18n/fr.tsindex c09eb69a..e16504d2 100644--- a/spaces/src/i18n/fr.ts+++ b/spaces/src/i18n/fr.ts@@ -248,6 +248,13 @@ export const fr: Catalog = {"Link — ⌘K": "Lien — ⌘K","Linked": "Lié","Linked from": "Liens entrants",+ "Unlinked mentions": "Mentions non liées",+ "Turn these words into a link to this page": "Transformer ces mots en lien vers cette page",+ "That text has changed — nothing was linked": "Ce texte a changé — rien n’a été lié",+ "also called “{name}”": "aussi appelée « {name} »",+ "NYC, the Big Apple": "NYC, la Grosse Pomme",+ "Names that also reach this page from [[links]], search and the page picker": "Noms qui mènent aussi à cette page depuis les [[liens]], la recherche et le sélecteur de pages",+ "Also known as": "Aussi appelée","Links to it become dead": "Les liens vers elle seront rompus","List": "Liste","Live": "En direct",diff --git a/spaces/src/i18n/it.ts b/spaces/src/i18n/it.tsindex 10c2e741..c07841db 100644--- a/spaces/src/i18n/it.ts+++ b/spaces/src/i18n/it.ts@@ -248,6 +248,13 @@ export const it: Catalog = {"Link — ⌘K": "Collegamento — ⌘K","Linked": "Collegata","Linked from": "Collegata da",+ "Unlinked mentions": "Menzioni non collegate",+ "Turn these words into a link to this page": "Trasforma queste parole in un collegamento a questa pagina",+ "That text has changed — nothing was linked": "Quel testo è cambiato: non è stato collegato nulla",+ "also called “{name}”": "detta anche «{name}»",+ "NYC, the Big Apple": "NYC, la Grande Mela",+ "Names that also reach this page from [[links]], search and the page picker": "Nomi che raggiungono questa pagina anche dai [[collegamenti]], dalla ricerca e dal selettore di pagine",+ "Also known as": "Detta anche","Links to it become dead": "I collegamenti a questa pagina si interrompono","List": "Elenco","Live": "Dal vivo",diff --git a/spaces/src/i18n/ja.ts b/spaces/src/i18n/ja.tsindex 4030154f..37ffc5bc 100644--- a/spaces/src/i18n/ja.ts+++ b/spaces/src/i18n/ja.ts@@ -248,6 +248,13 @@ export const ja: Catalog = {"Link — ⌘K": "リンク — ⌘K","Linked": "リンク","Linked from": "リンク元",+ "Unlinked mentions": "未リンクの言及",+ "Turn these words into a link to this page": "この語句をこのページへのリンクにします",+ "That text has changed — nothing was linked": "その箇所は変更されています。リンクは作成されませんでした",+ "also called “{name}”": "別名「{name}」",+ "NYC, the Big Apple": "NYC, 大りんご",+ "Names that also reach this page from [[links]], search and the page picker": "[[リンク]]・検索・ページ選択からもこのページに届く別名",+ "Also known as": "別名","Links to it become dead": "このページへのリンクが切れます","List": "リスト","Live": "ライブ",diff --git a/spaces/src/i18n/packed.ts b/spaces/src/i18n/packed.tsindex 4c696851..b294e2c1 100644--- a/spaces/src/i18n/packed.ts+++ b/spaces/src/i18n/packed.ts@@ -56,6 +56,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Adds status, priority, assignee, estimate": ["ステータス・優先度・担当者・見積もりを追加します","添加状态、优先级、负责人和估算","新增狀態、優先順序、負責人與估算","Añade estado, prioridad, responsable y estimación","Ajoute statut, priorité, responsable et estimation","Fügt Status, Priorität, Bearbeiter:in und Schätzung hinzu","Aggiunge stato, priorità, assegnatario e stima","Adiciona estado, prioridade, responsável e estimativa"],"All text. Nothing is embedded, so this file is as small as a space gets.": ["すべてテキストです。埋め込みはないので、このファイルはスペースとして最小の大きさです。","全是文字。没有嵌入任何内容,所以这个文件已是空间能达到的最小体积。","全是文字。沒有嵌入任何內容,所以這個檔案已是空間能達到的最小體積。","Todo es texto. No hay nada incrustado, así que este archivo es lo más pequeño que puede ser un espacio.","Que du texte. Rien n’est intégré, donc ce fichier est aussi léger qu’un espace peut l’être.","Nur Text. Nichts ist eingebettet, also ist diese Datei so klein, wie ein Space nur sein kann.","Solo testo. Non c’è nulla di incorporato, quindi questo file è il più piccolo possibile per uno spazio.","Só texto. Nada está incorporado, por isso este ficheiro é o mais pequeno que um espaço pode ser."],"Already an issue": ["すでにイシューです","已经是事项","已經是項目","Ya es una incidencia","Déjà un ticket","Ist bereits ein Issue","È già una issue","Já é uma tarefa"],+ "Also known as": ["別名","又名","又名","También conocida como","Aussi appelée","Auch bekannt als","Detta anche","Também conhecida como"],"Also open in another window on this computer — not shared online": ["このパソコンの別のウィンドウでも開いています — オンライン共有はしていません","本机的另一个窗口中也已打开 — 未在线共享","本機的另一個視窗中也已開啟 — 未線上分享","También abierto en otra ventana de este ordenador — no compartido en línea","Également ouvert dans une autre fenêtre de cet ordinateur — pas partagé en ligne","Auch in einem anderen Fenster auf diesem Computer geöffnet — nicht online geteilt","Aperto anche in un’altra finestra di questo computer — non condiviso online","Também aberto noutra janela deste computador — não partilhado online"],"Alt text": ["代替テキスト","替代文本","替代文字","Texto alternativo","Texte alternatif","Alternativtext","Testo alternativo","Texto alternativo"],"An update check is the only network this app makes on its own. It asks the release server for a signed manifest and sends nothing about you or this document — no ids, no telemetry.": ["更新の確認は、このアプリが自分から行う唯一の通信です。リリースサーバーに署名済みのマニフェストを求めるだけで、あなたやこの文書に関する情報は何も送りません。ID もテレメトリもありません。","检查更新是这个应用唯一会自行发起的网络请求。它只向发布服务器索取一份已签名的清单,不发送任何关于你或这份文档的信息——没有标识符,没有遥测。","檢查更新是這個應用程式唯一會自行發起的網路請求。它只向發布伺服器索取一份已簽署的清單,不傳送任何關於你或這份文件的資訊——沒有識別碼,沒有遙測。","La comprobación de actualizaciones es la única conexión de red que esta aplicación hace por su cuenta. Pide al servidor de versiones un manifiesto firmado y no envía nada sobre ti ni sobre este documento: sin identificadores, sin telemetría.","La vérification des mises à jour est la seule connexion réseau que cette application établit d’elle-même. Elle demande au serveur de versions un manifeste signé et n’envoie rien sur vous ni sur ce document — aucun identifiant, aucune télémétrie.","Die Update-Prüfung ist die einzige Netzverbindung, die diese App von sich aus herstellt. Sie holt vom Release-Server ein signiertes Manifest und sendet nichts über Sie oder dieses Dokument — keine Kennungen, keine Telemetrie.","Il controllo degli aggiornamenti è l’unica connessione di rete che questa app apre da sola. Chiede al server delle versioni un manifesto firmato e non invia nulla su di te o su questo documento: nessun identificativo, nessuna telemetria.","A verificação de atualizações é a única ligação de rede que esta aplicação faz por iniciativa própria. Pede ao servidor de versões um manifesto assinado e não envia nada sobre si nem sobre este documento — sem identificadores, sem telemetria."],@@ -288,8 +289,10 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Move down": ["下へ移動","下移","下移","Bajar","Descendre","Nach unten","Sposta giù","Mover para baixo"],"Move up": ["上へ移動","上移","上移","Subir","Monter","Nach oben","Sposta su","Mover para cima"],"Muted": ["ミュート","静音","靜音","Silenciado","Muet","Stumm","Muto","Sem som"],+ "NYC, the Big Apple": ["NYC, 大りんご","NYC, 大苹果","NYC, 大蘋果","NYC, la Gran Manzana","NYC, la Grosse Pomme","NYC, Big Apple","NYC, la Grande Mela","NYC, a Big Apple"],"Name": ["名前","名称","名稱","Nombre","Nom","Name","Nome","Nome"],"Name this canvas": ["このキャンバスに名前を付ける","为此画布命名","為此畫布命名","Nombra este lienzo","Nommez ce canevas","Diese Leinwand benennen","Dai un nome a questa tela","Dê um nome a esta tela"],+ "Names that also reach this page from [[links]], search and the page picker": ["[[リンク]]・検索・ページ選択からもこのページに届く別名","在 [[链接]]、搜索和页面选择器中同样指向本页的名称","在 [[連結]]、搜尋和頁面選擇器中同樣指向本頁的名稱","Nombres que también llegan a esta página desde [[enlaces]], la búsqueda y el selector de páginas","Noms qui mènent aussi à cette page depuis les [[liens]], la recherche et le sélecteur de pages","Namen, die auch aus [[Links]], der Suche und der Seitenauswahl auf diese Seite führen","Nomi che raggiungono questa pagina anche dai [[collegamenti]], dalla ricerca e dal selettore di pagine","Nomes que também chegam a esta página a partir de [[ligações]], da pesquisa e do seletor de páginas"],"Nested under": ["この下のページ","嵌套于","巢狀於","Anidadas en","Imbriquées sous","Verschachtelt unter","Annidate sotto","Aninhadas em"],"New issue": ["新しいイシュー","新建事项","新增項目","Nueva incidencia","Nouveau ticket","Neues Issue","Nuova issue","Nova tarefa"],"New page": ["新規ページ","新建页面","新增頁面","Nueva página","Nouvelle page","Neue Seite","Nuova pagina","Nova página"],@@ -472,6 +475,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"That is {n} files — importing them all may take a moment. Continue?": ["{n} 個のファイルがあります。すべて読み込むには少し時間がかかります。続けますか?","一共 {n} 个文件,全部导入需要一点时间。继续吗?","共 {n} 個檔案,全部匯入需要一點時間。要繼續嗎?","Son {n} archivos: importarlos todos puede tardar un momento. ¿Continuar?","Cela fait {n} fichiers — tout importer peut prendre un moment. Continuer ?","Das sind {n} Dateien — der Import kann einen Moment dauern. Fortfahren?","Sono {n} file — importarli tutti può richiedere un momento. Continuare?","São {n} ficheiros — importar todos pode demorar um momento. Continuar?"],"That needs to be an http or https address": ["http または https のアドレスを入力してください","这里需要填写 http 或 https 地址","這裡需要填 http 或 https 位址","Tiene que ser una dirección http o https","Il faut une adresse http ou https","Das muss eine http- oder https-Adresse sein","Serve un indirizzo http o https","Tem de ser um endereço http ou https"],"That space is password-protected. Open it, then export the pages you want.": ["そのスペースはパスワードで保護されています。開いてから、必要なページを書き出してください。","该空间受密码保护。请先打开它,再导出你需要的页面。","該空間受密碼保護。請先開啟它,再匯出你需要的頁面。","Ese espacio está protegido con contraseña. Ábrelo y exporta desde allí las páginas que quieras.","Cet espace est protégé par un mot de passe. Ouvrez-le, puis exportez-en les pages voulues.","Dieser Space ist passwortgeschützt. Öffnen Sie ihn und exportieren Sie dort die gewünschten Seiten.","Quello spazio è protetto da password. Aprilo e da lì esporta le pagine che vuoi.","Esse espaço está protegido por palavra-passe. Abra-o e exporte de lá as páginas que quiser."],+ "That text has changed — nothing was linked": ["その箇所は変更されています。リンクは作成されませんでした","该文字已更改,未创建链接","該文字已變更,未建立連結","Ese texto ha cambiado: no se enlazó nada","Ce texte a changé — rien n’a été lié","Dieser Text hat sich geändert – es wurde nichts verlinkt","Quel testo è cambiato: non è stato collegato nulla","Esse texto mudou — nada foi ligado"],"That version could not be read": ["そのバージョンを読み込めませんでした","无法读取该版本","無法讀取該版本","No se pudo leer esa versión","Cette version n’a pas pu être lue","Diese Version konnte nicht gelesen werden","Non è stato possibile leggere quella versione","Não foi possível ler essa versão"],"The block menu, on an empty line": ["空行でブロックメニュー","在空行上打开块菜单","在空行上開啟區塊選單","El menú de bloques, en una línea vacía","Le menu de blocs, sur une ligne vide","Das Blockmenü, in einer leeren Zeile","Il menu dei blocchi, su una riga vuota","O menu de blocos, numa linha vazia"],"The day after": ["翌日","后一天","後一天","El día siguiente","Le lendemain","Der Tag danach","Il giorno dopo","O dia seguinte"],@@ -529,12 +533,14 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Too many changes at once — live sync is catching up.": ["変更が多すぎます — ライブ同期が追いついています。","更改过多 — 实时同步正在追赶。","變更太多 — 即時同步正在追趕。","Demasiados cambios a la vez — la sincronización en vivo se está poniendo al día.","Trop de modifications à la fois — la synchronisation en direct rattrape son retard.","Zu viele Änderungen auf einmal — die Live-Synchronisierung holt auf.","Troppe modifiche insieme — la sincronizzazione dal vivo sta recuperando.","Alterações demais de uma vez — a sincronização ao vivo está se atualizando."],"Top level": ["最上位","顶层","最上層","Nivel superior","Premier niveau","Oberste Ebene","Primo livello","Nível superior"],"Turn into…": ["種類を変更…","转换为…","轉換為…","Convertir en…","Convertir en…","Umwandeln in…","Converti in…","Converter em…"],+ "Turn these words into a link to this page": ["この語句をこのページへのリンクにします","把这些文字变成指向本页的链接","把這些文字變成指向本頁的連結","Convertir estas palabras en un enlace a esta página","Transformer ces mots en lien vers cette page","Diese Wörter in einen Link auf diese Seite verwandeln","Trasforma queste parole in un collegamento a questa pagina","Transformar estas palavras numa ligação para esta página"],"Type / for blocks, [[ to link a page": ["/ でブロック、[[ でページにリンク","输入 / 插入块,[[ 链接页面","輸入 / 插入區塊,輸入 [[ 連結頁面","Escribe / para bloques, [[ para enlazar una página","Tapez / pour les blocs, [[ pour lier une page","Tippe / für Blöcke, [[ für einen Seitenlink","Digita / per i blocchi, [[ per collegare una pagina","Escreva / para blocos, [[ para ligar uma página"],"Underline": ["下線","下划线","底線","Subrayado","Souligné","Unterstrichen","Sottolineato","Sublinhado"],"Underline — ⌘U": ["下線 — ⌘U","下划线 — ⌘U","底線 — ⌘U","Subrayado — ⌘U","Souligné — ⌘U","Unterstrichen — ⌘U","Sottolineato — ⌘U","Sublinhado — ⌘U"],"Undo": ["元に戻す","撤销","還原","Deshacer","Annuler","Rückgängig","Annulla","Desfazer"],"Undo (⌘Z)": ["元に戻す (⌘Z)","撤销 (⌘Z)","還原 (⌘Z)","Deshacer (⌘Z)","Annuler (⌘Z)","Rückgängig (⌘Z)","Annulla (⌘Z)","Desfazer (⌘Z)"],"Undo, redo": ["取り消し・やり直し","撤销、重做","復原、重做","Deshacer, rehacer","Annuler, rétablir","Rückgängig, wiederherstellen","Annulla, ripeti","Anular, refazer"],+ "Unlinked mentions": ["未リンクの言及","未链接的提及","未連結的提及","Menciones sin enlazar","Mentions non liées","Nicht verlinkte Erwähnungen","Menzioni non collegate","Menções sem ligação"],"Unlock": ["ロック解除","解锁","解鎖","Desbloquear","Déverrouiller","Entsperren","Sblocca","Desbloquear"],"Unlocked, but the document inside could not be read.": ["ロックは解除しましたが、中のドキュメントを読み取れませんでした。","已解锁,但无法读取其中的文档。","已解鎖,但無法讀取裡面的文件。","Desbloqueado, pero no se pudo leer el documento de dentro.","Déverrouillé, mais le document à l’intérieur n’a pas pu être lu.","Entsperrt, aber das Dokument darin konnte nicht gelesen werden.","Sbloccato, ma non è stato possibile leggere il documento all’interno.","Desbloqueado, mas não foi possível ler o documento lá dentro."],"Unsaved changes from a previous session were found.": ["前回のセッションの未保存の変更が見つかりました。","发现上一次会话未保存的更改。","發現上一次工作階段未儲存的變更。","Se encontraron cambios sin guardar de una sesión anterior.","Des modifications non enregistrées d’une session précédente ont été trouvées.","Nicht gespeicherte Änderungen aus einer früheren Sitzung gefunden.","Sono state trovate modifiche non salvate di una sessione precedente.","Foram encontradas alterações não guardadas de uma sessão anterior."],@@ -587,6 +593,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"Your name": ["あなたの名前","你的名字","你的名字","Tu nombre","Votre nom","Dein Name","Il tuo nome","Seu nome"],"Your name (shown on comments):": ["あなたの名前(コメントに表示):","您的名字(显示在评论中):","您的名字(顯示於註解):","Tu nombre (visible en los comentarios):","Votre nom (affiché sur les commentaires) :","Ihr Name (bei Kommentaren sichtbar):","Il tuo nome (visibile nei commenti):","Seu nome (exibido nos comentários):"],"Your name (shown on new comments):": ["あなたの名前(新しいコメントに表示):","您的名字(显示在新评论中):","您的名字(顯示於新註解):","Tu nombre (visible en los nuevos comentarios):","Votre nom (affiché sur les nouveaux commentaires) :","Ihr Name (bei neuen Kommentaren sichtbar):","Il tuo nome (visibile nei nuovi commenti):","Seu nome (exibido em novos comentários):"],+ "also called “{name}”": ["別名「{name}」","又名“{name}”","又名「{name}」","también llamada «{name}»","aussi appelée « {name} »","auch „{name}“ genannt","detta anche «{name}»","também chamada “{name}”"],"archived": ["アーカイブ済み","已归档","已封存","archivada","archivée","archiviert","archiviata","arquivada"],"bento/spaces is MIT-licensed and carries no third-party runtime — the full notices travel in this file’s source.": ["bento/spaces は MIT ライセンスで、サードパーティのランタイムは含みません。完全な表示はこのファイルのソースに入っています。","bento/spaces 采用 MIT 许可,且不含任何第三方运行时——完整声明就在这个文件的源码里。","bento/spaces 採用 MIT 授權,且不含任何第三方執行環境——完整聲明就在這個檔案的原始碼裡。","bento/spaces tiene licencia MIT y no incluye ningún runtime de terceros: los avisos completos viajan en el código fuente de este archivo.","bento/spaces est sous licence MIT et n’embarque aucun runtime tiers — les mentions complètes voyagent dans le source de ce fichier.","bento/spaces steht unter MIT-Lizenz und enthält keine Fremd-Runtime — die vollständigen Hinweise reisen im Quelltext dieser Datei mit.","bento/spaces è rilasciato con licenza MIT e non include alcun runtime di terze parti: le note complete viaggiano nel sorgente di questo file.","O bento/spaces tem licença MIT e não inclui qualquer runtime de terceiros — os avisos completos viajam no código-fonte deste ficheiro."],"format v{v}": ["フォーマット v{v}","格式 v{v}","格式 v{v}","formato v{v}","format v{v}","Format v{v}","formato v{v}","formato v{v}"],diff --git a/spaces/src/i18n/pt.ts b/spaces/src/i18n/pt.tsindex 35cac181..72b177c8 100644--- a/spaces/src/i18n/pt.ts+++ b/spaces/src/i18n/pt.ts@@ -248,6 +248,13 @@ export const pt: Catalog = {"Link — ⌘K": "Link — ⌘K","Linked": "Externo","Linked from": "Ligado a partir de",+ "Unlinked mentions": "Menções sem ligação",+ "Turn these words into a link to this page": "Transformar estas palavras numa ligação para esta página",+ "That text has changed — nothing was linked": "Esse texto mudou — nada foi ligado",+ "also called “{name}”": "também chamada “{name}”",+ "NYC, the Big Apple": "NYC, a Big Apple",+ "Names that also reach this page from [[links]], search and the page picker": "Nomes que também chegam a esta página a partir de [[ligações]], da pesquisa e do seletor de páginas",+ "Also known as": "Também conhecida como","Links to it become dead": "As ligações para ela ficam quebradas","List": "Lista","Live": "Ao vivo",diff --git a/spaces/src/i18n/zh-Hans.ts b/spaces/src/i18n/zh-Hans.tsindex 4680955e..9fcab6ef 100644--- a/spaces/src/i18n/zh-Hans.ts+++ b/spaces/src/i18n/zh-Hans.ts@@ -248,6 +248,13 @@ export const zh_Hans: Catalog = {"Link — ⌘K": "链接 — ⌘K","Linked": "链接","Linked from": "链接来源",+ "Unlinked mentions": "未链接的提及",+ "Turn these words into a link to this page": "把这些文字变成指向本页的链接",+ "That text has changed — nothing was linked": "该文字已更改,未创建链接",+ "also called “{name}”": "又名“{name}”",+ "NYC, the Big Apple": "NYC, 大苹果",+ "Names that also reach this page from [[links]], search and the page picker": "在 [[链接]]、搜索和页面选择器中同样指向本页的名称",+ "Also known as": "又名","Links to it become dead": "指向它的链接会失效","List": "列表","Live": "已连接",diff --git a/spaces/src/i18n/zh-Hant.ts b/spaces/src/i18n/zh-Hant.tsindex 491f4bc8..08989884 100644--- a/spaces/src/i18n/zh-Hant.ts+++ b/spaces/src/i18n/zh-Hant.ts@@ -248,6 +248,13 @@ export const zh_Hant: Catalog = {"Link — ⌘K": "連結 — ⌘K","Linked": "連結","Linked from": "連結來源",+ "Unlinked mentions": "未連結的提及",+ "Turn these words into a link to this page": "把這些文字變成指向本頁的連結",+ "That text has changed — nothing was linked": "該文字已變更,未建立連結",+ "also called “{name}”": "又名「{name}」",+ "NYC, the Big Apple": "NYC, 大蘋果",+ "Names that also reach this page from [[links]], search and the page picker": "在 [[連結]]、搜尋和頁面選擇器中同樣指向本頁的名稱",+ "Also known as": "又名","Links to it become dead": "指向它的連結會失效","List": "清單","Live": "已連線",diff --git a/spaces/src/main.ts b/spaces/src/main.tsindex 7c41946c..8d227b88 100644--- a/spaces/src/main.ts+++ b/spaces/src/main.ts@@ -29,6 +29,7 @@ import {type Plan, type PlanError, type IssueQuery, type CommentQuery,} from './agent'import { starterDoc } from './starter'+import { mentionsOf, mentionIndex } from './mentions.ts'import { todayISO, isISO, journalFor } from './journal'import { textOf } from './sanitize'import { evaluate, format, pageContext } from './calc'@@ -472,6 +473,18 @@ function boot(doc: SpacesDoc, repaired: string[], frozen?: 'policy' | 'version')validate: (target?: SpacesDoc) => validateDoc(target ?? store.doc),/** the whole space as a tree, for orienting in one call */outline: (target?: SpacesDoc) => outlineDoc(target ?? store.doc),+ /**+ * Where this space names a page without linking to it.+ *+ * With a page id, that page's unlinked mentions; with none, every page's,+ * as `{ pageId: Mention[] }`. READ ONLY — it reports, it does not link.+ * Deciding that a sentence meant the page is a judgement, and an agent+ * that silently rewrote a hundred blocks' html on a guess would be+ * unreviewable. Link them with `updateBlock`, or leave them for the panel.+ */+ mentions: (pageId?: string) => pageId+ ? mentionsOf(store.doc, store.index, pageId)+ : Object.fromEntries(mentionIndex(store.doc)),/** where the bytes are */stats: (target?: SpacesDoc) => statsDoc(target ?? store.doc),/**diff --git a/spaces/src/mentions.ts b/spaces/src/mentions.tsnew file mode 100644index 00000000..2d1944ab--- /dev/null+++ b/spaces/src/mentions.ts@@ -0,0 +1,612 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// ALIASES AND UNLINKED MENTIONS.+//+// Two features that are one idea: a page is known by more than one NAME, and+// those names appear in prose whether or not anybody typed `[[ ]]` around them.+//+// · `Page.aliases` — additive, absent on every page written before this. A+// page answering to "NYC" and "New York" is reachable by either from the+// `[[…]]` resolver, ⌘K, and the page picker, so a link made through an+// alias produces an ordinary `#p/<id>` href and an ordinary backlink. That+// is the whole reason aliases resolve at LINK time rather than at render+// time: nothing downstream of the resolver has to learn what an alias is.+// · Unlinked mentions — every place a page's names appear as plain words in+// some OTHER page, offered beside the backlinks with a one-click link.+//+// ---------------------------------------------------------------------------+// WHY THIS IS NOT QUADRATIC+//+// "Every page's title matched against every page's text" is N×M, and this app+// is one file that may hold hundreds of pages. It is not computed that way.+//+// The UI only ever asks about ONE page — the one you are reading. So+// `mentionsOf(doc, index, pageId)` builds a single regex from THAT page's names+// and makes one pass over the document's text: O(total text), independent of+// how many pages exist. Opening a page therefore costs the same whether the+// space has 20 pages or 2000, which is the property that matters, because+// this runs on every repaint.+//+// `mentionIndex()` computes the all-pairs answer for the agent surface and for+// measurement. It is still not N passes: names are compiled into CHUNKED+// alternations (`NAMES_PER_RE`), so the cost is (total text) × (chunks), and a+// space small enough to fit in one chunk gets a single pass. Measured numbers+// live in the rig, scripts/test-spaces-mentions.ts.+//+// ---------------------------------------------------------------------------+// THE MATCHING RULE, and why every clause of it is load-bearing+//+// False positives are the entire design problem: a page called "Notes" that+// claims to be mentioned by every page in the space is worse than no feature,+// because it teaches the reader to stop looking at the panel.+//+// 1. MINIMUM LENGTH, by script. Three code points for a name written in a+// script that uses spaces, TWO for one containing Han/kana/Hangul. Latin+// "It", "AI" and "PR" mention everything; two Han characters are a whole+// word. Under the minimum a name still LINKS — it is only excluded from+// the mention scan.+// 2. WORD BOUNDARIES, applied per SIDE of each name and only where they mean+// something. `\b` is a Latin rule wearing a Unicode coat: applied to+// Japanese it requires a non-letter beside the name, and since every+// neighbouring kana IS a letter it produces exactly ZERO matches in ja,+// zh-Hans and zh-Hant — a silent total failure in three of this app's+// nine locales. So a boundary is required only where the name's own edge+// character is a spacing-script word character. Where the edge is CJK the+// match is a plain substring, which is what every CJK-aware search in the+// world does and carries the known cost that 京都 matches inside 東京都.+// That cost is visible and bounded; the alternative is a feature that+// does not exist for a third of the supported languages.+// 3. CASE-INSENSITIVE, because "the roadmap" is a mention of "Roadmap".+// 4. NEVER inside a code block, a code span, an existing `<a>`, a bare URL,+// or the page's own text. `scanRuns` below is the single decision about+// what text is eligible; everything else reads its output.+// 5. NEVER in a block that already links to the target — you did link it,+// the panel telling you that you did not is a lie.+//+// UNTRUSTED INPUT. Names come out of a file somebody mailed you. Every one is+// escaped before it reaches a RegExp (`escapeRe`) — a page titled `a(b` is an+// obvious crash and an obvious attack. Map lookups on document data use+// `Object.hasOwn`, never a bare `in` or a truthiness test.++import type { SpacesDoc, Page, SpaceIndex } from './model.ts'++// ---------------------------------------------------------------------------+// names+// ---------------------------------------------------------------------------++/** Han, kana or Hangul anywhere: the scripts that do not separate words. */+const CJK = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u+/** A word character in a script that DOES separate words, for boundary tests. */+const WORDY = /[\p{L}\p{N}_]/u++/** Shortest name that may be scanned for, by script. See rule 1. */+export const MIN_LATIN = 3+export const MIN_CJK = 2++/** Every regex metacharacter, neutralised. Nothing builds a RegExp without it. */+export const escapeRe = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')++/** Comparison form for a name: trimmed, NFC-folded, case-folded. */+export const nameKey = (raw: string): string => {+ let s = String(raw ?? '').trim()+ try { s = s.normalize('NFC') } catch { /* an exotic engine: uncomposed is still consistent */ }+ return s.toLowerCase()+}++/**+ * A page's declared aliases, defended against the file.+ *+ * `aliases` arrives from a document nobody validated. Anything that is not an+ * array of non-empty strings yields none, and the field is left ALONE on the+ * page so it round-trips untouched (format additivity: this build must not+ * repair what it does not understand).+ */+export function aliasesOf(page: Page): string[] {+ const raw = (page as { aliases?: unknown }).aliases+ if (!Array.isArray(raw)) return []+ const out: string[] = []+ const seen = new Set<string>()+ for (const a of raw) {+ if (typeof a !== 'string') continue+ const trimmed = a.trim()+ if (!trimmed) continue+ const k = nameKey(trimmed)+ if (seen.has(k)) continue+ seen.add(k)+ out.push(trimmed)+ }+ return out+}++/** Title first, then aliases — every name this page answers to. */+export function namesOf(page: Page): string[] {+ const out: string[] = []+ const seen = new Set<string>()+ const push = (n: string) => {+ const trimmed = String(n ?? '').trim()+ if (!trimmed) return+ const k = nameKey(trimmed)+ if (seen.has(k)) return+ seen.add(k)+ out.push(trimmed)+ }+ push(page.title)+ for (const a of aliasesOf(page)) push(a)+ return out+}++/** Is this name long enough to be scanned for? Rule 1. */+export function scannable(name: string): boolean {+ const n = name.trim()+ if (!n) return false+ const len = [...n].length+ return len >= (CJK.test(n) ? MIN_CJK : MIN_LATIN)+}++// ---------------------------------------------------------------------------+// the name index — aliases reaching resolution, search and the picker+// ---------------------------------------------------------------------------++export interface NameIndex {+ /** nameKey → the page it names. First claimant wins; see `collisions`. */+ byName: Map<string, string>+ /** nameKey → every page claiming it, only where more than one does */+ collisions: Map<string, string[]>+}++/**+ * THE ONE PLACE a name becomes a page id.+ *+ * Titles are laid down first, all of them, and only then aliases — so an alias+ * can never shadow a real page's title, however the pages happen to be+ * ordered. That ordering is the whole collision policy for the common case: a+ * page aliased "Projects" while another page is TITLED "Projects" resolves to+ * the titled one, deterministically, and validate() reports the clash rather+ * than the app silently picking by array order.+ *+ * Among two aliases, or two identical titles, the FIRST in document order+ * wins — deterministic, and the same answer in every replica, which matters+ * because two collaborators must not resolve one `[[name]]` differently.+ */+export function nameIndex(doc: SpacesDoc): NameIndex {+ const byName = new Map<string, string>()+ const claims = new Map<string, string[]>()+ const pages = Array.isArray(doc.pages) ? doc.pages : []++ const claim = (name: string, id: string) => {+ const k = nameKey(name)+ if (!k) return+ const list = claims.get(k)+ if (list) { if (!list.includes(id)) list.push(id) }+ else claims.set(k, [id])+ if (!byName.has(k)) byName.set(k, id)+ }++ for (const p of pages) if (p && typeof p.id === 'string') claim(String(p.title ?? ''), p.id)+ for (const p of pages) if (p && typeof p.id === 'string') for (const a of aliasesOf(p)) claim(a, p.id)++ const collisions = new Map<string, string[]>()+ for (const [k, ids] of claims) if (ids.length > 1) collisions.set(k, ids)+ return { byName, collisions }+}++// ---------------------------------------------------------------------------+// eligible text+// ---------------------------------------------------------------------------++/**+ * A run of scannable text, and where its bytes are in the html.+ *+ * Offsets are kept so a mention can be LINKED in place: the panel's button+ * wraps exactly the characters that matched, in the block's own html, without+ * re-finding them by string search (which would hit the wrong occurrence when+ * a name appears twice).+ *+ * Every run is entity-free, so within one run `htmlStart + (i - textStart)` is+ * exact. An entity gets a run of its own, whose text length and html length+ * differ — hence `atomic`, which stops a partial offset being computed inside+ * it.+ */+interface Run {+ htmlStart: number+ htmlEnd: number+ textStart: number+ text: string+ /** html and text lengths differ (an entity): offsets inside are not linear */+ atomic: boolean+}++/**+ * The separator written where a skipped region was.+ *+ * NOT a space. With a space, `New<a>x</a>York` collapses to `New York` and the+ * scanner reports a mention of the page "New York" that nobody wrote — the+ * separator has to be a character no name can contain, and U+0000 is the one+ * the markdown parser already strips from every input.+ */+const SEP = '\u0000'+const SEP_RE = /\u0000/g++/** A region of html a mention may never be found in. */+const SKIP_RE = /<code\b[^>]*>[\s\S]*?<\/code>|<a\b[^>]*>[\s\S]*?<\/a>|<[^>]*>/gi+/**+ * An address sitting in TEXT rather than in an href.+ *+ * A URL is a name-shaped haystack — `example.com/Roadmap/2026` contains the+ * word and means nothing by it — and so is a mail address. Both are masked+ * before matching. Addresses inside an `<a>` are already gone; this is for the+ * ones an author typed as plain text.+ */+const BARE_URL_RE = /(?:https?:\/\/|www\.|mailto:)\S+|[\w.+-]+@[\w-]+(?:\.[\w-]+)+/gi+/** No address can exist without one of these; the cheap gate in front of it. */+const ADDRESSY = /[:@]|www\./i+/** Entities, kept atomic so an offset is never computed halfway through one. */+const ENTITY_RE = /&(?:#\d+|#[xX][0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);/g++const ENTITIES: Record<string, string> = {+ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ',+}++function decodeEntity(ent: string): string {+ const body = ent.slice(1, -1)+ if (body.startsWith('#')) {+ const n = body[1] === 'x' || body[1] === 'X'+ ? parseInt(body.slice(2), 16)+ : parseInt(body.slice(1), 10)+ if (Number.isFinite(n) && n >= 0 && n <= 0x10ffff) {+ try { return String.fromCodePoint(n) } catch { return ent }+ }+ return ent+ }+ // `Object.hasOwn`, not `ENTITIES[body]`: `constructor` and `__proto__` are+ // both legal entity-shaped names and both truthy on a bare object lookup.+ return Object.hasOwn(ENTITIES, body) ? ENTITIES[body] : ent+}++/**+ * Split a block's html into runs of text a mention may be found in.+ *+ * The separator between eligible runs is a U+0000, which no name can contain+ * (`nameKey` never produces one and the parser strips them from input), so a+ * match can never span a skipped region — a title cannot be assembled out of+ * half a link and half the prose after it.+ */+export function scanRuns(html: string): { text: string; runs: Run[] } {+ const src = String(html ?? '')+ const runs: Run[] = []+ let text = ''++ const pushPlain = (chunk: string, at: number) => {+ if (!chunk) return+ // Entities inside a plain chunk become atomic runs of their own.+ let last = 0+ ENTITY_RE.lastIndex = 0+ for (const m of chunk.matchAll(ENTITY_RE)) {+ const i = m.index ?? 0+ if (i > last) {+ const s = chunk.slice(last, i)+ runs.push({ htmlStart: at + last, htmlEnd: at + i, textStart: text.length, text: s, atomic: false })+ text += s+ }+ const dec = decodeEntity(m[0])+ runs.push({+ htmlStart: at + i, htmlEnd: at + i + m[0].length,+ textStart: text.length, text: dec, atomic: true,+ })+ text += dec+ last = i + m[0].length+ }+ if (last < chunk.length) {+ const s = chunk.slice(last)+ runs.push({ htmlStart: at + last, htmlEnd: at + chunk.length, textStart: text.length, text: s, atomic: false })+ text += s+ }+ }++ /**+ * A chunk of raw text between tags: mask bare addresses, keep the rest.+ *+ * THE `:@.` GUARD IS NOT DECORATION. `BARE_URL_RE`'s mail branch begins+ * `[\w.+-]+`, so without a guard it starts an attempt at every word in the+ * document and then backtracks — it took the per-page scan on the 2.5MB rig+ * space from 7ms to 21ms, three times the cost of the matching it exists to+ * protect. An address needs one of these three characters, and prose that+ * has none cannot contain one.+ */+ const pushText = (chunk: string, at: number) => {+ if (!ADDRESSY.test(chunk)) { pushPlain(chunk, at); return }+ let last = 0+ BARE_URL_RE.lastIndex = 0+ for (const m of chunk.matchAll(BARE_URL_RE)) {+ const i = m.index ?? 0+ pushPlain(chunk.slice(last, i), at + last)+ text += SEP+ last = i + m[0].length+ }+ pushPlain(chunk.slice(last), at + last)+ }++ let last = 0+ SKIP_RE.lastIndex = 0+ for (const m of src.matchAll(SKIP_RE)) {+ const i = m.index ?? 0+ if (i > last) pushText(src.slice(last, i), last)+ text += SEP+ last = i + m[0].length+ }+ if (last < src.length) pushText(src.slice(last), last)+ return { text, runs }+}++/** Text offset → html offset, exact. `end` picks the run's trailing edge. */+function htmlOffset(runs: Run[], at: number, end: boolean): number {+ // linear is fine: a block's runs are counted in tens+ for (const r of runs) {+ const lo = r.textStart+ const hi = r.textStart + r.text.length+ if (end ? (at > lo && at <= hi) : (at >= lo && at < hi)) {+ if (r.atomic) return end ? r.htmlEnd : r.htmlStart+ return r.htmlStart + (at - lo)+ }+ }+ return end ? (runs.length ? runs[runs.length - 1].htmlEnd : 0) : 0+}++// ---------------------------------------------------------------------------+// matching+// ---------------------------------------------------------------------------++/**+ * The boundary assertions, and why they are an ALTERNATION rather than a class.+ *+ * What a boundary has to exclude is "a word character in a script that+ * separates words". `[\p{L}\p{N}_]` is the obvious spelling and it is wrong at+ * exactly one place: a Latin-initial name inside Japanese prose. `Bento日本` in+ * `これはBento日本です` is preceded by `は`, which IS a letter, so a plain+ * lookbehind rejects it and the name is unfindable in the only language it was+ * written for.+ *+ * The `v` flag can subtract one class from another and would say this in one+ * term. It is NOT used, and the reason is not taste: `v` is Safari 17, while+ * this app's floor is Safari 16.4 — where `DecompressionStream` (which the+ * shell's own loader needs) and lookbehind both land. A regex the engine+ * cannot COMPILE throws at construction, so getting that wrong is not a+ * missing feature, it is a panel that throws on every page open. The+ * alternation below says the same thing under `u`: "no word character before"+ * OR "a CJK character before" — which is exactly "no non-CJK word character+ * before". Measured, the four ways of spelling this boundary (plain `\p{L}`,+ * this alternation, a lookbehind wrapping a lookahead, and the `v` set+ * difference) all run within noise of each other on a 210KB haystack — 0.03 to+ * 0.05ms a pass. So the choice is decided entirely by the browser floor, and+ * not at all by speed. Worth saying because the first draft of this comment+ * claimed the `v` form was three times slower: that was a per-page timing+ * moving for an unrelated reason, and it would have sent the next person+ * optimising the wrong line.+ */+const UNSPACED = '[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}]'+const WORD_CLASS = '[\\p{L}\\p{N}_]'+const LEAD = `(?:(?<!${WORD_CLASS})|(?<=${UNSPACED}))`+const TAIL = `(?:(?!${WORD_CLASS})|(?=${UNSPACED}))`++/**+ * One alternative for `name`, with a boundary on each side that needs one.+ *+ * The side is decided by the NAME's own edge character: an edge that is not a+ * spacing-script word character (a bracket, a symbol, a Han character) needs no+ * boundary, because there is nothing there to be glued to.+ */+function alternative(name: string): string {+ const chars = [...name]+ const first = chars[0] ?? ''+ const lastCh = chars[chars.length - 1] ?? ''+ const lead = WORDY.test(first) && !CJK.test(first) ? LEAD : ''+ const tail = WORDY.test(lastCh) && !CJK.test(lastCh) ? TAIL : ''+ return lead + escapeRe(name) + tail+}++/** Names per compiled RegExp. Alternation is fast; an unbounded one is not. */+const NAMES_PER_RE = 256++/**+ * Compile names into as few case-insensitive Unicode regexes as possible.+ *+ * LONGEST FIRST: alternation in JS is first-match-wins, so with "New" before+ * "New York" every mention of the city would be reported as a mention of+ * "New". Sorting by code-point length fixes that for every pair at once.+ */+export function compileNames(names: string[]): RegExp[] {+ const usable = names.filter(scannable)+ usable.sort((a, b) => [...b].length - [...a].length)+ const out: RegExp[] = []+ for (let i = 0; i < usable.length; i += NAMES_PER_RE) {+ const part = usable.slice(i, i + NAMES_PER_RE).map(alternative).join('|')+ // `u` for the script escapes, `i` because "the roadmap" mentions "Roadmap",+ // `g` to walk every occurrence in a block.+ out.push(new RegExp(part, 'giu'))+ }+ return out+}++export interface Mention {+ /** the page the name belongs to */+ pageId: string+ /** the page the name was found in */+ fromPage: string+ fromBlock: string+ /** the text exactly as written where it was found, not the name as declared */+ matched: string+ /** offsets into the block's html, for `linkMention` */+ htmlStart: number+ htmlEnd: number+ /** a readable line of context, the match included */+ snippet: string+}++/** Block types whose content is literal and must never be scanned. */+const CODE_TYPES = new Set(['code', 'katex', 'math', 'mermaid', 'embed'])++const SNIPPET_PAD = 60++/**+ * How many names still make a substring pre-filter cheaper than the regex.+ *+ * `String.prototype.includes` is a tuned substring search and a compiled+ * alternation with two lookarounds per branch is not, so for a handful of+ * names it is far cheaper to ask "could this block possibly match" first and+ * skip the regex on the overwhelming majority that cannot. Past a few names+ * the probes cost more than they save, and the all-pairs path (hundreds of+ * names) must not pay them at all.+ */+const MAX_PROBES = 8++/**+ * Every mention of the compiled names in the document, skipping `skipPages`.+ *+ * `owner` maps the text that matched back to the page that owns the name, so+ * the per-page and all-pairs callers share one scanner and one reading of+ * rules 4 and 5 — neither of them re-parses hrefs or re-decides what counts.+ */+function scanDoc(+ doc: SpacesDoc,+ res: RegExp[],+ owner: (matched: string) => string | undefined,+ skipPages: Set<string>,+ limit: number,+ probes: string[] = [],+): Mention[] {+ const out: Mention[] = []+ const pages = Array.isArray(doc.pages) ? doc.pages : []+ const probe = probes.length && probes.length <= MAX_PROBES ? probes : null+ for (const p of pages) {+ if (!p || typeof p.id !== 'string') continue+ if (skipPages.has(p.id)) continue+ const blocks = Array.isArray(p.blocks) ? p.blocks : []+ for (const b of blocks) {+ if (!b || typeof b.id !== 'string') continue+ if (typeof b.type === 'string' && CODE_TYPES.has(b.type)) continue+ const html = typeof b.html === 'string' ? b.html : ''+ if (!html) continue+ const { text, runs } = scanRuns(html)+ if (!text) continue+ // The pre-filter may only ever say "definitely not here", so it runs on+ // the SAME decoded text the regex will see. Probing the raw html instead+ // is faster and wrong: `R&D Team` is written `R&D Team`, so the probe+ // misses it and the mention silently disappears — which is how this was+ // found. What it skips is the alternation, not the decode; a hit that+ // turns out to be inside a code span is still rejected properly below.+ if (probe) {+ const lc = text.toLowerCase()+ let maybe = false+ for (const q of probe) if (lc.includes(q)) { maybe = true; break }+ if (!maybe) continue+ }+ for (const re of res) {+ re.lastIndex = 0+ let m: RegExpExecArray | null+ while ((m = re.exec(text))) {+ if (m[0] === '') { re.lastIndex++; continue }+ const target = owner(m[0])+ // `p.id !== target` is rule 4's last clause and it is DELIBERATELY+ // redundant with `skipPages` on the per-page path: skipPages is the+ // fast path (the page is never scanned), this is the one that holds+ // for the all-pairs path, where every page is scanned for every+ // name. Removing either alone changes nothing, which is worth+ // knowing before someone deletes one as dead code.+ //+ // Rule 5: the block already links there, so it is not "unlinked".+ if (target && p.id !== target && !html.includes(`#p/${target}`)) {+ const s = m.index+ const e = s + m[0].length+ const from = Math.max(0, s - SNIPPET_PAD)+ const to = Math.min(text.length, e + SNIPPET_PAD)+ out.push({+ pageId: target,+ fromPage: p.id,+ fromBlock: b.id,+ matched: m[0],+ htmlStart: htmlOffset(runs, s, false),+ htmlEnd: htmlOffset(runs, e, true),+ snippet: (from > 0 ? '…' : '') ++ text.slice(from, to).replace(SEP_RE, ' ').replace(/\s+/g, ' ').trim() ++ (to < text.length ? '…' : ''),+ })+ if (out.length >= limit) return out+ }+ }+ }+ }+ }+ return out+}++/** How many mentions one page's panel will ever show. */+export const MENTION_LIMIT = 200++/**+ * Unlinked mentions of ONE page — the path the reader's panel takes.+ *+ * One regex built from one page's names, one pass over the document. Cost is+ * O(total text) and does NOT grow with the number of pages, which is why+ * opening a page in a 2000-page space costs what it costs in a 20-page one.+ */+export function mentionsOf(doc: SpacesDoc, index: SpaceIndex, pageId: string): Mention[] {+ const page = index.page.get(pageId)+ if (!page) return []+ const names = namesOf(page).filter(scannable)+ if (!names.length) return []+ const res = compileNames(names)+ if (!res.length) return []+ // Rule 4's last clause: never the page's own text.+ return scanDoc(doc, res, () => pageId, new Set([pageId]), MENTION_LIMIT,+ names.map((n) => n.toLowerCase()))+}++/**+ * Every unlinked mention in the document, grouped by mentioned page.+ *+ * The agent/measurement path. Not used by the panel — see the header — but the+ * one call that answers "what is this space not linking".+ */+export function mentionIndex(doc: SpacesDoc, limit = 5000): Map<string, Mention[]> {+ const pages = Array.isArray(doc.pages) ? doc.pages : []+ const owner = new Map<string, string>()+ const all: string[] = []+ for (const p of pages) {+ if (!p || typeof p.id !== 'string') continue+ for (const n of namesOf(p)) {+ if (!scannable(n)) continue+ const k = nameKey(n)+ // first claimant wins, exactly as nameIndex resolves it+ if (!owner.has(k)) { owner.set(k, p.id); all.push(n) }+ }+ }+ const res = compileNames(all)+ const found = scanDoc(doc, res, (matched) => owner.get(nameKey(matched)), new Set(), limit)+ const byPage = new Map<string, Mention[]>()+ for (const m of found) {+ const list = byPage.get(m.pageId)+ if (list) list.push(m)+ else byPage.set(m.pageId, [m])+ }+ return byPage+}++/**+ * The block html with one mention turned into a real link.+ *+ * Returns null when the offsets no longer describe the html they were computed+ * from — the document may have been edited since the panel was painted, and+ * splicing a link into a moved offset would corrupt the block. The caller+ * re-derives and tries again rather than writing anything.+ */+export function linkMention(html: string, m: Mention, targetId: string): string | null {+ const src = String(html ?? '')+ if (m.htmlStart < 0 || m.htmlEnd > src.length || m.htmlStart >= m.htmlEnd) return null+ const inner = src.slice(m.htmlStart, m.htmlEnd)+ // the bytes must still be the text that matched, entities and all+ if (scanRuns(inner).text !== m.matched) return null+ const href = String(targetId).replace(/[^A-Za-z0-9_-]/g, '')+ if (!href) return null+ return src.slice(0, m.htmlStart) + `<a href="#p/${href}">` + inner + '</a>' + src.slice(m.htmlEnd)+}diff --git a/spaces/src/model.ts b/spaces/src/model.tsindex 4c30a32f..a53a3a13 100644--- a/spaces/src/model.ts+++ b/spaces/src/model.ts@@ -311,6 +311,29 @@ export interface Page {* falls back to the measure rather than to nothing.*/width?: 'wide' | 'full'+ /**+ * Other names this page answers to — `[[NYC]]` and `[[New York]]` reaching+ * the same page.+ *+ * A LINK-TIME notion, deliberately. An alias is resolved where a name+ * becomes a page id (src/mentions.ts `nameIndex`, read by the `[[…]]`+ * resolver, ⌘K and the page picker), so the link that gets written is an+ * ordinary `#p/<id>` href and the backlink index, the graph, export and+ * collaboration never learn that aliases exist. Nothing downstream has a+ * second way to name a page.+ *+ * Additive: absent on every page written before this, and an ABSENT key is+ * the default — clearing the last alias deletes the field rather than+ * storing `[]`, so a page that never had one is byte-identical to a page+ * that had one and lost it. A build that predates this round-trips the+ * array untouched and simply does not resolve by it.+ *+ * Two pages may claim the same alias; nothing here prevents it, because a+ * file arrives already written. `nameIndex` resolves it deterministically+ * (titles before aliases, then document order) and validate() reports it —+ * see `alias-collision` in agent.ts.+ */+ aliases?: string[]/** the one page daily entries hang from, so the sidebar stays a tree */journalHome?: boolean/** out of the sidebar, still searchable and linkable, and ENUMERATED atdiff --git a/spaces/src/props.ts b/spaces/src/props.tsindex 10822a56..7f01c582 100644--- a/spaces/src/props.ts+++ b/spaces/src/props.ts@@ -28,6 +28,7 @@ import { tableOf, TABLE_MAX_COLS, TABLE_MAX_ROWS } from './model'import { CALLOUT_TONES, SPEC } from './blocks'import { toneLabel } from './render'import { CODE_LANGS, normLang } from './highlight'+import { aliasesOf } from './mentions.ts'import { t } from './i18n'/**@@ -351,6 +352,45 @@ export class PropsPanel {this.app.repaint()}))+ // OTHER NAMES THIS PAGE ANSWERS TO — one comma-separated field, because+ // that is how it reads back ("New York, NYC, the Big Apple") and a+ // list-of-chips editor for a field most pages never use is a lot of+ // surface for nothing.+ //+ // The ABSENT key is the default and clearing the field restores it: a page+ // that had an alias and lost it must be byte-identical to one that never+ // had one, or every space that ever opened this panel grows an `aliases:+ // []` nobody asked for.+ if (!this.app.locked()) {+ const aliases = mk('input', 'sp-insp-text') as HTMLInputElement+ aliases.type = 'text'+ aliases.value = aliasesOf(page).join(', ')+ aliases.placeholder = t('NYC, the Big Apple')+ aliases.title = t('Names that also reach this page from [[links]], search and the page picker')+ // `change`, not `input`: one commit per edit, so this is exactly one ⌘Z.+ aliases.addEventListener('change', () => {+ if (s.readOnly) return+ const next: string[] = []+ const seen = new Set<string>()+ for (const raw of aliases.value.split(',')) {+ const n = raw.trim()+ if (!n || seen.has(n.toLowerCase())) continue+ seen.add(n.toLowerCase())+ next.push(n)+ }+ s.commit(() => {+ const p = s.index.page.get(page.id)+ if (!p) return+ if (next.length) p.aliases = next+ else delete p.aliases+ }, { scope: 'doc' })+ this.app.repaint()+ })+ this.row(t('Also known as'), aliases)+ } else if (aliasesOf(page).length) {+ this.row(t('Also known as'), mk('span', 'sp-insp-val', aliasesOf(page).join(', ')))+ }+if (typeof page.journal === 'string') {this.row(t('Journal date'), mk('span', 'sp-mono', page.journal))}diff --git a/spaces/src/styles.css b/spaces/src/styles.cssindex 3f4d2823..4705f6f2 100644--- a/spaces/src/styles.css+++ b/spaces/src/styles.css@@ -887,6 +887,19 @@ button.sp-callout-chip:hover { text-decoration: underline; text-underline-offset.sp-backlink-list a:hover { text-decoration: underline; }.sp-snippet { color: var(--muted); margin-inline-start: 8px; }+/* Unlinked mentions: the same list as the backlinks, one step quieter, with+ the Link button only visible on hover/focus so a page with thirty of them+ is not thirty buttons shouting. Focus-within keeps it reachable by keyboard,+ where hover does not exist at all. */+.sp-mentions { padding-top: 16px; margin-top: 22px; }+.sp-mentions:empty { display: none; }+.sp-mentions .sp-backlink-list li { display: flex; align-items: baseline; gap: 6px; }+.sp-mentions .sp-snippet { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.sp-mention-link { flex: none; padding: 1px 8px; font-size: 12px; opacity: 0; transition: opacity 0.12s; }+.sp-mentions li:hover .sp-mention-link,+.sp-mentions li:focus-within .sp-mention-link { opacity: 1; }+@media (hover: none) { .sp-mention-link { opacity: 1; } }+/* ————— dialogs: the kernel's (kernel/src/ui/dialog.css) —————Every modal is `createDialog`. Its look comes through `--bkd-*`, set on theroot because the scrim is mounted on <body>, outside `.sp-app`. The heading@@ -1416,7 +1429,8 @@ button.sp-callout-chip:hover { text-decoration: underline; text-underline-offsetbody.sp-printing .sp-printroot { display: block; }.sp-printroot .sp-page { break-after: page; }.sp-printroot .sp-page:last-child { break-after: auto; }- .sp-printroot .sp-pageicon, .sp-printroot .sp-backlinks { display: none; }+ .sp-printroot .sp-pageicon, .sp-printroot .sp-backlinks,+ .sp-printroot .sp-mentions { display: none; }@page { margin: 18mm 16mm; }}