Core without documents: no slugs; a node's top; targets by titles from the library root

The model has no slug any more (field, ops, canonical row, slugFor, freeSlug, RESERVED,
findDoc). The child of the root a node is under is a derived relation, topOf (docOf and
documents stay as deprecated aliases for the UI until step 2); ancestorsInDoc becomes
ancestorsBelowRoot. Slug keys and a target's old `doc` in stored libraries are ignored.

A node target's path is the titles down from the library root; `rel` marks a path read
below a top (a file being imported, what the agent or a person typed). Where two sections
share a title, the one the link is written in wins. The text format writes /Top title/…,
and ./… inside the exported subtree. The agent may give a node id as a target.

renderContext renders the top's outline in an <outline> tag, and steps down the focus
path when even titles are over budget. Prompts, the reviewer and the scanner speak of
the library, trees and tops; the scanner's unit is the top, with the same behaviour
(scripts/linkEval.ts gives identical metrics).

src/core/library.ts keeps a slug-free shim for the UI's document features (names made
from titles) until step 2 removes them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
thalladaandClaude Opus 5.5 committed 2026-11-16 23:32:08 -05:00
1 parent 626dc19e1b
commit 44d2e437eb
32 files changed
+634 -577

No files matched your search

+7 -7
View File
@@ -1,12 +1,12 @@
/**
* The library's sections as vectors, for "closely matching nodes across documents": a VectorIndex
* The library's sections as vectors, for "closely matching nodes under other tops": a VectorIndex
* (server/embed.ts) of each section's title and text, kept current from the snapshot's patches.
* A patch only marks the nodes it touched; they are re-embedded later, a batch at a time, off the
* request that made the edit (a section whose text is unchanged is skipped by its hash). Without a
* model the index still holds the texts, so BM25 search works and "related" is text-only.
*/
import { inArticles } from "../../src/core/article";
import { Doc, docOf, isLibraryRoot, type NodeId, type Snap } from "../../src/core/model";
import { Doc, isLibraryRoot, topOf, type NodeId, type Snap } from "../../src/core/model";
import { plain } from "../../src/core/text";
import { VectorIndex, type Embedder, type Hit, type HybridHit } from "../embed";
@@ -16,7 +16,7 @@ const nodeText = (snap: Snap, id: NodeId) => {
return `${n.title}\n${plain(n.body)}`.trim();
};
/** Sections (and documents) worth indexing: not the library root, not notes, not the Wikipedia container's, and with some text. */
/** Sections (the root's children too) worth indexing: not the library root, not notes, not the Wikipedia container's, and with some text. */
const indexable = (snap: Snap, id: NodeId) => {
const n = snap.nodes[id];
return !!n && n.kind === "section" && !isLibraryRoot(snap, id) && !inArticles(snap, id) && (n.body.trim().length > 0 || n.title.trim().length > 0);
@@ -102,14 +102,14 @@ export class NodeIndex {
}
/**
* Sections close in meaning to a text, from other documents, best first. Excludes the node, its
* ancestors and its descendants. Null if there is no model.
* Sections close in meaning to a text, from under other tops than `top`, best first. Excludes the
* node, its ancestors and its descendants. Null if there is no model.
*/
async near(text: string, o: { exclude: Set<NodeId>; doc: NodeId | null; k?: number; snap: Snap; vector?: Float32Array | null }): Promise<Hit[] | null> {
async near(text: string, o: { exclude: Set<NodeId>; top: NodeId | null; k?: number; snap: Snap; vector?: Float32Array | null }): Promise<Hit[] | null> {
const k = o.k ?? 8;
// Never built (a first start): build it now rather than answer from nothing.
if (!this.vectors.size && (this.all || this.running)) await this.refresh();
const filter = (id: string) => !o.exclude.has(id as NodeId) && !!o.snap.nodes[id as NodeId] && docOf(o.snap, id as NodeId) !== o.doc;
const filter = (id: string) => !o.exclude.has(id as NodeId) && !!o.snap.nodes[id as NodeId] && topOf(o.snap, id as NodeId) !== o.top;
if (o.vector) return this.vectors.searchVector(o.vector, k, filter);
const v = await this.vectors.vector(text);
return v ? this.vectors.searchVector(v, k, filter) : null;
+24 -25
View File
@@ -3,7 +3,7 @@
* Wikipedia editor would, and its verdicts (link or not, with a one-line reason) are kept in the
* pending store. It is given no tools: each call is one structured reply of verdicts.
*
* Cost. Proposals are reviewed many to a call (BATCH), grouped by document and section, each with
* Cost. Proposals are reviewed many to a call (BATCH), grouped by top and section, each with
* just what it takes to judge it: its sentence, the section's title and path, the target's title,
* description and (when the cache has it) first sentence, and, for a library target, how it stands
* to the section. Anything judged before is never sent again. Each caller gives a budget of calls;
@@ -12,7 +12,7 @@
* model, as it does when the model writes.
*/
import { ownerSection } from "../../src/core/links";
import { ancestors, docOf, documents, label, notesOf, sections, type NodeId, type Snap } from "../../src/core/model";
import { ancestors, label, notesOf, sections, topOf, tops, type NodeId, type Snap } from "../../src/core/model";
import type { Ref } from "../../src/core/ref";
import { clip, plain, sentences } from "../../src/core/text";
import type { LinkVerdicts, LLM } from "../../src/llm/types";
@@ -44,16 +44,16 @@ export interface ReviewReport {
fallback?: string;
}
export const REVIEW_SYSTEM = `You review proposed links in a personal library of documents. A scanner has proposed linking phrases in the text to Wikipedia articles or to other sections of the library. Decide, for each proposal, whether a reader of this document would be glad of the link, as a careful Wikipedia editor applying the Manual of Style on linking would. A link is worth making only when it helps; when unsure, do not link. Expect to reject most proposals.
export const REVIEW_SYSTEM = `You review proposed links in a personal library of text, kept as one tree of sections. A scanner has proposed linking phrases in the text to Wikipedia articles or to other sections of the library. Decide, for each proposal, whether a reader of this text would be glad of the link, as a careful Wikipedia editor applying the Manual of Style on linking would. A link is worth making only when it helps; when unsure, do not link. Expect to reject most proposals.
Reject a proposal when:
- the phrase is an everyday word, or a thing so famous that every reader knows it (a country, a major city, a common animal or material, an ordinary idea such as energy, water or the brain, a household name mentioned in passing);
- the target is a different sense of the phrase than the text means, or a different person, place or thing with the same name;
- the phrase is a fragment of a longer name or term in the text (a surname out of a full name, one word of a technical term), or the target is about the fragment alone;
- the same thing is already linked in this section, or earlier in the document (listed as "Already linked"), or by another proposal before it in this list: link a thing once, at its first mention that matters;
- the same thing is already linked in this section, or earlier in the same tree (listed as "Already linked"), or by another proposal before it in this list: link a thing once, at its first mention that matters;
- a library target is this section's own subsection, parent or sibling (its relation is given): the outline already joins them;
- a library target matches the phrase only by its title, and the text does not mean what that section is about;
- the phrase is inside a verbatim quotation of the request or prompt the document was written from (instructions addressed to an assistant): such text stays as it was written;
- the phrase is inside a verbatim quotation of the request or prompt the text was written from (instructions addressed to an assistant): such text stays as it was written;
- the target is a list, a disambiguation page, a name page, or an article about a film, album, band, company or other namesake.
Approve a proposal when the phrase names a specific concept, result, work, person, organism, place or event that the text means and that a curious reader may well want to look up: a technical term, a named theorem or process, a figure the passage discusses, or a library section elsewhere that treats the phrase's own subject in more depth.
@@ -68,7 +68,7 @@ The scanner's tier ("sure" or "unsure") is a weak hint only. Give a verdict for
export function describe(snap: Snap, s: Suggestion, given?: Given) {
const n = snap.nodes[s.node];
const body = given?.node === s.node && given.text !== undefined ? given.text : (n?.body ?? "");
const d = n ? docOf(snap, s.node) : (given?.doc ?? null);
const d = n ? topOf(snap, s.node) : (given?.top ?? null);
const sent = sentences(body).find(([a, b]) => s.range[0] >= a && s.range[0] < b) ?? [0, body.length];
const path: string[] = [];
for (let x: NodeId | null = s.node; x && x !== d && snap.nodes[x]; x = snap.nodes[x].parent) path.unshift(label(snap, x));
@@ -76,8 +76,7 @@ export function describe(snap: Snap, s: Suggestion, given?: Given) {
return {
...s,
nodeTitle: n ? label(snap, s.node) : given?.title || "a new section",
document: d ? snap.nodes[d].title : null,
docSlug: d ? snap.nodes[d].slug ?? null : null,
top: d ? snap.nodes[d].title : null,
path: path.join(" › "),
sentence: clip(plain(body.slice(sent[0], sent[1])).trim(), 400),
};
@@ -88,7 +87,7 @@ export interface Given {
node: NodeId;
text?: string;
title?: string;
doc?: NodeId | null;
top?: NodeId | null;
}
/** How a library target stands to the section a phrase is in. */
@@ -101,9 +100,9 @@ function relation(snap: Snap, from: NodeId, target: NodeId): string {
if (snap.nodes[sec]?.parent === target) return "this section's parent";
if (ancestors(snap, sec).includes(target)) return "an ancestor of this section";
if (t.parent && t.parent === snap.nodes[sec]?.parent) return "a sibling of this section";
const d = docOf(snap, target);
if (d && d === docOf(snap, sec)) return "elsewhere in this document";
return d ? `in another document, “${snap.nodes[d].title}”` : "elsewhere in the library";
const d = topOf(snap, target);
if (d && d === topOf(snap, sec)) return "elsewhere in this tree";
return d ? `in another tree, “${snap.nodes[d].title}”` : "elsewhere in the library";
}
const firstSentence = (text: string) => {
@@ -121,14 +120,14 @@ const linkedTitles = (snap: Snap, id: NodeId): string[] =>
const targetTitle = (snap: Snap, r: Ref) => (r.kind === "wiki" ? r.title : r.kind === "url" ? (r.title ?? r.url) : r.id && snap.nodes[r.id] ? label(snap, r.id) : (r.path ?? []).join(" › ") || "a note");
/** Everything already linked in a document, in reading order, each title once. */
function linkedInDoc(snap: Snap, doc: NodeId): string[] {
/** Everything already linked under a top, in reading order, each title once. */
function linkedInTop(snap: Snap, top: NodeId): string[] {
const out = new Set<string>();
const visit = (id: NodeId) => {
for (const t of linkedTitles(snap, id)) out.add(t);
for (const c of sections(snap, id)) visit(c);
};
visit(doc);
visit(top);
return [...out];
}
@@ -156,11 +155,11 @@ export class Reviewer {
if (!list.length) return report;
const llm = this.o.llm();
if (!llm) return { ...report, fallback: "no model is configured" };
// By document, then in reading order, so a call sees a document's proposals together.
// By top, then in reading order, so a call sees a tree's proposals together.
const snap = this.o.snap();
const order = new Map<NodeId, number>();
let i = 0;
for (const d of documents(snap)) for (const id of [d, ...descendantsInOrder(snap, d)]) order.set(id, i++);
for (const d of tops(snap)) for (const id of [d, ...descendantsInOrder(snap, d)]) order.set(id, i++);
const sorted = [...list].sort((a, b) => (order.get(a.node) ?? 1e9) - (order.get(b.node) ?? 1e9) || a.range[0] - b.range[0]);
for (let at = 0; at < sorted.length; at += BATCH) {
if (budget.calls >= budget.max) return { ...report, fallback: `the reviewer's limit of ${budget.max} model call${budget.max === 1 ? "" : "s"} was reached` };
@@ -190,25 +189,25 @@ export class Reviewer {
return report;
}
/** The call for one batch: the document and section headings, and a line per proposal. */
/** The call for one batch: the top and section headings, and a line per proposal. */
private async request(batch: Suggestion[], given?: Given) {
const snap = this.o.snap();
const wiki = this.o.wiki();
const ids = new Map<string, Suggestion>();
const lines: string[] = [];
const proposals: { id: string; tier: string; quote: string; sentence: string }[] = [];
let doc: NodeId | null | undefined;
let top: NodeId | null | undefined;
let node: NodeId | undefined;
for (const [k, s] of batch.entries()) {
const id = `p${k + 1}`;
ids.set(id, s);
const where = describe(snap, s, given);
const d = snap.nodes[s.node] ? docOf(snap, s.node) : (given?.doc ?? null);
if (d !== doc) {
doc = d;
const d = snap.nodes[s.node] ? topOf(snap, s.node) : (given?.top ?? null);
if (d !== top) {
top = d;
node = undefined;
const already = d ? linkedInDoc(snap, d) : [];
lines.push("", `# Document: ${d ? snap.nodes[d].title : "(none)"}`, `Already linked in this document: ${already.length ? already.slice(0, 60).join("; ") : "nothing"}`);
const already = d ? linkedInTop(snap, d) : [];
lines.push("", `# Tree: ${d ? snap.nodes[d].title : "(none)"}`, `Already linked in this tree: ${already.length ? already.slice(0, 60).join("; ") : "nothing"}`);
}
if (s.node !== node) {
node = s.node;
@@ -230,7 +229,7 @@ export class Reviewer {
const prompt = `Proposals (${batch.length}):\n${lines.join("\n").trim()}\n\nGive a verdict for each of the ${batch.length} proposals.`;
return {
ids,
json: { task: "review-links", schema: "review" as const, system: REVIEW_SYSTEM, context: "Proposed links, grouped by document and section.", prompt, vars: { proposals: JSON.stringify(proposals) }, effort: "low" as const, maxTokens: 8000 },
json: { task: "review-links", schema: "review" as const, system: REVIEW_SYSTEM, context: "Proposed links, grouped by tree and section.", prompt, vars: { proposals: JSON.stringify(proposals) }, effort: "low" as const, maxTokens: 8000 },
};
}
}
+14 -16
View File
@@ -1,23 +1,23 @@
/**
* HTTP routes for link discovery. Wired into server/index.ts before the 404.
*
* POST /api/links/scan { node, text?, title?, doc?, docTitle?, ancestors?, occupied?, rejected?, forced?, within?, save?, review? }
* POST /api/links/scan { node, text?, title?, top?, topTitle?, ancestors?, occupied?, rejected?, forced?, within?, save?, review? }
* → { suggestions, related, unresolved, degraded, stats, entries?, apply?, review? }; save (default
* true) records the suggestions as pending for the node, and `entries` is then everything
* stored for it, with determinations. review ("all", or "unmarked" to leave out [[marks]],
* which a person typed) has the model reviewer judge what is undecided; `apply` is then the
* approved links handed to the caller to make, and `review` the reviewer's report
* GET /api/links/pending ?doc=<slug|id>&node=<id>&tier=auto|suggest&limit=&offset=&all=1&claim=1
* → { total, suggestions: [{ …, nodeTitle, document, docSlug, path, sentence }], apply? };
* GET /api/links/pending ?doc=<top's id or name>&node=<id>&tier=auto|suggest&limit=&offset=&all=1&claim=1
* → { total, suggestions: [{ …, nodeTitle, top, path, sentence }], apply? };
* all=1 lists every entry whatever was decided, with its determinations; claim=1 hands
* out the approved links no page has made yet (in `apply`), to be made by the caller
* POST /api/links/accept { ids, author? } → applied with applyLinks as one commit by "linker"
* POST /api/links/reject { ids, author? } → the phrases recorded in each node's `nolink` (one commit)
* POST /api/links/decide { ids, link, by } → a person's decision, made in their own replica, recorded
* GET /api/links/related ?node=<id> → { related, degraded }; or POST { node, text, title, doc, docTitle, ancestors }
* GET /api/links/nearby ?node=<id>&k=5 → { nearby: [{ handle, title, document }] } (hybrid search on the node);
* GET /api/links/related ?node=<id> → { related, degraded }; or POST { node, text, title, top, topTitle, ancestors }
* GET /api/links/nearby ?node=<id>&k=5 → { nearby: [{ handle, title, top }] } (hybrid search on the node);
* or POST { node, text, title, ancestors }
* POST /api/links/jobs { scope: "doc" | "library", doc?, review? } → the job's state; it runs in the background
* POST /api/links/jobs { scope: "doc" | "library", doc?, review? } → the job's state (doc: a top's id or name); it runs in the background
* (with review, the model reviewer judges what it finds, within IE_REVIEW_CALLS calls)
* GET /api/links/jobs → { job } (the current or last one)
* DELETE /api/links/jobs → cancel the running job
@@ -27,7 +27,8 @@
*/
import type { IncomingMessage, ServerResponse } from "node:http";
import { applyLinks, type LinkSpec } from "../../src/core/links";
import { descendants, docOf, documents, findDoc, isLibraryRoot, type Doc, type NodeId, type Op, type Snap } from "../../src/core/model";
import { findTop } from "../../src/core/library";
import { descendants, isLibraryRoot, tops, type Doc, type NodeId, type Op, type Snap } from "../../src/core/model";
import type { Embedder } from "../embed";
import { HttpError, abortOnClose, readJson as readBody, sendJson as send } from "../util";
import type { Jobs } from "./jobs";
@@ -56,15 +57,12 @@ class Bad extends HttpError {
const readJson = <T>(req: IncomingMessage) => readBody<T>(req, 4 * 1024 * 1024);
/** A document by slug or node id. */
function docArg(snap: Snap, v: string | null): NodeId | null {
if (!v) return null;
return findDoc(snap, v) ?? (snap.nodes[v as NodeId] && docOf(snap, v as NodeId) === v ? (v as NodeId) : null);
}
/** A child of the root by its node id or name (TEMPORARY: step 2 scopes by any node). */
const docArg = (snap: Snap, v: string | null): NodeId | null => (v ? (findTop(snap, v) ?? null) : null);
/** The nodes of a document (or of the library), in reading order: sections and notes with text. */
/** The nodes of a top's tree (or of the library), in reading order: sections and notes with text. */
export function scopeNodes(snap: Snap, doc: NodeId | null): NodeId[] {
const roots = doc ? [doc] : documents(snap);
const roots = doc ? [doc] : tops(snap);
const out: NodeId[] = [];
for (const r of roots) for (const id of [r, ...descendants(snap, r)]) if (snap.nodes[id].body.trim() && !isLibraryRoot(snap, id)) out.push(id);
return out;
@@ -96,7 +94,7 @@ export function linkRoutes(deps: LinkDeps) {
const found = new Set(r.suggestions.map((s) => s.id));
const mine = deps.pending.of(input.node).filter((s) => found.has(s.id));
const todo = mine.filter((s) => !s.review && !s.decided && (input.review === "all" || s.kind !== "forced"));
const report = deps.reviewer ? await deps.reviewer.review(todo, { calls: 0, max: SCAN_CALLS }, signal, { node: input.node, text: input.text, title: input.title, doc: input.doc }) : { approved: 0, rejected: 0, calls: 0, left: todo.length, fallback: "no reviewer" };
const report = deps.reviewer ? await deps.reviewer.review(todo, { calls: 0, max: SCAN_CALLS }, signal, { node: input.node, text: input.text, title: input.title, top: input.top }) : { approved: 0, rejected: 0, calls: 0, left: todo.length, fallback: "no reviewer" };
const apply = deps.pending.handOut(mine);
return send(res, 200, { ...r, entries: deps.pending.of(input.node), apply, review: report }), true;
}
@@ -146,7 +144,7 @@ export function linkRoutes(deps: LinkDeps) {
return send(res, 200, { decided: deps.pending.decide(input.ids as string[], input.link, by) }), true;
}
if (route === "related" && (method === "GET" || method === "POST")) {
// GET ?node=<id> for a node the server has; POST { node, text, title, doc, docTitle, ancestors } for one it may not have yet.
// GET ?node=<id> for a node the server has; POST { node, text, title, top, topTitle, ancestors } for one it may not have yet.
const input = method === "POST" ? await readJson<ScanInput>(req) : { node: url.searchParams.get("node") as NodeId };
if (!input.node || (!snap.nodes[input.node] && typeof input.text !== "string")) throw new Bad("give an existing node, or its text");
const r = await deps.linker().related(input.node, 5, input);
+73 -64
View File
@@ -4,8 +4,8 @@
*
* forced a [[mark]] the writer typed: verified, then linked (or reported as not found)
* library a phrase that is another section's title (normalised), never the node itself or
* an ancestor, other documents preferred
* meaning a section of another document close in meaning to this node, when a phrase here
* an ancestor, other tops' trees preferred
* meaning a section under another top close in meaning to this node, when a phrase here
* names it; when nothing here names it, it is only listed as Related (never forced
* onto arbitrary words)
* wikipedia a batched lookup of the candidates; disambiguation pages resolved by embedding fit
@@ -16,9 +16,12 @@
* is dropped. Then Wikipedia's own manners: first mention only, a few links a paragraph, the
* strongest kept. See judge() for the rule. Only phrases and search queries go to Wikipedia;
* embeddings are local.
*
* "The same text" here means the tree under one top (a child of the library root, `topOf`): the
* rule was tuned with that as the unit, for centrality, first mention and "meaning from elsewhere".
*/
import { inArticles } from "../../src/core/article";
import { docOf, notesOf, sections, ancestors as ancestorsOf, descendants, type Doc, type NodeId, type Snap } from "../../src/core/model";
import { notesOf, sections, topOf, ancestors as ancestorsOf, descendants, type Doc, type NodeId, type Snap } from "../../src/core/model";
import { nodeRef, targetKey } from "../../src/core/links";
import type { Mark } from "../../src/core/marks";
import type { Nearby } from "../../src/llm/prompts";
@@ -77,7 +80,8 @@ export interface Decision {
export interface Related {
node: NodeId;
title: string;
doc: string;
/** Where it is: the title of the top it is under. */
top: string;
score: number;
why: string;
}
@@ -87,8 +91,9 @@ export interface ScanInput {
/** The node's text; by default the server's copy. A browser sends its own, which may be newer. */
text?: string;
title?: string;
doc?: NodeId | null;
docTitle?: string;
/** The top the node is under, and its title (a page sends them for a node the server may not have yet). */
top?: NodeId | null;
topTitle?: string;
ancestors?: NodeId[];
/** Spans already under a note: [start, end, linked]. */
occupied?: [number, number, boolean][];
@@ -118,7 +123,7 @@ export interface TraceRow {
chosen: boolean;
why: string;
/** What judge() saw. */
features: { words: number; rarity: number; exact: boolean; redirect: boolean; sense: boolean; margin: number | null; searched: boolean; central: boolean; firstInDoc: boolean; sentenceStart: boolean };
features: { words: number; rarity: number; exact: boolean; redirect: boolean; sense: boolean; margin: number | null; searched: boolean; central: boolean; firstInTop: boolean; sentenceStart: boolean };
}
export interface ScanResult {
@@ -203,14 +208,14 @@ interface Hit {
/** Found by title search, not by lookup. */
searched: boolean;
central: boolean;
firstInDoc: boolean;
/** A library target in the same document as the node. */
sameDoc?: boolean;
firstInTop: boolean;
/** A library target under the same top as the node. */
sameTop?: boolean;
}
/** A hit with the defaults most sources share: an exact title, no description or fit yet, nothing special about it. */
const hitOf = (c: Candidate, target: Ref, source: Source, title: string, more: Partial<Hit> = {}): Hit => ({
c, target, source, title, description: null, fit: null, exact: true, redirect: false, sense: false, searched: false, central: false, firstInDoc: true, ...more,
c, target, source, title, description: null, fit: null, exact: true, redirect: false, sense: false, searched: false, central: false, firstInTop: true, ...more,
});
const keyWords = (key: string) => key.split(" ").filter(Boolean).length;
@@ -235,12 +240,12 @@ const NOT_A_CONCEPT = /^(surname|given name|family name|index of|list of|topics
* ("Old World", "Sun"), from fit 0.55; never a country, a surname page or a list
* noun (one lower-case word) only if rare (rank ≥ 8,000); auto only when very rare (≥ 15,000),
* the exact title, and fit ≥ 0.70
* library a section title: in the same document from fit 0.72 (auto) or 0.64 (suggest); in
* another document only a multi-word or uncommon title, and never auto below 0.72
* library a section title: under the same top from fit 0.72 (auto) or 0.64 (suggest); under
* another top only a multi-word or uncommon title, and never auto below 0.72
*
* Never auto: a disambiguation sense chosen by fit (suggested only for names and terms, with a
* clear margin), a title found by search, a redirect to a differently named page from one word, and
* a concept central to the document (linked once, at its first mention, and only suggested).
* a concept central to the top's tree (linked once, at its first mention, and only suggested).
*/
export function judge(h: Hit, t: Tuning = TUNING): Judgement {
const c = h.c;
@@ -251,28 +256,28 @@ export function judge(h: Hit, t: Tuning = TUNING): Judgement {
const ok = fit === null ? !h.sense : fit >= t.suggest.term - 0.1;
return { score: fit ?? 0.7, tier: ok ? "auto" : null, why: `marked by the writer; ${fit === null ? "found" : f}` };
}
if (h.central && !h.firstInDoc) return { score: 0, tier: null, why: "central to the document: linked once, at its first mention" };
if (h.central && !h.firstInTop) return { score: 0, tier: null, why: "central to the text: linked once, at its first mention" };
const tierBy = (autoOk: boolean, autoAt: number, suggestAt: number): Tier | null => {
// Text only (no embeddings): the strongest are suggested, nothing is applied unasked.
if (fit === null) return autoOk ? "suggest" : null;
// Unasked, a concept is linked once per document, where it is first mentioned; later mentions are only suggested.
if (autoOk && fit >= autoAt && !h.central && h.firstInDoc) return "auto";
// Unasked, a concept is linked once per top's tree, where it is first mentioned; later mentions are only suggested.
if (autoOk && fit >= autoAt && !h.central && h.firstInTop) return "auto";
return fit >= suggestAt ? "suggest" : null;
};
const done = (tier: Tier | null, why: string[]) => ({ score: Math.round((fit ?? 0.6) * 1000) / 1000, tier, why: why.filter(Boolean).join("; ") });
if (h.source === "library") {
const strong = c.words > 1 || c.rarity >= t.nounRank.auto;
if (!h.sameDoc && !strong) return done(null, ["a common word that titles a section elsewhere"]);
if (!h.sameTop && !strong) return done(null, ["a common word that titles a section elsewhere"]);
// A one-word title ("The comma", "Pythagorean") is a heading more often than the concept itself: suggested at most.
const tier = tierBy(keyWords(c.key) > 1, t.auto.library, h.sameDoc ? t.suggest.library : t.auto.library - 0.06);
const tier = tierBy(keyWords(c.key) > 1, t.auto.library, h.sameTop ? t.suggest.library : t.auto.library - 0.06);
return done(h.central && tier ? "suggest" : tier, [`the title of “${h.title}” in this library`, f]);
}
const desc = h.description ?? "";
if (NOT_A_CONCEPT.test(desc)) return done(null, [`“${h.title}” is ${desc.toLowerCase()}`]);
const why = [f];
if (h.central) why.push("central to the document: first mention only");
if (h.central) why.push("central to the text: first mention only");
if (h.sense) {
// A sense chosen by fit: offered for names and terms when it clearly beats the next one.
why.push(`one of the senses of “${c.text}”`);
@@ -338,11 +343,11 @@ function titleIndex(snap: Snap): Map<string, NodeId[]> {
return ix;
}
/** For each document: its sections in reading order, each with its normalised text. */
const docCache = new WeakMap<object, { id: NodeId; text: string }[]>();
function docTexts(snap: Snap, doc: NodeId): { id: NodeId; text: string }[] {
const d = snap.nodes[doc];
let out = docCache.get(d);
/** For each top: the sections of its tree in reading order, each with its normalised text. */
const topCache = new WeakMap<object, { id: NodeId; text: string }[]>();
function topTexts(snap: Snap, top: NodeId): { id: NodeId; text: string }[] {
const d = snap.nodes[top];
let out = topCache.get(d);
if (out) return out;
out = [];
const visit = (id: NodeId) => {
@@ -350,8 +355,8 @@ function docTexts(snap: Snap, doc: NodeId): { id: NodeId; text: string }[] {
out!.push({ id, text: ` ${phraseKey(`${n.title} ${n.body}`)} ` });
for (const c of sections(snap, id)) visit(c);
};
visit(doc);
docCache.set(d, out);
visit(top);
topCache.set(d, out);
return out;
}
@@ -376,8 +381,8 @@ export class Linker {
const n = snap.nodes[input.node];
const text = input.text ?? n?.body ?? "";
const title = input.title ?? n?.title ?? "";
const docId = input.doc !== undefined ? input.doc : n ? docOf(snap, input.node) : null;
const docTitle = input.docTitle ?? (docId && snap.nodes[docId] ? snap.nodes[docId].title : "");
const topId = input.top !== undefined ? input.top : n ? topOf(snap, input.node) : null;
const topTitle = input.topTitle ?? (topId && snap.nodes[topId] ? snap.nodes[topId].title : "");
const ancestors = new Set(input.ancestors ?? (n ? ancestorsOf(snap, input.node) : []));
const occupied = input.occupied ?? (n ? notesOf(snap, input.node).flatMap((c) => snap.nodes[c].anchors.map((a): [number, number, boolean] => [a.start, a.end, !!snap.nodes[c].ref])) : []);
const rejected = new Set(input.rejected ?? n?.nolink ?? []);
@@ -396,16 +401,16 @@ export class Linker {
// Targets already linked in this node: first mention means they are not offered again.
const linkedHere = new Set(n ? notesOf(snap, input.node).map((c) => snap.nodes[c].ref).filter((r): r is Ref => !!r).map(targetKey) : []);
// Centrality: in the document's title, or in many of its sections.
const doc = docId && snap.nodes[docId] ? docTexts(snap, docId) : [];
const docTitleKey = ` ${phraseKey(docTitle)} `;
// Centrality: in the top's title, or in many of its tree's sections.
const tree = topId && snap.nodes[topId] ? topTexts(snap, topId) : [];
const topTitleKey = ` ${phraseKey(topTitle)} `;
const owner = n?.kind === "note" ? [...ancestors].find((a) => snap.nodes[a]?.kind === "section") ?? input.node : input.node;
const centrality = (key: string) => {
const k = ` ${key} `;
const holders = doc.filter((d) => d.text.includes(k));
const central = docTitleKey.includes(k) || (doc.length >= 6 && holders.length >= Math.max(3, doc.length * 0.3));
const firstInDoc = !holders.length || holders[0].id === owner;
return { central, firstInDoc };
const holders = tree.filter((d) => d.text.includes(k));
const central = topTitleKey.includes(k) || (tree.length >= 6 && holders.length >= Math.max(3, tree.length * 0.3));
const firstInTop = !holders.length || holders[0].id === owner;
return { central, firstInTop };
};
const exceptSelf = new Set<NodeId>([input.node, ...ancestors]);
@@ -429,15 +434,15 @@ export class Linker {
if (resolved.has(c)) continue;
const ids = (titles.get(c.key) ?? []).filter((id) => !exceptSelf.has(id) && snap.nodes[id]);
if (!ids.length) continue;
const pick = ids.find((id) => docOf(snap, id) !== docId) ?? ids[0];
const { central, firstInDoc } = centrality(c.key);
const d = docOf(snap, pick);
hits.push(hitOf(c, nodeRef(snap, pick), c.kind === "forced" ? "forced" : "library", `${snap.nodes[pick].title}${d && d !== pick && d !== docId ? ` (${snap.nodes[d].title})` : ""}`, { central, firstInDoc, sameDoc: d === docId }));
const pick = ids.find((id) => topOf(snap, id) !== topId) ?? ids[0];
const { central, firstInTop } = centrality(c.key);
const d = topOf(snap, pick);
hits.push(hitOf(c, nodeRef(snap, pick), c.kind === "forced" ? "forced" : "library", `${snap.nodes[pick].title}${d && d !== pick && d !== topId ? ` (${snap.nodes[d].title})` : ""}`, { central, firstInTop, sameTop: d === topId }));
resolved.add(c);
}
// The text a target must fit: the node in its document.
const context = `${docTitle}. ${title}.\n${plain(text)}`.slice(0, 2000);
// The text a target must fit: the node under its top.
const context = `${topTitle}. ${title}.\n${plain(text)}`.slice(0, 2000);
const ctx = this.o.embedder ? await this.o.embedder.embed([context]) : null;
const ctxVec = ctx?.[0] ?? null;
if (!ctxVec) degraded.push("embeddings unavailable: matched by text only");
@@ -471,8 +476,8 @@ export class Linker {
continue;
}
const key = phraseKey(stripParen(item.title));
const { central, firstInDoc } = centrality(c.key);
hits.push(hitOf(c, { kind: "wiki", title: item.title, lang: wiki.lang }, "wikipedia", item.title, { description: item.description, exact: key === c.key, redirect: item.redirect, central, firstInDoc }));
const { central, firstInTop } = centrality(c.key);
hits.push(hitOf(c, { kind: "wiki", title: item.title, lang: wiki.lang }, "wikipedia", item.title, { description: item.description, exact: key === c.key, redirect: item.redirect, central, firstInTop }));
}
// Disambiguation pages: the most promising few, by the phrase's own worth.
const worth = (c: Candidate) => (c.kind === "forced" ? 3 : c.kind === "name" ? 2 : c.kind === "term" ? 1.5 : c.rarity > 15_000 ? 1 : 0);
@@ -489,10 +494,10 @@ export class Linker {
const scored = await this.fit(ctxVec, r.value.map((s) => ({ title: s.title, description: s.description })));
if (!scored?.length) continue;
const [best, next] = scored;
const { central, firstInDoc } = centrality(c.key);
const { central, firstInTop } = centrality(c.key);
hits.push(
hitOf(c, { kind: "wiki", title: best.title, lang: wiki.lang }, "wikipedia", best.title, {
description: best.description, fit: best.fit, exact: phraseKey(stripParen(best.title)) === c.key, sense: true, margin: best.fit - (next?.fit ?? 0), central, firstInDoc,
description: best.description, fit: best.fit, exact: phraseKey(stripParen(best.title)) === c.key, sense: true, margin: best.fit - (next?.fit ?? 0), central, firstInTop,
}),
);
}
@@ -508,8 +513,8 @@ export class Linker {
if (!r.ok) continue;
const match = r.value.find((s) => phraseKey(stripParen(s.title)) === c.key);
if (!match) continue;
const { central, firstInDoc } = centrality(c.key);
hits.push(hitOf(c, { kind: "wiki", title: match.title, lang: wiki.lang }, "wikipedia", match.title, { description: match.description, searched: true, central, firstInDoc }));
const { central, firstInTop } = centrality(c.key);
hits.push(hitOf(c, { kind: "wiki", title: match.title, lang: wiki.lang }, "wikipedia", match.title, { description: match.description, searched: true, central, firstInTop }));
}
// Fit for every article hit that has none yet.
if (ctxVec) {
@@ -519,11 +524,11 @@ export class Linker {
}
}
// 4. Meaning: sections of other documents close to this node.
// 4. Meaning: sections under other tops close to this node.
const related: Related[] = [];
if (ctxVec) {
const exclude = new Set<NodeId>([...exceptSelf, ...(n ? descendants(snap, input.node) : [])]);
const near = (await this.o.index.near(context, { exclude, doc: docId, snap, vector: ctxVec, k: 8 })) ?? [];
const near = (await this.o.index.near(context, { exclude, top: topId, snap, vector: ctxVec, k: 8 })) ?? [];
for (const hit of near) {
if (hit.score < t.relatedAt) continue;
const m = snap.nodes[hit.id as NodeId];
@@ -531,13 +536,12 @@ export class Linker {
const mRef = m.ref?.kind === "wiki" ? m.ref.title : null;
// A phrase here names it: its title's head ("the triple-alpha process" ← "triple-alpha process"), or what it is about.
const namer = cands.find((c) => !resolved.has(c) && ((c.words > 1 && (` ${mKey}`.endsWith(` ${c.key}`) || ` ${mKey} `.includes(` ${c.key} `))) || (mRef && phraseKey(stripParen(mRef)) === c.key)));
const d = docOf(snap, m.id);
const where = d && d !== m.id ? snap.nodes[d].title : "its own document";
const where = whereIs(snap, m.id);
if (namer) {
hits.push(hitOf(namer, nodeRef(snap, m.id), "meaning", `${m.title} (${where})`, { fit: hit.score }));
resolved.add(namer);
} else if (related.length < 5) {
related.push({ node: m.id, title: m.title, doc: where, score: Math.round(hit.score * 1000) / 1000, why: `close in meaning (${hit.score.toFixed(2)})${shared(context, `${m.title} ${m.body}`)}` });
related.push({ node: m.id, title: m.title, top: where, score: Math.round(hit.score * 1000) / 1000, why: `close in meaning (${hit.score.toFixed(2)})${shared(context, `${m.title} ${m.body}`)}` });
}
}
}
@@ -594,7 +598,7 @@ export class Linker {
const picked = new Set(chosen.map((x) => x.h));
for (const h of best.values()) {
const j = judge(h, t);
input.trace.push({ phrase: h.c.text, key: h.c.key, start: h.c.start, kind: h.c.kind, source: h.source, target: h.target.kind === "wiki" ? `w:${h.target.title}` : `node:${h.title}`, description: h.description, fit: h.fit, score: j.score, tier: picked.has(h) ? j.tier : null, chosen: picked.has(h), why: j.why, features: { words: h.c.words, rarity: h.c.rarity, exact: h.exact, redirect: h.redirect, sense: h.sense, margin: h.margin ?? null, searched: h.searched, central: h.central, firstInDoc: h.firstInDoc, sentenceStart: h.c.sentenceStart } });
input.trace.push({ phrase: h.c.text, key: h.c.key, start: h.c.start, kind: h.c.kind, source: h.source, target: h.target.kind === "wiki" ? `w:${h.target.title}` : `node:${h.title}`, description: h.description, fit: h.fit, score: j.score, tier: picked.has(h) ? j.tier : null, chosen: picked.has(h), why: j.why, features: { words: h.c.words, rarity: h.c.rarity, exact: h.exact, redirect: h.redirect, sense: h.sense, margin: h.margin ?? null, searched: h.searched, central: h.central, firstInTop: h.firstInTop, sentenceStart: h.c.sentenceStart } });
}
}
const suggestions = chosen
@@ -625,29 +629,28 @@ export class Linker {
}
/**
* Sections of other documents close in meaning to a node, for its Related list: derived, never
* Sections under other tops close in meaning to a node, for its Related list: derived, never
* stored. Ones the node already links to are left out.
*/
async related(node: NodeId, k = 5, given: Pick<ScanInput, "text" | "title" | "doc" | "docTitle" | "ancestors"> = {}): Promise<{ related: Related[]; degraded: string[] }> {
async related(node: NodeId, k = 5, given: Pick<ScanInput, "text" | "title" | "top" | "topTitle" | "ancestors"> = {}): Promise<{ related: Related[]; degraded: string[] }> {
const snap = this.o.doc().snap();
const n = snap.nodes[node];
// A node the server has not seen yet (its replica is a moment behind the browser's) is described by the request.
if (!n && given.text === undefined) return { related: [], degraded: [] };
const docId = given.doc !== undefined ? given.doc : docOf(snap, node);
const docTitle = given.docTitle ?? (docId && snap.nodes[docId] ? snap.nodes[docId].title : "");
const context = `${docTitle}. ${given.title ?? n?.title ?? ""}.\n${plain(given.text ?? n!.body)}`.slice(0, 2000);
const topId = given.top !== undefined ? given.top : topOf(snap, node);
const topTitle = given.topTitle ?? (topId && snap.nodes[topId] ? snap.nodes[topId].title : "");
const context = `${topTitle}. ${given.title ?? n?.title ?? ""}.\n${plain(given.text ?? n!.body)}`.slice(0, 2000);
const vec = this.o.embedder ? (await this.o.embedder.embed([context]))?.[0] ?? null : null;
if (!vec) return { related: [], degraded: ["embeddings unavailable: no Related list"] };
const linked = new Set(n ? notesOf(snap, node).map((c) => snap.nodes[c].ref).flatMap((r) => (r?.kind === "node" && r.id ? [r.id] : [])) : []);
const exclude = new Set<NodeId>([node, ...(given.ancestors ?? (n ? ancestorsOf(snap, node) : [])), ...(n ? descendants(snap, node) : [])]);
const near = (await this.o.index.near(context, { exclude, doc: docId, snap, vector: vec, k: k + linked.size + 3 })) ?? [];
const near = (await this.o.index.near(context, { exclude, top: topId, snap, vector: vec, k: k + linked.size + 3 })) ?? [];
const related = near
.filter((h) => h.score >= this.tuning.relatedAt && !linked.has(h.id as NodeId))
.slice(0, k)
.map((h): Related => {
const m = snap.nodes[h.id as NodeId];
const d = docOf(snap, m.id);
return { node: m.id, title: m.title, doc: d && d !== m.id ? snap.nodes[d].title : "its own document", score: Math.round(h.score * 1000) / 1000, why: `close in meaning (${h.score.toFixed(2)})${shared(context, `${m.title} ${m.body}`)}` };
return { node: m.id, title: m.title, top: whereIs(snap, m.id), score: Math.round(h.score * 1000) / 1000, why: `close in meaning (${h.score.toFixed(2)})${shared(context, `${m.title} ${m.body}`)}` };
});
return { related, degraded: [] };
}
@@ -665,8 +668,8 @@ export class Linker {
const hits = await this.o.index.hybrid(query, k, (id) => !exclude.has(id as NodeId) && !!snap.nodes[id as NodeId]);
return hits.map((h) => {
const m = snap.nodes[h.id as NodeId];
const d = docOf(snap, m.id);
return { handle: m.id, title: m.title, document: d ? snap.nodes[d].title : "" };
const d = topOf(snap, m.id);
return { handle: m.id, title: m.title, top: d ? snap.nodes[d].title : "" };
});
}
@@ -687,6 +690,12 @@ export class Linker {
}
}
/** Where a related section is, in words: the title of the top it is under, or "the library" for a top itself. */
function whereIs(snap: Snap, id: NodeId): string {
const d = topOf(snap, id);
return d && d !== id ? snap.nodes[d].title : "the library";
}
/** The uncommon words two texts share, for saying why they are related. */
function shared(a: string, b: string): string {
const mine = new Set(tokenize(a).filter((w) => w.length > 3 && rank(w) > 3000));