Link discovery: local embeddings, scanner, suggestions, background jobs
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
1 parent
36ad305406
commit
dfa08f6e0c
10 files changed
+21993
No files matched your search
@@ -0,0 +1,231 @@
|
||||
/**
|
||||
* Candidate phrases for linking, from a node's text, without an NLP stack. The text is cut into
|
||||
* runs of content words (function words, punctuation, `code` and existing links break a run); every
|
||||
* short span of a run is a candidate, kept in the text's own casing, since Wikipedia titles are
|
||||
* case-sensitive after the first letter. Proper names (capitalised words not at the start of a
|
||||
* sentence) and multi-word spans are always candidates; a single lower-case word only when it is
|
||||
* uncommon (words.ts). Over-generating is cheap (a batched lookup checks 50 phrases a request), so
|
||||
* this ranks rather than filters: the most promising candidates come first, and a cap keeps the
|
||||
* lookups per node bounded.
|
||||
*/
|
||||
import type { Mark } from "../../src/core/marks";
|
||||
import { UNLISTED, listed, rank, singular } from "./words";
|
||||
|
||||
export type Kind = "forced" | "name" | "term" | "noun";
|
||||
|
||||
export interface Candidate {
|
||||
start: number;
|
||||
end: number;
|
||||
/** The phrase as written. */
|
||||
text: string;
|
||||
/** Normalised: what first mention, rejections and title matching compare. */
|
||||
key: string;
|
||||
kind: Kind;
|
||||
/** Phrases to look up, best first: as written, then singular. */
|
||||
variants: string[];
|
||||
words: number;
|
||||
/** The rarest word's rank (higher is rarer; UNLISTED if not in the list). */
|
||||
rarity: number;
|
||||
/** The first word opens a sentence, so its capital says nothing. */
|
||||
sentenceStart: boolean;
|
||||
/** A [[phrase|handle]] mark: the library node it names. */
|
||||
handle?: string;
|
||||
}
|
||||
|
||||
/** Words that never start, end or make up a link on their own. */
|
||||
const STOP = new Set(
|
||||
`a about above across after afterwards again against all almost alone along already also although always am among amongst an and another any anyone anything anyway anywhere are around as at back be became because become becomes becoming been before beforehand behind being below beside besides between beyond both but by can cannot could did do does doing done down during each either else elsewhere enough even ever every everyone everything everywhere except few for former formerly from further had has have having he hence her here hereby herein hers herself him himself his how however i if in indeed into is it its itself just last latter least less let like likely made mainly make makes many may me meanwhile might mine more moreover most mostly much must my myself namely neither never nevertheless next no nobody none nor not nothing now nowhere of off often on once one only onto or other others otherwise our ours ourselves out over own per perhaps quite rather really same seem seemed seeming seems several she should since so some somehow someone something sometime sometimes somewhere still such than that the their theirs them themselves then thence there thereafter thereby therefore therein thereupon these they this those though through throughout thus to together too toward towards under until up upon us used uses using very via was we well were what whatever when whence whenever where whereas whereby wherever whether which while whither who whoever whole whom whose why will with within without would yet you your yours yourself yourselves
|
||||
two three four five six seven eight nine ten hundred thousand million billion first second third half twice
|
||||
get gets got give gives gave given go goes went gone come comes came take takes took taken see sees saw seen say says said know knows knew known think thinks thought find finds found keep keeps kept put puts call calls called tell tells told show shows showed shown turn turns turned need needs needed want wants wanted try tries tried mean means meant ask asks asked work works worked look looks looked leave leaves left run runs ran become becomes able unable new old good bad great little big small large long short high low right wrong true false real certain possible different similar simple whole full early late least kind sort way ways thing things lot lots part parts case cases fact point points time times year years day days place places`.split(/\s+/),
|
||||
);
|
||||
|
||||
/** Common verb forms that end a run of content words more often than they end a name. */
|
||||
const VERBS = new Set(
|
||||
`grew grow grows began begin begins became brought build builds built felt fell held lay led lost lose loses met paid rose sat sent spoke stood struck taught wrote written drew drawn ate fed fled flew fought hid hit hung knelt laid lent lit meant read rode rang sang sank shot shut slept slid sold sought spent spun stuck stung swam swept swore threw thrown tore torn wore won wound broke broken chose chosen froze frozen hidden risen spoken stolen woke woken forgot forgotten lies lie seem appear appears appeared remain remains remained contain contains include includes allow allows require requires produce produces depend depends exist exists happen happens explain explains suggest suggests describe describes form forms`.split(/\s+/),
|
||||
);
|
||||
|
||||
/** Lower-case words that may sit inside a proper name: "Bank of England", "Ludwig van Beethoven". */
|
||||
const CONNECT = new Set(["of", "de", "da", "del", "der", "di", "du", "la", "le", "van", "von", "y", "al", "bin", "ibn"]);
|
||||
|
||||
/** A single lower-case word ranked above this is too common to be worth a link. */
|
||||
export const COMMON_RANK = 6000;
|
||||
const MAX_WORDS = 4;
|
||||
|
||||
interface Tok {
|
||||
start: number;
|
||||
end: number;
|
||||
text: string;
|
||||
/** Opens a sentence. */
|
||||
open: boolean;
|
||||
/** Nothing but whitespace separates it from the next token. */
|
||||
joined: boolean;
|
||||
/** Written with a possessive: a phrase ends here. */
|
||||
possessive: boolean;
|
||||
}
|
||||
|
||||
const WORD = /[\p{L}\p{N}]+(?:['’][\p{L}]+|[-–‑][\p{L}\p{N}]+)*/gu;
|
||||
|
||||
/** Spans of the text that hold no candidates: `code`, and whatever the caller excludes (existing links). */
|
||||
function blocked(text: string, exclude: [number, number][]): (a: number, b: number) => boolean {
|
||||
const zones = [...exclude];
|
||||
for (const m of text.matchAll(/`[^`\n]+`/g)) zones.push([m.index!, m.index! + m[0].length]);
|
||||
return (a, b) => zones.some(([s, e]) => a < e && b > s);
|
||||
}
|
||||
|
||||
function tokens(text: string): Tok[] {
|
||||
const out: Tok[] = [];
|
||||
let prevEnd = 0;
|
||||
for (const m of text.matchAll(WORD)) {
|
||||
let w = m[0];
|
||||
const start = m.index!;
|
||||
// A possessive belongs to the word but not to the phrase: "the octopus's arms" links "octopus".
|
||||
const possessive = /['’]s?$/i.test(w);
|
||||
if (/['’]s$/i.test(w)) w = w.slice(0, -2);
|
||||
else if (/['’]$/.test(w)) w = w.slice(0, -1);
|
||||
const gap = text.slice(prevEnd, start);
|
||||
const open = out.length === 0 || /[.!?]["'”’)*]*\s+["“(*]*$/.test(gap) || /\n\s*\n/.test(gap);
|
||||
if (out.length) out[out.length - 1].joined = /^[ \t]+$/.test(gap) || gap === "";
|
||||
out.push({ start, end: start + w.length, text: w, open, joined: false, possessive });
|
||||
prevEnd = start + m[0].length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const isCap = (w: string) => /^\p{Lu}/u.test(w);
|
||||
/** Lower-case form for the frequency list and the stop list. */
|
||||
const low = (w: string) => w.toLowerCase();
|
||||
/** An adverb in -ly ("roughly", "independently"), when the stem is a word. */
|
||||
const adverb = (w: string) => /ly$/i.test(w) && w.length > 5 && listed(low(w)) && rank(low(w)) < UNLISTED && (listed(low(w).slice(0, -2)) || listed(low(w).slice(0, -3) + "e") || /ally$/i.test(w));
|
||||
|
||||
/** Normalised form of a phrase, for comparing phrases with each other and with titles. */
|
||||
export function phraseKey(s: string): string {
|
||||
return s
|
||||
.normalize("NFKD")
|
||||
.replace(/\p{M}/gu, "")
|
||||
.toLowerCase()
|
||||
.replace(/['’]s\b/g, "")
|
||||
.replace(/[-–‑_/]/g, " ")
|
||||
.replace(/[^\p{L}\p{N}\s]/gu, "")
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
.filter((w, i, all) => !(i === 0 && all.length > 1 && (w === "the" || w === "a" || w === "an")))
|
||||
.map(singular)
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function variants(text: string): string[] {
|
||||
const out = [text];
|
||||
const parts = text.split(" ");
|
||||
const last = parts[parts.length - 1];
|
||||
const s = singular(last);
|
||||
if (s !== last) out.push([...parts.slice(0, -1), s].join(" "));
|
||||
// "-ses" is ambiguous ("octopuses" / "causes"): try dropping just the s as well.
|
||||
if (/[^s]es$/i.test(last) && last.slice(0, -1) !== s) out.push([...parts.slice(0, -1), last.slice(0, -1)].join(" "));
|
||||
return out;
|
||||
}
|
||||
|
||||
interface ExtractOptions {
|
||||
/** Spans to skip: existing links and notes the scanner may not touch. */
|
||||
exclude?: [number, number][];
|
||||
/** Marked phrases ([[…]] already taken out): candidates whatever they look like. */
|
||||
forced?: Mark[];
|
||||
/** Normalised phrases never to offer (the node's own title, its document's, rejected ones). */
|
||||
skip?: Set<string>;
|
||||
}
|
||||
|
||||
/** At most this many candidates per text, best first. */
|
||||
const CAP = 120;
|
||||
|
||||
/** The candidates in a text, most promising first. */
|
||||
export function extract(text: string, o: ExtractOptions = {}): Candidate[] {
|
||||
const isBlocked = blocked(text, o.exclude ?? []);
|
||||
const toks = tokens(text);
|
||||
const out: Candidate[] = [];
|
||||
const seen = new Set<string>();
|
||||
const push = (c: Candidate) => {
|
||||
const id = `${c.start}:${c.end}`;
|
||||
if (seen.has(id) || (o.skip?.has(c.key) && c.kind !== "forced")) return;
|
||||
seen.add(id);
|
||||
out.push(c);
|
||||
};
|
||||
|
||||
for (const m of o.forced ?? []) {
|
||||
const t = text.slice(m.start, m.end);
|
||||
if (!t.trim()) continue;
|
||||
const words = t.split(/\s+/).length;
|
||||
push({ start: m.start, end: m.end, text: t, key: phraseKey(t), kind: "forced", variants: variants(t), words, rarity: Math.max(...t.split(/\s+/).map(rank)), sentenceStart: false, ...(m.handle ? { handle: m.handle } : {}) });
|
||||
}
|
||||
|
||||
// Content words: not on the stop list, not an -ly adverb, not a bare number.
|
||||
const content = (t: Tok) => {
|
||||
const w = low(t.text);
|
||||
if (/^\d+$/.test(w)) return false;
|
||||
if (STOP.has(w) && !(isCap(t.text) && !t.open)) return false;
|
||||
return !adverb(t.text);
|
||||
};
|
||||
// A capitalised word means a name only away from a sentence's start, or when the word is not an ordinary one.
|
||||
// A sentence's first word is a name only when the text says so: written with a capital elsewhere
|
||||
// too, followed by another capitalised word ("Fred Hoyle"), or with a capital inside ("DNA").
|
||||
const capsElsewhere = new Set(toks.filter((t) => !t.open && isCap(t.text)).map((t) => t.text));
|
||||
const proper = (t: Tok, next?: Tok) =>
|
||||
isCap(t.text) && (!t.open || capsElsewhere.has(t.text) || /\p{Lu}.*\p{Lu}/u.test(t.text) || (!!next && next.start - t.end <= 1 && isCap(next.text) && !STOP.has(low(next.text))));
|
||||
|
||||
// Runs of content words, broken by punctuation, function words and blocked text.
|
||||
const runs: Tok[][] = [];
|
||||
let run: Tok[] = [];
|
||||
const flush = () => {
|
||||
if (run.length) runs.push(run);
|
||||
run = [];
|
||||
};
|
||||
for (let i = 0; i < toks.length; i++) {
|
||||
const t = toks[i];
|
||||
if (isBlocked(t.start, t.end)) {
|
||||
flush();
|
||||
continue;
|
||||
}
|
||||
const connector = CONNECT.has(t.text) && run.length && proper(run[run.length - 1]) && toks[i + 1] && proper(toks[i + 1]) && t.joined && toks[i - 1]?.joined;
|
||||
if (t.open && run.length) flush();
|
||||
if (content(t) || connector) run.push(t);
|
||||
else flush();
|
||||
if (!t.joined || t.possessive) flush();
|
||||
}
|
||||
flush();
|
||||
|
||||
for (const r of runs) {
|
||||
for (let a = 0; a < r.length; a++) {
|
||||
for (let b = a; b < Math.min(r.length, a + MAX_WORDS); b++) {
|
||||
const span = r.slice(a, b + 1);
|
||||
// A phrase neither starts nor ends on a connector ("of England", "Bank of").
|
||||
if (CONNECT.has(span[0].text) || CONNECT.has(span[span.length - 1].text)) continue;
|
||||
const start = span[0].start;
|
||||
const end = span[span.length - 1].end;
|
||||
if (isBlocked(start, end)) continue;
|
||||
const t = text.slice(start, end);
|
||||
const isProper = (x: Tok, i: number) => proper(x, span[i + 1]);
|
||||
const names = span.filter((x) => !CONNECT.has(x.text));
|
||||
const allProper = span.every((x, i) => CONNECT.has(x.text) || isProper(x, i));
|
||||
const rarity = Math.max(...names.map((x) => (isCap(x.text) && !listed(low(x.text)) ? UNLISTED : rank(x.text))));
|
||||
const words = span.length;
|
||||
// A phrase rarely ends on a verb: "Hoyle predicted", "branch grew".
|
||||
const tail = low(span[span.length - 1].text);
|
||||
if (words > 1 && ((/ed$/.test(tail) && rank(tail) < UNLISTED) || VERBS.has(tail))) continue;
|
||||
if (words === 1 && t.length < 2) continue;
|
||||
let kind: Kind;
|
||||
if (allProper) kind = "name";
|
||||
else if (words > 1) kind = "term";
|
||||
else if (rarity > COMMON_RANK) kind = "noun";
|
||||
else continue;
|
||||
// A lower-case single word must look like a noun: not a verb form in -ed/-ing that is common.
|
||||
if (kind === "noun" && /(ed|ing)$/.test(t) && rank(t) < 15_000) continue;
|
||||
// Sentence-initial ordinary words are read in lower case.
|
||||
const sentenceStart = span[0].open;
|
||||
const shown = sentenceStart && !isProper(span[0], 0) ? low(t[0]) + t.slice(1) : t;
|
||||
push({ start, end, text: t, key: phraseKey(t), kind, variants: variants(shown), words, rarity, sentenceStart });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const weight = (c: Candidate) =>
|
||||
(c.kind === "forced" ? 1000 : c.kind === "name" ? 300 : 0) + (c.words > 1 ? 100 + Math.min(c.rarity, 20_000) / 200 : Math.min(c.rarity, 20_000) / 100) - c.words * 5;
|
||||
return out.sort((x, y) => weight(y) - weight(x) || x.start - y.start).slice(0, CAP);
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Scanning a document or the whole library in the background: one job at a time, a node at a
|
||||
* time, at bulk priority (a person's own requests to Wikipedia go first), with progress announced
|
||||
* and a cancel. Lookups are gathered across the next few nodes and asked together, 50 phrases a
|
||||
* request, which is most of what keeps a bulk pass affordable. A job only fills the pending list;
|
||||
* applying is up to whoever reviews it (the browser applies the auto tier itself, so `u` can take
|
||||
* it back; a reviewing agent uses the accept route).
|
||||
*/
|
||||
import type { NodeId, Snap } from "../../src/core/model";
|
||||
import type { WikiClient } from "../wiki";
|
||||
import { extract } from "./extract";
|
||||
import type { NodeIndex } from "./nodeIndex";
|
||||
import type { PendingStore } from "./pending";
|
||||
import type { Linker } from "./scan";
|
||||
|
||||
export interface JobState {
|
||||
id: string;
|
||||
scope: "doc" | "library";
|
||||
/** The document scanned, for a document job. */
|
||||
doc?: NodeId;
|
||||
title: string;
|
||||
state: "running" | "done" | "cancelled" | "failed";
|
||||
done: number;
|
||||
total: number;
|
||||
auto: number;
|
||||
suggest: number;
|
||||
requests: number;
|
||||
startedAt: number;
|
||||
finishedAt?: number;
|
||||
/** Seconds left, estimated from the requests still to make and the client's spacing. */
|
||||
etaSec: number | null;
|
||||
/** The client is spacing requests for want of a contact (IE_WIKI_CONTACT). */
|
||||
slow: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/** Nodes whose lookups are asked together. */
|
||||
const CHUNK = 15;
|
||||
|
||||
export class Jobs {
|
||||
current: JobState | null = null;
|
||||
private stop: AbortController | null = null;
|
||||
|
||||
constructor(
|
||||
private o: {
|
||||
snap: () => Snap;
|
||||
linker: () => Linker;
|
||||
wiki: () => WikiClient | null;
|
||||
index: NodeIndex;
|
||||
pending: PendingStore;
|
||||
announce: (state: JobState) => void;
|
||||
},
|
||||
) {}
|
||||
|
||||
/** Start a job over these nodes (in reading order). A running job is cancelled first. */
|
||||
start(scope: "doc" | "library", nodes: NodeId[], title: string, doc?: NodeId): JobState {
|
||||
this.cancel();
|
||||
const wiki = this.o.wiki();
|
||||
const spacing = wiki?.spacingMs ?? 0;
|
||||
const state: JobState = {
|
||||
id: Math.random().toString(36).slice(2, 10),
|
||||
scope,
|
||||
...(doc ? { doc } : {}),
|
||||
title,
|
||||
state: "running",
|
||||
done: 0,
|
||||
total: nodes.length,
|
||||
auto: 0,
|
||||
suggest: 0,
|
||||
requests: 0,
|
||||
startedAt: Date.now(),
|
||||
etaSec: null,
|
||||
slow: spacing > 2000,
|
||||
};
|
||||
// First estimate: the uncached phrases in batches of 50, plus about one sense or search for every other node.
|
||||
const snap = this.o.snap();
|
||||
const phrases = new Set(nodes.flatMap((id) => (snap.nodes[id] ? extract(snap.nodes[id].body).flatMap((c) => c.variants) : [])));
|
||||
const uncached = wiki ? wiki.uncached([...phrases]) : 0;
|
||||
state.etaSec = Math.round(((Math.ceil(uncached / 50) + nodes.length * 0.5) * spacing) / 1000);
|
||||
this.current = state;
|
||||
const ac = (this.stop = new AbortController());
|
||||
void this.run(state, nodes, ac.signal);
|
||||
this.o.announce(state);
|
||||
return state;
|
||||
}
|
||||
|
||||
cancel(): boolean {
|
||||
if (!this.stop || this.current?.state !== "running") return false;
|
||||
this.stop.abort();
|
||||
this.current.state = "cancelled";
|
||||
this.current.finishedAt = Date.now();
|
||||
this.o.announce(this.current);
|
||||
return true;
|
||||
}
|
||||
|
||||
private async run(state: JobState, nodes: NodeId[], signal: AbortSignal) {
|
||||
const wiki = this.o.wiki();
|
||||
const spacing = wiki?.spacingMs ?? 0;
|
||||
const r0 = wiki?.requests ?? 0;
|
||||
let lastAnnounce = 0;
|
||||
try {
|
||||
await this.o.index.refresh();
|
||||
for (let i = 0; i < nodes.length; i += CHUNK) {
|
||||
if (signal.aborted) return;
|
||||
const chunk = nodes.slice(i, i + CHUNK);
|
||||
const snap = this.o.snap();
|
||||
if (wiki) {
|
||||
const phrases = [...new Set(chunk.flatMap((id) => (snap.nodes[id] ? extract(snap.nodes[id].body).flatMap((c) => c.variants) : [])))];
|
||||
await wiki.lookup(phrases, { priority: "bulk", signal });
|
||||
}
|
||||
for (const id of chunk) {
|
||||
if (signal.aborted) return;
|
||||
if (this.o.snap().nodes[id]) {
|
||||
const r = await this.o.linker().scan({ node: id, priority: "bulk" }, signal);
|
||||
if (signal.aborted) return;
|
||||
this.o.pending.put(id, r.suggestions);
|
||||
for (const s of r.suggestions) state[s.tier]++;
|
||||
}
|
||||
state.done++;
|
||||
state.requests = (wiki?.requests ?? 0) - r0;
|
||||
// What is left: the uncached phrases of the nodes not yet scanned, at the client's pace.
|
||||
const left = nodes.slice(state.done);
|
||||
const snapNow = this.o.snap();
|
||||
const phrases = new Set(left.slice(0, 200).flatMap((x) => (snapNow.nodes[x] ? extract(snapNow.nodes[x].body).flatMap((c) => c.variants) : [])));
|
||||
const scale = left.length > 200 ? left.length / 200 : 1;
|
||||
state.etaSec = Math.round((((wiki ? Math.ceil(wiki.uncached([...phrases]) / 50) * scale : 0) + left.length * 0.5) * spacing) / 1000);
|
||||
if (Date.now() - lastAnnounce > 500 || state.done === state.total) {
|
||||
lastAnnounce = Date.now();
|
||||
this.o.announce(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
state.state = "done";
|
||||
state.etaSec = 0;
|
||||
} catch (e) {
|
||||
if (signal.aborted) return;
|
||||
state.state = "failed";
|
||||
state.message = (e as Error).message ?? String(e);
|
||||
} finally {
|
||||
if (!signal.aborted) {
|
||||
state.finishedAt = Date.now();
|
||||
this.o.announce(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* The library's sections as vectors, for "closely matching nodes across documents": 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 { Doc, docOf, isLibraryRoot, type NodeId, type Snap } from "../../src/core/model";
|
||||
import { plain } from "../../src/core/text";
|
||||
import { VectorIndex, type Embedder, type Hit, type HybridHit } from "../embed";
|
||||
|
||||
/** What a section is embedded as. */
|
||||
const nodeText = (snap: Snap, id: NodeId) => {
|
||||
const n = snap.nodes[id];
|
||||
return `${n.title}\n${plain(n.body)}`.trim();
|
||||
};
|
||||
|
||||
/** Sections (and documents) worth indexing: not the library root, not notes, and with some text. */
|
||||
const indexable = (snap: Snap, id: NodeId) => {
|
||||
const n = snap.nodes[id];
|
||||
return !!n && n.kind === "section" && !isLibraryRoot(snap, id) && (n.body.trim().length > 0 || n.title.trim().length > 0);
|
||||
};
|
||||
|
||||
interface IndexStatus {
|
||||
size: number;
|
||||
pending: number;
|
||||
/** Embeddings are unavailable: the index holds texts only. */
|
||||
degraded: boolean;
|
||||
lastMs: number | null;
|
||||
}
|
||||
|
||||
export class NodeIndex {
|
||||
readonly vectors: VectorIndex;
|
||||
private dirty = new Set<NodeId>();
|
||||
private all = true;
|
||||
private running: Promise<void> | null = null;
|
||||
private timer: ReturnType<typeof setTimeout> | null = null;
|
||||
degraded = false;
|
||||
lastMs: number | null = null;
|
||||
|
||||
constructor(
|
||||
private doc: () => Doc,
|
||||
o: { file: string | null; embedder: Embedder | null; delayMs?: number },
|
||||
) {
|
||||
this.vectors = new VectorIndex(o.file, o.embedder);
|
||||
this.delay = o.delayMs ?? 2000;
|
||||
}
|
||||
private delay: number;
|
||||
|
||||
/** Follow a library's patches. Marking is all a patch costs; the embedding happens later. */
|
||||
watch(doc: Doc) {
|
||||
doc.onPatch((was) => {
|
||||
if (!was) this.all = true;
|
||||
else for (const id of was.keys()) this.dirty.add(id);
|
||||
this.schedule();
|
||||
});
|
||||
this.schedule();
|
||||
}
|
||||
|
||||
/** Start keeping the index current (and so load the model): on the first request that needs it. */
|
||||
activate() {
|
||||
if (this.active) return;
|
||||
this.active = true;
|
||||
this.schedule();
|
||||
}
|
||||
private active = false;
|
||||
|
||||
private schedule() {
|
||||
if (this.timer || !this.delay || !this.active) return;
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = null;
|
||||
void this.refresh();
|
||||
}, this.delay);
|
||||
this.timer.unref?.();
|
||||
}
|
||||
|
||||
get status(): IndexStatus {
|
||||
return { size: this.vectors.size, pending: this.all ? -1 : this.dirty.size, degraded: this.degraded, lastMs: this.lastMs };
|
||||
}
|
||||
|
||||
/** Bring the index up to date with the library: the marked nodes, or all of them after a whole read. */
|
||||
refresh(): Promise<void> {
|
||||
if (this.running) return this.running.then(() => (this.all || this.dirty.size ? this.refresh() : undefined));
|
||||
this.running = (async () => {
|
||||
const t0 = performance.now();
|
||||
const snap = this.doc().snap();
|
||||
const ids = this.all ? (Object.keys(snap.nodes) as NodeId[]) : [...this.dirty];
|
||||
const whole = this.all;
|
||||
this.all = false;
|
||||
this.dirty.clear();
|
||||
const items = ids.filter((id) => indexable(snap, id)).map((id) => ({ id, text: nodeText(snap, id) }));
|
||||
const gone = whole ? this.vectors.ids().filter((id) => !indexable(snap, id as NodeId)) : ids.filter((id) => !indexable(snap, id));
|
||||
this.vectors.remove(gone, false);
|
||||
const report = await this.vectors.upsert(items);
|
||||
if (report.degraded) this.degraded = true;
|
||||
else if (report.embedded) this.degraded = false;
|
||||
if (gone.length && !report.embedded && !report.withoutVector) this.vectors.save();
|
||||
this.lastMs = Math.round(performance.now() - t0);
|
||||
})().finally(() => (this.running = null));
|
||||
return this.running;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
async near(text: string, o: { exclude: Set<NodeId>; doc: 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;
|
||||
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;
|
||||
}
|
||||
|
||||
/** Text and meaning fused (BM25 alone without a model): for the model's "nearby" list. */
|
||||
async hybrid(query: string, k: number, filter?: (id: string) => boolean): Promise<HybridHit[]> {
|
||||
if (!this.vectors.size && (this.all || this.running)) await this.refresh();
|
||||
return this.vectors.hybrid(query, k, filter);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* Suggestions waiting for a writer. Derived data, so they live on the server under
|
||||
* <IE_DATA>/links/pending.json and never in the library: a scan replaces what was pending for its
|
||||
* node. They are checked against the library whenever they are read, because the text moves on:
|
||||
* a suggestion whose words are gone, already linked, or declined (a phrase in the node's `nolink`)
|
||||
* is not offered, and one whose words moved is offered where they now are.
|
||||
*/
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { notesOf, type NodeId, type Snap } from "../../src/core/model";
|
||||
import { overlaps } from "../../src/core/text";
|
||||
import { writeAtomic } from "../util";
|
||||
import type { Suggestion } from "./scan";
|
||||
|
||||
interface Entry {
|
||||
at: number;
|
||||
suggestions: Suggestion[];
|
||||
}
|
||||
|
||||
export class PendingStore {
|
||||
private byNode = new Map<string, Entry>();
|
||||
private timer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
constructor(private file: string | null) {
|
||||
if (file && existsSync(file)) {
|
||||
try {
|
||||
const data = JSON.parse(readFileSync(file, "utf8")) as Record<string, Entry>;
|
||||
for (const [k, v] of Object.entries(data)) this.byNode.set(k, v);
|
||||
} catch (e) {
|
||||
console.warn(`pending links: could not read ${file}: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What a scan of this node found, replacing what was pending for it. */
|
||||
put(node: NodeId, suggestions: Suggestion[]) {
|
||||
if (suggestions.length) this.byNode.set(node, { at: Date.now(), suggestions });
|
||||
else this.byNode.delete(node);
|
||||
this.saveSoon();
|
||||
}
|
||||
|
||||
/** Forget these suggestions (accepted or declined). */
|
||||
drop(ids: Iterable<string>) {
|
||||
const gone = new Set(ids);
|
||||
for (const [k, e] of this.byNode) {
|
||||
const left = e.suggestions.filter((s) => !gone.has(s.id));
|
||||
if (left.length === e.suggestions.length) continue;
|
||||
if (left.length) e.suggestions = left;
|
||||
else this.byNode.delete(k);
|
||||
}
|
||||
this.saveSoon();
|
||||
}
|
||||
|
||||
/** Every suggestion still valid against the library, optionally for some nodes only. */
|
||||
list(snap: Snap, nodes?: Set<NodeId>): Suggestion[] {
|
||||
const out: Suggestion[] = [];
|
||||
for (const [k, e] of this.byNode) {
|
||||
if (nodes && !nodes.has(k as NodeId)) continue;
|
||||
for (const s of e.suggestions) {
|
||||
const live = check(snap, s);
|
||||
if (live) out.push(live);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
get(snap: Snap, id: string): Suggestion | undefined {
|
||||
for (const e of this.byNode.values()) {
|
||||
const s = e.suggestions.find((x) => x.id === id);
|
||||
if (s) return check(snap, s) ?? undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
get size() {
|
||||
let n = 0;
|
||||
for (const e of this.byNode.values()) n += e.suggestions.length;
|
||||
return n;
|
||||
}
|
||||
|
||||
private saveSoon() {
|
||||
if (!this.file || this.timer) return;
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = null;
|
||||
this.flush();
|
||||
}, 500);
|
||||
this.timer.unref?.();
|
||||
}
|
||||
|
||||
flush() {
|
||||
if (!this.file) return;
|
||||
try {
|
||||
writeAtomic(this.file, JSON.stringify(Object.fromEntries(this.byNode)));
|
||||
} catch (e) {
|
||||
console.warn(`pending links: could not save: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A suggestion as it applies to the library now, or null if it no longer does. */
|
||||
function check(snap: Snap, s: Suggestion): Suggestion | null {
|
||||
const n = snap.nodes[s.node];
|
||||
if (!n) return null;
|
||||
if (n.nolink?.includes(s.key)) return null;
|
||||
let range = s.range;
|
||||
if (n.body.slice(range[0], range[1]) !== s.quote) {
|
||||
const at = n.body.indexOf(s.quote);
|
||||
if (at < 0) return null;
|
||||
range = [at, at + s.quote.length];
|
||||
}
|
||||
for (const c of notesOf(snap, s.node)) {
|
||||
const note = snap.nodes[c];
|
||||
if (!note.ref) continue;
|
||||
if (note.anchors.some((a) => overlaps([a.start, a.end], range))) return null;
|
||||
}
|
||||
return range === s.range ? s : { ...s, range };
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* 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? }
|
||||
* → { suggestions, related, unresolved, degraded, stats }; save (default true) records
|
||||
* the suggestions as pending for the node
|
||||
* GET /api/links/pending ?doc=<slug|id>&node=<id>&tier=auto|suggest&limit=&offset=
|
||||
* → { total, suggestions: [{ …, nodeTitle, document, docSlug, path, sentence }] }
|
||||
* 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)
|
||||
* 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);
|
||||
* or POST { node, text, title, ancestors }
|
||||
* POST /api/links/jobs { scope: "doc" | "library", doc? } → the job's state; it runs in the background
|
||||
* GET /api/links/jobs → { job } (the current or last one)
|
||||
* DELETE /api/links/jobs → cancel the running job
|
||||
* GET /api/links/status → embeddings, the node index, the pending count, the job
|
||||
*
|
||||
* Job progress is also announced on /api/events as { linkJob: state }.
|
||||
*/
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { applyLinks, type LinkSpec } from "../../src/core/links";
|
||||
import { descendants, docOf, documents, findDoc, isLibraryRoot, label, type Doc, type NodeId, type Op, type Snap } from "../../src/core/model";
|
||||
import { clip, plain, sentences } from "../../src/core/text";
|
||||
import type { Embedder } from "../embed";
|
||||
import { HttpError, abortOnClose, readJson as readBody, sendJson as send } from "../util";
|
||||
import type { Jobs } from "./jobs";
|
||||
import type { NodeIndex } from "./nodeIndex";
|
||||
import type { PendingStore } from "./pending";
|
||||
import type { Linker, ScanInput, Suggestion } from "./scan";
|
||||
|
||||
interface LinkDeps {
|
||||
main: () => Doc;
|
||||
linker: () => Linker;
|
||||
index: NodeIndex;
|
||||
pending: PendingStore;
|
||||
jobs: Jobs;
|
||||
embedder: Embedder | null;
|
||||
/** A server-side write: saved soon and announced to every replica. */
|
||||
wrote: () => void;
|
||||
}
|
||||
|
||||
class Bad extends HttpError {
|
||||
constructor(message: string) {
|
||||
super(400, message);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/** Everything a reviewer needs to judge a suggestion without the page. */
|
||||
function describe(snap: Snap, s: Suggestion) {
|
||||
const n = snap.nodes[s.node];
|
||||
const d = docOf(snap, s.node);
|
||||
const sent = sentences(n.body).find(([a, b]) => s.range[0] >= a && s.range[0] < b) ?? [0, n.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));
|
||||
return {
|
||||
...s,
|
||||
nodeTitle: label(snap, s.node),
|
||||
document: d ? snap.nodes[d].title : null,
|
||||
docSlug: d ? snap.nodes[d].slug ?? null : null,
|
||||
path: path.join(" › "),
|
||||
sentence: clip(plain(n.body.slice(sent[0], sent[1])).trim(), 400),
|
||||
};
|
||||
}
|
||||
|
||||
/** The nodes of a document (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 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;
|
||||
}
|
||||
|
||||
export function linkRoutes(deps: LinkDeps) {
|
||||
return async function handle(req: IncomingMessage, res: ServerResponse, url: URL): Promise<boolean> {
|
||||
if (!url.pathname.startsWith("/api/links/")) return false;
|
||||
const route = url.pathname.slice("/api/links/".length).replace(/\/$/, "");
|
||||
const method = req.method ?? "GET";
|
||||
try {
|
||||
const snap = deps.main().snap();
|
||||
if (route === "scan" && method === "POST") {
|
||||
const input = await readJson<ScanInput & { save?: boolean }>(req);
|
||||
if (typeof input.node !== "string" || !input.node) throw new Bad("give the node's id");
|
||||
if (input.text !== undefined && typeof input.text !== "string") throw new Bad("text must be a string");
|
||||
if ((input.text?.length ?? 0) > 200_000) throw new Bad("text is too long");
|
||||
const r = await deps.linker().scan({ ...input, trace: undefined }, abortOnClose(res));
|
||||
if (input.save !== false) deps.pending.put(input.node, r.suggestions);
|
||||
return send(res, 200, r), true;
|
||||
}
|
||||
if (route === "pending" && method === "GET") {
|
||||
const docId = docArg(snap, url.searchParams.get("doc"));
|
||||
if (url.searchParams.get("doc") && !docId) throw new Bad(`no document ${url.searchParams.get("doc")}`);
|
||||
const node = url.searchParams.get("node") as NodeId | null;
|
||||
const scope = node ? new Set([node]) : docId ? new Set(scopeNodes(snap, docId)) : undefined;
|
||||
const tier = url.searchParams.get("tier");
|
||||
let list = deps.pending.list(snap, scope);
|
||||
if (tier) list = list.filter((s) => s.tier === tier);
|
||||
const order = new Map((scope ? [...scope] : scopeNodes(snap, null)).map((id, i) => [id, i]));
|
||||
list.sort((a, b) => (order.get(a.node) ?? 1e9) - (order.get(b.node) ?? 1e9) || a.range[0] - b.range[0]);
|
||||
const offset = Math.max(0, Number(url.searchParams.get("offset") ?? 0) || 0);
|
||||
const limit = Math.min(5000, Math.max(1, Number(url.searchParams.get("limit") ?? 1000) || 1000));
|
||||
return send(res, 200, { total: list.length, suggestions: list.slice(offset, offset + limit).map((s) => describe(snap, s)) }), true;
|
||||
}
|
||||
if ((route === "accept" || route === "reject") && method === "POST") {
|
||||
const input = await readJson<{ ids?: unknown; author?: unknown }>(req);
|
||||
if (!Array.isArray(input.ids) || !input.ids.every((x) => typeof x === "string")) throw new Bad("give { ids: [...] }");
|
||||
const found = (input.ids as string[]).map((id) => deps.pending.get(snap, id)).filter((s): s is Suggestion => !!s);
|
||||
const author = typeof input.author === "string" && input.author.trim() ? input.author.trim().slice(0, 100) : "linker";
|
||||
const main = deps.main();
|
||||
if (route === "accept") {
|
||||
const specs: LinkSpec[] = found.map((s) => ({ node: s.node, range: s.range, target: s.target }));
|
||||
const r = applyLinks(main, specs, { author, actor: "llm", tag: "autolink", message: `Link ${specs.length} phrase${specs.length === 1 ? "" : "s"} (reviewed suggestions)` });
|
||||
deps.pending.drop(found.map((s) => s.id));
|
||||
if (r.created.length || r.merged.length) deps.wrote();
|
||||
return send(res, 200, { accepted: found.length, unknown: input.ids.length - found.length, ...r }), true;
|
||||
}
|
||||
const byNode = new Map<NodeId, Set<string>>();
|
||||
for (const s of found) byNode.set(s.node, (byNode.get(s.node) ?? new Set()).add(s.key));
|
||||
const ops: Op[] = [...byNode].map(([id, keys]) => ({ op: "update", id, nolink: [...keys] }));
|
||||
if (ops.length) {
|
||||
main.as(author, () => main.apply(ops, `Decline ${found.length} link suggestion${found.length === 1 ? "" : "s"}`, { actor: "human", tag: "nolink" }));
|
||||
deps.wrote();
|
||||
}
|
||||
deps.pending.drop(found.map((s) => s.id));
|
||||
return send(res, 200, { rejected: found.length, unknown: input.ids.length - found.length }), 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.
|
||||
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);
|
||||
return send(res, 200, r), true;
|
||||
}
|
||||
if (route === "nearby" && (method === "GET" || method === "POST")) {
|
||||
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 k = Math.min(10, Math.max(1, Number(url.searchParams.get("k") ?? 5) || 5));
|
||||
return send(res, 200, { nearby: await deps.linker().nearby(input.node, k, input) }), true;
|
||||
}
|
||||
if (route === "jobs") {
|
||||
if (method === "GET") return send(res, 200, { job: deps.jobs.current }), true;
|
||||
if (method === "DELETE") return send(res, 200, { cancelled: deps.jobs.cancel(), job: deps.jobs.current }), true;
|
||||
if (method === "POST") {
|
||||
const input = await readJson<{ scope?: string; doc?: string }>(req);
|
||||
if (input.scope !== "doc" && input.scope !== "library") throw new Bad('scope is "doc" or "library"');
|
||||
const docId = input.scope === "doc" ? docArg(snap, input.doc ?? null) : null;
|
||||
if (input.scope === "doc" && !docId) throw new Bad(`no document ${input.doc ?? ""}`);
|
||||
const nodes = scopeNodes(snap, docId);
|
||||
const title = docId ? snap.nodes[docId].title : "the library";
|
||||
return send(res, 202, { job: deps.jobs.start(input.scope, nodes, title, docId ?? undefined) }), true;
|
||||
}
|
||||
}
|
||||
if (route === "status" && method === "GET") {
|
||||
return send(res, 200, {
|
||||
embeddings: deps.embedder ? { state: deps.embedder.state, model: deps.embedder.spec.id, error: deps.embedder.error } : { state: "off" },
|
||||
index: deps.index.status,
|
||||
pending: deps.pending.size,
|
||||
job: deps.jobs.current,
|
||||
}), true;
|
||||
}
|
||||
send(res, 404, { error: `no route ${method} /api/links/${route}` });
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (e instanceof HttpError) send(res, e.status, { error: e.message });
|
||||
else {
|
||||
console.error("links:", e);
|
||||
send(res, 500, { error: (e as Error).message ?? String(e) });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,673 @@
|
||||
/**
|
||||
* The link scanner: given a node's text and where it sits, what in it is worth linking, and to
|
||||
* what. Four sources, in order of preference for any one phrase:
|
||||
*
|
||||
* 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
|
||||
* 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
|
||||
* against the text (a few per scan); a title search as a second try for multi-word
|
||||
* misses; every hit scored by fit between the text and "Title: description"
|
||||
*
|
||||
* Each suggestion gets a tier: `auto` (safe to apply without asking) or `suggest`; anything weaker
|
||||
* 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.
|
||||
*/
|
||||
import { docOf, notesOf, sections, ancestors as ancestorsOf, descendants, type Doc, type NodeId, type Snap } from "../../src/core/model";
|
||||
import { nodeRef } from "../../src/core/links";
|
||||
import type { Mark } from "../../src/core/marks";
|
||||
import type { Nearby } from "../../src/llm/prompts";
|
||||
import { wikiKey, type Ref } from "../../src/core/ref";
|
||||
import { digest, overlaps, paragraphs, plain, type Range } from "../../src/core/text";
|
||||
import { VectorIndex, dot, tokenize, type Embedder } from "../embed";
|
||||
import type { CallOpts, LookupItem, WikiClient } from "../wiki";
|
||||
import { COMMON_RANK, extract, phraseKey, type Candidate, type Kind } from "./extract";
|
||||
import type { NodeIndex } from "./nodeIndex";
|
||||
import { UNLISTED, rank } from "./words";
|
||||
|
||||
export type Tier = "auto" | "suggest";
|
||||
export type Source = "forced" | "library" | "meaning" | "wikipedia";
|
||||
|
||||
export interface Suggestion {
|
||||
/** Stable for the same node, words and target. */
|
||||
id: string;
|
||||
node: NodeId;
|
||||
range: Range;
|
||||
quote: string;
|
||||
/** The normalised phrase: what a rejection records. */
|
||||
key: string;
|
||||
target: Ref;
|
||||
score: number;
|
||||
tier: Tier;
|
||||
why: string;
|
||||
source: Source;
|
||||
/** The target's title (an article's, or a section's), and an article's short description. */
|
||||
title: string;
|
||||
description: string | null;
|
||||
kind: Kind;
|
||||
}
|
||||
|
||||
export interface Related {
|
||||
node: NodeId;
|
||||
title: string;
|
||||
doc: string;
|
||||
score: number;
|
||||
why: string;
|
||||
}
|
||||
|
||||
export interface ScanInput {
|
||||
node: NodeId;
|
||||
/** 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;
|
||||
ancestors?: NodeId[];
|
||||
/** Spans already under a note: [start, end, linked]. */
|
||||
occupied?: [number, number, boolean][];
|
||||
/** Normalised phrases the writer declined in this node. */
|
||||
rejected?: string[];
|
||||
/** [[marks]], already taken out of `text`. */
|
||||
forced?: Mark[];
|
||||
/** Wikipedia queue lane: "scan" (the default: after an edit, behind anything a person waits on) or "bulk" (a job). */
|
||||
priority?: "interactive" | "bulk" | "scan";
|
||||
/** Only phrases inside these spans are looked at (the new text of an edit); default the whole text. */
|
||||
within?: Range[];
|
||||
/** For evaluation: every phrase that resolved to something, with its judgement, is pushed here. */
|
||||
trace?: TraceRow[];
|
||||
}
|
||||
|
||||
export interface TraceRow {
|
||||
phrase: string;
|
||||
key: string;
|
||||
start: number;
|
||||
kind: Kind;
|
||||
source: Source;
|
||||
target: string;
|
||||
description: string | null;
|
||||
fit: number | null;
|
||||
score: number;
|
||||
tier: Tier | null;
|
||||
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 };
|
||||
}
|
||||
|
||||
export interface ScanResult {
|
||||
node: NodeId;
|
||||
suggestions: Suggestion[];
|
||||
related: Related[];
|
||||
/** Marked phrases that resolved to nothing. */
|
||||
unresolved: string[];
|
||||
/** What was not available, in words ("embeddings unavailable: matched by text only"). */
|
||||
degraded: string[];
|
||||
stats: { candidates: number; lookedUp: number; requests: number; ms: number };
|
||||
}
|
||||
|
||||
/**
|
||||
* The numbers judge() and the scan use, tuned on the labelled sample (tests/fixtures/link-labels.json,
|
||||
* scripts/linkEval.ts). Fits are on bge-small's scale.
|
||||
*/
|
||||
export interface Tuning {
|
||||
/** Least fit for a link made without asking: a multi-word term, a name, a single word, a library title. */
|
||||
auto: { term: number; name: number; noun: number; library: number };
|
||||
/** Least fit for a suggestion. */
|
||||
suggest: { term: number; name: number; noun: number; library: number };
|
||||
/** A single word must be at least this rare (words.ts rank) to be suggested, and this rare to be applied. */
|
||||
nounRank: { suggest: number; auto: number };
|
||||
/** A multi-word term is applied without asking only when one of its words is this rare. */
|
||||
termRank: number;
|
||||
/** A disambiguation sense is offered only when it beats the runner-up by this much. */
|
||||
senseMargin: number;
|
||||
/** Cosine at or above which another section counts as close in meaning. */
|
||||
relatedAt: number;
|
||||
/** Disambiguation pages resolved per scan (each costs a request), and title searches. */
|
||||
maxSenses: number;
|
||||
maxSearches: number;
|
||||
/** Links per paragraph, counting those already there. */
|
||||
perParagraph: number;
|
||||
/**
|
||||
* Fit as judged = a + b × cosine, clipped to [0, 1]. Embedding models spread their cosines
|
||||
* differently; the thresholds above are for bge-small, so another model is mapped onto its scale.
|
||||
*/
|
||||
fit: [number, number];
|
||||
}
|
||||
|
||||
export const TUNING: Tuning = {
|
||||
auto: { term: 0.55, name: 0.55, noun: 0.7, library: 0.72 },
|
||||
suggest: { term: 0.6, name: 0.6, noun: 0.64, library: 0.64 },
|
||||
nounRank: { suggest: 8000, auto: 15_000 },
|
||||
termRank: 6000,
|
||||
senseMargin: 0.04,
|
||||
relatedAt: 0.78,
|
||||
maxSenses: 2,
|
||||
maxSearches: 1,
|
||||
perParagraph: 3,
|
||||
fit: [0, 1],
|
||||
};
|
||||
|
||||
/**
|
||||
* Per-model adjustments. The test model (IE_EMBED=fake: hashed words) gives a 7-word description
|
||||
* and a paragraph a cosine of 0.1–0.3 when they share a word and 0 when they share none.
|
||||
*/
|
||||
const PROFILES: Record<string, Partial<Tuning>> = {
|
||||
fake: { fit: [0.5, 1.5], relatedAt: 0.15 },
|
||||
};
|
||||
|
||||
/** Descriptions of articles that are almost never what prose means by an ordinary phrase. */
|
||||
const OFF_TOPIC = /\b(album|song|single|film|movie|band|group|singer|rapper|musician|episode|television|tv series|sitcom|novel|video game|comic|manga|anime|company|brand|restaurant|chain|surname|given name|family name|name list|fictional|character|play by|racehorse|ship|football|basketball|baseball|cricketer|footballer|politician|disambiguation|topics referred to|list of|wikimedia)\b/i;
|
||||
|
||||
interface Hit {
|
||||
c: Candidate;
|
||||
target: Ref;
|
||||
source: Source;
|
||||
title: string;
|
||||
description: string | null;
|
||||
/** Fit between the text and the target, or null without a model. */
|
||||
fit: number | null;
|
||||
/** The title is the phrase itself (up to case and number), not a redirect from something else. */
|
||||
exact: boolean;
|
||||
redirect: boolean;
|
||||
/** Chosen among a disambiguation page's senses. */
|
||||
sense: boolean;
|
||||
/** Margin of the chosen sense over the next. */
|
||||
margin?: number;
|
||||
/** 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;
|
||||
}
|
||||
|
||||
/** 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,
|
||||
});
|
||||
|
||||
const keyWords = (key: string) => key.split(" ").filter(Boolean).length;
|
||||
|
||||
export interface Judgement {
|
||||
score: number;
|
||||
tier: Tier | null;
|
||||
why: string;
|
||||
}
|
||||
|
||||
/** Descriptions of pages that are not the concept a phrase in prose means: lists, name pages, countries. */
|
||||
const NOT_A_CONCEPT = /^(surname|given name|family name|index of|list of|topics referred to)|\b(surname list|name list|set index)\b|^country in\b|^sovereign state\b/i;
|
||||
|
||||
/**
|
||||
* The rule, as tuned. Fit separates right senses from wrong ones (docs/wikipedia.md §5: about 0.6
|
||||
* for bge-small) but does not say whether a phrase is worth linking, so each kind of phrase has its
|
||||
* own bar, and `auto` needs the phrase's form to vouch for it too:
|
||||
*
|
||||
* term (several words, not a name) auto when the title is the phrase itself (up to case and
|
||||
* number), one word is uncommon, and fit ≥ 0.55; suggest otherwise from fit 0.6
|
||||
* name (capitalised) auto when the title is the name itself and it is not an ordinary word
|
||||
* ("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
|
||||
*
|
||||
* 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).
|
||||
*/
|
||||
export function judge(h: Hit, t: Tuning = TUNING): Judgement {
|
||||
const c = h.c;
|
||||
const fit = h.fit;
|
||||
const f = fit === null ? "" : `fits the text ${fit.toFixed(2)}`;
|
||||
if (h.source === "meaning") return { score: fit ?? 0, tier: "suggest", why: `close in meaning (${(fit ?? 0).toFixed(2)}) to “${h.title}”, and named here` };
|
||||
if (h.source === "forced" || c.kind === "forced") {
|
||||
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" };
|
||||
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";
|
||||
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"]);
|
||||
// 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);
|
||||
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.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}”`);
|
||||
const clear = (h.margin ?? 0) >= t.senseMargin && c.kind !== "noun";
|
||||
return done(clear ? tierBy(false, 1, t.suggest.name + 0.08) : null, why);
|
||||
}
|
||||
if (h.searched) why.push("found by title search");
|
||||
if (!h.exact) why.push(h.redirect ? `redirects to “${h.title}”` : `titled “${h.title}”`);
|
||||
if (OFF_TOPIC.test(desc)) {
|
||||
why.push("an article about something else");
|
||||
return done(null, why);
|
||||
}
|
||||
const plain = h.exact && !h.searched;
|
||||
if (c.kind === "term") {
|
||||
why.push(c.rarity >= t.termRank ? "a technical term" : "a multi-word phrase");
|
||||
return done(tierBy(plain && c.rarity >= t.termRank, t.auto.term, t.suggest.term + (h.exact ? 0 : 0.05)), why);
|
||||
}
|
||||
if (c.kind === "name") {
|
||||
why.push("a proper name");
|
||||
// A capitalised ordinary word ("Sun", "East", "Old World") is not a name worth a link.
|
||||
if (c.rarity < 1000) return done(null, [...why, "an ordinary word"]);
|
||||
const single = c.words === 1;
|
||||
return done(tierBy(plain && (!single || c.rarity >= UNLISTED), single ? t.auto.name + 0.05 : t.auto.name, t.suggest.name), why);
|
||||
}
|
||||
// A single lower-case word.
|
||||
if (c.rarity < t.nounRank.suggest) return done(null, [...why, "a fairly common word"]);
|
||||
why.push(c.rarity >= UNLISTED ? "an uncommon word" : "a fairly uncommon word");
|
||||
return done(tierBy(plain && c.rarity >= t.nounRank.auto, t.auto.noun, t.suggest.noun + (h.exact ? 0 : 0.03)), why);
|
||||
}
|
||||
|
||||
// ---- the library's titles ----
|
||||
|
||||
/** A title worth matching: a short concept name, not a sentence or a lone common word. */
|
||||
function titleKeyOf(title: string): string | null {
|
||||
const key = phraseKey(title);
|
||||
const words = key.split(" ").filter(Boolean);
|
||||
if (!words.length || words.length > 4) return null;
|
||||
if (words.length === 1 && rank(words[0]) <= COMMON_RANK) return null;
|
||||
return key;
|
||||
}
|
||||
|
||||
const titleCache = new WeakMap<object, Map<string, NodeId[]>>();
|
||||
/**
|
||||
* Sections by normalised title, built once per state of the library. Keyed by the root's entry,
|
||||
* which is replaced whenever anything beneath it changes (the snapshot's record of nodes is not:
|
||||
* it is patched in place).
|
||||
*/
|
||||
function titleIndex(snap: Snap): Map<string, NodeId[]> {
|
||||
const key = snap.nodes[snap.root];
|
||||
let ix = titleCache.get(key);
|
||||
if (ix) return ix;
|
||||
ix = new Map();
|
||||
for (const id in snap.nodes) {
|
||||
const n = snap.nodes[id as NodeId];
|
||||
if (n.kind !== "section" || !n.parent) continue;
|
||||
const key = titleKeyOf(n.title);
|
||||
if (!key) continue;
|
||||
const list = ix.get(key) ?? [];
|
||||
list.push(n.id);
|
||||
ix.set(key, list);
|
||||
}
|
||||
titleCache.set(key, ix);
|
||||
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);
|
||||
if (out) return out;
|
||||
out = [];
|
||||
const visit = (id: NodeId) => {
|
||||
const n = snap.nodes[id];
|
||||
out!.push({ id, text: ` ${phraseKey(`${n.title} ${n.body}`)} ` });
|
||||
for (const c of sections(snap, id)) visit(c);
|
||||
};
|
||||
visit(doc);
|
||||
docCache.set(d, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
const refKey = (r: Ref) => (r.kind === "wiki" ? wikiKey(r.lang, r.title) : r.kind === "node" ? `node:${r.id}` : r.url);
|
||||
const stripParen = (t: string) => t.replace(/\s*\([^)]*\)\s*$/, "");
|
||||
|
||||
export class Linker {
|
||||
readonly tuning: Tuning;
|
||||
/** Vectors of "Title: description" strings, remembered between scans. */
|
||||
private senseVectors: VectorIndex;
|
||||
|
||||
constructor(
|
||||
private o: { doc: () => Doc; wiki: () => WikiClient | null; embedder: Embedder | null; index: NodeIndex; tuning?: Partial<Tuning> },
|
||||
) {
|
||||
this.tuning = { ...TUNING, ...(o.embedder ? PROFILES[o.embedder.spec.id] : undefined), ...o.tuning };
|
||||
this.senseVectors = new VectorIndex(null, o.embedder);
|
||||
}
|
||||
|
||||
async scan(input: ScanInput, signal?: AbortSignal): Promise<ScanResult> {
|
||||
const t0 = performance.now();
|
||||
const t = this.tuning;
|
||||
const snap = this.o.doc().snap();
|
||||
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 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 ?? []);
|
||||
const degraded: string[] = [];
|
||||
const wiki = this.o.wiki();
|
||||
const requests0 = wiki?.requests ?? 0;
|
||||
const opts: CallOpts = { priority: input.priority ?? "scan", signal };
|
||||
|
||||
// Linked spans are off limits; a plain note's exact span may take a target (it becomes a note that also links).
|
||||
const plainNotes = occupied.filter(([, , linked]) => !linked);
|
||||
const exclude = occupied.filter(([, , linked]) => linked).map(([s, e]): [number, number] => [s, e]);
|
||||
const skip = new Set([phraseKey(title), ...rejected].filter(Boolean));
|
||||
let cands = extract(text, { exclude, forced: input.forced, skip });
|
||||
cands = cands.filter((c) => !plainNotes.some(([s, e]) => overlaps([s, e], [c.start, c.end]) && !(s === c.start && e === c.end)));
|
||||
if (input.within?.length) cands = cands.filter((c) => c.kind === "forced" || input.within!.some((r) => overlaps(r, [c.start, c.end])));
|
||||
// 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(refKey) : []);
|
||||
|
||||
// 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)} `;
|
||||
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 exceptSelf = new Set<NodeId>([input.node, ...ancestors]);
|
||||
const hits: Hit[] = [];
|
||||
const resolved = new Set<Candidate>();
|
||||
const unresolved: string[] = [];
|
||||
|
||||
// 1. Forced marks with a handle name a library node outright.
|
||||
for (const c of cands) {
|
||||
if (c.kind !== "forced" || !c.handle) continue;
|
||||
const id = c.handle as NodeId;
|
||||
if (snap.nodes[id] && !exceptSelf.has(id)) {
|
||||
hits.push(hitOf(c, nodeRef(snap, id), "forced", snap.nodes[id].title || "a note"));
|
||||
resolved.add(c);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Library titles.
|
||||
const titles = titleIndex(snap);
|
||||
for (const c of cands) {
|
||||
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 }));
|
||||
resolved.add(c);
|
||||
}
|
||||
|
||||
// The text a target must fit: the node in its document.
|
||||
const context = `${docTitle}. ${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");
|
||||
// A library title must also fit: "nucleus" in a physics text is not the cell's nucleus.
|
||||
for (const h of hits) {
|
||||
if (h.target.kind !== "node" || !ctxVec) continue;
|
||||
const v = this.o.index.vectors.vectorOf(h.target.id!);
|
||||
if (v) h.fit = this.calibrate(dot(ctxVec, v));
|
||||
}
|
||||
|
||||
// 3. Wikipedia.
|
||||
let lookedUp = 0;
|
||||
if (!wiki) degraded.push("Wikipedia is off");
|
||||
else {
|
||||
const todo = cands.filter((c) => !resolved.has(c) && !(c.kind === "forced" && c.handle));
|
||||
const variants = [...new Set(todo.flatMap((c) => c.variants))];
|
||||
lookedUp = variants.length;
|
||||
const found = new Map<string, LookupItem>();
|
||||
for (const item of await wiki.lookup(variants, opts)) found.set(item.input, item);
|
||||
if ([...found.values()].some((i) => i.status === "unavailable")) degraded.push("Wikipedia did not answer for some phrases");
|
||||
const disamb: { c: Candidate; title: string }[] = [];
|
||||
const misses: Candidate[] = [];
|
||||
for (const c of todo) {
|
||||
const item = c.variants.map((v) => found.get(v)).find((i) => i?.status === "found");
|
||||
if (item?.status !== "found") {
|
||||
if (c.words > 1 && (c.kind !== "noun") && c.variants.every((v) => found.get(v)?.status === "missing")) misses.push(c);
|
||||
continue;
|
||||
}
|
||||
if (item.disambiguation) {
|
||||
disamb.push({ c, title: item.title });
|
||||
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 }));
|
||||
}
|
||||
// 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);
|
||||
disamb.sort((a, b) => worth(b.c) - worth(a.c));
|
||||
let senseBudget = t.maxSenses;
|
||||
for (const { c, title: page } of disamb) {
|
||||
if (!ctxVec) break;
|
||||
if (c.kind !== "forced") {
|
||||
if (senseBudget <= 0 || worth(c) < 1) continue;
|
||||
senseBudget--;
|
||||
}
|
||||
const r = await wiki.senses(page, opts);
|
||||
if (!r.ok || !r.value.length) continue;
|
||||
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);
|
||||
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,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// A multi-word miss may be a case problem ("Church-Turing thesis"): one title search.
|
||||
let searchBudget = t.maxSearches;
|
||||
misses.sort((a, b) => worth(b) - worth(a));
|
||||
for (const c of misses) {
|
||||
if (c.kind !== "forced") {
|
||||
if (searchBudget <= 0) break;
|
||||
searchBudget--;
|
||||
}
|
||||
const r = await wiki.suggest(c.text, 5, opts);
|
||||
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 }));
|
||||
}
|
||||
// Fit for every article hit that has none yet.
|
||||
if (ctxVec) {
|
||||
const need = hits.filter((h) => h.source !== "library" && h.target.kind === "wiki" && h.fit === null);
|
||||
const scored = await this.fit(ctxVec, need.map((h) => ({ title: h.title, description: h.description })), false);
|
||||
if (scored) need.forEach((h, i) => (h.fit = scored[i].fit));
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Meaning: sections of other documents 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 })) ?? [];
|
||||
for (const hit of near) {
|
||||
if (hit.score < t.relatedAt) continue;
|
||||
const m = snap.nodes[hit.id as NodeId];
|
||||
const mKey = phraseKey(m.title);
|
||||
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";
|
||||
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}`)}` });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. One target per phrase (library before meaning before Wikipedia), judged.
|
||||
const order: Record<Source, number> = { forced: 0, library: 1, meaning: 2, wikipedia: 3 };
|
||||
const best = new Map<Candidate, Hit>();
|
||||
for (const h of hits) {
|
||||
const cur = best.get(h.c);
|
||||
if (!cur || order[h.source] < order[cur.source]) best.set(h.c, h);
|
||||
}
|
||||
const judged = [...best.values()]
|
||||
.map((h) => ({ h, j: judge(h, t) }))
|
||||
.filter(({ h, j }) => {
|
||||
if (j.tier) return true;
|
||||
if (h.c.kind === "forced") unresolved.push(h.c.text);
|
||||
return false;
|
||||
});
|
||||
for (const c of cands) if (c.kind === "forced" && !best.has(c) && !unresolved.includes(c.text)) unresolved.push(c.text);
|
||||
|
||||
// 6. Density: first mention of each target and phrase, no overlaps, a few per paragraph.
|
||||
judged.sort((a, b) => a.h.c.start - b.h.c.start);
|
||||
const firstOf = new Map<string, number>();
|
||||
for (const x of judged) {
|
||||
for (const k of [refKey(x.h.target), `p:${x.h.c.key}`]) if (!firstOf.has(k)) firstOf.set(k, x.h.c.start);
|
||||
}
|
||||
const firsts = judged.filter((x) => x.h.c.kind === "forced" || (firstOf.get(refKey(x.h.target)) === x.h.c.start && firstOf.get(`p:${x.h.c.key}`) === x.h.c.start && !linkedHere.has(refKey(x.h.target))));
|
||||
const rankOf = (x: (typeof firsts)[number]) => (x.h.c.kind === "forced" ? 2 : x.j.tier === "auto" ? 1 : 0);
|
||||
firsts.sort((a, b) => rankOf(b) - rankOf(a) || b.j.score - a.j.score || b.h.c.words - a.h.c.words);
|
||||
const paras = paragraphs(text);
|
||||
const paraOf = (at: number) => paras.findIndex(([s, e]) => at >= s && at < e);
|
||||
const perPara = new Map<number, number>();
|
||||
for (const [s, , linked] of occupied) if (linked) perPara.set(paraOf(s), (perPara.get(paraOf(s)) ?? 0) + 1);
|
||||
const chosen: typeof firsts = [];
|
||||
const used = new Set<string>();
|
||||
for (const x of firsts) {
|
||||
const r: Range = [x.h.c.start, x.h.c.end];
|
||||
if (chosen.some((y) => overlaps(r, [y.h.c.start, y.h.c.end]))) continue;
|
||||
const tk = refKey(x.h.target);
|
||||
if (used.has(tk)) continue;
|
||||
const p = paraOf(r[0]);
|
||||
if (x.h.c.kind !== "forced" && (perPara.get(p) ?? 0) >= t.perParagraph) continue;
|
||||
perPara.set(p, (perPara.get(p) ?? 0) + 1);
|
||||
used.add(tk);
|
||||
chosen.push(x);
|
||||
}
|
||||
// A word already linked inside a longer phrase here ("beryllium" beside "beryllium-8") is not linked again on its own.
|
||||
for (let i = chosen.length - 1; i >= 0; i--) {
|
||||
const x = chosen[i];
|
||||
if (x.h.c.kind !== "forced" && chosen.some((y) => y !== x && keyWords(y.h.c.key) > keyWords(x.h.c.key) && ` ${y.h.c.key} `.includes(` ${x.h.c.key} `))) chosen.splice(i, 1);
|
||||
}
|
||||
|
||||
if (input.trace) {
|
||||
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 } });
|
||||
}
|
||||
}
|
||||
const suggestions = chosen
|
||||
.sort((a, b) => a.h.c.start - b.h.c.start)
|
||||
.map(({ h, j }): Suggestion => ({
|
||||
id: digest(`${input.node}\u0000${h.c.start}\u0000${h.c.end}\u0000${refKey(h.target)}`),
|
||||
node: input.node,
|
||||
range: [h.c.start, h.c.end],
|
||||
quote: h.c.text,
|
||||
key: h.c.key,
|
||||
target: h.target,
|
||||
score: j.score,
|
||||
tier: j.tier!,
|
||||
why: j.why,
|
||||
source: h.source,
|
||||
title: h.title,
|
||||
description: h.description,
|
||||
kind: h.c.kind,
|
||||
}));
|
||||
return {
|
||||
node: input.node,
|
||||
suggestions,
|
||||
related,
|
||||
unresolved,
|
||||
degraded,
|
||||
stats: { candidates: cands.length, lookedUp, requests: (wiki?.requests ?? 0) - requests0, ms: Math.round(performance.now() - t0) },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Sections of other documents 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[] }> {
|
||||
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 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 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 { related, degraded: [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* The few sections a model writing at this node might link: hybrid search (text and meaning,
|
||||
* text alone without a model) on the node's text, the node itself and its line excluded.
|
||||
*/
|
||||
async nearby(node: NodeId, k = 5, given: Pick<ScanInput, "text" | "title" | "ancestors"> = {}): Promise<Nearby[]> {
|
||||
const snap = this.o.doc().snap();
|
||||
const n = snap.nodes[node];
|
||||
if (!n && given.text === undefined) return [];
|
||||
const exclude = new Set<NodeId>([node, ...(given.ancestors ?? (n ? ancestorsOf(snap, node) : [])), ...(n ? descendants(snap, node) : [])]);
|
||||
const query = `${given.title ?? n?.title ?? ""}\n${plain(given.text ?? n!.body)}`.slice(0, 1000);
|
||||
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 : "" };
|
||||
});
|
||||
}
|
||||
|
||||
private calibrate(cos: number): number {
|
||||
const [a, b] = this.tuning.fit;
|
||||
return Math.round(Math.max(0, Math.min(1, a + b * cos)) * 1000) / 1000;
|
||||
}
|
||||
|
||||
/** Fit of each "Title: description" to the context, in the order given or (sorted) best first. */
|
||||
private async fit(ctx: Float32Array, items: { title: string; description: string | null }[], sorted = true) {
|
||||
if (!items.length) return [];
|
||||
const texts = items.map((i) => ({ id: `${i.title}\u0000${i.description ?? ""}`, text: `${i.title}: ${i.description ?? ""}` }));
|
||||
if (this.senseVectors.size > 20_000) this.senseVectors = new VectorIndex(null, this.o.embedder);
|
||||
const rep = await this.senseVectors.upsert(texts, false);
|
||||
if (rep.degraded) return null;
|
||||
const out = items.map((i, k) => ({ ...i, fit: this.calibrate(dot(ctx, this.senseVectors.vectorOf(texts[k].id)!)) }));
|
||||
return sorted ? out.sort((a, b) => b.fit - a.fit) : out;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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));
|
||||
const both = [...new Set(tokenize(b))].filter((w) => mine.has(w)).slice(0, 3);
|
||||
return both.length ? `; both mention ${both.join(", ")}` : "";
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* How common an English word is, from a bundled frequency list (words.txt: 20,000 words, most
|
||||
* frequent first). A word's rank is its line; a word not in the list ranks after all of them.
|
||||
* Rarity is the cheapest link-worthiness signal there is: "octopus" (rank ~9,700) and "cephalopod"
|
||||
* (absent) are worth a link where "brain" (~900) is not.
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
let ranks: Map<string, number> | null = null;
|
||||
|
||||
function load(): Map<string, number> {
|
||||
if (ranks) return ranks;
|
||||
ranks = new Map();
|
||||
const file = fileURLToPath(new URL("./words.txt", import.meta.url));
|
||||
let i = 0;
|
||||
for (const line of readFileSync(file, "utf8").split("\n")) {
|
||||
if (!line || line.startsWith("#")) continue;
|
||||
ranks.set(line, ++i);
|
||||
}
|
||||
return ranks;
|
||||
}
|
||||
|
||||
/** Ranks run 1 (most common) to 20,000; a word not in the list gets this. */
|
||||
export const UNLISTED = 50_000;
|
||||
|
||||
/** The rank of a word (case-insensitive), with a plural or possessive read as its singular. */
|
||||
export function rank(word: string): number {
|
||||
const w = word.toLowerCase().replace(/['’]s$/, "");
|
||||
const r = load();
|
||||
const direct = r.get(w);
|
||||
if (direct !== undefined) return direct;
|
||||
const s = singular(w);
|
||||
return s !== w ? (r.get(s) ?? UNLISTED) : UNLISTED;
|
||||
}
|
||||
|
||||
/** Whether a lower-case word is in the list at all. */
|
||||
export const listed = (word: string) => load().has(word.toLowerCase());
|
||||
|
||||
/** A light English singular: enough for "cephalopods", "octopuses", "theories", "boxes". */
|
||||
export function singular(w: string): string {
|
||||
if (w.length <= 3) return w;
|
||||
if (/ies$/i.test(w) && w.length > 4) return w.slice(0, -3) + (w[w.length - 1] === "S" ? "Y" : "y");
|
||||
if (/(uses|sses|shes|ches|xes|zes)$/i.test(w)) return w.slice(0, -2);
|
||||
if (/s$/i.test(w) && !/(ss|us|is|ous)$/i.test(w) && !/ies$/i.test(w)) return w.slice(0, -1);
|
||||
return w;
|
||||
}
|
||||
+20003
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user