A model reviewer for found links, with every determination kept

server/links/review.ts asks the configured model to judge the scanner's candidates
as a careful Wikipedia editor would: up to 60 a call, grouped by document and
section, each with its sentence, its section's path, the target's title and
description (and first sentence when cached) and, for a library target, how it
stands to the section. No tools; structured verdicts with a one-line reason. The
prompt names the scanner's known blind spots.

The pending store keeps verdicts, a person's decisions and when an approved link
was handed out, keyed by phrase and target, so a candidate found again is never
judged twice and a rejected phrase is not looked for again. Its file keeps the
old shape; old entries read as pending.

The scan route reviews what it found when asked (at most 2 calls) and hands the
approved links back to be made; jobs review as they go within IE_REVIEW_CALLS
(default 50) calls, with the count in their state. No model, a failed call or
the cap leaves the rest pending, with the reason. The mock reviewer links names
and terms, not single lower-case words, and fails on 'mockfail'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
thalladaandClaude Opus 5.5 committed 2026-11-16 16:39:15 -05:00
1 parent 428f7290ee
commit 46b48d3497
10 files changed
+889 -93

No files matched your search

+49 -7
View File
@@ -2,16 +2,19 @@
* 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).
* request, which is most of what keeps a bulk pass affordable. A job started with `review` also has
* the model reviewer judge what it finds as it goes (review.ts: many proposals a call, within a
* budget of calls for the job). A job only fills the pending list and records verdicts; making the
* links is up to a page (the browser makes the approved ones itself, as one commit by "reviewer",
* so `u` can take them 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";
import { BATCH, JOB_CALLS, type Reviewer } from "./review";
import type { Linker, Suggestion } from "./scan";
export interface JobState {
id: string;
@@ -32,6 +35,8 @@ export interface JobState {
/** The client is spacing requests for want of a contact (IE_WIKI_CONTACT). */
slow: boolean;
message?: string;
/** The reviewer's part, for a job started with review: verdicts so far, calls made of those allowed, and why it stopped early if it did. */
review?: { approved: number; rejected: number; left: number; calls: number; max: number; fallback?: string };
}
/** Nodes whose lookups are asked together. */
@@ -49,11 +54,14 @@ export class Jobs {
index: NodeIndex;
pending: PendingStore;
announce: (state: JobState) => void;
reviewer?: Reviewer;
/** Calls a job's review may make (IE_REVIEW_CALLS). */
reviewCalls?: number;
},
) {}
/** 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 {
start(scope: "doc" | "library", nodes: NodeId[], title: string, doc?: NodeId, review = false): JobState {
this.cancel();
const wiki = this.o.wiki();
const spacing = wiki?.spacingMs ?? 0;
@@ -71,6 +79,7 @@ export class Jobs {
startedAt: Date.now(),
etaSec: null,
slow: spacing > 2000,
...(review && this.o.reviewer ? { review: { approved: 0, rejected: 0, left: 0, calls: 0, max: this.o.reviewCalls ?? JOB_CALLS } } : {}),
};
// First estimate: the uncached phrases in batches of 50, plus about one sense or search for every other node.
const snap = this.o.snap();
@@ -98,6 +107,32 @@ export class Jobs {
const spacing = wiki?.spacingMs ?? 0;
const r0 = wiki?.requests ?? 0;
let lastAnnounce = 0;
// What waits for the reviewer: gathered across chunks, sent when a call's worth is ready.
let queue: Suggestion[] = [];
const review = async (all: boolean) => {
const r = state.review;
if (!r || !this.o.reviewer) return;
if (r.fallback) {
r.left += queue.length;
queue = [];
return;
}
while (queue.length >= BATCH || (all && queue.length)) {
const batch = queue.splice(0, BATCH);
const budget = { calls: r.calls, max: r.max };
const rep = await this.o.reviewer.review(batch, budget, signal);
r.calls = budget.calls;
r.approved += rep.approved;
r.rejected += rep.rejected;
r.left += rep.left;
if (rep.fallback) {
r.fallback = rep.fallback;
r.left += queue.length;
queue = [];
}
this.o.announce(state);
}
};
try {
await this.o.index.refresh();
for (let i = 0; i < nodes.length; i += CHUNK) {
@@ -110,11 +145,15 @@ export class Jobs {
}
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);
const n = this.o.snap().nodes[id];
if (n) {
// Declined phrases and those the reviewer rejected are not looked for again.
const rejected = [...(n.nolink ?? []), ...this.o.pending.rejectedKeys(id)];
const r = await this.o.linker().scan({ node: id, priority: "bulk", rejected }, signal);
if (signal.aborted) return;
this.o.pending.put(id, r.suggestions);
for (const s of r.suggestions) state[s.tier]++;
if (state.review) queue.push(...this.o.pending.undecided(this.o.snap(), [id]));
}
state.done++;
state.requests = (wiki?.requests ?? 0) - r0;
@@ -129,7 +168,10 @@ export class Jobs {
this.o.announce(state);
}
}
await review(false);
}
await review(true);
if (signal.aborted) return;
state.state = "done";
state.etaSec = 0;
} catch (e) {
+142 -40
View File
@@ -1,21 +1,35 @@
/**
* 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.
* Suggestions and what was decided about them. 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, but what was decided is kept: the model
* reviewer's verdict (link or not, and why), a person's decision, and when an approved link was
* handed to a page to be made. A suggestion found again by a later scan (the same phrase and target
* in the node, wherever its words now are) keeps its determination, so it is never reviewed twice;
* one the scan no longer finds (it was linked, or rejected and so skipped) stays as a record.
*
* Entries are checked against the library whenever they are read, because the text moves on: one
* whose words are gone is not listed, and one whose words moved is listed where they now are. The
* file is the one earlier versions wrote; their entries carry no determinations and read as pending.
*/
import { existsSync, readFileSync } from "node:fs";
import { targetKey } from "../../src/core/links";
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";
import type { Suggestion, Verdict } from "./scan";
interface Entry {
at: number;
suggestions: Suggestion[];
}
/** What a determination is about: a phrase in a node and where it would link. Offsets move; this does not. */
export const decisionKey = (s: Pick<Suggestion, "key" | "target">) => `${s.key}\u0000${targetKey(s.target)}`;
/** Records kept per node beyond what the last scan found, oldest dropped first. */
const KEEP = 200;
export class PendingStore {
private byNode = new Map<string, Entry>();
private timer: ReturnType<typeof setTimeout> | null = null;
@@ -24,39 +38,49 @@ export class PendingStore {
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);
for (const [k, v] of Object.entries(data)) if (v && Array.isArray(v.suggestions)) 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 });
/**
* What a scan of this node found. It replaces what was pending; determinations carry over to the
* same phrase and target found again, and decided entries the scan did not find are kept.
*/
put(node: NodeId, found: Suggestion[]) {
const old = this.byNode.get(node)?.suggestions ?? [];
const was = new Map(old.map((s) => [decisionKey(s), s]));
const out: Suggestion[] = found.map((s) => {
const o = was.get(decisionKey(s));
return o ? { ...s, ...carried(o) } : s;
});
const seen = new Set(out.map(decisionKey));
const kept = old.filter((o) => !seen.has(decisionKey(o)) && (o.review || o.decided));
out.push(...kept.slice(Math.max(0, kept.length - KEEP)));
if (out.length) this.byNode.set(node, { at: Date.now(), suggestions: out });
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();
/** Everything stored for a node, as stored. */
of(node: NodeId): Suggestion[] {
return this.byNode.get(node)?.suggestions ?? [];
}
/** Every suggestion still valid against the library, optionally for some nodes only. */
list(snap: Snap, nodes?: Set<NodeId>): Suggestion[] {
/**
* Suggestions under some nodes (all, by default). Pending ones only: still valid against the
* library (words there, not linked, not declined) and not rejected by the reviewer. With `all`,
* every entry whose words are still in its node, whatever was decided: what a page needs to
* list them.
*/
list(snap: Snap, nodes?: Set<NodeId>, all = false): 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);
const live = all ? placed(snap, s) : open(s) ? check(snap, s) : null;
if (live) out.push(live);
}
}
@@ -64,19 +88,85 @@ export class PendingStore {
}
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;
const s = this.find(id);
return s ? (check(snap, s) ?? undefined) : undefined;
}
/** Still valid, and nobody has judged them: what the reviewer is to see. */
undecided(snap: Snap, nodes: Iterable<NodeId>): Suggestion[] {
const out: Suggestion[] = [];
for (const id of nodes) {
for (const s of this.of(id)) {
const live = !s.review && !s.decided ? check(snap, s) : null;
if (live) out.push(live);
}
}
return out;
}
/** Record the reviewer's verdict on a suggestion. */
review(id: string, verdict: Verdict) {
const s = this.find(id);
if (s) s.review = verdict;
this.saveSoon();
}
/** Record a person's decision on these suggestions. Returns how many were found. */
decide(ids: Iterable<string>, link: boolean, by: string): number {
let n = 0;
for (const id of ids) {
const s = this.find(id);
if (!s) continue;
s.decided = { link, by, at: Date.now() };
n++;
}
if (n) this.saveSoon();
return n;
}
/**
* The links the reviewer approved that no page has made yet, under some nodes, marked as handed
* out: the page that asked makes them (its own commit, so `u` takes them back), and no other page
* makes them again.
*/
claim(snap: Snap, nodes?: Iterable<NodeId>): Suggestion[] {
const live: Suggestion[] = [];
for (const id of nodes ?? (this.byNode.keys() as Iterable<NodeId>)) for (const s of this.of(id)) if (check(snap, s)) live.push(s);
return this.handOut(live);
}
/** Of these stored entries, the approved links no page has made yet, marked as handed out (as `claim`). */
handOut(list: Suggestion[]): Suggestion[] {
const out: Suggestion[] = [];
for (const s of list) {
if (!s.review?.link || s.decided || s.applied) continue;
s.applied = Date.now();
out.push({ ...s });
}
if (out.length) this.saveSoon();
return out;
}
/** Phrases the reviewer rejected in a node (and no person has linked since): the scanner skips them. */
rejectedKeys(node: NodeId): string[] {
return [...new Set(this.of(node).filter((s) => s.review && !s.review.link && !s.decided?.link).map((s) => s.key))];
}
/** Pending suggestions, by the default list's reckoning, without checking them against the library. */
get size() {
let n = 0;
for (const e of this.byNode.values()) n += e.suggestions.length;
for (const e of this.byNode.values()) n += e.suggestions.filter(open).length;
return n;
}
private find(id: string): Suggestion | undefined {
for (const e of this.byNode.values()) {
const s = e.suggestions.find((x) => x.id === id);
if (s) return s;
}
return undefined;
}
private saveSoon() {
if (!this.file || this.timer) return;
this.timer = setTimeout(() => {
@@ -96,21 +186,33 @@ export class PendingStore {
}
}
/** A suggestion as it applies to the library now, or null if it no longer does. */
function check(snap: Snap, s: Suggestion): Suggestion | null {
/** The determinations of a stored suggestion, to carry onto the same one found again. */
function carried(s: Suggestion): Partial<Suggestion> {
return { ...(s.review ? { review: s.review } : {}), ...(s.decided ? { decided: s.decided } : {}), ...(s.applied ? { applied: s.applied } : {}) };
}
/** Not yet settled: no person has decided, and the reviewer has not rejected it. */
const open = (s: Suggestion) => !s.decided && s.review?.link !== false;
/** A suggestion with its words where they now are in its node, or null if they are gone. */
function placed(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];
}
if (n.body.slice(s.range[0], s.range[1]) === s.quote) return s;
const at = n.body.indexOf(s.quote);
return at < 0 ? null : { ...s, range: [at, at + s.quote.length] };
}
/** A suggestion as it applies to the library now (placed, not declined, not under a link), or null if it no longer does. */
function check(snap: Snap, s: Suggestion): Suggestion | null {
const n = snap.nodes[s.node];
if (!n || n.nolink?.includes(s.key)) return null;
const p = placed(snap, s);
if (!p) return null;
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;
if (note.anchors.some((a) => overlaps([a.start, a.end], p.range))) return null;
}
return range === s.range ? s : { ...s, range };
return p;
}
+249
View File
@@ -0,0 +1,249 @@
/**
* The link reviewer: the configured model judges what the scanner proposed, as a careful
* Wikipedia editor would, and its verdicts (link or not, with a one-line reason) are kept in the
* pending store. It is given no tools: each call is one structured reply of verdicts.
*
* Cost. Proposals are reviewed many to a call (BATCH), grouped by document and section, each with
* just what it takes to judge it: its sentence, the section's title and path, the target's title,
* description and (when the cache has it) first sentence, and, for a library target, how it stands
* to the section. Anything judged before is never sent again. Each caller gives a budget of calls;
* when it is spent, or a call fails, or there is no model, what is left stays pending for a person,
* and the report says why. Only phrases and titles ever go to Wikipedia; the text goes only to the
* model, as it does when the model writes.
*/
import { ownerSection } from "../../src/core/links";
import { ancestors, docOf, documents, label, notesOf, sections, type NodeId, type Snap } from "../../src/core/model";
import type { Ref } from "../../src/core/ref";
import { clip, plain, sentences } from "../../src/core/text";
import type { LinkVerdicts, LLM } from "../../src/llm/types";
import type { WikiClient } from "../wiki";
import type { PendingStore } from "./pending";
import type { Suggestion } from "./scan";
/** Proposals per call. */
export const BATCH = 60;
/** Calls a background job may make, unless IE_REVIEW_CALLS says otherwise. */
export const JOB_CALLS = 50;
/** Calls the scan after one edit may make. */
export const SCAN_CALLS = 2;
/** Calls made and calls allowed, shared by every review in one job. */
export interface Budget {
calls: number;
max: number;
}
export interface ReviewReport {
approved: number;
rejected: number;
calls: number;
/** Proposals left unreviewed. */
left: number;
/** Why some were left: no model, the budget spent, a failed call. */
fallback?: string;
}
export const REVIEW_SYSTEM = `You review proposed links in a personal library of documents. A scanner has proposed linking phrases in the text to Wikipedia articles or to other sections of the library. Decide, for each proposal, whether a reader of this document would be glad of the link, as a careful Wikipedia editor applying the Manual of Style on linking would. A link is worth making only when it helps; when unsure, do not link. Expect to reject most proposals.
Reject a proposal when:
- the phrase is an everyday word, or a thing so famous that every reader knows it (a country, a major city, a common animal or material, an ordinary idea such as energy, water or the brain, a household name mentioned in passing);
- the target is a different sense of the phrase than the text means, or a different person, place or thing with the same name;
- the phrase is a fragment of a longer name or term in the text (a surname out of a full name, one word of a technical term), or the target is about the fragment alone;
- the same thing is already linked in this section, or earlier in the document (listed as "Already linked"), or by another proposal before it in this list: link a thing once, at its first mention that matters;
- a library target is this section's own subsection, parent or sibling (its relation is given): the outline already joins them;
- a library target matches the phrase only by its title, and the text does not mean what that section is about;
- the phrase is inside a verbatim quotation of the request or prompt the document was written from (instructions addressed to an assistant): such text stays as it was written;
- the target is a list, a disambiguation page, a name page, or an article about a film, album, band, company or other namesake.
Approve a proposal when the phrase names a specific concept, result, work, person, organism, place or event that the text means and that a curious reader may well want to look up: a technical term, a named theorem or process, a figure the passage discusses, or a library section elsewhere that treats the phrase's own subject in more depth.
The scanner's tier ("sure" or "unsure") is a weak hint only. Give a verdict for every proposal, by its id, each with a reason of at most twelve words that a person can read in a list.`;
/**
* What a reviewer needs about one suggestion, besides the suggestion: where it is and what is
* around it. `given` is the node's text and title as a page sent them, which may be newer than the
* server's copy (or the node may not have reached the server yet).
*/
export function describe(snap: Snap, s: Suggestion, given?: Given) {
const n = snap.nodes[s.node];
const body = given?.node === s.node && given.text !== undefined ? given.text : (n?.body ?? "");
const d = n ? docOf(snap, s.node) : (given?.doc ?? null);
const sent = sentences(body).find(([a, b]) => s.range[0] >= a && s.range[0] < b) ?? [0, body.length];
const path: string[] = [];
for (let x: NodeId | null = s.node; x && x !== d && snap.nodes[x]; x = snap.nodes[x].parent) path.unshift(label(snap, x));
if (!n) path.push(given?.title || "a new section");
return {
...s,
nodeTitle: n ? label(snap, s.node) : given?.title || "a new section",
document: d ? snap.nodes[d].title : null,
docSlug: d ? snap.nodes[d].slug ?? null : null,
path: path.join(" › "),
sentence: clip(plain(body.slice(sent[0], sent[1])).trim(), 400),
};
}
/** A node as the page that asked for its scan sent it. */
export interface Given {
node: NodeId;
text?: string;
title?: string;
doc?: NodeId | null;
}
/** How a library target stands to the section a phrase is in. */
function relation(snap: Snap, from: NodeId, target: NodeId): string {
if (!snap.nodes[from]) return "elsewhere in the library";
const sec = ownerSection(snap, from);
const t = snap.nodes[target];
if (!t) return "a section that is gone";
if (t.parent === sec) return "a subsection of this section";
if (snap.nodes[sec]?.parent === target) return "this section's parent";
if (ancestors(snap, sec).includes(target)) return "an ancestor of this section";
if (t.parent && t.parent === snap.nodes[sec]?.parent) return "a sibling of this section";
const d = docOf(snap, target);
if (d && d === docOf(snap, sec)) return "elsewhere in this document";
return d ? `in another document, “${snap.nodes[d].title}”` : "elsewhere in the library";
}
const firstSentence = (text: string) => {
const t = plain(text).trim();
const [r] = sentences(t);
return clip(r ? t.slice(r[0], r[1]).trim() : t, 220);
};
/** The titles a node's links go to. */
const linkedTitles = (snap: Snap, id: NodeId): string[] =>
notesOf(snap, id).flatMap((c) => {
const r = snap.nodes[c].ref;
return r ? [targetTitle(snap, r)] : [];
});
const targetTitle = (snap: Snap, r: Ref) => (r.kind === "wiki" ? r.title : r.kind === "url" ? (r.title ?? r.url) : r.id && snap.nodes[r.id] ? label(snap, r.id) : (r.path ?? []).join(" › ") || "a note");
/** Everything already linked in a document, in reading order, each title once. */
function linkedInDoc(snap: Snap, doc: NodeId): string[] {
const out = new Set<string>();
const visit = (id: NodeId) => {
for (const t of linkedTitles(snap, id)) out.add(t);
for (const c of sections(snap, id)) visit(c);
};
visit(doc);
return [...out];
}
export class Reviewer {
constructor(
private o: {
llm: () => LLM | null;
wiki: () => WikiClient | null;
pending: PendingStore;
snap: () => Snap;
},
) {}
/** Whether there is a model to ask. */
get available() {
return !!this.o.llm();
}
/**
* Review these suggestions (already known to be undecided), in batches, within the budget.
* Verdicts go into the pending store as they come. Throws only if the signal aborts.
*/
async review(list: Suggestion[], budget: Budget, signal?: AbortSignal, given?: Given): Promise<ReviewReport> {
const report: ReviewReport = { approved: 0, rejected: 0, calls: 0, left: list.length };
if (!list.length) return report;
const llm = this.o.llm();
if (!llm) return { ...report, fallback: "no model is configured" };
// By document, then in reading order, so a call sees a document's proposals together.
const snap = this.o.snap();
const order = new Map<NodeId, number>();
let i = 0;
for (const d of documents(snap)) for (const id of [d, ...descendantsInOrder(snap, d)]) order.set(id, i++);
const sorted = [...list].sort((a, b) => (order.get(a.node) ?? 1e9) - (order.get(b.node) ?? 1e9) || a.range[0] - b.range[0]);
for (let at = 0; at < sorted.length; at += BATCH) {
if (budget.calls >= budget.max) return { ...report, fallback: `the reviewer's limit of ${budget.max} model call${budget.max === 1 ? "" : "s"} was reached` };
const batch = sorted.slice(at, at + BATCH);
const req = await this.request(batch, given);
budget.calls++;
report.calls++;
let reply: LinkVerdicts;
try {
reply = await llm.json<LinkVerdicts>(req.json, signal);
} catch (e) {
if (signal?.aborted) throw e;
return { ...report, fallback: `the reviewer failed: ${clip((e as Error)?.message ?? String(e), 200)}` };
}
signal?.throwIfAborted();
const now = Date.now();
for (const v of Array.isArray(reply?.verdicts) ? reply.verdicts : []) {
const s = req.ids.get(String(v.id));
if (!s || typeof v.link !== "boolean") continue;
req.ids.delete(String(v.id));
this.o.pending.review(s.id, { link: v.link, reason: clip(String(v.reason ?? "").trim(), 160), at: now });
if (v.link) report.approved++;
else report.rejected++;
report.left--;
}
}
return report;
}
/** The call for one batch: the document and section headings, and a line per proposal. */
private async request(batch: Suggestion[], given?: Given) {
const snap = this.o.snap();
const wiki = this.o.wiki();
const ids = new Map<string, Suggestion>();
const lines: string[] = [];
const proposals: { id: string; tier: string; quote: string; sentence: string }[] = [];
let doc: NodeId | null | undefined;
let node: NodeId | undefined;
for (const [k, s] of batch.entries()) {
const id = `p${k + 1}`;
ids.set(id, s);
const where = describe(snap, s, given);
const d = snap.nodes[s.node] ? docOf(snap, s.node) : (given?.doc ?? null);
if (d !== doc) {
doc = d;
node = undefined;
const already = d ? linkedInDoc(snap, d) : [];
lines.push("", `# Document: ${d ? snap.nodes[d].title : "(none)"}`, `Already linked in this document: ${already.length ? already.slice(0, 60).join("; ") : "nothing"}`);
}
if (s.node !== node) {
node = s.node;
const here = snap.nodes[s.node] ? linkedTitles(snap, s.node) : [];
lines.push("", `## Section: ${where.path || where.nodeTitle}`, `Already linked in this section: ${here.length ? here.join("; ") : "nothing"}`);
}
let target: string;
if (s.target.kind === "node" && s.target.id) {
const t = snap.nodes[s.target.id];
target = `library section “${t ? label(snap, s.target.id) : s.title}”, ${relation(snap, s.node, s.target.id)}${t?.body.trim() ? `. It begins: ${firstSentence(t.body)}` : ""}`;
} else if (s.target.kind === "wiki") {
const sum = wiki ? await wiki.summary(s.target.title, { cacheOnly: true }) : null;
const first = sum?.ok ? firstSentence(sum.value.extract) : "";
target = `Wikipedia article “${s.target.title}”${s.description ? ` (${s.description})` : ""}${first ? `. It begins: ${first}` : ""}`;
} else target = `web page ${s.title}`;
lines.push(`- ${id}: “${s.quote}” → ${target} [scanner: ${s.tier === "auto" ? "sure" : "unsure"}]`, ` in: “${where.sentence}”`);
proposals.push({ id, tier: s.tier, quote: s.quote, sentence: where.sentence });
}
const prompt = `Proposals (${batch.length}):\n${lines.join("\n").trim()}\n\nGive a verdict for each of the ${batch.length} proposals.`;
return {
ids,
json: { task: "review-links", schema: "review" as const, system: REVIEW_SYSTEM, context: "Proposed links, grouped by document and section.", prompt, vars: { proposals: JSON.stringify(proposals) }, effort: "low" as const, maxTokens: 8000 },
};
}
}
/** A node's sections and notes, depth first, in reading order. */
function descendantsInOrder(snap: Snap, id: NodeId): NodeId[] {
const out: NodeId[] = [];
const visit = (x: NodeId) => {
for (const c of snap.nodes[x].children) {
out.push(c);
visit(c);
}
};
visit(id);
return out;
}
+49 -35
View File
@@ -1,17 +1,24 @@
/**
* 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/scan { node, text?, title?, doc?, docTitle?, ancestors?, occupied?, rejected?, forced?, within?, save?, review? }
* → { suggestions, related, unresolved, degraded, stats, entries?, apply?, review? }; save (default
* true) records the suggestions as pending for the node, and `entries` is then everything
* stored for it, with determinations. review ("all", or "unmarked" to leave out [[marks]],
* which a person typed) has the model reviewer judge what is undecided; `apply` is then the
* approved links handed to the caller to make, and `review` the reviewer's report
* GET /api/links/pending ?doc=<slug|id>&node=<id>&tier=auto|suggest&limit=&offset=&all=1&claim=1
* → { total, suggestions: [{ …, nodeTitle, document, docSlug, path, sentence }], apply? };
* all=1 lists every entry whatever was decided, with its determinations; claim=1 hands
* out the approved links no page has made yet (in `apply`), to be made by the caller
* POST /api/links/accept { ids, author? } → applied with applyLinks as one commit by "linker"
* POST /api/links/reject { ids, author? } → the phrases recorded in each node's `nolink` (one commit)
* POST /api/links/decide { ids, link, by } → a person's decision, made in their own replica, recorded
* GET /api/links/related ?node=<id> → { related, degraded }; or POST { node, text, title, doc, docTitle, ancestors }
* GET /api/links/nearby ?node=<id>&k=5 → { nearby: [{ handle, title, document }] } (hybrid search on the node);
* or POST { node, text, title, ancestors }
* POST /api/links/jobs { scope: "doc" | "library", doc? } → the job's state; it runs in the background
* POST /api/links/jobs { scope: "doc" | "library", doc?, review? } → the job's state; it runs in the background
* (with review, the model reviewer judges what it finds, within IE_REVIEW_CALLS calls)
* GET /api/links/jobs → { job } (the current or last one)
* DELETE /api/links/jobs → cancel the running job
* GET /api/links/status → embeddings, the node index, the pending count, the job
@@ -20,13 +27,13 @@
*/
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 { descendants, docOf, documents, findDoc, isLibraryRoot, type Doc, type NodeId, type Op, type Snap } from "../../src/core/model";
import type { Embedder } from "../embed";
import { HttpError, abortOnClose, readJson as readBody, sendJson as send } from "../util";
import type { Jobs } from "./jobs";
import type { NodeIndex } from "./nodeIndex";
import type { PendingStore } from "./pending";
import { SCAN_CALLS, describe, type Reviewer } from "./review";
import type { Linker, ScanInput, Suggestion } from "./scan";
interface LinkDeps {
@@ -36,6 +43,7 @@ interface LinkDeps {
pending: PendingStore;
jobs: Jobs;
embedder: Embedder | null;
reviewer?: Reviewer;
/** A server-side write: saved soon and announced to every replica. */
wrote: () => void;
}
@@ -54,23 +62,6 @@ function docArg(snap: Snap, v: string | null): NodeId | 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);
@@ -87,13 +78,27 @@ export function linkRoutes(deps: LinkDeps) {
try {
const snap = deps.main().snap();
if (route === "scan" && method === "POST") {
const input = await readJson<ScanInput & { save?: boolean }>(req);
const input = await readJson<ScanInput & { save?: boolean; review?: "all" | "unmarked" }>(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;
const signal = abortOnClose(res);
// What the reviewer rejected here is not looked for again, any more than what a person declined.
const reviewed = deps.pending.rejectedKeys(input.node);
const rejected = reviewed.length ? [...(input.rejected ?? snap.nodes[input.node]?.nolink ?? []), ...reviewed] : input.rejected;
const r = await deps.linker().scan({ ...input, rejected, trace: undefined }, signal);
if (input.save === false) return send(res, 200, r), true;
deps.pending.put(input.node, r.suggestions);
if (!input.review) return send(res, 200, { ...r, entries: deps.pending.of(input.node) }), true;
// The reviewer sees what this scan found that nobody has judged yet (a person's [[marks]] are
// theirs, not its), within the scan's budget. Found against the text the caller sent, which
// may be ahead of the server's copy.
const found = new Set(r.suggestions.map((s) => s.id));
const mine = deps.pending.of(input.node).filter((s) => found.has(s.id));
const todo = mine.filter((s) => !s.review && !s.decided && (input.review === "all" || s.kind !== "forced"));
const report = deps.reviewer ? await deps.reviewer.review(todo, { calls: 0, max: SCAN_CALLS }, signal, { node: input.node, text: input.text, title: input.title, doc: input.doc }) : { approved: 0, rejected: 0, calls: 0, left: todo.length, fallback: "no reviewer" };
const apply = deps.pending.handOut(mine);
return send(res, 200, { ...r, entries: deps.pending.of(input.node), apply, review: report }), true;
}
if (route === "pending" && method === "GET") {
const docId = docArg(snap, url.searchParams.get("doc"));
@@ -101,13 +106,15 @@ export function linkRoutes(deps: LinkDeps) {
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);
const all = url.searchParams.get("all") === "1";
const apply = url.searchParams.get("claim") === "1" ? deps.pending.claim(snap, scope ?? scopeNodes(snap, null)) : undefined;
let list = deps.pending.list(snap, scope, all);
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;
return send(res, 200, { total: list.length, suggestions: list.slice(offset, offset + limit).map((s) => describe(snap, s)), ...(apply ? { apply } : {}) }), true;
}
if ((route === "accept" || route === "reject") && method === "POST") {
const input = await readJson<{ ids?: unknown; author?: unknown }>(req);
@@ -118,7 +125,7 @@ export function linkRoutes(deps: LinkDeps) {
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));
deps.pending.decide(found.map((s) => s.id), true, author);
if (r.created.length || r.merged.length) deps.wrote();
return send(res, 200, { accepted: found.length, unknown: input.ids.length - found.length, ...r }), true;
}
@@ -129,9 +136,15 @@ export function linkRoutes(deps: LinkDeps) {
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));
deps.pending.decide(found.map((s) => s.id), false, author);
return send(res, 200, { rejected: found.length, unknown: input.ids.length - found.length }), true;
}
if (route === "decide" && method === "POST") {
const input = await readJson<{ ids?: unknown; link?: unknown; by?: unknown }>(req);
if (!Array.isArray(input.ids) || !input.ids.every((x) => typeof x === "string") || typeof input.link !== "boolean") throw new Bad("give { ids: [...], link: true | false, by }");
const by = typeof input.by === "string" && input.by.trim() ? input.by.trim().slice(0, 100) : "someone";
return send(res, 200, { decided: deps.pending.decide(input.ids as string[], input.link, by) }), true;
}
if (route === "related" && (method === "GET" || method === "POST")) {
// GET ?node=<id> for a node the server has; POST { node, text, title, doc, docTitle, ancestors } for one it may not have yet.
const input = method === "POST" ? await readJson<ScanInput>(req) : { node: url.searchParams.get("node") as NodeId };
@@ -149,13 +162,13 @@ export function linkRoutes(deps: LinkDeps) {
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);
const input = await readJson<{ scope?: string; doc?: string; review?: boolean }>(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;
return send(res, 202, { job: deps.jobs.start(input.scope, nodes, title, docId ?? undefined, input.review === true) }), true;
}
}
if (route === "status" && method === "GET") {
@@ -163,6 +176,7 @@ export function linkRoutes(deps: LinkDeps) {
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,
reviewer: deps.reviewer?.available ?? false,
job: deps.jobs.current,
}), true;
}
+29 -8
View File
@@ -19,10 +19,10 @@
*/
import { inArticles } from "../../src/core/article";
import { docOf, notesOf, sections, ancestors as ancestorsOf, descendants, type Doc, type NodeId, type Snap } from "../../src/core/model";
import { nodeRef } from "../../src/core/links";
import { nodeRef, targetKey } 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 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";
@@ -50,6 +50,28 @@ export interface Suggestion {
title: string;
description: string | null;
kind: Kind;
/**
* Determinations, kept with the suggestion in the pending store (server/links/pending.ts): the
* model reviewer's verdict, a person's decision, and when an approved link was handed out to be
* made. A scan never sets these; the store carries them from one scan of the node to the next.
*/
review?: Verdict;
decided?: Decision;
applied?: number;
}
/** The model reviewer's verdict on a suggestion, with its one-line reason. */
export interface Verdict {
link: boolean;
reason: string;
at: number;
}
/** A person's decision on a suggestion: linked or declined, by whom. */
export interface Decision {
link: boolean;
by: string;
at: number;
}
export interface Related {
@@ -333,7 +355,6 @@ function docTexts(snap: Snap, doc: NodeId): { id: NodeId; text: string }[] {
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 {
@@ -373,7 +394,7 @@ export class Linker {
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) : []);
const linkedHere = new Set(n ? notesOf(snap, input.node).map((c) => snap.nodes[c].ref).filter((r): r is Ref => !!r).map(targetKey) : []);
// Centrality: in the document's title, or in many of its sections.
const doc = docId && snap.nodes[docId] ? docTexts(snap, docId) : [];
@@ -541,9 +562,9 @@ export class Linker {
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);
for (const k of [targetKey(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 firsts = judged.filter((x) => x.h.c.kind === "forced" || (firstOf.get(targetKey(x.h.target)) === x.h.c.start && firstOf.get(`p:${x.h.c.key}`) === x.h.c.start && !linkedHere.has(targetKey(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);
@@ -555,7 +576,7 @@ export class Linker {
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);
const tk = targetKey(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;
@@ -579,7 +600,7 @@ export class Linker {
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)}`),
id: digest(`${input.node}\u0000${h.c.start}\u0000${h.c.end}\u0000${targetKey(h.target)}`),
node: input.node,
range: [h.c.start, h.c.end],
quote: h.c.text,