Article nodes and annotation anchors in the library

A node per annotated Wikipedia article, created with its first annotation
under one container: a section of the library root flagged articles. It is
not a document (sections() and documents() skip it, it has no slug), its
nodes never go stale, the link scanner, the vector index, the title index
and the backlinks index leave it out, and a prompt about an annotation
carries its article's node rather than the whole container.

An annotation is an ordinary note under the article's node whose anchor is
a WikiAnchor (headings, exact words, context either side, revision) instead
of CRDT cursors. reanchor() finds it again in a later revision: its own
section, then anywhere, exactly, then tolerantly, never inside other words;
otherwise it is detached. Two replicas annotating a new article at once keep
both nodes; readers take annotations from all of them and write under the
first, so they read as one. The new fields hash only when set, so old
commits still verify. Property tests for re-anchoring, a convergence test,
and the tasks that write a note from an article's lead and section.

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-15 21:53:00 -05:00
1 parent 02e044af35
commit f63fc10dc0
8 files changed
+502 -18

No files matched your search

+3 -2
View File
@@ -5,6 +5,7 @@
* request that made the edit (a section whose text is unchanged is skipped by its hash). Without a
* model the index still holds the texts, so BM25 search works and "related" is text-only.
*/
import { inArticles } from "../../src/core/article";
import { Doc, docOf, isLibraryRoot, type NodeId, type Snap } from "../../src/core/model";
import { plain } from "../../src/core/text";
import { VectorIndex, type Embedder, type Hit, type HybridHit } from "../embed";
@@ -15,10 +16,10 @@ const nodeText = (snap: Snap, id: NodeId) => {
return `${n.title}\n${plain(n.body)}`.trim();
};
/** Sections (and documents) worth indexing: not the library root, not notes, and with some text. */
/** Sections (and documents) worth indexing: not the library root, not notes, not the Wikipedia container's, and with some text. */
const indexable = (snap: Snap, id: NodeId) => {
const n = snap.nodes[id];
return !!n && n.kind === "section" && !isLibraryRoot(snap, id) && (n.body.trim().length > 0 || n.title.trim().length > 0);
return !!n && n.kind === "section" && !isLibraryRoot(snap, id) && !inArticles(snap, id) && (n.body.trim().length > 0 || n.title.trim().length > 0);
};
interface IndexStatus {
+2 -1
View File
@@ -17,6 +17,7 @@
* strongest kept. See judge() for the rule. Only phrases and search queries go to Wikipedia;
* embeddings are local.
*/
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 type { Mark } from "../../src/core/marks";
@@ -304,7 +305,7 @@ function titleIndex(snap: Snap): Map<string, NodeId[]> {
ix = new Map();
for (const id in snap.nodes) {
const n = snap.nodes[id as NodeId];
if (n.kind !== "section" || !n.parent) continue;
if (n.kind !== "section" || !n.parent || inArticles(snap, n.id)) continue;
const key = titleKeyOf(n.title);
if (!key) continue;
const list = ix.get(key) ?? [];
+180
View File
@@ -0,0 +1,180 @@
/**
* Annotations on Wikipedia articles.
*
* An article is never copied into the library: it stays in the server's cache and is fetched as it
* is. What the library keeps is a node per annotated article, under one container (a section of
* the library root flagged `articles`, created with the first annotation), and under it the
* annotations: ordinary notes, written, edited, versioned and undone like any other, except that
* where a note is anchored by CRDT cursors into its parent's text, an annotation is anchored by a
* WikiAnchor into the article's: the section's headings, the exact words, a little text either
* side, and the revision it was made against. When the article is shown, each anchor is found
* again in the revision at hand (`reanchor`); one whose words are gone is shown as detached, never
* moved onto other words.
*
* Two replicas annotating the same new article at once each create its node (a tree CRDT cannot
* make two creates one node). Both are kept; every reader takes the article's annotations from all
* of its nodes, and writes new ones under the first in library order, which every replica agrees
* on. So they read as one, with nothing rewritten.
*/
import { docOf, type NodeId, type Op, type Snap } from "./model";
import { wikiTitle } from "./ref";
import type { Range } from "./text";
export interface WikiAnchor {
/** The headings down to the section the words are in; [] for the lead. */
sec: string[];
/** The words, exactly as they were. */
q: string;
/** Up to CONTEXT characters before and after them in the section, to tell repeats apart. */
pre: string;
post: string;
/** The revision of the article the anchor was made against. */
rev: number;
}
export const CONTEXT = 32;
export function makeAnchor(text: string, range: Range, sec: string[], rev: number): WikiAnchor {
return { sec, q: text.slice(range[0], range[1]), pre: text.slice(Math.max(0, range[0] - CONTEXT), range[0]), post: text.slice(range[1], range[1] + CONTEXT), rev };
}
/** A section's text, as the page shows it (see src/ui/articleText.ts), with its headings. */
export interface SectionText {
path: string[];
text: string;
}
/** Where an anchor is in the article as it now reads: a section (an index into the list given) and a range, or detached. */
export type Placed = { sec: number; range: Range } | { detached: true; sec: number | null };
const WORD = /[\p{L}\p{N}]/u;
/**
* Find an anchor's words again: in its own section first, then anywhere in the article, exactly;
* then the same tolerantly (ignoring case, punctuation and spacing), again its own section first.
* Among several matches the one whose surroundings best agree with the recorded ones wins. A match
* must start and end on word boundaries wherever the original did, so words are never matched
* inside other words. Nothing found: detached, with its section if that still exists.
*/
export function reanchor(a: WikiAnchor, secs: SectionText[]): Placed {
const home = homeOf(a.sec, secs);
const all = secs.map((_, i) => i);
const order = home >= 0 ? [home, ...all.filter((i) => i !== home)] : all;
const startsMid = WORD.test(a.pre.slice(-1)) && WORD.test(a.q[0] ?? "");
const endsMid = WORD.test(a.post[0] ?? "") && WORD.test(a.q.slice(-1));
const bounded = (t: string, s: number, e: number) => (startsMid || !WORD.test(t[s - 1] ?? "") || !WORD.test(t[s] ?? "")) && (endsMid || !WORD.test(t[e] ?? "") || !WORD.test(t[e - 1] ?? ""));
for (const tolerant of [false, true]) {
for (const i of order) {
const t = secs[i].text;
const hits = (tolerant ? tolerantHits(t, a.q) : exactHits(t, a.q)).filter(([s, e]) => bounded(t, s, e));
if (hits.length) return { sec: i, range: best(t, hits, a) };
}
}
return { detached: true, sec: home >= 0 ? home : null };
}
/** The section an anchor was made in: by its headings, else by its last heading alone. */
function homeOf(path: string[], secs: SectionText[]): number {
const key = JSON.stringify(path);
const exact = secs.findIndex((s) => JSON.stringify(s.path) === key);
if (exact >= 0 || !path.length) return exact;
const last = path[path.length - 1].toLowerCase();
return secs.findIndex((s) => s.path.length > 0 && s.path[s.path.length - 1].toLowerCase() === last);
}
function exactHits(text: string, q: string): Range[] {
const out: Range[] = [];
if (!q) return out;
for (let i = text.indexOf(q); i >= 0; i = text.indexOf(q, i + 1)) out.push([i, i + q.length]);
return out;
}
/** Text folded for a tolerant match: lower case, every run of anything but letters and digits one space; with where each character came from. */
export function fold(text: string): { s: string; at: number[] } {
let s = "";
const at: number[] = [];
for (let i = 0; i < text.length; ) {
const ch = String.fromCodePoint(text.codePointAt(i)!);
if (WORD.test(ch)) {
for (const c of ch.toLowerCase()) (s += c), at.push(i);
} else if (s && !s.endsWith(" ")) (s += " "), at.push(i);
i += ch.length;
}
if (s.endsWith(" ")) (s = s.slice(0, -1)), at.pop();
return { s, at };
}
function tolerantHits(text: string, q: string): Range[] {
const fq = fold(q).s;
if (!fq) return [];
const ft = fold(text);
return exactHits(ft.s, fq).map(([s, e]): Range => [ft.at[s], ft.at[e - 1] + 1]);
}
/** The hit whose surroundings agree longest with the recorded ones. */
function best(text: string, hits: Range[], a: WikiAnchor): Range {
let top = hits[0];
let score = -1;
for (const h of hits) {
let p = 0;
while (p < a.pre.length && h[0] - p - 1 >= 0 && text[h[0] - p - 1] === a.pre[a.pre.length - p - 1]) p++;
let n = 0;
while (n < a.post.length && h[1] + n < text.length && text[h[1] + n] === a.post[n]) n++;
if (p + n > score) (score = p + n), (top = h);
}
return top;
}
// ---- the container and the article nodes ----
/** The Wikipedia containers (one, unless two replicas made one each at once), in library order. */
export function containers(snap: Snap): NodeId[] {
return snap.library ? snap.nodes[snap.root].children.filter((c) => snap.nodes[c].articles) : [];
}
/** Whether a node is the Wikipedia container or anything in it: never a document's text. */
export function inArticles(snap: Snap, id: NodeId): boolean {
const d = docOf(snap, id);
return !!d && !!snap.nodes[d].articles;
}
/** An article as the library files it: its language, its title, and its page id when known (which survives a rename). */
export interface ArticleKey {
lang: string;
title: string;
pageId?: number;
}
/** The nodes of an article, in library order: what its annotations hang from. Usually one; see the top of this file. */
export function articleNodes(snap: Snap, a: ArticleKey): NodeId[] {
const title = wikiTitle(a.title);
return containers(snap).flatMap((c) =>
snap.nodes[c].children.filter((id) => {
const r = snap.nodes[id].ref;
return r?.kind === "wiki" && r.lang === a.lang && (a.pageId && r.pageId ? r.pageId === a.pageId : r.title === title);
}),
);
}
/** An article's annotations: the notes under its nodes. */
export function annotationsOf(snap: Snap, a: ArticleKey): NodeId[] {
return articleNodes(snap, a).flatMap((id) => snap.nodes[id].children.filter((c) => snap.nodes[c].kind === "note" && snap.nodes[c].wanchor));
}
/**
* The ops that create whatever is missing for a first annotation on an article (the container, the
* article's node) and the parent to give the annotation: an existing node's id, or "$n" for one
* created earlier in the same batch (see Doc.apply).
*/
export function articleParent(snap: Snap, a: ArticleKey): { ops: Op[]; parent: NodeId } {
const have = articleNodes(snap, a)[0];
if (have) return { ops: [], parent: have };
const ops: Op[] = [];
let box = containers(snap)[0];
if (!box) {
ops.push({ op: "create", parent: snap.root, kind: "section", title: "Wikipedia", body: "", articles: true });
box = "$0" as NodeId;
}
ops.push({ op: "create", parent: box, kind: "section", title: wikiTitle(a.title), body: "", ref: { kind: "wiki", lang: a.lang, title: wikiTitle(a.title), ...(a.pageId ? { pageId: a.pageId } : {}) } });
return { ops, parent: `$${ops.length - 1}` as NodeId };
}
+5 -2
View File
@@ -74,7 +74,7 @@ export class LinkIndex {
for (const [id, before] of was) {
if (before?.ref) this.file(id, before.ref, false);
const after = nodes[id];
if (after?.ref) this.file(id, after.ref, true);
if (after?.ref && !articleNode(nodes, after)) this.file(id, after.ref, true);
}
});
this.rebuild(doc.snap().nodes);
@@ -86,7 +86,7 @@ export class LinkIndex {
this.unresolved.clear();
for (const id in nodes) {
const r = nodes[id as NodeId].ref;
if (r) this.file(id as NodeId, r, true);
if (r && !articleNode(nodes, nodes[id as NodeId])) this.file(id as NodeId, r, true);
}
}
@@ -136,6 +136,9 @@ export class LinkIndex {
}
}
/** An article's own node in the Wikipedia container (article.ts) is where its annotations hang, not a mention of it. */
const articleNode = (nodes: Record<NodeId, NodeSnap>, n: NodeSnap) => !!n.parent && !!nodes[n.parent]?.articles;
const indexes = new WeakMap<Doc, LinkIndex>();
/** The backlinks index of a library, made on first use and kept current from then on. */
export function linkIndex(doc: Doc): LinkIndex {
+47 -11
View File
@@ -16,6 +16,7 @@
*/
import { Cursor, LoroDoc, LoroText, type LoroEventBatch, type LoroMap, type LoroTreeNode, type TreeID } from "loro-crdt";
import { RefError, canonRef, validateRef, type Ref } from "./ref";
import type { WikiAnchor } from "./article";
import { digest, sha256, slugify, words, type Form, type Range } from "./text";
export type { Ref } from "./ref";
@@ -55,6 +56,13 @@ export interface NodeSnap {
* replicas declining at once both keep theirs.
*/
nolink?: string[];
/**
* The Wikipedia container (see article.ts): a section of the library root that holds a node per
* annotated article. It is not a document: it is listed nowhere and never reconciled.
*/
articles?: boolean;
/** An annotation on a Wikipedia article: where in the article it attaches (its parent is the article's node). */
wanchor?: WikiAnchor;
anchors: Anchor[];
seenUp: string;
seenDown: string;
@@ -92,6 +100,10 @@ export type Op =
slug?: string;
/** What the node is about, elsewhere. A note with a target and no body is a link. */
ref?: Ref;
/** Make this section of the library root the Wikipedia container (article.ts). */
articles?: boolean;
/** For an annotation on an article: where in the article it attaches, in place of anchors. */
wanchor?: WikiAnchor;
}
/** `ref: null` removes the target. Changing a target is not a change of content: it leaves authorship and staleness alone. */
/** `nolink` adds phrases the writer declined to link; like a target, it is not a change of content. */
@@ -368,6 +380,8 @@ export class Doc {
if (d.lens) snap.lens = d.lens as string;
if (d.slug) snap.slug = d.slug as string;
if (d.ref && typeof d.ref === "object") snap.ref = d.ref as Ref;
if (d.articles) snap.articles = true;
if (d.wanchor && typeof d.wanchor === "object") snap.wanchor = d.wanchor as WikiAnchor;
const declined = Object.keys(d).filter((k) => k.startsWith(NOLINK)).map((k) => k.slice(NOLINK.length)).sort();
if (declined.length) snap.nolink = declined;
return snap;
@@ -557,6 +571,7 @@ export class Doc {
const n = snap.nodes[id];
const row: unknown[] = [n.kind, n.title, n.body, n.by, n.pinned, n.form ?? null, n.lens ?? null, n.anchors.map((a) => [a.start, a.end]), n.children.map(visit)];
// A node target is compared by where its target sits, since ids differ between copies.
if (n.wanchor || n.articles) row.push(n.wanchor ?? null, n.articles ?? null);
if (n.ref) row.push(n.ref.kind === "node" ? ["node", n.ref.id && snap.nodes[n.ref.id] ? position(snap, n.ref.id) : [n.ref.doc ?? null, n.ref.path ?? null], n.ref.quote ?? null] : canonRef(n.ref));
return row;
};
@@ -651,6 +666,7 @@ export class Doc {
if (s.form) n.data.set("form", s.form);
if (s.lens) n.data.set("lens", s.lens);
if (s.ref) n.data.set("ref", s.ref as never);
if (s.wanchor) n.data.set("wanchor", s.wanchor as never);
if (s.nolink?.length) setNolink(n, s.nolink);
n.data.set("up", s.seenUp);
n.data.set("down", s.seenDown);
@@ -692,14 +708,15 @@ export class Doc {
switch (op.op) {
case "create": {
const parent = this.node(op.parent);
const kind: Kind = op.kind ?? (op.anchors || op.quote ? "note" : "section");
const kind: Kind = op.kind ?? (op.anchors || op.quote || op.wanchor ? "note" : "section");
let ranges = op.anchors;
if (!ranges && op.quote) {
const at = this.bodyOf(parent).toString().indexOf(op.quote);
if (at < 0) throw new OpError(`quote not found in parent body: "${op.quote}"`);
ranges = [[at, at + op.quote.length]];
}
if (kind === "note" && !ranges?.length) throw new OpError("a note needs an anchor or a quote");
if (kind === "note" && !ranges?.length && !op.wanchor) throw new OpError("a note needs an anchor or a quote");
if (op.articles && (kind !== "section" || !parent.data.get("library"))) throw new OpError("only a section of the library can be the Wikipedia container");
const count = parent.children()?.length ?? 0;
const n = parent.createNode(Math.max(0, Math.min(op.index ?? count, count)));
this.mark(parent.id);
@@ -713,7 +730,10 @@ export class Doc {
if (op.lens) n.data.set("lens", op.lens);
if (op.ref) n.data.set("ref", checkRef(op.ref) as never);
if (ranges?.length) n.data.set("anchors", this.makeAnchors(parent, ranges) as never);
const slug = kind === "section" ? this.slugFor(n, op.slug, op.title || "untitled") : undefined;
else if (op.wanchor) n.data.set("wanchor", checkWikiAnchor(op.wanchor) as never);
if (op.articles) n.data.set("articles", true);
// The container is not a document, so it has no address.
const slug = kind === "section" && !op.articles ? this.slugFor(n, op.slug, op.title || "untitled") : undefined;
if (op.slug && kind !== "section") throw new OpError("only a document (a section of the library) has a slug");
if (slug) n.data.set("slug", slug);
created.push(n.id);
@@ -880,7 +900,7 @@ export function setNolink(n: LoroTreeNode, phrases: string[]) {
for (const p of phrases) if (n.data.get(NOLINK + p) === undefined) n.data.set(NOLINK + p, 1);
}
const sameNode = (a: NodeSnap, b: NodeSnap) =>
refString(a.ref) === refString(b.ref) && (a.nolink ?? []).join("\u0000") === (b.nolink ?? []).join("\u0000") && a.parent === b.parent && a.kind === b.kind && a.title === b.title && a.body === b.body && a.by === b.by && a.pinned === b.pinned &&
refString(a.ref) === refString(b.ref) && a.articles === b.articles && JSON.stringify(a.wanchor) === JSON.stringify(b.wanchor) && (a.nolink ?? []).join("\u0000") === (b.nolink ?? []).join("\u0000") && a.parent === b.parent && a.kind === b.kind && a.title === b.title && a.body === b.body && a.by === b.by && a.pinned === b.pinned &&
a.form === b.form && a.lens === b.lens && a.slug === b.slug && a.seenUp === b.seenUp && a.seenDown === b.seenDown && a.depth === b.depth &&
a.children.length === b.children.length && a.children.every((c, i) => c === b.children[i]) &&
a.anchors.length === b.anchors.length && a.anchors.every((x, i) => x.start === b.anchors[i].start && x.end === b.anchors[i].end && x.quote === b.anchors[i].quote && x.text === b.anchors[i].text);
@@ -889,10 +909,10 @@ const sameNode = (a: NodeSnap, b: NodeSnap) =>
const row = (n: NodeSnap) => {
const r: unknown[] = [n.id, n.parent, n.kind, n.title, n.body, n.by, n.pinned, n.form ?? null, n.lens ?? null, n.anchors.map((a) => [a.start, a.end]), n.seenUp, n.seenDown];
// Optional fields go last, and only when set, so commits made before they existed still verify.
if (n.slug || n.ref || n.nolink) r.push(n.slug ?? null);
if (n.ref || n.nolink) r.push(n.ref ? canonRef(n.ref) : null);
if (n.nolink) r.push(n.nolink);
// Optional fields go last, and only up to the last one set, so commits made before they existed still verify.
const tail = [n.slug ?? null, n.ref ? canonRef(n.ref) : null, n.nolink ?? null, n.wanchor ?? null, n.articles ? true : null];
while (tail.length && tail[tail.length - 1] === null) tail.pop();
r.push(...tail);
return r;
};
@@ -942,7 +962,8 @@ export function freeSlug(hint: string, taken: Set<string | undefined>): string {
// ---- staleness: computed, never stored ----
export const sections = (snap: Snap, id: NodeId) => snap.nodes[id].children.filter((c) => snap.nodes[c].kind === "section");
/** A node's sections, in order. The Wikipedia container (article.ts) is nobody's section: it is not a document. */
export const sections = (snap: Snap, id: NodeId) => snap.nodes[id].children.filter((c) => snap.nodes[c].kind === "section" && !snap.nodes[c].articles);
/**
* Hash of what a node's body should be a summary of: its section children, in order. The
@@ -1005,10 +1026,15 @@ export function staleness(snap: Snap, id: NodeId): Staleness {
const parent = n.parent ? snap.nodes[n.parent] : undefined;
const seen = memo.get(n);
if (seen && seen.parent === parent) return seen.s;
const orphan = n.kind === "note" && (!n.anchors.length || n.anchors.every(anchorLost));
// An annotation is anchored in an article, which is not in the library: whether its words are still
// there is found when the article is shown (article.ts), never here.
const orphan = n.kind === "note" && !n.wanchor && (!n.anchors.length || n.anchors.every(anchorLost));
// A link has no text of its own to fall out of date: it is never stale, so it never asks a model
// to rewrite it, and nothing else looks at it (a parent summarises its sections, not its notes).
const s = isLink(n) ? { up: false, down: false, orphan } : { up: n.seenUp !== upInput(snap, id), down: n.seenDown !== downInput(snap, id), orphan };
// Nor are the Wikipedia container and its article nodes, which hold no text, nor an annotation
// against the article it elaborates.
const fixed = isLink(n) || n.articles || !!(parent?.articles);
const s = fixed ? { up: false, down: false, orphan } : { up: n.seenUp !== upInput(snap, id), down: !n.wanchor && n.seenDown !== downInput(snap, id), orphan };
memo.set(n, { parent, s });
return s;
}
@@ -1030,6 +1056,16 @@ function position(snap: Snap, id: NodeId): number[] {
return out;
}
/** An annotation's place in an article, checked like a target. */
function checkWikiAnchor(a: unknown): WikiAnchor {
const x = a as Record<string, unknown>;
const str = (v: unknown, max: number) => typeof v === "string" && v.length <= max;
if (!x || typeof x !== "object" || !str(x.q, 2000) || !(x.q as string).trim() || !str(x.pre, 200) || !str(x.post, 200)) throw new OpError("an article anchor needs its words (q) and the text around them (pre, post)");
if (!Array.isArray(x.sec) || x.sec.length > 16 || !x.sec.every((h) => str(h, 300))) throw new OpError("an article anchor's section is a list of headings");
if (!Number.isInteger(x.rev) || (x.rev as number) < 0) throw new OpError("an article anchor's revision must be a whole number");
return { sec: x.sec as string[], q: x.q as string, pre: x.pre as string, post: x.post as string, rev: x.rev as number };
}
/** An op's target, checked: a bad one is refused like any other bad op. */
function checkRef(r: unknown): Ref {
try {
+31 -1
View File
@@ -50,7 +50,9 @@ Web research (only in a run where you have web search and web fetch tools):
*/
export function renderContext(snap: Snap, focus: NodeId, opts: { ids?: boolean; budget?: number } = {}): string {
const budget = opts.budget ?? 160_000;
const top = docOf(snap, focus);
let top = docOf(snap, focus);
// An annotation on an article is read in its article's node, not the whole Wikipedia container.
if (top && snap.nodes[top].articles) top = [focus, ...ancestors(snap, focus)].find((x) => snap.nodes[x].parent === top) ?? top;
if (!top) {
const lines = documents(snap).map((d) => `- ${opts.ids ? `[${d}] ` : ""}${snap.nodes[d].title || "(untitled)"}`);
return `<library>\n${lines.join("\n")}\n</library>`;
@@ -135,6 +137,34 @@ export function expandPrompt(snap: Snap, id: NodeId, range: [number, number], fo
].filter(Boolean).join("\n\n");
}
/** What a note on words of a Wikipedia article is written from: the article's lead, the section the words are in (trimmed), the words, and the reader's own sentence when they came from one. */
export interface ArticleContext {
title: string;
lead: string;
/** The headings down to the section, or null when the words are in the lead. */
heading: string | null;
section: string;
selection: string;
/** The sentence of the reader's own text the article was opened from, if any. */
from?: string;
}
/** The article as a prompt's cached context: its title and lead. */
export const articleContext = (c: ArticleContext) => `<wikipedia_article title="${c.title}">\n${c.lead}\n</wikipedia_article>`;
/** Ask for a note on a selection inside a Wikipedia article. */
export function articlePrompt(c: ArticleContext, form: Form, lens: string, question?: string): string {
return [
`The reader is reading the Wikipedia article “${c.title}”, whose lead is given above${c.heading ? `, in its section “${c.heading}”` : ""}.`,
c.heading ? `The passage around the selection:\n<section>\n${c.section}\n</section>` : "",
`They selected:\n<selection>\n${c.selection}\n</selection>`,
c.from ? `They came to this article from their own notes, from this sentence:\n<their_text>\n${plain(c.from)}\n</their_text>` : "",
question ? `They asked about the selection: ${question}` : (LENS[lens] ?? LENS.elaborate),
SIZE[form],
"The note sits beside Wikipedia's text as the reader's own: do not restate the article, and say so plainly where the article and what you know disagree or where you are unsure.",
].filter(Boolean).join("\n\n");
}
/** Ask for subsections of a node that has none. */
export function deepenPrompt(snap: Snap, id: NodeId, nearby?: Nearby[]): string {
const n = snap.nodes[id];
+42 -1
View File
@@ -8,8 +8,9 @@ import { nodeRef, resolveNode as resolveTargetPath } from "../core/links";
import { mergeBranch, resolveConflict, type MergeReport } from "../core/repo";
import { clip, digest, type Form } from "../core/text";
import { stripMarks, type Mark } from "../core/marks";
import { articleParent, type ArticleKey, type WikiAnchor } from "../core/article";
import {
AGENT_SYSTEM, SYSTEM, type Grounding, type Nearby, cascadePrompt, contradictionPrompt, deepenPrompt, expandPrompt, pathOf, regenDownPrompt,
AGENT_SYSTEM, SYSTEM, type ArticleContext, type Grounding, type Nearby, articleContext, articlePrompt, cascadePrompt, contradictionPrompt, deepenPrompt, expandPrompt, pathOf, regenDownPrompt,
regenUpPrompt, renderContext, resolvePrompt, writePrompt,
} from "./prompts";
import type { Block, CascadeDecision, Contradictions, LLM, Resolutions, ToolUseBlock, TurnReq } from "./types";
@@ -98,6 +99,46 @@ export function commitExpansion(doc: Doc, r: ExpansionRequest, text: string, onM
return report(created[0]);
}
/** A note on words of a Wikipedia article: where it attaches, and what it is written from. */
export interface ArticleNoteRequest {
article: ArticleKey;
anchor: WikiAnchor;
form: Form;
lens: string;
question?: string;
context: ArticleContext;
}
/** Stream a note on words of an article. Does not touch the library. */
export function streamArticleNote(llm: LLM, r: ArticleNoteRequest, onText: OnText = noop, signal?: AbortSignal): Promise<string> {
return llm.stream(
{
task: "expand",
system: SYSTEM,
context: articleContext(r.context),
prompt: articlePrompt(r.context, r.form, r.lens, r.question),
vars: { quote: r.anchor.q, form: r.form, lens: r.question ?? r.lens },
effort: "low",
maxTokens: r.form === "passage" ? 2000 : 800,
},
onText,
signal,
);
}
/** Keep a note on an article: under the article's node, made (with its container) on the first one. Link marks are dropped: nothing in an article's notes is linked. */
export function commitArticleNote(doc: Doc, r: ArticleNoteRequest, text: string): NodeId {
text = stripMarks(text.trim()).text;
if (r.form === "gloss") text = text.replace(/[.\s]+$/, "");
const { ops, parent } = articleParent(doc.snap(), r.article);
const { created } = doc.apply(
[...ops, { op: "create", parent, kind: "note", wanchor: r.anchor, form: r.form, lens: r.question ?? r.lens, body: text }],
`Expand “${clip(r.anchor.q, 40)}” in “${clip(r.context.title, 40)}”`,
{ actor: "llm", tag: "expand" },
);
return created[created.length - 1];
}
export function parseSections(text: string): { title: string; body: string }[] {
const out: { title: string; body: string }[] = [];
for (const chunk of text.split(/^##\s+/m).slice(1)) {
+192
View File
@@ -0,0 +1,192 @@
/** Annotations on Wikipedia articles: finding an anchor again in a later revision, and the article nodes in the library. */
import fc from "fast-check";
import { describe, expect, it } from "vitest";
import { annotationsOf, articleNodes, articleParent, containers, fold, inArticles, makeAnchor, reanchor, type ArticleKey, type SectionText } from "../src/core/article";
import { Doc, documents, isStale, staleness, type NodeId, type Op } from "../src/core/model";
import { mergeUpdate, verifyHistory } from "../src/core/repo";
import { listDocs } from "../src/core/library";
import type { Range } from "../src/core/text";
// ---- re-anchoring ----
const VOCAB = ["the", "octopus", "arm", "tastes", "what", "it", "touches", "nerve", "cord", "brain", "sucker", "Ink", "Hoyle", "state", "of", "carbon-12", "fusion", "star"];
const PUNCT = [" ", " ", " ", ", ", ". ", "; ", " (", ") "];
/** A random text of words and punctuation. */
const textArb = fc.array(fc.tuple(fc.constantFrom(...VOCAB), fc.constantFrom(...PUNCT)), { minLength: 8, maxLength: 60 }).map((ws) => ws.map(([w, p]) => w + p).join("").trim());
/** A quote of whole words from the text: its range. */
function wordsRange(text: string, from: number, count: number): Range | null {
const ws = [...text.matchAll(/[\p{L}\p{N}][\p{L}\p{N}-]*/gu)];
if (!ws.length) return null;
const a = ws[from % ws.length];
const b = ws[Math.min(ws.length - 1, (from % ws.length) + count - 1)];
return [a.index!, b.index! + b[0].length];
}
/** An edit to a text: insert, delete or replace a span. Tracks where a range moves, or that it was touched. */
type Edit = { at: number; del: number; ins: string };
const editArb = fc.record({ at: fc.nat(), del: fc.nat({ max: 12 }), ins: fc.oneof(fc.constant(""), fc.constantFrom(...VOCAB).map((w) => ` ${w} `), fc.string({ maxLength: 6 })) });
function applyEdit(text: string, e: Edit, r: Range | null): { text: string; r: Range | null } {
const at = e.at % (text.length + 1);
const del = Math.min(e.del, text.length - at);
const out = text.slice(0, at) + e.ins + text.slice(at + del);
if (!r) return { text: out, r };
const shift = e.ins.length - del;
// An edit touching the quote, or right at its edges, may change its words: stop tracking it.
if (at + del >= r[0] && at <= r[1]) return { text: out, r: null };
return { text: out, r: at < r[0] ? [r[0] + shift, r[1] + shift] : r };
}
describe("reanchor", () => {
it("finds the quote where it moved to while it survives, and never puts it on other words", () => {
fc.assert(
fc.property(textArb, fc.nat(), fc.integer({ min: 1, max: 4 }), fc.array(editArb, { maxLength: 8 }), (text, from, count, edits) => {
const r = wordsRange(text, from, count);
if (!r) return;
const a = makeAnchor(text, r, ["Section"], 1);
let cur: { text: string; r: Range | null } = { text, r };
for (const e of edits) cur = applyEdit(cur.text, e, cur.r);
const secs: SectionText[] = [{ path: [], text: "A lead with nothing in it." }, { path: ["Section"], text: cur.text }];
const got = reanchor(a, secs);
if ("detached" in got) {
// Detached only when the words are nowhere, even tolerantly.
expect(fold(cur.text).s.includes(fold(a.q).s) && cur.r !== null).toBe(false);
return;
}
// Wherever it lands, it is on the same words (up to case, punctuation and spacing).
const landed = secs[got.sec].text.slice(got.range[0], got.range[1]);
expect(fold(landed).s).toBe(fold(a.q).s);
// While the quote survived untouched and occurs once, it is found exactly there.
const once = cur.text.indexOf(a.q) >= 0 && cur.text.indexOf(a.q) === cur.text.lastIndexOf(a.q);
if (cur.r && once) expect(got).toEqual({ sec: 1, range: cur.r });
}),
{ numRuns: 1500 },
);
});
it("reports an anchor detached when its words were deleted, never anchoring it elsewhere", () => {
fc.assert(
fc.property(textArb, fc.nat(), fc.integer({ min: 1, max: 3 }), fc.array(editArb, { maxLength: 5 }), (text, from, count, edits) => {
const r = wordsRange(text, from, count);
if (!r) return;
const a = makeAnchor(text, r, ["Section"], 1);
let cur = text.slice(0, r[0]) + text.slice(r[1]);
for (const e of edits) cur = applyEdit(cur, e, null).text;
// Take out every remaining occurrence too, in any case or spacing.
const fq = fold(a.q).s;
for (let guard = 0; fold(cur).s.includes(fq) && guard < 50; guard++) {
const f = fold(cur);
const i = f.s.indexOf(fq);
cur = cur.slice(0, f.at[i]) + cur.slice(f.at[i + fq.length - 1] + 1);
}
const got = reanchor(a, [{ path: [], text: "Lead." }, { path: ["Section"], text: cur }]);
expect(got).toEqual({ detached: true, sec: 1 });
}),
{ numRuns: 1000 },
);
});
it("prefers its own section, then the same words elsewhere, then a tolerant match; tells repeats apart by context", () => {
const secs: SectionText[] = [
{ path: [], text: "The Hoyle state is an excited state of carbon-12." },
{ path: ["Prediction"], text: "Hoyle predicted the state. Later, the state was found." },
{ path: ["Structure"], text: "Its structure: three alpha particles." },
];
const at = (sec: number, q: string, nth = 0) => {
let i = -1;
for (let k = 0; k <= nth; k++) i = secs[sec].text.indexOf(q, i + 1);
return makeAnchor(secs[sec].text, [i, i + q.length], secs[sec].path, 7);
};
// The second "the state" in Prediction, by its context.
expect(reanchor(at(1, "the state", 1), secs)).toEqual({ sec: 1, range: [34, 43] });
// Moved to another section.
expect(reanchor({ ...at(2, "three alpha particles"), sec: ["Prediction"] }, secs)).toEqual({ sec: 2, range: [15, 36] });
// Edited: case and punctuation differ.
const edited = secs.map((s, i) => (i === 2 ? { ...s, text: "Its structure: Three-alpha particles, loosely bound." } : s));
const r = reanchor(at(2, "three alpha particles"), edited);
expect("range" in r && edited[2].text.slice(r.range[0], r.range[1])).toBe("Three-alpha particles");
// Not inside another word.
expect(reanchor(makeAnchor("a state b", [2, 7], [], 1), [{ path: [], text: "restated twice" }])).toEqual({ detached: true, sec: 0 });
// Its section gone: detached with no section.
expect(reanchor({ ...at(2, "three alpha particles"), q: "gone words" }, secs.slice(0, 2))).toEqual({ detached: true, sec: null });
});
});
// ---- the article nodes ----
const OCTOPUS: ArticleKey = { lang: "en", title: "Octopus", pageId: 1200106 };
/** One annotation on an article, with whatever the library lacks for it, in one commit. */
function annotate(doc: Doc, a: ArticleKey, q: string, body = `About ${q}.`): NodeId {
const { ops, parent } = articleParent(doc.snap(), a);
const note: Op = { op: "create", parent, kind: "note", form: "gloss", body, wanchor: { sec: [], q, pre: "", post: "", rev: 1 } };
const { created } = doc.apply([...ops, note], `Annotate ${q}`, { actor: "llm" });
return created[created.length - 1];
}
function library() {
const doc = Doc.library("tester");
doc.apply([{ op: "create", parent: doc.snap().root, title: "Minds", body: "An octopus has arms." }], "Base");
return doc;
}
const sync = (a: Doc, b: Doc) => {
mergeUpdate(a, b.loro.export({ mode: "update", from: a.loro.version() }), b.loro.version().toJSON());
mergeUpdate(b, a.loro.export({ mode: "update", from: b.loro.version() }), a.loro.version().toJSON());
};
describe("article nodes", () => {
it("are made on the first annotation, once; the container is not a document and nothing in it goes stale", () => {
const doc = library();
const before = listDocs(doc.snap());
expect(containers(doc.snap())).toEqual([]);
const first = annotate(doc, OCTOPUS, "arms");
const second = annotate(doc, { lang: "en", title: "octopus" }, "suckers");
const snap = doc.snap();
expect(containers(snap)).toHaveLength(1);
expect(articleNodes(snap, OCTOPUS)).toHaveLength(1);
expect(annotationsOf(snap, OCTOPUS)).toEqual([first, second]);
// Found by page id under another title (a rename), and not by a different page id.
expect(articleNodes(snap, { lang: "en", title: "Octopodes", pageId: 1200106 })).toHaveLength(1);
expect(articleNodes(snap, { lang: "fr", title: "Octopus" })).toHaveLength(0);
// Not a document: not listed, no slug, no count.
expect(listDocs(snap)).toEqual(before);
expect(documents(snap)).toHaveLength(1);
const box = containers(snap)[0];
expect(snap.nodes[box].slug).toBeUndefined();
expect(inArticles(snap, first) && inArticles(snap, box) && !inArticles(snap, documents(snap)[0])).toBe(true);
for (const id of [box, articleNodes(snap, OCTOPUS)[0], first, second]) expect(isStale(snap, id)).toBe(false);
// An annotation is edited like any note, and stays fresh.
doc.apply([{ op: "update", id: first, body: "Eight of them." }], "Edit");
expect(staleness(doc.snap(), first)).toEqual({ up: false, down: false, orphan: false });
expect(verifyHistory(doc).mismatches).toEqual([]);
});
it("two replicas annotating the same new article converge, and read as one article", () => {
const doc = library();
const other = doc.fork("other");
const mine = annotate(doc, OCTOPUS, "arms");
const theirs = annotate(other, OCTOPUS, "ink");
sync(doc, other);
expect(doc.stateHash()).toBe(other.stateHash());
for (const d of [doc, other]) {
const snap = d.snap();
// Each made the container and the article's node; both are kept, and read as one.
expect(articleNodes(snap, OCTOPUS)).toHaveLength(2);
expect(new Set(annotationsOf(snap, OCTOPUS))).toEqual(new Set([mine, theirs]));
expect(documents(snap)).toHaveLength(1);
}
// The next annotation goes under the same node on either replica.
expect(articleParent(doc.snap(), OCTOPUS)).toEqual(articleParent(other.snap(), OCTOPUS));
expect(articleParent(doc.snap(), OCTOPUS).ops).toEqual([]);
});
it("an article anchor is checked like any op input", () => {
const doc = library();
const { ops, parent } = articleParent(doc.snap(), OCTOPUS);
expect(() => doc.apply([...ops, { op: "create", parent, kind: "note", body: "x", wanchor: { sec: "lead", q: "x", pre: "", post: "", rev: 1 } as never }], "Bad")).toThrow(/headings/);
expect(() => doc.apply([{ op: "create", parent: documents(doc.snap())[0], title: "Box", articles: true }], "Bad")).toThrow(/container/);
});
});