Core model: CRDT tree, op API, staleness, history and merge

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
thalladaandClaude Fable 5.2 committed 2026-11-15 14:30:50 -05:00
1 parent f67141d055
commit 7130c7e2b3
6 files changed
+2374

No files matched your search

+236
View File
@@ -0,0 +1,236 @@
/**
* Links between nodes, and from nodes to Wikipedia and the web: the backlinks index, finding a
* node target again when its id is gone, and applying a batch of links through the op API.
*
* A link is a note with a target and no body, so it is anchored, orphaned, healed, merged, undone
* and versioned like any note. Nothing here is stored except through ops; the index is derived.
*/
import { Doc, docOf, findDoc, notesOf, sections, type Actor, type NodeId, type NodeSnap, type Op, type Snap } from "./model";
import { sameTarget, wikiKey, type Ref } from "./ref";
import { clip, type Range } from "./text";
// ---- finding a node target ----
/** The nearest section at or above a node: the place a note's text is read in. */
export function ownerSection(snap: Snap, id: NodeId): NodeId {
let n = snap.nodes[id];
while (n && n.kind === "note" && n.parent) n = snap.nodes[n.parent];
return n?.id ?? id;
}
/** A target naming a node, with the hint that finds it again: its document's slug and the titles down to it. */
export function nodeRef(snap: Snap, id: NodeId): Ref & { kind: "node" } {
const n = snap.nodes[id];
const d = docOf(snap, id);
const sec = ownerSection(snap, id);
const path: string[] = [];
for (let x = snap.nodes[sec]; x && x.id !== d && x.parent; x = snap.nodes[x.parent]) path.unshift(x.title);
const out: Ref & { kind: "node" } = { kind: "node", id };
const slug = d ? snap.nodes[d].slug : undefined;
if (slug) out.doc = slug;
out.path = path;
if (n.kind === "note") out.quote = n.anchors[0]?.text || n.anchors[0]?.quote || "";
return out;
}
/**
* The node a target names: by id while it exists, else by its hint (document, section titles,
* and a note's quote). `here` is the document a relative path is read from. Null if neither finds it.
*/
export function resolveNode(snap: Snap, ref: Ref & { kind: "node" }, here?: NodeId): NodeId | null {
if (ref.id && snap.nodes[ref.id]) return ref.id;
if (!ref.path && !ref.doc) return null;
let at = ref.doc ? findDoc(snap, ref.doc) : here;
if (!at || !snap.nodes[at]) return null;
for (const title of ref.path ?? []) {
const kids = sections(snap, at);
const next = kids.find((c) => snap.nodes[c].title === title) ?? kids.find((c) => snap.nodes[c].title.toLowerCase() === title.toLowerCase());
if (!next) return null;
at = next;
}
if (ref.quote !== undefined) {
const note = notesOf(snap, at).find((c) => snap.nodes[c].anchors.some((a) => a.text === ref.quote || a.quote === ref.quote));
return note ?? null;
}
return at;
}
// ---- the backlinks index ----
/**
* For each node, the nodes that link to it; for each Wikipedia article, the nodes that link to it.
* Kept current from the snapshot's patches (Doc.onPatch), so a change costs what it touched, and
* built whole only when the snapshot is read whole (boot, checkout).
*/
export class LinkIndex {
private byNode = new Map<NodeId, Set<NodeId>>();
private byWiki = new Map<string, Set<NodeId>>();
/** Node targets with no id yet (written from a file, waiting for their target to be imported). */
private unresolved = new Set<NodeId>();
constructor(private doc: Doc) {
doc.onPatch((was, nodes) => {
if (!was) return this.rebuild(nodes);
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);
}
});
this.rebuild(doc.snap().nodes);
}
private rebuild(nodes: Record<NodeId, NodeSnap>) {
this.byNode.clear();
this.byWiki.clear();
this.unresolved.clear();
for (const id in nodes) {
const r = nodes[id as NodeId].ref;
if (r) this.file(id as NodeId, r, true);
}
}
private file(id: NodeId, r: Ref, add: boolean) {
if (r.kind === "url") return;
if (r.kind === "node" && !r.id) {
if (add) this.unresolved.add(id);
else this.unresolved.delete(id);
return;
}
const map = r.kind === "node" ? this.byNode : this.byWiki;
const key = r.kind === "node" ? r.id! : wikiKey(r.lang, r.title);
let set = map.get(key);
if (add) {
if (!set) map.set(key, (set = new Set()));
set.add(id);
} else if (set) {
set.delete(id);
if (!set.size) map.delete(key);
}
}
/** The nodes whose target is this node. */
linksTo(id: NodeId): NodeId[] {
this.doc.snap();
return [...(this.byNode.get(id) ?? [])];
}
/** The nodes whose target is this article. */
mentions(lang: string, title: string): NodeId[] {
this.doc.snap();
return [...(this.byWiki.get(wikiKey(lang, title)) ?? [])];
}
/** Nodes whose node target is gone or was never found: what healing tries to find again. */
broken(): NodeId[] {
const snap = this.doc.snap();
const out = [...this.unresolved];
for (const [target, from] of this.byNode) if (!snap.nodes[target]) out.push(...from);
return out;
}
/** Every Wikipedia article linked from the library, with how many nodes link to it. */
articles(): { key: string; count: number }[] {
this.doc.snap();
return [...this.byWiki].map(([key, s]) => ({ key, count: s.size }));
}
}
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 {
let ix = indexes.get(doc);
if (!ix) indexes.set(doc, (ix = new LinkIndex(doc)));
return ix;
}
// ---- healing ----
/**
* Find node targets again whose node is gone (undoing a delete brings nodes back under new ids)
* or was never found (a file linking to a document imported later), from the hint each carries.
* One system commit, which undo steps over. Returns how many were found.
*/
export function healLinks(doc: Doc): number {
const snap = doc.snap();
const ops: Op[] = [];
for (const id of linkIndex(doc).broken()) {
const n = snap.nodes[id];
if (!n || n.ref?.kind !== "node") continue;
const found = resolveNode(snap, n.ref, docOf(snap, id) ?? undefined);
if (found && found !== n.ref.id) ops.push({ op: "update", id, ref: nodeRef(snap, found) });
}
if (ops.length) doc.apply(ops, `Find ${ops.length} link target${ops.length > 1 ? "s" : ""} again`, { actor: "llm", tag: "regen" });
return ops.length;
}
// ---- applying links ----
export interface LinkSpec {
/** The node whose text is linked. */
node: NodeId;
/** The linked words: the first occurrence of this text in the node's body… */
quote?: string;
/** …or these offsets into it. */
range?: Range;
target: Ref;
}
export interface LinkResult {
created: NodeId[];
/** Existing notes on the same span that took the target. */
merged: NodeId[];
/** Spans that already had this target. */
same: number;
/** Spans that already had a different target: left alone, so a person's link is never replaced. */
occupied: number;
/** Specs whose node or words could not be found. */
missing: number;
}
/**
* Link spans of text to targets, as one commit through the op API: a span that already carries
* the target is skipped, a span that carries a note without a target gives that note the target
* (one node, not two stacked on the same words), and a span that already links elsewhere is left
* alone. Running the same batch twice changes nothing the second time. Made for bulk use: link
* discovery calls this with whatever it found.
*/
export function applyLinks(doc: Doc, specs: LinkSpec[], meta: { message?: string; actor?: Actor; author?: string; tag?: string } = {}): LinkResult {
const snap = doc.snap();
const out: LinkResult = { created: [], merged: [], same: 0, occupied: 0, missing: 0 };
const ops: Op[] = [];
const claimed = new Map<string, Ref>();
for (const s of specs) {
const n = snap.nodes[s.node];
let range = s.range;
if (n && !range && s.quote) {
const at = n.body.indexOf(s.quote);
if (at >= 0) range = [at, at + s.quote.length];
}
if (!n || !range || range[1] <= range[0] || range[1] > n.body.length) {
out.missing++;
continue;
}
const key = `${s.node}:${range[0]}:${range[1]}`;
const earlier = claimed.get(key);
const onSpan = notesOf(snap, s.node).filter((c) => snap.nodes[c].anchors.some((a) => a.start === range![0] && a.end === range![1]));
const current = earlier ?? onSpan.map((c) => snap.nodes[c].ref).find(Boolean);
if (current) {
if (sameTarget(current, s.target)) out.same++;
else out.occupied++;
continue;
}
claimed.set(key, s.target);
const plain = onSpan.find((c) => !snap.nodes[c].ref);
if (plain) {
ops.push({ op: "update", id: plain, ref: s.target });
out.merged.push(plain);
} else ops.push({ op: "create", parent: s.node, kind: "note", anchors: [range], ref: s.target });
}
if (!ops.length) return out;
const first = specs.find((s) => s.target)?.target;
const message = meta.message ?? (ops.length === 1 && first ? `Link to ${clip(first.kind === "wiki" ? first.title : first.kind === "url" ? first.url : (first.path ?? []).join(" › ") || "a node", 50)}` : `Add ${ops.length} links`);
out.created = doc.as(meta.author ?? doc.author, () => doc.apply(ops, message, { actor: meta.actor ?? "human", tag: meta.tag ?? "link" }).created);
return out;
}
+51
View File
@@ -0,0 +1,51 @@
/**
* Link marks: `[[phrase]]` asks for the phrase to be linked to whatever it names (a library node
* or a Wikipedia article, verified before a link is made); `[[phrase|handle]]` names a library node
* by its handle (its id, as given to a model in the "nearby" list). A writer, human or model, types
* them; they are never stored. On save the brackets are taken out and each mark becomes a forced
* candidate for the scanner (server/links). While a model streams, the reader sees the text
* without them.
*/
export interface Mark {
/** Offsets of the phrase in the text with the marks taken out. */
start: number;
end: number;
phrase: string;
handle?: string;
}
const MARK = /\[\[([^\[\]|\n]{1,200}?)(?:\|([^\[\]|\n]{1,100}))?\]\]/g;
/** The text without its marks, and where each marked phrase now sits. */
export function stripMarks(raw: string): { text: string; marks: Mark[] } {
const marks: Mark[] = [];
let text = "";
let last = 0;
MARK.lastIndex = 0;
for (let m; (m = MARK.exec(raw)); ) {
text += raw.slice(last, m.index);
const phrase = m[1].trim();
const lead = m[1].length - m[1].trimStart().length;
const start = text.length + lead;
text += m[1];
if (phrase) marks.push({ start, end: start + phrase.length, phrase, ...(m[2]?.trim() ? { handle: m[2].trim() } : {}) });
last = m.index + m[0].length;
}
text += raw.slice(last);
return { text, marks };
}
/**
* What a reader sees of text still arriving: complete marks taken out, and an unfinished one at
* the end shown as its phrase so far (its brackets and handle hidden), so nothing flickers.
*/
export function streamView(raw: string): string {
const { text } = stripMarks(raw);
const open = text.lastIndexOf("[[");
if (open < 0) return text.endsWith("[") ? text.slice(0, -1) : text;
const tail = text.slice(open + 2);
if (tail.includes("]]") || tail.includes("\n")) return text;
const bar = tail.indexOf("|");
return text.slice(0, open) + (bar < 0 ? tail.replace(/\]$/, "") : tail.slice(0, bar));
}
+1083
View File
File diff suppressed because it is too large. Load diff
+290
View File
@@ -0,0 +1,290 @@
/**
* A node's target: what it is about, elsewhere. A Wikipedia article, another node in the library,
* or a web page. A note with a target and no body is a link; with a body it is a commentary on
* something that also has an article. Targets are plain data in the node, so they replicate,
* version, merge and undo like a title does.
*
* Also the one text form of a target, shared by the .md format, the command bar and the editor
* agent's tools:
*
* w:Fixed-point combinator English Wikipedia (w.fr:Point fixe for another language)
* /fixed-points/Recursion/How Y works a node, by document slug and section titles
* ./How Y works the same, inside the document it is written in
* /fixed-points/The idea ^"one repels them" a note, by its section and its quote
* https://example.org/page "Title" a web page, with an optional title
* "w:Star Wars: Episode IV" any of them in quotes, when it contains ": "
*
* In a path, `\/`, `\^` and `\\` stand for a slash, a caret and a backslash inside a title.
*/
import type { NodeId } from "./model";
export type Ref =
| { kind: "wiki"; title: string; lang: string; pageId?: number }
/**
* A node in the library. `id` is what counts; `doc` (a document's slug) and `path` (section
* titles below the document, and a note's quote) let the link be found again when the id has
* gone: undoing a delete re-creates nodes under new ids. A path with no `doc` is relative to the
* document it is written in (only in a parsed file, before it is written into the library).
*/
| { kind: "node"; id?: NodeId; doc?: string; path?: string[]; quote?: string }
| { kind: "url"; url: string; title?: string };
const DEFAULT_LANG = "en";
const LANG = /^[a-z][a-z0-9-]{1,15}$/;
const SLUG = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
/** Characters MediaWiki never allows in a title. */
const ILLEGAL = /[#<>[\]|{}\u0000-\u001f\u007f]/;
export class RefError extends Error {}
/** How MediaWiki would spell a main-namespace title: spaces for underscores, first letter capital. */
export function wikiTitle(s: string): string {
const t = s.replace(/_/g, " ").replace(/\s+/g, " ").trim();
if (!t) return t;
const first = String.fromCodePoint(t.codePointAt(0)!);
return first.toUpperCase() + t.slice(first.length);
}
/** Check a target from outside (an op, a file, a model) and return a clean copy. Throws RefError. */
export function validateRef(input: unknown): Ref {
if (!input || typeof input !== "object") throw new RefError("a target must be an object");
const r = input as Record<string, unknown>;
const str = (v: unknown, name: string, max: number) => {
if (typeof v !== "string") throw new RefError(`a target's ${name} must be a string`);
if (v.length > max) throw new RefError(`a target's ${name} is longer than ${max} characters`);
return v;
};
switch (r.kind) {
case "wiki": {
const title = wikiTitle(str(r.title, "title", 255));
if (!title || ILLEGAL.test(title)) throw new RefError(`not a Wikipedia title: “${r.title}”`);
const lang = r.lang === undefined ? DEFAULT_LANG : str(r.lang, "lang", 16);
if (!LANG.test(lang)) throw new RefError(`not a Wikipedia language: ${lang}`);
const out: Ref = { kind: "wiki", title, lang };
if (r.pageId !== undefined) {
if (!Number.isInteger(r.pageId) || (r.pageId as number) <= 0) throw new RefError("a page id must be a positive integer");
out.pageId = r.pageId as number;
}
return out;
}
case "node": {
const out: Ref = { kind: "node" };
if (r.id !== undefined && r.id !== "") out.id = str(r.id, "id", 64) as NodeId;
if (r.doc !== undefined) {
const d = str(r.doc, "document", 64);
if (!SLUG.test(d)) throw new RefError(`not a document slug: ${d}`);
out.doc = d;
}
if (r.path !== undefined) {
if (!Array.isArray(r.path) || r.path.length > 64) throw new RefError("a target's path must be a list of titles");
out.path = r.path.map((t) => str(t, "path", 500));
}
if (r.quote !== undefined) out.quote = str(r.quote, "quote", 2000);
if (!out.id && !out.path && !out.doc) throw new RefError("a node target needs an id or a path");
return out;
}
case "url": {
const url = str(r.url, "url", 2000).trim();
let ok = false;
try {
ok = /^https?:$/.test(new URL(url).protocol) && /^https?:\/\//i.test(url);
} catch {
ok = false;
}
if (!ok) throw new RefError(`only http and https addresses can be linked: ${url}`);
const out: Ref = { kind: "url", url };
if (r.title !== undefined && r.title !== "") out.title = str(r.title, "title", 300).replace(/\s+/g, " ").trim();
return out;
}
default:
throw new RefError(`unknown kind of target: ${String(r.kind)}`);
}
}
/** A canonical form, for hashing and comparing: the same target always gives the same value. */
export function canonRef(r: Ref): unknown[] {
switch (r.kind) {
case "wiki":
return ["wiki", r.lang, r.title, r.pageId ?? null];
case "node":
return ["node", r.id ?? null, r.doc ?? null, r.path ?? null, r.quote ?? null];
case "url":
return ["url", r.url, r.title ?? null];
}
}
/** Whether two targets name the same thing (a node by its id when both have one; a fallback hint does not count). */
export function sameTarget(a: Ref | undefined, b: Ref | undefined): boolean {
if (!a || !b || a.kind !== b.kind) return !a && !b;
if (a.kind === "wiki" && b.kind === "wiki") return a.lang === b.lang && a.title === b.title;
if (a.kind === "url" && b.kind === "url") return a.url === b.url;
if (a.kind === "node" && b.kind === "node") {
if (a.id || b.id) return a.id === b.id;
return a.doc === b.doc && JSON.stringify(a.path ?? []) === JSON.stringify(b.path ?? []) && (a.quote ?? "") === (b.quote ?? "");
}
return false;
}
/** The key a Wikipedia target is filed under. */
export const wikiKey = (lang: string, title: string) => `${lang}:${wikiTitle(title)}`;
// ---- the text form ----
const escapeSeg = (s: string) => s.replace(/[\\/^]/g, (c) => "\\" + c);
/** A string in quotes, with `\\`, `\"` and `\n` escaped: how the text form writes quotes, titles and lenses. */
export const quoteStr = (s: string) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
/** Read a "quoted" string at s[i] === '"': the text and the index after the closing quote. */
export function readQuoted(s: string, i: number): [string, number] | null {
let out = "";
for (let j = i + 1; j < s.length; j++) {
const c = s[j];
if (c === '"') return [out, j + 1];
if (c === "\\" && j + 1 < s.length) {
const n = s[j + 1];
if (n === '"' || n === "\\") (out += n), j++;
else if (n === "n") (out += "\n"), j++;
else out += c;
} else out += c;
}
return null;
}
/**
* A target in the text form. A node target is written from its `doc` and `path`, so refresh them
* first (`nodeRef` in links.ts); `here` is the slug of the document it is written in, which makes
* a path inside that document relative.
*/
export function formatTarget(r: Ref, here?: string): string {
let s: string;
if (r.kind === "wiki") s = `${r.lang === DEFAULT_LANG ? "w" : `w.${r.lang}`}:${r.title}`;
else if (r.kind === "url") return r.url + (r.title ? " " + quoteStr(r.title) : "");
else {
const segs = (r.path ?? []).map(escapeSeg).join("/");
const head = !r.doc || r.doc === here ? "." : `/${r.doc}`;
s = `${head}${segs || head === "." ? "/" : ""}${segs}`;
if (r.quote !== undefined) s += ` ^${quoteStr(r.quote)}`;
}
// Unquoted, a target ends at ": " (where a note's text begins), so one that contains that is quoted.
return /:(\s|$)/.test(s) || s.startsWith('"') ? quoteStr(s) : s;
}
const PREFIX = /^(w(?:\.[a-z][a-z0-9-]{1,15})?:|\.?\/|https?:\/\/)/i;
/** Whether text at this point would be read as a target (used to tell `-> target` from prose). */
export const looksLikeTarget = (s: string) => PREFIX.test(s) || (s.startsWith('"') && PREFIX.test(s.slice(1)));
/** Where an unquoted wiki title or path ends: at ": ", or a ":" that ends the text. Inside quotes, at the end. */
function stopAt(s: string, i: number, whole: boolean): number {
if (whole) return s.length;
for (let j = i; j < s.length; j++) if (s[j] === ":" && (j + 1 === s.length || /\s/.test(s[j + 1]))) return j;
return s.length;
}
function parsePath(text: string): Ref | string {
let rest = text;
let quote: string | undefined;
const caret = /(?:^|[^\\])\s\^"/.exec(rest);
if (caret) {
const at = rest.indexOf('^"', caret.index);
const q = readQuoted(rest, at + 1);
if (!q || rest.slice(q[1]).trim()) return "the quote after ^ is not closed";
quote = q[0];
rest = rest.slice(0, at).trimEnd();
}
const relative = rest.startsWith("./") || rest === ".";
const body = relative ? rest.slice(2) : rest.slice(1);
const segs: string[] = [];
let cur = "";
for (let i = 0; i < body.length; i++) {
const c = body[i];
if (c === "\\" && i + 1 < body.length) cur += body[++i];
else if (c === "/") segs.push(cur), (cur = "");
else cur += c;
}
if (cur || body.endsWith("/")) segs.push(cur);
if (relative) return { kind: "node", path: segs, ...(quote !== undefined ? { quote } : {}) };
const [doc, ...path] = segs;
if (!doc || !SLUG.test(doc)) return `not a document slug: “${doc ?? ""}”`;
return { kind: "node", doc, path, ...(quote !== undefined ? { quote } : {}) };
}
/** Read the target that starts at s[i]. Returns it and where it ended, or why it is not one. */
export function readTarget(s: string, i: number, whole = false): { ref: Ref; end: number } | string {
if (s[i] === '"' && !whole) {
const q = readQuoted(s, i);
if (!q) return "the target's quote is not closed";
const inner = readTarget(q[0], 0, true);
if (typeof inner === "string") return inner;
if (inner.end !== q[0].length) return `unexpected text in the target: “${q[0].slice(inner.end)}”`;
return { ref: inner.ref, end: q[1] };
}
const tail = s.slice(i);
const wiki = /^w(?:\.([a-z][a-z0-9-]{1,15}))?:/i.exec(tail);
try {
if (wiki) {
const end = stopAt(s, i + wiki[0].length, whole);
return { ref: validateRef({ kind: "wiki", lang: wiki[1]?.toLowerCase() ?? DEFAULT_LANG, title: s.slice(i + wiki[0].length, end) }), end };
}
if (/^https?:\/\//i.test(tail)) {
let end = i + (/^\S+/.exec(tail)?.[0].length ?? 0);
if (s[end - 1] === ":" && (end === s.length || /\s/.test(s[end]))) end--;
const url = s.slice(i, end);
const t = /^\s+"/.exec(s.slice(end));
if (t) {
const q = readQuoted(s, end + t[0].length - 1);
if (!q) return "the link's title is not closed";
return { ref: validateRef({ kind: "url", url, title: q[0] }), end: q[1] };
}
return { ref: validateRef({ kind: "url", url }), end };
}
if (tail.startsWith("/") || tail.startsWith("./") || tail === ".") {
const end = stopAt(s, i, whole);
const ref = parsePath(s.slice(i, end).trimEnd());
if (typeof ref === "string") return ref;
return { ref: validateRef(ref), end };
}
} catch (err) {
if (err instanceof RefError) return err.message;
throw err;
}
return "a target is w:Title, /document/Section, ./Section or an http(s) address";
}
/** A whole string as a target, or why it is not one. */
export function parseTarget(text: string): Ref | string {
const s = text.trim();
const r = readTarget(s, 0);
if (typeof r === "string") return r;
if (s.slice(r.end).trim()) return `unexpected text after the target: “${s.slice(r.end).trim()}”`;
return r.ref;
}
/** What a person types: a target in the text form, or else a Wikipedia title. */
export function parseTargetLoose(text: string): Ref | string {
const s = text.trim();
if (!s) return "give a target: w:Title, /document/Section or an address";
if (looksLikeTarget(s)) return parseTarget(s);
try {
return validateRef({ kind: "wiki", title: s, lang: DEFAULT_LANG });
} catch (err) {
return (err as Error).message;
}
}
/** A one-line description, for lists and messages. */
export function describeTarget(r: Ref): string {
if (r.kind === "wiki") return `Wikipedia: ${r.title}${r.lang === DEFAULT_LANG ? "" : ` (${r.lang})`}`;
if (r.kind === "url") return r.title ? `${r.title} (${hostOf(r.url)})` : r.url;
return [r.doc, ...(r.path ?? [])].filter(Boolean).join(" › ") || "a node";
}
/** A page's site, for showing: its host without "www.". */
export function hostOf(url: string): string {
try {
return new URL(url).host.replace(/^www\./, "");
} catch {
return url;
}
}
+563
View File
@@ -0,0 +1,563 @@
/**
* Git-shaped operations over the CRDT: history, verified checkout, revert, branches, and a merge
* that is structural first (the CRDT, deterministic) and semantic second (three-way comparison
* against the merge base, producing conflict records for a model or a person to resolve).
*/
import { VersionVector, type LoroText, type OpId, type PeerID } from "loro-crdt";
import { healLinks } from "./links";
import { Doc, NOLINK, OpError, anchorLost, label, setNolink, type CommitMeta, type Conflict, type NodeId, type NodeSnap, type Op, type Snap, descendants } from "./model";
import { canonRef, formatTarget, parseTarget, validateRef, type Ref } from "./ref";
import { clip, digest } from "./text";
/** A run of one peer's ops. */
export interface Span {
peer: PeerID;
counter: number;
length: number;
}
export interface Commit {
/** `${counter}@${peer}` of the commit's last op: a stable name for this point in history. */
id: string;
peer: PeerID;
lamport: number;
/** Unix seconds. */
time: number;
message: string;
by: string;
actor: string;
tag?: string;
/** Recorded SHA-256 of the tree state at this commit, if the commit carries one. */
hash?: string;
parents: string[];
frontiers: OpId[];
/** The ops the commit is made of. */
spans: Span[];
}
const opName = (o: OpId) => `${o.counter}@${o.peer}`;
export function history(doc: Doc): Commit[] {
const out: Commit[] = [];
const parse = (message: string | undefined): Partial<CommitMeta> => {
if (!message) return {};
try {
return JSON.parse(message);
} catch {
return { m: message };
}
};
for (const changes of doc.loro.getAllChanges().values()) {
for (let i = 0; i < changes.length; i++) {
const first = changes[i];
// One commit can be stored as several consecutive changes: Loro splits large ones, and
// commits early when a deleted cursor is resolved mid-transaction. They carry the same
// commit id; the commit starts at the first and its state is the state after the last.
let c = first;
let meta = parse(c.message);
for (let next = changes[i + 1]; next && meta.n; next = changes[i + 1]) {
const follows = next.deps.length === 1 && next.deps[0].peer === c.peer && next.deps[0].counter === c.counter + c.length - 1;
const nextMeta = parse(next.message);
if (!follows || nextMeta.n !== meta.n) break;
c = next;
meta = { ...meta, ...nextMeta };
i++;
}
const last = { peer: c.peer, counter: c.counter + c.length - 1 };
out.push({
id: opName(last),
peer: c.peer,
lamport: c.lamport + c.length - 1,
time: c.timestamp,
message: meta.m ?? "(undo/redo)",
by: meta.by ?? "?",
actor: meta.a ?? "human",
tag: meta.t,
hash: meta.h,
parents: first.deps.map(opName),
frontiers: [last],
spans: [{ peer: c.peer, counter: first.counter, length: c.counter + c.length - first.counter }],
});
}
}
// Newest first. Lamport order is consistent with causality; peer breaks ties deterministically.
return out.sort((a, b) => b.lamport - a.lamport || (a.peer < b.peer ? 1 : -1));
}
/** A read-only replica of the document as it stood at a commit. */
export function at(doc: Doc, commit: Pick<Commit, "frontiers">): Doc {
return new Doc(doc.loro.forkAt(commit.frontiers), doc.author);
}
/**
* The nodes some ops wrote to, read from the containers they changed: a node's data map shares
* the node's id, and its body sits under it. Tree ops are read for what they created, moved or
* deleted. Nodes that have since been deleted are still named (by id).
*/
export function touched(doc: Doc, spans: Span[]): { nodes: Set<NodeId>; deleted: Set<NodeId>; unknown: boolean } {
const nodes = new Set<NodeId>();
const deleted = new Set<NodeId>();
let unknown = false;
for (const s of spans) {
if (s.length <= 0) continue;
let tree = false;
for (const cid of doc.loro.getChangedContainersIn({ peer: s.peer, counter: s.counter }, s.length)) {
if (cid === "cid:root-tree:Tree") tree = true;
if (cid.startsWith("cid:root-")) continue;
const m = /^cid:(\d+@\d+):(\w+)$/.exec(cid);
if (!m) continue;
if (m[2] === "Map") nodes.add(m[1] as NodeId);
else {
const path = doc.loro.getPathToContainer(cid);
if (path?.[0] === "tree" && typeof path[1] === "string") nodes.add(path[1] as NodeId);
else unknown = true;
}
}
if (!tree) continue;
for (const change of doc.loro.exportJsonInIdSpan(s)) {
for (const op of change.ops) {
const c = op.content as { type?: string; target?: string; parent?: string };
if (!op.container.endsWith(":Tree") || !c.target) continue;
if (c.type === "delete") deleted.add(c.target as NodeId);
else {
nodes.add(c.target as NodeId);
if (c.parent) nodes.add(c.parent as NodeId);
}
}
}
}
return { nodes, deleted, unknown };
}
export interface Verification {
checked: number;
unhashed: number;
mismatches: { id: string; message: string; recorded: string; actual: string }[];
}
/**
* Check out every commit and confirm the tree hashes to what the commit recorded. One detached
* replica walks the commits oldest first: a checkout moves it from one state to the next, where
* forking a fresh replica for each would replay the library's history every time. A detached
* replica can resolve an anchor whose characters were deleted later differently from the replica
* that made the commit, so a mismatch is checked again in a fresh fork before it is reported.
*/
export function verifyHistory(doc: Doc): Verification {
const result: Verification = { checked: 0, unhashed: 0, mismatches: [] };
const walker = doc.fork();
for (const c of history(doc).reverse()) {
if (!c.hash) {
result.unhashed++;
continue;
}
walker.loro.checkout(c.frontiers);
walker.reread();
let actual = walker.stateHash();
if (actual !== c.hash) actual = at(doc, c).stateHash();
result.checked++;
if (actual !== c.hash) result.mismatches.push({ id: c.id, message: c.message, recorded: c.hash, actual });
}
return result;
}
/** Point a node's anchors back at the spans they had in `was`, if they have moved since. */
function reanchor(doc: Doc, id: NodeId, was: NodeSnap, now: NodeSnap) {
const same = was.anchors.length === now.anchors.length && was.anchors.every((a, i) => a.start === now.anchors[i].start && a.end === now.anchors[i].end);
const node = doc.tree.getNodeByID(id);
const parent = node?.parent();
if (same || !was.anchors.length || !node || !parent) return;
node.data.set("anchors", doc.makeAnchors(parent, was.anchors.map((a) => [a.start, a.end])) as never);
doc.mark(id);
}
/** Roll the whole tree back to a commit by writing the inverse as a new commit. History is kept. */
export function revertTo(doc: Doc, commit: Commit) {
const target = at(doc, commit).snap();
if (doc.snap().library && !target.library) throw new OpError("that commit is from before the library existed; revert one document to it instead");
doc.begin(`Revert to “${clip(commit.message, 60)}”`, "human", "revert");
doc.loro.revertTo(commit.frontiers);
doc.reread();
// A reverted deletion comes back as new characters and new nodes, which old cursors do not
// point at. The two trees have the same shape, so walk them together and re-anchor.
const now = doc.snap();
const fix = (was: NodeId, is: NodeId) => {
const w = target.nodes[was];
const n = now.nodes[is];
if (!w || !n) return;
reanchor(doc, is, w, n);
w.children.forEach((c, i) => n.children[i] && fix(c, n.children[i]));
};
fix(target.root, now.root);
doc.commit(`Revert to “${clip(commit.message, 60)}”`, "human", "revert");
}
/**
* Roll one subtree (a document) back to how it stood at a commit, leaving the rest of the library
* as it is now. Nodes that still exist keep their ids and are moved, rewritten and re-anchored to
* match; nodes deleted since come back as copies under new ids; nodes added since are deleted.
* The document node itself stays where it is now.
*/
export function revertDocTo(doc: Doc, commit: Commit, id: NodeId) {
const target = at(doc, commit).snap();
const now = doc.snap();
if (!target.nodes[id]) throw new OpError(`“${clip(label(now, id), 40)}” did not exist yet at “${clip(commit.message, 40)}”`);
if (!now.nodes[id]) throw new OpError("that node no longer exists");
const message = `Revert “${clip(label(now, id), 40)}” to “${clip(commit.message, 50)}”`;
const tree = doc.tree;
const alive = (x: NodeId) => !!tree.getNodeByID(x) && !tree.isNodeDeleted(x);
const wanted = new Set([id, ...descendants(target, id)]);
doc.begin(message, "human", "revert");
const place = (tid: NodeId, parent: NodeId | null, index: number) => {
const t = target.nodes[tid];
if (!alive(tid)) {
doc.graft(target, tid, parent!, { index });
return;
}
const n = tree.getNodeByID(tid)!;
if (parent) {
const from = n.parent()!;
const at = (from.children() ?? []).findIndex((c) => c.id === tid);
if (from.id !== parent || at !== index) {
tree.move(tid, parent, index);
doc.mark(from.id);
doc.mark(parent);
}
}
doc.mark(tid);
const d = n.data;
for (const [key, value] of [["kind", t.kind], ["title", t.title], ["by", t.by], ["pinned", t.pinned], ["up", t.seenUp], ["down", t.seenDown]] as const) {
if (d.get(key) !== value) d.set(key, value);
}
for (const [key, value] of [["form", t.form], ["lens", t.lens]] as const) {
if (value === undefined) d.get(key) !== undefined && d.delete(key);
else if (d.get(key) !== value) d.set(key, value);
}
if (!t.ref) d.get("ref") !== undefined && d.delete("ref");
else if (JSON.stringify(canonRef(t.ref)) !== JSON.stringify(d.get("ref") ? canonRef(d.get("ref") as Ref) : null)) d.set("ref", t.ref as never);
// Declined phrases only ever grow; going back to a commit forgets the ones added since.
for (const k of d.keys()) if (k.startsWith(NOLINK) && !t.nolink?.includes(k.slice(NOLINK.length))) d.delete(k);
if (t.nolink?.length) setNolink(n, t.nolink);
const body = d.get("body") as LoroText | undefined;
if (body && body.toString() !== t.body) {
body.update(t.body);
doc.markAnchoredIn(body.id);
}
t.children.forEach((c, i) => place(c, tid, i));
};
place(id, null, 0);
// What was added since goes; then a second pass puts the survivors back in order.
for (const x of descendants(doc.snap(), id)) {
if (!wanted.has(x) && alive(x)) {
doc.mark(tree.getNodeByID(x)!.parent()!.id);
tree.delete(x);
}
}
place(id, null, 0);
// Re-anchor what no longer points where it pointed then.
const snap = doc.snap();
for (const x of wanted) if (snap.nodes[x] && x !== id) reanchor(doc, x, target.nodes[x], snap.nodes[x]);
doc.commit(message, "human", "revert");
}
/**
* Re-attach notes whose anchor was lost but whose quoted text is back in the parent's body, as
* happens when a deletion is undone: the text returns as new characters that old cursors do not
* point at. Returns how many were re-anchored.
*/
export function healAnchors(doc: Doc): number {
const snap = doc.snap();
const ops: Op[] = [];
for (const n of Object.values(snap.nodes)) {
if (n.kind !== "note" || !n.parent || !n.anchors.length || !n.anchors.every(anchorLost)) continue;
const quote = n.anchors[0].quote;
const at = quote ? snap.nodes[n.parent].body.indexOf(quote) : -1;
if (at >= 0) ops.push({ op: "update", id: n.id, anchors: [[at, at + quote.length]] }, { op: "bless", id: n.id, dir: "down" });
}
if (ops.length) doc.apply(ops, `Re-anchor ${ops.length / 2} note${ops.length > 2 ? "s" : ""} to restored text`, { actor: "llm", tag: "regen" });
// Links to nodes that came back under new ids are found again the same way, from what they recorded.
healLinks(doc);
return ops.length / 2;
}
// ---- version-vector arithmetic ----
type VV = Map<PeerID, number>;
const vvOf = (doc: Doc): VV => doc.loro.version().toJSON();
function vvMin(a: VV, b: VV): VV {
const out: VV = new Map();
for (const [peer, n] of a) {
const m = Math.min(n, b.get(peer) ?? 0);
if (m > 0) out.set(peer, m);
}
return out;
}
export const vvIncludes = (a: VV, b: VV) => [...b].every(([peer, n]) => (a.get(peer) ?? 0) >= n);
/** The ops in `to` that `from` lacks. */
function spansBetween(from: VV, to: VV): Span[] {
const out: Span[] = [];
for (const [peer, n] of to) {
const m = from.get(peer) ?? 0;
if (n > m) out.push({ peer, counter: m, length: n - m });
}
return out;
}
export const encodeVV = (vv: VV) => JSON.stringify([...vv]);
export const decodeVV = (s: string): VV => new Map(JSON.parse(s));
// ---- merge ----
export interface MergeReport {
/** nothing: already contained. forward: the other side was strictly ahead. merge: histories had diverged. */
kind: "nothing" | "forward" | "merge";
conflicts: Conflict[];
/** For a real merge: the three states it was computed from, for anything that wants to look further. */
base?: Snap;
ours?: Snap;
theirs?: Snap;
}
/**
* Bring another replica's changes in. `bytes` is its update, `theirVV` its version.
* The CRDT does the structural merge; what it cannot see is then looked for by comparing
* base, ours and theirs node by node.
*
* Comparing whole states costs the size of the library, so unless `full` is asked for, it is
* done only when the two sides could disagree: when they wrote to a node in common, or one side
* deleted something. Sync rounds take the short way; explicit merges ask for the states.
*/
export function mergeUpdate(doc: Doc, bytes: Uint8Array, theirVV: VV, opts: { full?: boolean } = {}): MergeReport {
const ourVV = vvOf(doc);
if (vvIncludes(ourVV, theirVV)) return { kind: "nothing", conflicts: [] };
if (vvIncludes(theirVV, ourVV)) {
doc.loro.import(bytes);
doc.touch();
return { kind: "forward", conflicts: [] };
}
const mine = opts.full ? null : touched(doc, spansBetween(theirVV, ourVV));
// A copy: a snapshot taken before a write answers lookups but cannot be enumerated (see Doc.patch).
const oursNow = opts.full ? { ...doc.snap(), nodes: { ...doc.snap().nodes } } : null;
doc.loro.import(bytes);
doc.touch();
if (mine) {
const theirs = touched(doc, spansBetween(ourVV, theirVV));
const overlap = [...mine.nodes].some((id) => theirs.nodes.has(id));
const deletes = (mine.deleted.size && theirs.nodes.size + theirs.deleted.size) || (theirs.deleted.size && mine.nodes.size);
if (!overlap && !deletes && !mine.unknown && !theirs.unknown) return { kind: "merge", conflicts: [] };
}
const merged = doc.snap();
const stateAt = (vv: VV) => new Doc(doc.loro.forkAt(doc.loro.vvToFrontiers(new VersionVector(vv)))).snap();
const ours = oursNow ?? stateAt(ourVV);
const base = stateAt(vvMin(ourVV, theirVV));
const theirs = stateAt(theirVV);
const found = detectConflicts(base, ours, theirs, merged);
const known = new Set(doc.conflicts().map((c) => c.id));
const fresh = found.filter((c) => !known.has(c.id));
if (fresh.length) {
for (const c of fresh) doc.conflictMap.set(c.id, JSON.stringify(c));
doc.touch();
doc.commit(`Detected ${fresh.length} semantic conflict${fresh.length > 1 ? "s" : ""}`, "llm", "conflict");
}
return { kind: "merge", conflicts: fresh, base, ours, theirs };
}
/** Merge a branch (another Doc) into this one, leaving a merge commit that names it. */
export function mergeBranch(doc: Doc, other: Doc, name: string): MergeReport {
const report = mergeUpdate(doc, other.loro.export({ mode: "update", from: doc.loro.version() }), vvOf(other), { full: true });
if (report.kind === "merge") {
const n = report.conflicts.length;
doc.loro.getMap("meta").set("merges", ((doc.loro.getMap("meta").get("merges") as number) ?? 0) + 1);
doc.commit(`Merge ${name}${n ? ` (${n} conflict${n > 1 ? "s" : ""} to review)` : ""}`, "human", "merge");
}
return report;
}
/** The semantic conflicts a structural merge leaves behind. Pure: same inputs, same records. */
export function detectConflicts(base: Snap, ours: Snap, theirs: Snap, merged: Snap): Conflict[] {
const out: Conflict[] = [];
const ids = new Set<NodeId>([...Object.keys(ours.nodes), ...Object.keys(theirs.nodes)] as NodeId[]);
const order = (x: string, y: string): [string, string] => (x <= y ? [x, y] : [y, x]);
for (const id of ids) {
const b = base.nodes[id];
const o = ours.nodes[id];
const t = theirs.nodes[id];
if (!b) continue; // created on one side only: nothing to disagree with
if (o && t) {
// Both sides changed the same field to different things. The CRDT's interleaving is
// well-formed text that neither author wrote.
for (const field of ["title", "body"] as const) {
if (o[field] !== b[field] && t[field] !== b[field] && o[field] !== t[field]) {
const [a, bb] = order(o[field], t[field]);
out.push({
id: digest(["edit-edit", id, field, a, bb].join("\u0000")),
type: "edit-edit",
node: id,
field,
title: merged.nodes[id]?.title ?? b.title,
base: b[field],
a,
b: bb,
merged: merged.nodes[id]?.[field] ?? "",
status: "open",
});
}
}
// Both sides pointed the same node at different targets: the CRDT keeps one; say which was lost.
const [rb, ro, rt] = [b, o, t].map((n) => refText(n.ref));
if (ro !== rb && rt !== rb && ro !== rt) {
const [a, bb] = order(ro, rt);
out.push({
id: digest(["edit-edit", id, "ref", a, bb].join("\u0000")),
type: "edit-edit",
node: id,
field: "ref",
title: merged.nodes[id] ? label(merged, id) : b.title,
base: rb,
a,
b: bb,
merged: refText(merged.nodes[id]?.ref),
status: "open",
});
}
} else if (!!o !== !!t) {
// One side deleted the node (or an ancestor); the other kept working in it.
const kept = (o ? ours : theirs) as Snap;
const k = kept.nodes[id];
const parentGone = b.parent && !(o ? theirs : ours).nodes[b.parent];
if (parentGone) continue; // reported once, at the top of the deleted subtree
const touchedHere = [id, ...descendants(kept, id)].filter((x) => {
const was = base.nodes[x];
const now = kept.nodes[x];
return !was || was.title !== now.title || was.body !== now.body || refText(was.ref) !== refText(now.ref);
});
if (!touchedHere.length) continue;
out.push({
id: digest(["edit-delete", id, k.title, k.body].join("\u0000")),
type: "edit-delete",
node: id,
field: "body",
title: k.title || b.title,
base: b.body,
a: k.body,
b: "",
merged: "",
status: "open",
parent: b.parent ?? undefined,
});
}
}
return out.sort((x, y) => (x.id < y.id ? -1 : 1));
}
/**
* Settle a conflict by writing a chosen text as an ordinary commit. The record keeps what was
* there before, so the decision can be reopened.
*/
export function resolveConflict(
doc: Doc,
id: string,
text: string,
how: { by: string; rationale?: string; actor?: "human" | "llm" },
) {
const c = doc.conflicts().find((x) => x.id === id);
if (!c) throw new Error(`no such conflict: ${id}`);
const snap = doc.snap();
const actor = how.actor ?? "human";
const record: Conflict = { ...c, status: "resolved", resolved: text, rationale: how.rationale, resolvedBy: how.by };
doc.conflictMap.set(id, JSON.stringify(record));
doc.touch();
const message = `Resolve conflict in “${clip(c.title, 40)}” (${how.by})`;
if (c.type === "edit-edit" && c.field === "ref" && snap.nodes[c.node]) {
const ref = readRefText(text);
if (typeof ref === "string") throw new OpError(`not a target: ${ref}`);
doc.apply([{ op: "update", id: c.node, ref }], message, { actor, tag: "resolve" });
} else if (c.type === "edit-edit" && snap.nodes[c.node]) {
doc.apply([{ op: "update", id: c.node, [c.field!]: text }], message, { actor, tag: "resolve" });
} else if (c.type === "edit-delete" && text && c.parent && snap.nodes[c.parent] && !snap.nodes[c.node]) {
// Restoring: tree nodes cannot be undeleted, so the kept text comes back as a new node.
doc.apply([{ op: "create", parent: c.parent, title: c.title, body: text }], message, { actor, tag: "resolve" });
} else if (c.type === "contradiction" && snap.nodes[c.node] && text !== snap.nodes[c.node].body) {
doc.apply([{ op: "update", id: c.node, body: text }], message, { actor, tag: "resolve" });
} else {
doc.commit(message, actor, "resolve");
}
}
/** Undo a resolution: put back what the merge produced and mark the conflict open again. */
export function reopenConflict(doc: Doc, id: string) {
const c = doc.conflicts().find((x) => x.id === id);
if (!c || c.status !== "resolved") return;
const { resolved: _r, rationale: _why, resolvedBy: _by, ...rest } = c;
doc.conflictMap.set(id, JSON.stringify({ ...rest, status: "open" }));
doc.touch();
const snap = doc.snap();
if (c.field === "ref" && snap.nodes[c.node]) {
const ref = readRefText(c.merged);
doc.apply([{ op: "update", id: c.node, ref: typeof ref === "string" ? null : ref }], `Reopen conflict in “${clip(c.title, 40)}”`, { actor: "llm", tag: "resolve" });
} else if ((c.type === "edit-edit" || c.type === "contradiction") && snap.nodes[c.node]) {
doc.apply([{ op: "update", id: c.node, [c.field ?? "body"]: c.merged }], `Reopen conflict in “${clip(c.title, 40)}”`, {
actor: "llm",
tag: "resolve",
});
} else {
doc.commit(`Reopen conflict in “${clip(c.title, 40)}”`, "human", "resolve");
}
}
// ---- branches ----
/** A set of named replicas of one library. */
export class Repo {
branches = new Map<string, Doc>();
current = "main";
constructor(main: Doc) {
this.branches.set("main", main);
}
get doc(): Doc {
return this.branches.get(this.current)!;
}
/** Create a branch from the current one, optionally from an earlier commit. */
branch(name: string, from?: Commit): Doc {
if (this.branches.has(name)) throw new Error(`branch exists: ${name}`);
const doc = from ? at(this.doc, from).fork() : this.doc.fork();
doc.author = this.doc.author;
this.branches.set(name, doc);
return doc;
}
switch(name: string) {
if (!this.branches.has(name)) throw new Error(`no such branch: ${name}`);
this.current = name;
}
merge(from: string): MergeReport {
const other = this.branches.get(from);
if (!other) throw new Error(`no such branch: ${from}`);
return mergeBranch(this.doc, other, from);
}
}
/** A target as text for a conflict record ("" for none): what a person reads and what resolving it parses back. */
function refText(r: Ref | undefined): string {
// A node target is kept whole (its id is what counts), the others in their text form.
return !r ? "" : r.kind === "node" ? JSON.stringify(r) : formatTarget(r);
}
function readRefText(text: string): Ref | null | string {
if (!text) return null;
if (text.startsWith("{")) {
try {
return validateRef(JSON.parse(text));
} catch (err) {
return (err as Error).message;
}
}
return parseTarget(text);
}
+151
View File
@@ -0,0 +1,151 @@
/** Text utilities: hashing, sentence/word segmentation, and the size → display-form rule. */
export type Range = [start: number, end: number];
export type Form = "gloss" | "note" | "passage";
// ---- SHA-256 (synchronous; needed inside commits, where WebCrypto's async API can't be used) ----
const K = new Uint32Array(64);
{
let n = 0;
for (let c = 2; n < 64; c++) {
let prime = true;
for (let d = 2; d * d <= c; d++) if (c % d === 0) { prime = false; break; }
if (prime) K[n++] = (Math.cbrt(c) * 2 ** 32) >>> 0;
}
}
const encoder = new TextEncoder();
export function sha256(input: string): string {
const data = encoder.encode(input);
const bitLen = data.length * 8;
const padded = new Uint8Array((((data.length + 8) >> 6) + 1) << 6);
padded.set(data);
padded[data.length] = 0x80;
const view = new DataView(padded.buffer);
view.setUint32(padded.length - 8, Math.floor(bitLen / 2 ** 32));
view.setUint32(padded.length - 4, bitLen >>> 0);
const h = new Uint32Array([
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
const w = new Uint32Array(64);
const rotr = (x: number, n: number) => (x >>> n) | (x << (32 - n));
for (let off = 0; off < padded.length; off += 64) {
for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + i * 4);
for (let i = 16; i < 64; i++) {
const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
}
let [a, b, c, d, e, f, g, hh] = h;
for (let i = 0; i < 64; i++) {
const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
const ch = (e & f) ^ (~e & g);
const t1 = (hh + S1 + ch + K[i] + w[i]) >>> 0;
const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
const maj = (a & b) ^ (a & c) ^ (b & c);
const t2 = (S0 + maj) >>> 0;
hh = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0;
}
h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
}
return Array.from(h, (x) => x.toString(16).padStart(8, "0")).join("");
}
/** Short content hash used for staleness bookkeeping. */
export const digest = (s: string) => sha256(s).slice(0, 16);
// ---- Segmentation ----
/** Paragraph ranges: runs of text separated by one or more blank lines. */
export function paragraphs(body: string): Range[] {
const out: Range[] = [];
const re = /\n\s*\n/g;
let start = 0;
for (let m; (m = re.exec(body)); ) {
if (m.index > start) out.push([start, m.index]);
start = m.index + m[0].length;
}
if (start < body.length) out.push([start, body.length]);
return out.filter(([s, e]) => body.slice(s, e).trim().length > 0);
}
/**
* Sentence ranges. A sentence ends at . ! or ? (plus any closing quote or bracket) followed by
* whitespace and something that looks like a sentence start, or at the end of its paragraph.
*/
export function sentences(body: string): Range[] {
const out: Range[] = [];
for (const [ps, pe] of paragraphs(body)) {
const para = body.slice(ps, pe);
const re = /[.!?]["”’)\]*`]*\s+(?=["“‘(\[*`]*[A-Z0-9])/g;
let start = 0;
const push = (s: number, e: number) => {
while (s < e && /\s/.test(para[s])) s++;
while (e > s && /\s/.test(para[e - 1])) e--;
if (e > s) out.push([ps + s, ps + e]);
};
for (let m; (m = re.exec(para)); ) {
const end = m.index + m[0].length;
push(start, end);
start = end;
}
push(start, para.length);
}
return out;
}
/** Word ranges (letters, digits, inner apostrophes and hyphens). */
export function words(body: string, within?: Range): Range[] {
const [s, e] = within ?? [0, body.length];
const out: Range[] = [];
const re = /[\p{L}\p{N}]+(?:['’\-.][\p{L}\p{N}]+)*/gu;
re.lastIndex = s;
for (let m; (m = re.exec(body)) && m.index < e; ) {
out.push([m.index, Math.min(e, m.index + m[0].length)]);
}
return out;
}
export const wordCount = (s: string) => words(s).length;
/**
* The display form follows the size of what is being expanded, so it is known before the first
* token arrives and nothing reflows while text streams in.
*/
export function formFor(selection: string): Form {
const n = wordCount(selection);
if (n <= 3) return "gloss";
if (n <= 45 && sentences(selection).length <= 2) return "note";
return "passage";
}
/** Index of the range containing offset, or the nearest one after it. */
export function rangeAt(ranges: Range[], offset: number): number {
for (let i = 0; i < ranges.length; i++) if (offset < ranges[i][1]) return i;
return ranges.length - 1;
}
export const overlaps = (a: Range, b: Range) => a[0] < b[1] && b[0] < a[1];
/** Strip the two inline markers so text can be shown or sent as plain prose. */
export const plain = (s: string) => s.replace(/[*`]/g, "");
export function clip(s: string, n: number): string {
s = s.replace(/\s+/g, " ").trim();
return s.length <= n ? s : s.slice(0, n - 1).trimEnd() + "…";
}
/** A file name or title as a document's slug: lowercase letters, digits and single hyphens. */
export function slugify(s: string): string {
return (
s
.normalize("NFKD")
.replace(/[̀-ͯ]/g, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 60)
.replace(/-+$/, "") || "untitled"
);
}