diff --git a/server/index.ts b/server/index.ts index a8379f2..00d14bd 100644 --- a/server/index.ts +++ b/server/index.ts @@ -34,6 +34,7 @@ import { embedder } from "./embed"; import { Jobs } from "./links/jobs"; import { NodeIndex } from "./links/nodeIndex"; import { PendingStore } from "./links/pending"; +import { JOB_CALLS, Reviewer } from "./links/review"; import { linkRoutes } from "./links/routes"; import { Linker } from "./links/scan"; @@ -127,6 +128,9 @@ let linker: Linker | null = null; const getLinker = () => (linker ??= new Linker({ doc: () => store.main, wiki: wikiClient, embedder: embed, index: nodeIndex })); const pending = new PendingStore(join(DATA, "links", "pending.json")); process.on("exit", () => pending.flush()); +// The link reviewer asks the configured model (no tools, structured verdicts); IE_REVIEW_CALLS caps a background job's calls. +const reviewer = new Reviewer({ llm: () => llm, wiki: wikiClient, pending, snap: () => store.main.snap() }); +const reviewCalls = Math.max(1, Number(process.env.IE_REVIEW_CALLS) || JOB_CALLS); const jobs = new Jobs({ snap: () => store.main.snap(), linker: getLinker, @@ -134,8 +138,10 @@ const jobs = new Jobs({ index: nodeIndex, pending, announce: (state) => announce({ linkJob: state }), + reviewer, + reviewCalls, }); -const handleLinks = linkRoutes({ main: () => store.main, linker: getLinker, index: nodeIndex, pending, jobs, embedder: embed, wrote: () => wrote("main") }); +const handleLinks = linkRoutes({ main: () => store.main, linker: getLinker, index: nodeIndex, pending, jobs, embedder: embed, reviewer, wrote: () => wrote("main") }); // ---- live notifications ---- diff --git a/server/links/jobs.ts b/server/links/jobs.ts index 3ed8d8c..e79fccc 100644 --- a/server/links/jobs.ts +++ b/server/links/jobs.ts @@ -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) { diff --git a/server/links/pending.ts b/server/links/pending.ts index a840852..aa3f3d2 100644 --- a/server/links/pending.ts +++ b/server/links/pending.ts @@ -1,21 +1,35 @@ /** - * Suggestions waiting for a writer. Derived data, so they live on the server under - * /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 + * /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) => `${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(); private timer: ReturnType | null = null; @@ -24,39 +38,49 @@ export class PendingStore { if (file && existsSync(file)) { try { const data = JSON.parse(readFileSync(file, "utf8")) as Record; - 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) { - 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): 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, 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): 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, 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): Suggestion[] { + const live: Suggestion[] = []; + for (const id of nodes ?? (this.byNode.keys() as Iterable)) 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 { + 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; } diff --git a/server/links/review.ts b/server/links/review.ts new file mode 100644 index 0000000..204f0aa --- /dev/null +++ b/server/links/review.ts @@ -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(); + 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 { + 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(); + 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(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(); + 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; +} diff --git a/server/links/routes.ts b/server/links/routes.ts index e6eff8d..5bea849 100644 --- a/server/links/routes.ts +++ b/server/links/routes.ts @@ -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=&node=&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=&node=&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= → { related, degraded }; or POST { node, text, title, doc, docTitle, ancestors } * GET /api/links/nearby ?node=&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(req); + const input = await readJson(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= 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(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; } diff --git a/server/links/scan.ts b/server/links/scan.ts index 5b44404..ebdbe93 100644 --- a/server/links/scan.ts +++ b/server/links/scan.ts @@ -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(); 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, diff --git a/server/schemas.ts b/server/schemas.ts index 377bb70..425ca05 100644 --- a/server/schemas.ts +++ b/server/schemas.ts @@ -8,4 +8,13 @@ export const schemas: Record = { contradictions: z.object({ contradictions: z.array(z.object({ node: z.string(), other: z.string(), explanation: z.string(), text: z.string() })), }), + review: z.object({ + verdicts: z.array( + z.object({ + id: z.string().describe("The proposal's id, as given."), + link: z.boolean().describe("true: make the link; false: leave the words unlinked."), + reason: z.string().describe("Why, in at most twelve words, for a person reading a list."), + }), + ), + }), }; diff --git a/src/llm/mock.ts b/src/llm/mock.ts index 5d90428..580c8ce 100644 --- a/src/llm/mock.ts +++ b/src/llm/mock.ts @@ -4,7 +4,7 @@ * It reads the structured `vars` of a request rather than the prose prompt. */ import { clip } from "../core/text"; -import type { CascadeDecision, Contradictions, JsonReq, LLM, Req, Resolutions, Turn, TurnReq } from "./types"; +import type { CascadeDecision, Contradictions, JsonReq, LinkVerdicts, LLM, Req, Resolutions, Turn, TurnReq } from "./types"; import { webOf } from "./web"; const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); @@ -47,9 +47,22 @@ function mockJson(req: JsonReq): unknown { } case "contradictions": return { contradictions: [] } satisfies Contradictions; + case "review": { + // The link reviewer, so a test knows each verdict in advance (mockLinks). A proposal whose + // words or sentence say "mockfail" makes the whole call fail, as a real one may (a limit + // reached, the network gone). + const props: { id: string; quote: string; sentence: string }[] = JSON.parse(v.proposals ?? "[]"); + if (props.some((p) => /mockfail/i.test(`${p.quote} ${p.sentence}`))) throw new Error("mock reviewer: the call failed"); + return { + verdicts: props.map((p) => ({ id: p.id, link: mockLinks(p.quote), reason: mockLinks(p.quote) ? "mock: a name or a term a reader may look up" : "mock: one ordinary word needs no link" })), + } satisfies LinkVerdicts; + } } } +/** The mock link reviewer's rule: a name or a term of several words is linked; a single lower-case word is not. */ +export const mockLinks = (quote: string) => /[A-Z0-9]/.test(quote) || /\s/.test(quote.trim()); + // ---- web research, without a network ---- /** What the mock web search finds, for any query. Fixed, so a test can name the URLs. */ diff --git a/src/llm/types.ts b/src/llm/types.ts index bdea87f..a31b1c7 100644 --- a/src/llm/types.ts +++ b/src/llm/types.ts @@ -19,7 +19,7 @@ export interface Req { maxTokens?: number; } -export type SchemaName = "cascade" | "resolve" | "contradictions"; +export type SchemaName = "cascade" | "resolve" | "contradictions" | "review"; export interface JsonReq extends Req { schema: SchemaName; @@ -89,3 +89,8 @@ export interface Resolutions { export interface Contradictions { contradictions: { node: string; other: string; explanation: string; text: string }[]; } + +/** The link reviewer's verdicts (server/links/review.ts): one per proposal, by its id. */ +export interface LinkVerdicts { + verdicts: { id: string; link: boolean; reason: string }[]; +} diff --git a/tests/review.test.ts b/tests/review.test.ts new file mode 100644 index 0000000..795cf0f --- /dev/null +++ b/tests/review.test.ts @@ -0,0 +1,335 @@ +/** + * The link reviewer and what it decides (server/links/review.ts, pending.ts): determinations kept + * across scans, a person's decisions, approved links handed out once, batching many proposals to a + * call, skipping what was judged before, falling back (no model, a failed call, the call budget), + * a pending file from before determinations, background jobs that review as they go, and the scan + * route in review mode. Offline: the mock model (whose verdicts follow the scanner's tier), the mock + * Wikipedia and the hashed-words embedder. + */ +import { mkdtempSync, writeFileSync } from "node:fs"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { Doc, type NodeId } from "../src/core/model"; +import { mockLLM, mockLinks } from "../src/llm/mock"; +import type { JsonReq, LLM } from "../src/llm/types"; +import { Embedder, fakeLoader } from "../server/embed"; +import { Jobs, type JobState } from "../server/links/jobs"; +import { NodeIndex } from "../server/links/nodeIndex"; +import { PendingStore } from "../server/links/pending"; +import { BATCH, REVIEW_SYSTEM, Reviewer } from "../server/links/review"; +import { linkRoutes, scopeNodes } from "../server/links/routes"; +import { Linker, type Suggestion } from "../server/links/scan"; +import { WikiClient } from "../server/wiki"; +import { makeMockWikiFetch } from "../server/wikiMock"; + +const W = (title: string) => ({ kind: "wiki" as const, title, lang: "en" }); + +function library() { + const doc = Doc.library("tester"); + const lib = doc.snap().root; + const { created } = doc.apply( + [ + { op: "create", parent: lib, title: "Octopus minds", body: "An essay on minds that evolved apart from ours." }, + { op: "create", parent: "$0" as NodeId, title: "Arms", body: "The cephalopod arm tastes what it touches. Fred Hoyle never studied one." }, + { op: "create", parent: lib, title: "Stars", body: "The cephalopod met Fred Hoyle.\n\nHe spoke of the Hoyle state of carbon-12 and of the lambda calculus." }, + ], + "Base", + { actor: "llm" }, + ); + const [minds, arms, stars] = created; + return { doc, lib, minds, arms, stars }; +} + +function setup(doc: Doc) { + const embedder = new Embedder({ model: "fake", loader: fakeLoader }); + const wiki = new WikiClient({ fetch: makeMockWikiFetch(0), spacingMs: 0, persist: false, offlineHoldMs: 0 }); + const index = new NodeIndex(() => doc, { file: null, embedder, delayMs: 0 }); + const linker = new Linker({ doc: () => doc, wiki: () => wiki, embedder, index }); + return { linker, index, wiki, embedder }; +} + +/** The mock model, counting its review calls and what each was sent; `fail` makes every call throw. */ +function counting(o: { fail?: boolean; delay?: number } = {}) { + const inner = mockLLM({ delay: o.delay }); + const calls: JsonReq[] = []; + const llm: LLM = { + ...inner, + async json(req: JsonReq, signal?: AbortSignal) { + calls.push(req); + if (o.fail) throw new Error("rate limited"); + return inner.json(req, signal); + }, + }; + return { llm, calls }; +} + +/** A made-up suggestion in a node. */ +const sugg = (node: NodeId, quote: string, at: number, more: Partial = {}): Suggestion => ({ + id: `${node}:${quote}:${at}`, node, range: [at, at + quote.length], quote, key: quote.toLowerCase(), target: W(quote), score: 0.7, tier: "suggest", why: "", source: "wikipedia", title: quote, description: null, kind: "term", ...more, +}); + +describe("the determination store", () => { + it("keeps verdicts and decisions across scans of a node, and records what a scan no longer finds", () => { + const { doc, arms } = library(); + const p = new PendingStore(null); + const body = doc.snap().nodes[arms].body; + const ceph = sugg(arms, "cephalopod", body.indexOf("cephalopod")); + const hoyle = sugg(arms, "Fred Hoyle", body.indexOf("Fred Hoyle"), { tier: "auto" }); + p.put(arms, [ceph, hoyle]); + p.review(ceph.id, { link: false, reason: "too general", at: 1 }); + p.review(hoyle.id, { link: true, reason: "a named person", at: 1 }); + // A later scan finds Fred Hoyle again (at new offsets, so a new id) and skips the rejected phrase. + doc.apply([{ op: "update", id: arms, body: `Indeed. ${body}` }], "Edit"); + const moved = sugg(arms, "Fred Hoyle", body.indexOf("Fred Hoyle") + 8, { tier: "auto" }); + p.put(arms, [moved]); + const stored = p.of(arms); + expect(stored.find((s) => s.quote === "Fred Hoyle")).toMatchObject({ id: moved.id, review: { link: true, reason: "a named person" } }); + expect(stored.find((s) => s.quote === "cephalopod")?.review).toMatchObject({ link: false }); + expect(p.rejectedKeys(arms)).toEqual(["cephalopod"]); + // Nothing judged is offered to the reviewer again; the default list leaves out what the reviewer rejected. + expect(p.undecided(doc.snap(), [arms])).toEqual([]); + expect(p.list(doc.snap()).map((s) => s.quote)).toEqual(["Fred Hoyle"]); + expect(p.list(doc.snap(), undefined, true).map((s) => s.quote).sort()).toEqual(["Fred Hoyle", "cephalopod"]); + // A person overrules the reviewer: the phrase is no longer skipped. + expect(p.decide([stored.find((s) => s.quote === "cephalopod")!.id], true, "tyler")).toBe(1); + expect(p.rejectedKeys(arms)).toEqual([]); + }); + + it("hands an approved link out once, to whichever page asks first", () => { + const { doc, arms } = library(); + const p = new PendingStore(null); + const body = doc.snap().nodes[arms].body; + const hoyle = sugg(arms, "Fred Hoyle", body.indexOf("Fred Hoyle")); + p.put(arms, [hoyle]); + expect(p.claim(doc.snap())).toEqual([]); + p.review(hoyle.id, { link: true, reason: "yes", at: 1 }); + expect(p.claim(doc.snap(), [arms]).map((s) => s.quote)).toEqual(["Fred Hoyle"]); + expect(p.claim(doc.snap(), [arms])).toEqual([]); + // Found again by a later scan, it is still marked as handed out. + p.put(arms, [hoyle]); + expect(p.claim(doc.snap())).toEqual([]); + }); + + it("reads a pending file written before determinations existed: its suggestions are pending, its declines stay declined", () => { + const { doc, arms } = library(); + doc.apply([{ op: "update", id: arms, nolink: ["fred hoyle"] }], "Decline"); + const body = doc.snap().nodes[arms].body; + const dir = mkdtempSync(join(tmpdir(), "ie-pending-")); + const file = join(dir, "pending.json"); + // The shape earlier versions wrote: { node: { at, suggestions } }, no verdicts. + const old = { [arms]: { at: 1, suggestions: [sugg(arms, "cephalopod", body.indexOf("cephalopod")), sugg(arms, "Fred Hoyle", body.indexOf("Fred Hoyle"))].map(({ review, decided, applied, ...s }) => s) } }; + writeFileSync(file, JSON.stringify(old)); + const p = new PendingStore(file); + expect(p.list(doc.snap()).map((s) => s.quote)).toEqual(["cephalopod"]); + expect(p.undecided(doc.snap(), [arms]).map((s) => s.quote)).toEqual(["cephalopod"]); + // Listed in full, the declined one is there too (the page shows it as declined, by the node's nolink). + expect(p.list(doc.snap(), undefined, true)).toHaveLength(2); + p.flush(); + expect(new PendingStore(file).of(arms)).toHaveLength(2); + }); +}); + +describe("the reviewer", () => { + /** n made-up proposals spread over the library's sections, on words that are there. */ + function proposals(doc: Doc, ids: NodeId[], n: number) { + const p = new PendingStore(null); + const out: Suggestion[] = []; + for (let i = 0; i < n; i++) { + const node = ids[i % ids.length]; + const body = doc.snap().nodes[node].body; + const quote = [["minds", "An essay"], ["cephalopod", "Fred Hoyle"]][Math.min(1, i % ids.length)][i % 2]; + out.push(sugg(node, quote, body.indexOf(quote), { id: `s${i}`, key: `k${i}`, target: W(`T${i}`) })); + } + for (const id of ids) p.put(id, out.filter((s) => s.node === id)); + return { p, list: out }; + } + + it("judges many proposals a call, grouped by document and section, with what it takes to judge each", async () => { + const { doc, minds, arms, stars } = library(); + const { p, list } = proposals(doc, [minds, arms, stars], BATCH * 2 + 10); + const { llm, calls } = counting(); + const r = new Reviewer({ llm: () => llm, wiki: () => null, pending: p, snap: () => doc.snap() }); + const budget = { calls: 0, max: 10 }; + const rep = await r.review(list, budget); + expect(calls).toHaveLength(3); + expect(budget.calls).toBe(3); + const yes = list.filter((s) => mockLinks(s.quote)).length; + expect(yes).toBeGreaterThan(0); + expect(yes).toBeLessThan(list.length); + expect(rep).toMatchObject({ calls: 3, left: 0, approved: yes, rejected: list.length - yes }); + expect(rep.fallback).toBeUndefined(); + const first = calls[0]; + expect(first).toMatchObject({ schema: "review", system: REVIEW_SYSTEM, effort: "low" }); + expect(first.prompt).toContain("# Document: Octopus minds"); + expect(first.prompt).toContain("## Section: Arms"); + expect(first.prompt).toContain("“cephalopod” → Wikipedia article “T4” [scanner: unsure]"); + expect(first.prompt).toContain("in: “The cephalopod arm tastes what it touches.”"); + expect(first.prompt).toContain("Already linked in this section"); + // Each verdict is stored with its reason; nothing is left for a second pass. + expect(p.of(arms).every((s) => s.review && s.review.reason.startsWith("mock:"))).toBe(true); + expect(p.undecided(doc.snap(), [minds, arms, stars])).toEqual([]); + }); + + it("says how a library target stands to the section, so a parent never links its own child", async () => { + const { doc, minds, arms } = library(); + const p = new PendingStore(null); + const body = doc.snap().nodes[minds].body; + const s = sugg(minds, "minds", body.indexOf("minds"), { target: { kind: "node", id: arms }, source: "library", title: "Arms" }); + p.put(minds, [s]); + const { llm, calls } = counting(); + await new Reviewer({ llm: () => llm, wiki: () => null, pending: p, snap: () => doc.snap() }).review([s], { calls: 0, max: 1 }); + expect(calls[0].prompt).toContain("library section “Arms”, a subsection of this section"); + expect(calls[0].prompt).toContain("It begins: The cephalopod arm tastes what it touches."); + }); + + it("falls back, leaving everything pending and saying why: no model, a failed call, the budget spent", async () => { + const { doc, minds, arms, stars } = library(); + const { p, list } = proposals(doc, [minds, arms, stars], BATCH + 5); + const none = await new Reviewer({ llm: () => null, wiki: () => null, pending: p, snap: () => doc.snap() }).review(list, { calls: 0, max: 5 }); + expect(none).toMatchObject({ calls: 0, left: list.length, fallback: "no model is configured" }); + const failing = counting({ fail: true }); + const failed = await new Reviewer({ llm: () => failing.llm, wiki: () => null, pending: p, snap: () => doc.snap() }).review(list, { calls: 0, max: 5 }); + expect(failed).toMatchObject({ calls: 1, left: list.length, approved: 0 }); + expect(failed.fallback).toContain("the reviewer failed: rate limited"); + expect(p.undecided(doc.snap(), [minds, arms, stars])).toHaveLength(list.length); + // The mock's own failure: a proposal that says mockfail. + const mock = await new Reviewer({ llm: () => mockLLM(), wiki: () => null, pending: p, snap: () => doc.snap() }).review([{ ...list[0], quote: "mockfail" }], { calls: 0, max: 5 }); + expect(mock.fallback).toContain("mock reviewer: the call failed"); + // A budget of one call reviews the first batch only. + const ok = counting(); + const capped = await new Reviewer({ llm: () => ok.llm, wiki: () => null, pending: p, snap: () => doc.snap() }).review(list, { calls: 0, max: 1 }); + expect(capped).toMatchObject({ calls: 1, left: 5 }); + expect(capped.fallback).toContain("limit of 1 model call was reached"); + }); +}); + +describe("background jobs with review", () => { + it("review what they find, many proposals a call, report it, and never ask about the same thing twice", async () => { + const doc = Doc.library("t"); + const ops = Array.from({ length: 40 }, (_, i) => ({ op: "create" as const, parent: doc.snap().root, title: `Doc ${i}`, body: `Fred Hoyle number ${i} met a cephalopod and the lambda calculus.` })); + doc.apply(ops, "x"); + const { linker, index, wiki } = setup(doc); + const pending = new PendingStore(null); + const { llm, calls } = counting(); + const reviewer = new Reviewer({ llm: () => llm, wiki: () => wiki, pending, snap: () => doc.snap() }); + const seen: JobState[] = []; + const jobs = new Jobs({ snap: () => doc.snap(), linker: () => linker, wiki: () => wiki, index, pending, announce: (s) => seen.push(structuredClone(s)), reviewer, reviewCalls: 5 }); + const nodes = scopeNodes(doc.snap(), null); + const job = jobs.start("library", nodes, "the library", undefined, true); + while (job.state === "running") await new Promise((r) => setTimeout(r, 5)); + expect(job.state).toBe("done"); + const found = job.auto + job.suggest; + expect(found).toBeGreaterThan(BATCH); + expect(job.review).toMatchObject({ max: 5, left: 0 }); + // Many proposals a call: far fewer calls than proposals. + expect(job.review!.calls).toBe(calls.length); + expect(calls.length).toBe(Math.ceil(found / BATCH)); + expect(job.review!.approved + job.review!.rejected).toBe(found); + expect(seen.some((s) => s.state === "running" && (s.review?.calls ?? 0) > 0)).toBe(true); + // Run again: everything was judged, so the model is not asked at all. + const again = jobs.start("library", nodes, "the library", undefined, true); + while (again.state === "running") await new Promise((r) => setTimeout(r, 5)); + expect(again.review).toMatchObject({ calls: 0, approved: 0, rejected: 0 }); + expect(calls.length).toBe(Math.ceil(found / BATCH)); + // A job without review asks nothing. + const plain = jobs.start("library", nodes, "the library"); + while (plain.state === "running") await new Promise((r) => setTimeout(r, 5)); + expect(plain.review).toBeUndefined(); + }); + + it("stop reviewing when cancelled, keeping the verdicts so far", async () => { + const doc = Doc.library("t"); + doc.apply(Array.from({ length: 40 }, (_, i) => ({ op: "create" as const, parent: doc.snap().root, title: `D ${i}`, body: `Fred Hoyle ${i} met a cephalopod and the lambda calculus.` })), "x"); + const { linker, index, wiki } = setup(doc); + const pending = new PendingStore(null); + const slow = counting({ delay: 40 }); + const seen: JobState[] = []; + const jobs = new Jobs({ snap: () => doc.snap(), linker: () => linker, wiki: () => wiki, index, pending, announce: (s) => seen.push(structuredClone(s)), reviewer: new Reviewer({ llm: () => slow.llm, wiki: () => wiki, pending, snap: () => doc.snap() }), reviewCalls: 10 }); + const job = jobs.start("library", scopeNodes(doc.snap(), null), "the library", undefined, true); + while (slow.calls.length < 2) await new Promise((r) => setTimeout(r, 2)); + expect(jobs.cancel()).toBe(true); + await new Promise((r) => setTimeout(r, 120)); + expect(job.state).toBe("cancelled"); + expect(seen[seen.length - 1].state).toBe("cancelled"); + expect(slow.calls).toHaveLength(2); + // The first call's verdicts are kept; the rest wait. + expect(job.review!.approved + job.review!.rejected).toBe(BATCH); + expect(pending.undecided(doc.snap(), scopeNodes(doc.snap(), null)).length).toBeGreaterThan(0); + }); + + it("stop at the job's cap, leaving the rest pending, and say so", async () => { + const doc = Doc.library("t"); + doc.apply(Array.from({ length: 40 }, (_, i) => ({ op: "create" as const, parent: doc.snap().root, title: `D ${i}`, body: `Fred Hoyle ${i} met a cephalopod and the lambda calculus.` })), "x"); + const { linker, index, wiki } = setup(doc); + const pending = new PendingStore(null); + const { llm } = counting(); + const jobs = new Jobs({ snap: () => doc.snap(), linker: () => linker, wiki: () => wiki, index, pending, announce: () => {}, reviewer: new Reviewer({ llm: () => llm, wiki: () => wiki, pending, snap: () => doc.snap() }), reviewCalls: 1 }); + const job = jobs.start("library", scopeNodes(doc.snap(), null), "the library", undefined, true); + while (job.state === "running") await new Promise((r) => setTimeout(r, 5)); + expect(job.review).toMatchObject({ calls: 1, approved: expect.any(Number) }); + expect(job.review!.left).toBe(job.auto + job.suggest - BATCH); + expect(job.review!.fallback).toContain("limit of 1 model call"); + expect(pending.list(doc.snap())).toHaveLength(job.review!.left + job.review!.approved); + }); +}); + +describe("the scan route in review mode", () => { + let server: Server; + let base: string; + let ids: ReturnType; + let calls: JsonReq[]; + beforeAll(async () => { + ids = library(); + const doc = ids.doc; + const { linker, index, wiki } = setup(doc); + const pending = new PendingStore(null); + const c = counting(); + calls = c.calls; + const reviewer = new Reviewer({ llm: () => c.llm, wiki: () => wiki, pending, snap: () => doc.snap() }); + const jobs = new Jobs({ snap: () => doc.snap(), linker: () => linker, wiki: () => wiki, index, pending, announce: () => {}, reviewer }); + const handle = linkRoutes({ main: () => doc, linker: () => linker, index, pending, jobs, embedder: null, reviewer, wrote: () => {} }); + server = createServer(async (req, res) => { + if (!(await handle(req, res, new URL(req.url ?? "/", "http://x")))) (res.writeHead(418), res.end()); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + }); + afterAll(() => server.close()); + const post = (path: string, body: unknown) => fetch(`${base}/api/links/${path}`, { method: "POST", body: JSON.stringify(body) }).then((r) => r.json()); + + it("reviews what a scan finds, hands out the approved links once, and never asks about them again", async () => { + const r = await post("scan", { node: ids.stars, review: "all" }); + expect(r.suggestions.length).toBeGreaterThan(1); + expect(r.review).toMatchObject({ calls: 1, left: 0 }); + expect(r.review.approved + r.review.rejected).toBe(r.suggestions.length); + expect(r.apply.map((s: Suggestion) => s.quote).sort()).toEqual(r.suggestions.filter((s: Suggestion) => mockLinks(s.quote)).map((s: Suggestion) => s.quote).sort()); + expect(r.entries.every((s: Suggestion) => s.review)).toBe(true); + // The same text scanned again: nothing new to judge, nothing handed out twice, and what was rejected is not looked for again. + const again = await post("scan", { node: ids.stars, review: "all" }); + expect(again.review).toMatchObject({ calls: 0, approved: 0, rejected: 0 }); + expect(again.apply).toEqual([]); + expect(calls).toHaveLength(1); + const rejected = r.entries.filter((s: Suggestion) => !s.review?.link).map((s: Suggestion) => s.quote); + expect(rejected).toEqual(["cephalopod"]); + for (const q of rejected) expect(again.suggestions.map((s: Suggestion) => s.quote)).not.toContain(q); + // The full list still shows them, with the reviewer's reasons. + const all = await (await fetch(`${base}/api/links/pending?node=${encodeURIComponent(ids.stars)}&all=1`)).json(); + expect(all.suggestions.filter((s: Suggestion) => s.review?.link === false).map((s: Suggestion) => s.quote).sort()).toEqual([...rejected].sort()); + }); + + it("records a person's decision, and leaves a person's own marks out of the review", async () => { + const all = await (await fetch(`${base}/api/links/pending?node=${encodeURIComponent(ids.stars)}&all=1`)).json(); + const one = all.suggestions.find((s: Suggestion) => s.review?.link === false); + expect(await post("decide", { ids: [one.id], link: true, by: "tyler" })).toEqual({ decided: 1 }); + const after = await (await fetch(`${base}/api/links/pending?node=${encodeURIComponent(ids.stars)}&all=1`)).json(); + expect(after.suggestions.find((s: Suggestion) => s.id === one.id).decided).toMatchObject({ link: true, by: "tyler" }); + expect((await post("decide", { ids: [one.id] })).error).toBeTruthy(); + const text = "A note on Fred Hoyle."; + const marked = await post("scan", { node: ids.arms, text, forced: [{ start: 10, end: 20, phrase: "Fred Hoyle" }], review: "unmarked" }); + expect(marked.suggestions.find((s: Suggestion) => s.kind === "forced")).toBeTruthy(); + expect(marked.entries.find((s: Suggestion) => s.kind === "forced").review).toBeUndefined(); + }); +});