Links: drop what the scanner computed or accepted for nobody

scan() also built a Related list that no caller reads (the page asks /links/related, which
related() answers); the `within` option was never sent; near() was only ever given a vector, so its
embed-the-text fallback and null answer could not happen. extract.ts and words.ts re-exported
phraseKey and singular from src/core/links, where they now come from directly. The suggestions
are unchanged.

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-17 16:10:45 -05:00
1 parent 7f6b9d8e77
commit 9f8245e6d7
6 files changed
+19 -37

No files matched your search

+3 -5
View File
@@ -9,10 +9,8 @@
* lookups per node bounded. * lookups per node bounded.
*/ */
import type { Mark } from "../../src/core/marks"; import type { Mark } from "../../src/core/marks";
import { phraseKey } from "../../src/core/links"; import { phraseKey, singular } from "../../src/core/links";
import { UNLISTED, listed, rank, singular } from "./words"; import { UNLISTED, listed, rank } from "./words";
export { phraseKey };
export type Kind = "forced" | "name" | "term" | "noun"; export type Kind = "forced" | "name" | "term" | "noun";
@@ -117,7 +115,7 @@ interface ExtractOptions {
exclude?: [number, number][]; exclude?: [number, number][];
/** Marked phrases ([[…]] already taken out): candidates whatever they look like. */ /** Marked phrases ([[…]] already taken out): candidates whatever they look like. */
forced?: Mark[]; forced?: Mark[];
/** Normalised phrases never to offer (the node's own title, its document's, rejected ones). */ /** Normalised phrases never to offer (the node's own title, rejected ones). */
skip?: Set<string>; skip?: Set<string>;
} }
+4 -7
View File
@@ -110,17 +110,14 @@ export class NodeIndex {
} }
/** /**
* Sections close in meaning to a text, from under other tops than `top`, best first. Excludes the * Sections close in meaning to a text's vector, from under other tops than `top`, best first.
* node, its ancestors and its descendants. Null if there is no model. * Excludes the node, its ancestors and its descendants.
*/ */
async near(text: string, o: { exclude: Set<NodeId>; top: NodeId | null; k?: number; snap: Snap; vector?: Float32Array | null }): Promise<Hit[] | null> { async near(vector: Float32Array, o: { exclude: Set<NodeId>; top: NodeId | null; k: number; snap: Snap }): Promise<Hit[]> {
const k = o.k ?? 8;
// Never built (a first start): build it now rather than answer from nothing. // Never built (a first start): build it now rather than answer from nothing.
if (!this.vectors.size && (this.all || this.running)) await this.refresh(); 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] && topOf(o.snap, id as NodeId) !== o.top; 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); return this.vectors.searchVector(vector, o.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. */ /** Text and meaning fused (BM25 alone without a model): for the model's "nearby" list. */
+3 -3
View File
@@ -1,8 +1,8 @@
/** /**
* HTTP routes for link discovery. Wired into server/index.ts before the 404. * HTTP routes for one library's link discovery, under /api/l/<id>/links/ (server/bundle.ts).
* *
* POST /api/links/scan { node, text?, title?, top?, topTitle?, ancestors?, occupied?, rejected?, forced?, within?, save?, review? } * POST /api/links/scan { node, text?, title?, top?, topTitle?, ancestors?, occupied?, rejected?, forced?, save?, review? }
* → { suggestions, related, unresolved, degraded, stats, entries?, apply?, review? }; save (default * → { suggestions, unresolved, degraded, stats, entries?, apply?, review? }; save (default
* true) records the suggestions as pending for the node, and `entries` is then everything * 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]], * 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 * which a person typed) has the model reviewer judge what is undecided; `apply` is then the
+6 -17
View File
@@ -22,14 +22,14 @@
*/ */
import { inArticles } from "../../src/core/article"; import { inArticles } from "../../src/core/article";
import { notesOf, sections, topOf, 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 { nodeRef, phraseKey, targetKey } from "../../src/core/links";
import type { Mark } from "../../src/core/marks"; import type { Mark } from "../../src/core/marks";
import type { Nearby } from "../../src/llm/prompts"; import type { Nearby } from "../../src/llm/prompts";
import type { Ref } from "../../src/core/ref"; import type { Ref } from "../../src/core/ref";
import { digest, overlaps, paragraphs, plain, type Range } from "../../src/core/text"; import { digest, overlaps, paragraphs, plain, type Range } from "../../src/core/text";
import { VectorIndex, dot, tokenize, type Embedder } from "../embed"; import { VectorIndex, dot, tokenize, type Embedder } from "../embed";
import type { CallOpts, LookupItem, WikiClient } from "../wiki"; import type { CallOpts, LookupItem, WikiClient } from "../wiki";
import { COMMON_RANK, extract, phraseKey, type Candidate, type Kind } from "./extract"; import { COMMON_RANK, extract, type Candidate, type Kind } from "./extract";
import type { NodeIndex } from "./nodeIndex"; import type { NodeIndex } from "./nodeIndex";
import { UNLISTED, rank } from "./words"; import { UNLISTED, rank } from "./words";
@@ -103,8 +103,6 @@ export interface ScanInput {
forced?: Mark[]; forced?: Mark[];
/** Wikipedia queue lane: "scan" (the default: after an edit, behind anything a person waits on) or "bulk" (a job). */ /** Wikipedia queue lane: "scan" (the default: after an edit, behind anything a person waits on) or "bulk" (a job). */
priority?: "interactive" | "bulk" | "scan"; 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. */ /** For evaluation: every phrase that resolved to something, with its judgement, is pushed here. */
trace?: TraceRow[]; trace?: TraceRow[];
} }
@@ -129,7 +127,6 @@ export interface TraceRow {
export interface ScanResult { export interface ScanResult {
node: NodeId; node: NodeId;
suggestions: Suggestion[]; suggestions: Suggestion[];
related: Related[];
/** Marked phrases that resolved to nothing. */ /** Marked phrases that resolved to nothing. */
unresolved: string[]; unresolved: string[];
/** What was not available, in words ("embeddings unavailable: matched by text only"). */ /** What was not available, in words ("embeddings unavailable: matched by text only"). */
@@ -397,7 +394,6 @@ export class Linker {
const skip = new Set([phraseKey(title), ...rejected].filter(Boolean)); const skip = new Set([phraseKey(title), ...rejected].filter(Boolean));
let cands = extract(text, { exclude, forced: input.forced, skip }); 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))); 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. // 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) : []); const linkedHere = new Set(n ? notesOf(snap, input.node).map((c) => snap.nodes[c].ref).filter((r): r is Ref => !!r).map(targetKey) : []);
@@ -525,24 +521,18 @@ export class Linker {
} }
// 4. Meaning: sections under other tops close to this node. // 4. Meaning: sections under other tops close to this node.
const related: Related[] = [];
if (ctxVec) { if (ctxVec) {
const exclude = new Set<NodeId>([...exceptSelf, ...(n ? descendants(snap, input.node) : [])]); const exclude = new Set<NodeId>([...exceptSelf, ...(n ? descendants(snap, input.node) : [])]);
const near = (await this.o.index.near(context, { exclude, top: topId, snap, vector: ctxVec, k: 8 })) ?? []; for (const hit of await this.o.index.near(ctxVec, { exclude, top: topId, snap, k: 8 })) {
for (const hit of near) {
if (hit.score < t.relatedAt) continue; if (hit.score < t.relatedAt) continue;
const m = snap.nodes[hit.id as NodeId]; const m = snap.nodes[hit.id as NodeId];
const mKey = phraseKey(m.title); const mKey = phraseKey(m.title);
const mRef = m.ref?.kind === "wiki" ? m.ref.title : null; 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. // 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 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 where = whereIs(snap, m.id); if (!namer) continue;
if (namer) { hits.push(hitOf(namer, nodeRef(snap, m.id), "meaning", `${m.title} (${whereIs(snap, m.id)})`, { fit: hit.score }));
hits.push(hitOf(namer, nodeRef(snap, m.id), "meaning", `${m.title} (${where})`, { fit: hit.score }));
resolved.add(namer); resolved.add(namer);
} else if (related.length < 5) {
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}`)}` });
}
} }
} }
@@ -621,7 +611,6 @@ export class Linker {
return { return {
node: input.node, node: input.node,
suggestions, suggestions,
related,
unresolved, unresolved,
degraded, degraded,
stats: { candidates: cands.length, lookedUp, requests: (wiki?.requests ?? 0) - requests0, ms: Math.round(performance.now() - t0) }, stats: { candidates: cands.length, lookedUp, requests: (wiki?.requests ?? 0) - requests0, ms: Math.round(performance.now() - t0) },
@@ -644,7 +633,7 @@ export class Linker {
if (!vec) return { related: [], degraded: ["embeddings unavailable: no Related list"] }; 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 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 exclude = new Set<NodeId>([node, ...(given.ancestors ?? (n ? ancestorsOf(snap, node) : [])), ...(n ? descendants(snap, node) : [])]);
const near = (await this.o.index.near(context, { exclude, top: topId, snap, vector: vec, k: k + linked.size + 3 })) ?? []; const near = await this.o.index.near(vec, { exclude, top: topId, snap, k: k + linked.size + 3 });
const related = near const related = near
.filter((h) => h.score >= this.tuning.relatedAt && !linked.has(h.id as NodeId)) .filter((h) => h.score >= this.tuning.relatedAt && !linked.has(h.id as NodeId))
.slice(0, k) .slice(0, k)
-2
View File
@@ -8,8 +8,6 @@ import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { singular } from "../../src/core/links"; import { singular } from "../../src/core/links";
export { singular };
let ranks: Map<string, number> | null = null; let ranks: Map<string, number> | null = null;
function load(): Map<string, number> { function load(): Map<string, number> {
+3 -3
View File
@@ -8,17 +8,17 @@ import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net"; import type { AddressInfo } from "node:net";
import { UndoManager } from "loro-crdt"; import { UndoManager } from "loro-crdt";
import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { applyLinks, linkIndex } from "../src/core/links"; import { applyLinks, linkIndex, phraseKey, singular } from "../src/core/links";
import { Doc, SYSTEM_ORIGIN, notesOf, type NodeId } from "../src/core/model"; import { Doc, SYSTEM_ORIGIN, notesOf, type NodeId } from "../src/core/model";
import { history, verifyHistory } from "../src/core/repo"; import { history, verifyHistory } from "../src/core/repo";
import { Embedder, fakeLoader, type Loader } from "../server/embed"; import { Embedder, fakeLoader, type Loader } from "../server/embed";
import { extract, phraseKey } from "../server/links/extract"; import { extract } from "../server/links/extract";
import { Jobs, type JobState } from "../server/links/jobs"; import { Jobs, type JobState } from "../server/links/jobs";
import { NodeIndex } from "../server/links/nodeIndex"; import { NodeIndex } from "../server/links/nodeIndex";
import { PendingStore } from "../server/links/pending"; import { PendingStore } from "../server/links/pending";
import { linkRoutes, scopeNodes } from "../server/links/routes"; import { linkRoutes, scopeNodes } from "../server/links/routes";
import { Linker, TUNING, judge, type ScanInput, type Tuning } from "../server/links/scan"; import { Linker, TUNING, judge, type ScanInput, type Tuning } from "../server/links/scan";
import { rank, singular } from "../server/links/words"; import { rank } from "../server/links/words";
import { WikiClient } from "../server/wiki"; import { WikiClient } from "../server/wiki";
import { makeMockWikiFetch } from "../server/wikiMock"; import { makeMockWikiFetch } from "../server/wikiMock";