Core without documents: no slugs; a node's top; targets by titles from the library root
The model has no slug any more (field, ops, canonical row, slugFor, freeSlug, RESERVED, findDoc). The child of the root a node is under is a derived relation, topOf (docOf and documents stay as deprecated aliases for the UI until step 2); ancestorsInDoc becomes ancestorsBelowRoot. Slug keys and a target's old `doc` in stored libraries are ignored. A node target's path is the titles down from the library root; `rel` marks a path read below a top (a file being imported, what the agent or a person typed). Where two sections share a title, the one the link is written in wins. The text format writes /Top title/…, and ./… inside the exported subtree. The agent may give a node id as a target. renderContext renders the top's outline in an <outline> tag, and steps down the focus path when even titles are over budget. Prompts, the reviewer and the scanner speak of the library, trees and tops; the scanner's unit is the top, with the same behaviour (scripts/linkEval.ts gives identical metrics). src/core/library.ts keeps a slug-free shim for the UI's document features (names made from titles) until step 2 removes them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
1 parent
626dc19e1b
commit
44d2e437eb
32 files changed
+634
-577
No files matched your search
@@ -2,7 +2,7 @@
|
||||
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 { Doc, isStale, staleness, tops, 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";
|
||||
@@ -151,12 +151,11 @@ describe("article nodes", () => {
|
||||
// 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.
|
||||
// Not one of the root's sections: not listed, no count.
|
||||
expect(listDocs(snap)).toEqual(before);
|
||||
expect(documents(snap)).toHaveLength(1);
|
||||
expect(tops(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);
|
||||
expect(inArticles(snap, first) && inArticles(snap, box) && !inArticles(snap, tops(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");
|
||||
@@ -176,7 +175,7 @@ describe("article nodes", () => {
|
||||
// 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);
|
||||
expect(tops(snap)).toHaveLength(1);
|
||||
}
|
||||
// The next annotation goes under the same node on either replica.
|
||||
expect(articleParent(doc.snap(), OCTOPUS)).toEqual(articleParent(other.snap(), OCTOPUS));
|
||||
@@ -187,6 +186,6 @@ describe("article nodes", () => {
|
||||
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/);
|
||||
expect(() => doc.apply([{ op: "create", parent: tops(doc.snap())[0], title: "Box", articles: true }], "Bad")).toThrow(/container/);
|
||||
});
|
||||
});
|
||||
+33
-10
@@ -1,6 +1,6 @@
|
||||
import { UndoManager } from "loro-crdt";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Doc, SYSTEM_ORIGIN, docOf, isStale, retitleOps, staleness, sections, notesOf, type NodeId } from "../src/core/model";
|
||||
import { Doc, SYSTEM_ORIGIN, ancestorsBelowRoot, isStale, retitleOps, staleness, sections, notesOf, topOf, tops, type NodeId } from "../src/core/model";
|
||||
import { healAnchors, history, verifyHistory, revertTo, revertDocTo, mergeBranch, mergeUpdate, resolveConflict, reopenConflict, at, touched, Repo } from "../src/core/repo";
|
||||
import { formFor, paragraphs, sentences, sha256, words } from "../src/core/text";
|
||||
|
||||
@@ -256,9 +256,9 @@ describe("merge", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---- the library: documents as sections of one tree ----
|
||||
// ---- the library: one tree, whose root's children are nodes like any other ----
|
||||
|
||||
/** A library of two documents, each with a part, a leaf, and a note. */
|
||||
/** A library of two tops, each with a part, a leaf, and a note. */
|
||||
function library() {
|
||||
const doc = Doc.library("alice");
|
||||
const lib = doc.snap().root;
|
||||
@@ -304,8 +304,9 @@ describe("library", () => {
|
||||
// The library's own text is the reader's; editing it marks no document.
|
||||
doc.apply([{ op: "update", id: lib, body: "My library." }], "Write the library's text");
|
||||
expect(staleIds(doc).sort()).toEqual(inAlpha);
|
||||
expect(docOf(doc.snap(), lib)).toBeNull();
|
||||
expect(docOf(doc.snap(), aLeaf)).toBe(a);
|
||||
expect(topOf(doc.snap(), lib)).toBeNull();
|
||||
expect(topOf(doc.snap(), aLeaf)).toBe(a);
|
||||
expect(ancestorsBelowRoot(doc.snap(), aLeaf)).toEqual([doc.snap().nodes[aLeaf].parent, a]);
|
||||
});
|
||||
|
||||
it("moves a node from one document to another with an ordinary move; its notes keep their anchors and undo moves it back", () => {
|
||||
@@ -315,21 +316,43 @@ describe("library", () => {
|
||||
doc.apply([{ op: "move", id: aPart, parent: b }], "Move Alpha's part into Beta");
|
||||
let snap = doc.snap();
|
||||
expect(snap.nodes[aPart].parent).toBe(b);
|
||||
expect(docOf(snap, aPart)).toBe(b);
|
||||
expect(topOf(snap, aPart)).toBe(b);
|
||||
expect(snap.nodes[aNote].anchors[0].text).toBe("a phrase worth a note");
|
||||
expect(sections(snap, a)).toEqual([]);
|
||||
// Both documents' summaries are now out of date, as with any move.
|
||||
expect(staleness(snap, a).up && staleness(snap, b).up).toBe(true);
|
||||
// A moved section was not a document, so it took no slug; one moved to the top level becomes one.
|
||||
expect(snap.nodes[aPart].slug).toBeUndefined();
|
||||
expect(verifyHistory(doc).mismatches).toEqual([]);
|
||||
expect(undo.undo()).toBe(true);
|
||||
doc.touch();
|
||||
snap = doc.snap();
|
||||
expect(snap.nodes[aPart].parent).toBe(a);
|
||||
expect(snap.nodes[aNote].anchors[0].text).toBe("a phrase worth a note");
|
||||
doc.apply([{ op: "move", id: aPart, parent: snap.root }], "Make it a document");
|
||||
expect(doc.snap().nodes[aPart].slug).toBe("alpha-part");
|
||||
// Moved to the root, it is a top like any other: nothing is stored to make it one.
|
||||
doc.apply([{ op: "move", id: aPart, parent: snap.root }], "Move it to the top");
|
||||
expect(topOf(doc.snap(), aPart)).toBe(aPart);
|
||||
expect(tops(doc.snap())).toEqual([a, b, aPart]);
|
||||
});
|
||||
|
||||
it("loads a library whose nodes still carry slugs (and node targets a document slug), ignoring them", () => {
|
||||
const { doc, a, aLeaf, b } = library();
|
||||
// As an older version wrote them: a slug on each top, and a target naming its document.
|
||||
const old = doc.fork();
|
||||
old.apply([{ op: "create", parent: b, kind: "note", quote: "Beta", ref: { kind: "node", id: aLeaf, path: ["Alpha part"] } }], "Link");
|
||||
const link = notesOf(old.snap(), b)[0];
|
||||
const hash = old.stateHash();
|
||||
old.tree.getNodeByID(a)!.data.set("slug", "alpha");
|
||||
old.tree.getNodeByID(b)!.data.set("slug", "beta");
|
||||
old.tree.getNodeByID(link)!.data.set("ref", { kind: "node", id: aLeaf, doc: "alpha", path: ["Alpha part"] } as never);
|
||||
old.loro.commit();
|
||||
const back = Doc.load(old.snapshotBytes(), "reader");
|
||||
const snap = back.snap();
|
||||
expect(Object.keys(snap.nodes[a])).not.toContain("slug");
|
||||
expect(back.shape(snap, a)).toBe(doc.shape(doc.snap(), a));
|
||||
expect(back.stateHash()).toBe(hash);
|
||||
// The old target still goes where it went, and writing works as ever.
|
||||
expect(snap.nodes[link].ref).toMatchObject({ kind: "node", id: aLeaf });
|
||||
back.apply([{ op: "update", id: b, title: "Beta renamed" }], "Rename");
|
||||
expect(back.snap().nodes[b].title).toBe("Beta renamed");
|
||||
});
|
||||
|
||||
it("copies a subtree whole: content, notes with their anchors, authorship", () => {
|
||||
|
||||
+47
-6
@@ -43,7 +43,7 @@ Deep.
|
||||
Last.
|
||||
`;
|
||||
|
||||
/** A document written into a fresh library: the library, and the document's node. */
|
||||
/** A tree written into a fresh library: the library, and the tree's top. */
|
||||
function build(top: SeedNode) {
|
||||
const doc = Doc.library("test");
|
||||
return { doc, id: writeTree(doc, top) };
|
||||
@@ -125,7 +125,7 @@ describe("parsing", () => {
|
||||
expect(p[3]).toMatch(/^doc\.md:9: expected a "quoted" text/);
|
||||
expect(p[4]).toMatch(/^doc\.md:10: .*no note above it/);
|
||||
expect(p[5]).toMatch(/^doc\.md:11: expected ':'/);
|
||||
expect(p[6]).toMatch(/^doc\.md:13: a document has one "# " heading/);
|
||||
expect(p[6]).toMatch(/^doc\.md:13: a file has one "# " heading/);
|
||||
expect(problems("Just text.\n")[0]).toMatch(/text before the "# Title" heading/);
|
||||
expect(problems("")).toEqual([`doc.md: no "# Title" heading`]);
|
||||
});
|
||||
@@ -210,9 +210,9 @@ function randomTree(seed: number): SeedNode {
|
||||
return n;
|
||||
};
|
||||
const top = node(0);
|
||||
// A node target names a section of this document by its titles (relative, as the format writes
|
||||
// one inside its own document). Only sections reachable by unique titles: a path is read by the
|
||||
// first title that matches, so a duplicate title names its first holder.
|
||||
// A node target names a section of this tree by its titles below the top (relative, as the format
|
||||
// writes one inside the subtree it exports). Only sections reachable by unique titles: a path is
|
||||
// read by the first title that matches, so a duplicate title names its first holder.
|
||||
const paths: string[][] = [[]];
|
||||
const walk = (n: SeedNode, path: string[]) => {
|
||||
const seen = new Set<string>();
|
||||
@@ -225,7 +225,7 @@ function randomTree(seed: number): SeedNode {
|
||||
}
|
||||
};
|
||||
walk(top, []);
|
||||
for (const h of pending) h.target = { kind: "node", path: r.pick(paths) };
|
||||
for (const h of pending) h.target = { kind: "node", path: r.pick(paths), rel: true };
|
||||
return top;
|
||||
}
|
||||
|
||||
@@ -292,3 +292,44 @@ describe("export and import", () => {
|
||||
expect(count(back.doc, back.id, "section")).toBe(count(doc, first, "section"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("node targets in the text format", () => {
|
||||
const A = `# Alpha\n\nAlpha text, which mentions Beta.\n\n^ "Beta" link -> /Beta/Gamma\n\n## Part\n\nThe part, which mentions the leaf.\n\n^ "the leaf" link -> ./Part/Leaf\n\n### Leaf\n\nThe leaf.\n`;
|
||||
const B = `# Beta\n\nBeta text.\n\n## Gamma\n\nGamma text.\n`;
|
||||
|
||||
it("writes a path from the library root, or below the exported subtree's top with ./, and reads both back", () => {
|
||||
const doc = Doc.library("test");
|
||||
const b = writeText(doc, B, "beta.md");
|
||||
const a = writeText(doc, A, "alpha.md");
|
||||
let snap = doc.snap();
|
||||
const part = sections(snap, a)[0];
|
||||
const leaf = sections(snap, part)[0];
|
||||
const gamma = sections(snap, b)[0];
|
||||
const [toBeta] = notesOf(snap, a);
|
||||
const [toLeaf] = notesOf(snap, part);
|
||||
expect(snap.nodes[toBeta].ref).toEqual({ kind: "node", id: gamma, path: ["Beta", "Gamma"] });
|
||||
expect(snap.nodes[toLeaf].ref).toEqual({ kind: "node", id: leaf, path: ["Alpha", "Part", "Leaf"] });
|
||||
expect(serializeDoc(snap, a).text).toBe(A);
|
||||
// Exported from lower down, a path inside the subtree is relative to it; one outside it is from the root.
|
||||
const lower = serializeDoc(snap, part).text;
|
||||
expect(lower).toContain(`^ "the leaf" link -> ./Leaf`);
|
||||
// Moved elsewhere, the target is written from where it is now.
|
||||
doc.apply([{ op: "move", id: gamma, parent: a }], "Move");
|
||||
snap = doc.snap();
|
||||
expect(serializeDoc(snap, a).text).toContain(`^ "Beta" link -> ./Gamma`);
|
||||
});
|
||||
|
||||
it("reads a relative path in its own tree, even where another top has the same titles", () => {
|
||||
const doc = Doc.library("test");
|
||||
const first = writeText(doc, A, "alpha.md");
|
||||
const second = writeText(doc, A, "alpha-again.md");
|
||||
const snap = doc.snap();
|
||||
const leafOf = (top: NodeId) => sections(snap, sections(snap, top)[0])[0];
|
||||
const linkIn = (top: NodeId) => snap.nodes[notesOf(snap, sections(snap, top)[0])[0]].ref;
|
||||
expect(linkIn(first)).toMatchObject({ id: leafOf(first) });
|
||||
expect(linkIn(second)).toMatchObject({ id: leafOf(second) });
|
||||
// A path to a tree that is not there yet is kept, and found when it arrives.
|
||||
const b = writeText(doc, B, "beta.md");
|
||||
expect(doc.snap().nodes[notesOf(doc.snap(), first)[0]].ref).toMatchObject({ id: sections(doc.snap(), b)[0] });
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Every starter document in library/ parses and builds. A failure names the file, the line, the
|
||||
* Every starter file in library/ parses and builds. A failure names the file, the line, the
|
||||
* section and the quote, all of them at once, so the files can be fixed in one pass.
|
||||
*/
|
||||
import { readFileSync, readdirSync } from "node:fs";
|
||||
@@ -10,7 +10,6 @@ import { writeText } from "../src/core/seed";
|
||||
import { slugify } from "../src/core/text";
|
||||
|
||||
const dir = new URL("../library/", import.meta.url);
|
||||
const id0 = (f: string) => slugify(f.slice(0, -3));
|
||||
const files = (() => {
|
||||
try {
|
||||
return readdirSync(dir).filter((f) => f.endsWith(".md")).sort();
|
||||
@@ -27,11 +26,11 @@ describe("library", () => {
|
||||
const id = f.slice(0, -3);
|
||||
if (slugify(id) !== id) failures.push(`${f}: the file name is not a valid id (lowercase letters, digits, hyphens); it would be imported as "${slugify(id)}"`);
|
||||
try {
|
||||
const id = writeText(lib, readFileSync(new URL(f, dir), "utf8"), f, { slug: id0(f) });
|
||||
const id = writeText(lib, readFileSync(new URL(f, dir), "utf8"), f);
|
||||
const snap = lib.snap();
|
||||
const stale = [id, ...descendants(snap, id)].filter((n) => isStale(snap, n));
|
||||
if (stale.length) failures.push(`${f}: ${stale.length} nodes start out stale`);
|
||||
if (!snap.nodes[id].title) failures.push(`${f}: the document has no title`);
|
||||
if (!snap.nodes[id].title) failures.push(`${f}: the file has no title`);
|
||||
} catch (err) {
|
||||
if (!(err instanceof FormatError)) throw err;
|
||||
failures.push(...err.problems);
|
||||
|
||||
+11
-11
@@ -96,7 +96,7 @@ describe("the extractor", () => {
|
||||
|
||||
describe("the tiering rule", () => {
|
||||
const hit = (over: Record<string, unknown>) =>
|
||||
({ c: { kind: "name", rarity: 50_000, words: 2, text: "Fred Hoyle", key: "fred hoyle", start: 0, end: 10, variants: [], sentenceStart: false }, target: W("Fred Hoyle"), source: "wikipedia", title: "Fred Hoyle", description: "British astronomer", fit: 0.75, exact: true, redirect: false, sense: false, searched: false, central: false, firstInDoc: true, ...over }) as never;
|
||||
({ c: { kind: "name", rarity: 50_000, words: 2, text: "Fred Hoyle", key: "fred hoyle", start: 0, end: 10, variants: [], sentenceStart: false }, target: W("Fred Hoyle"), source: "wikipedia", title: "Fred Hoyle", description: "British astronomer", fit: 0.75, exact: true, redirect: false, sense: false, searched: false, central: false, firstInTop: true, ...over }) as never;
|
||||
|
||||
it("applies an exact, well-fitting name without asking", () => {
|
||||
expect(judge(hit({})).tier).toBe("auto");
|
||||
@@ -110,19 +110,19 @@ describe("the tiering rule", () => {
|
||||
expect(judge(hit({ c: common, fit: 0.62 })).tier).toBe(null);
|
||||
});
|
||||
|
||||
it("applies a link unasked only at a concept's first mention in the document; later mentions are suggested", () => {
|
||||
expect(judge(hit({ firstInDoc: false })).tier).toBe("suggest");
|
||||
it("applies a link unasked only at a concept's first mention under its top; later mentions are suggested", () => {
|
||||
expect(judge(hit({ firstInTop: false })).tier).toBe("suggest");
|
||||
});
|
||||
|
||||
it("applies a library title unasked only when it has several words; a one-word title is at most suggested", () => {
|
||||
const lib = (key: string, words: number) => hit({ source: "library", target: { kind: "node", id: "1@1" }, sameDoc: true, fit: 0.9, c: { kind: "noun", rarity: 50_000, words, text: key, key, start: 0, end: key.length, variants: [], sentenceStart: false } });
|
||||
const lib = (key: string, words: number) => hit({ source: "library", target: { kind: "node", id: "1@1" }, sameTop: true, fit: 0.9, c: { kind: "noun", rarity: 50_000, words, text: key, key, start: 0, end: key.length, variants: [], sentenceStart: false } });
|
||||
expect(judge(lib("comma", 1)).tier).toBe("suggest");
|
||||
expect(judge(lib("diagonal lemma", 2)).tier).toBe("auto");
|
||||
});
|
||||
|
||||
it("links a concept central to the document once, at its first mention, and only as a suggestion", () => {
|
||||
expect(judge(hit({ central: true, firstInDoc: false })).tier).toBe(null);
|
||||
expect(judge(hit({ central: true, firstInDoc: true })).tier).toBe("suggest");
|
||||
it("links a concept central to its tree once, at its first mention, and only as a suggestion", () => {
|
||||
expect(judge(hit({ central: true, firstInTop: false })).tier).toBe(null);
|
||||
expect(judge(hit({ central: true, firstInTop: true })).tier).toBe("suggest");
|
||||
});
|
||||
|
||||
it("never applies a disambiguation sense, a country or a surname page unasked", () => {
|
||||
@@ -147,7 +147,7 @@ describe("scanning a node", () => {
|
||||
expect(r.degraded).toEqual([]);
|
||||
});
|
||||
|
||||
it("never links a section to itself or its ancestors, and prefers a section in another document", async () => {
|
||||
it("never links a section to itself or its ancestors, and prefers a section under another top", async () => {
|
||||
const { doc, ycomb, notes, lambda } = library();
|
||||
const { linker } = setup(doc, { wiki: null });
|
||||
// "lambda calculus" in its own child: the title is its parent's, so no library link.
|
||||
@@ -238,12 +238,12 @@ describe("the node index", () => {
|
||||
expect(seen.length - first).toBe(1);
|
||||
});
|
||||
|
||||
it("gives a Related list from other documents only", async () => {
|
||||
it("gives a Related list from under other tops only", async () => {
|
||||
const { doc, ycomb, notes } = library();
|
||||
const { linker } = setup(doc);
|
||||
const r = await linker.related(notes);
|
||||
expect(r.related.length).toBeGreaterThan(0);
|
||||
expect(r.related.every((x) => x.doc !== "Notes")).toBe(true);
|
||||
expect(r.related.every((x) => x.top !== "Notes")).toBe(true);
|
||||
expect(r.related.map((x) => x.node)).toContain(ycomb);
|
||||
});
|
||||
});
|
||||
@@ -303,7 +303,7 @@ describe("accepting and rejecting", () => {
|
||||
expect(scanned.suggestions.length).toBeGreaterThan(1);
|
||||
const list = await (await fetch(`${base}/api/links/pending?doc=octopus-minds`)).json();
|
||||
expect(list.total).toBe(scanned.suggestions.length);
|
||||
expect(list.suggestions[0]).toMatchObject({ nodeTitle: "Arms", document: "Octopus minds", docSlug: "octopus-minds" });
|
||||
expect(list.suggestions[0]).toMatchObject({ nodeTitle: "Arms", top: "Octopus minds" });
|
||||
expect(list.suggestions[0].sentence.length).toBeGreaterThan(10);
|
||||
const hoyle = list.suggestions.find((s: { quote: string }) => s.quote === "Fred Hoyle");
|
||||
const before = history(doc).length;
|
||||
|
||||
+33
-11
@@ -9,7 +9,7 @@ import { commitExpansion } from "../src/llm/tasks";
|
||||
|
||||
const W = (title: string): Ref => ({ kind: "wiki", title, lang: "en" });
|
||||
|
||||
/** A library of two documents; the second has a section the first links to. */
|
||||
/** A library of two trees; the second has a section the first links to. */
|
||||
function library() {
|
||||
const doc = Doc.library("tester");
|
||||
const lib = doc.snap().root;
|
||||
@@ -198,17 +198,30 @@ describe("the backlinks index", () => {
|
||||
});
|
||||
|
||||
describe("healing", () => {
|
||||
it("a node link whose target is gone is found again by its document and titles, else stays broken", () => {
|
||||
it("a node link whose target is gone is found again by its titles from the library root, else stays broken", () => {
|
||||
const { doc, fixed, minds, arms } = library();
|
||||
const link = linkOn(doc, fixed, "Octopus", nodeRef(doc.snap(), arms));
|
||||
expect(doc.snap().nodes[link].ref).toMatchObject({ doc: "minds", path: ["Arms"] });
|
||||
expect(doc.snap().nodes[link].ref).toEqual({ kind: "node", id: arms, path: ["Minds", "Arms"] });
|
||||
doc.apply([{ op: "delete", id: arms }], "Delete");
|
||||
expect(healLinks(doc)).toBe(0);
|
||||
expect(linkIndex(doc).broken()).toEqual([link]);
|
||||
const [again] = doc.apply([{ op: "create", parent: minds, title: "Arms", body: "Rewritten." }], "Recreate").created;
|
||||
expect(healLinks(doc)).toBe(1);
|
||||
expect((doc.snap().nodes[link].ref as { id: NodeId }).id).toBe(again);
|
||||
expect(resolveNode(doc.snap(), { kind: "node", doc: "minds", path: ["arms"] })).toBe(again);
|
||||
expect(resolveNode(doc.snap(), { kind: "node", path: ["minds", "arms"] })).toBe(again);
|
||||
// The root itself is the empty path; a relative path is read below the top of where it is written.
|
||||
expect(resolveNode(doc.snap(), { kind: "node", path: [] })).toBe(doc.snap().root);
|
||||
expect(resolveNode(doc.snap(), { kind: "node", path: ["Arms"], rel: true }, link)).toBeNull();
|
||||
expect(resolveNode(doc.snap(), { kind: "node", path: ["Arms"], rel: true }, again)).toBe(again);
|
||||
});
|
||||
|
||||
it("where two trees have the same titles, a path is found in the tree it is written in first", () => {
|
||||
const { doc, lib, minds } = library();
|
||||
const [copy] = doc.apply([{ op: "copy", id: minds, parent: lib }], "Copy").created;
|
||||
const copyArms = sections(doc.snap(), copy)[0];
|
||||
const path = { kind: "node" as const, path: ["Minds", "Arms"] };
|
||||
expect(resolveNode(doc.snap(), path)).toBe(sections(doc.snap(), minds)[0]);
|
||||
expect(resolveNode(doc.snap(), path, sections(doc.snap(), copyArms)[0])).toBe(copyArms);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -244,9 +257,10 @@ describe("the text form of a target", () => {
|
||||
["w:Fixed-point combinator", W("Fixed-point combinator")],
|
||||
["w.fr:Point fixe", { kind: "wiki", title: "Point fixe", lang: "fr" }],
|
||||
['"w:Star Wars: Episode IV"', W("Star Wars: Episode IV")],
|
||||
["/fixed-points/Recursion/How Y works", { kind: "node", doc: "fixed-points", path: ["Recursion", "How Y works"] }],
|
||||
["./A\\/B/C", { kind: "node", path: ["A/B", "C"] }],
|
||||
['/minds/Arms ^"tastes what"', { kind: "node", doc: "minds", path: ["Arms"], quote: "tastes what" }],
|
||||
["/Fixed points/Recursion/How Y works", { kind: "node", path: ["Fixed points", "Recursion", "How Y works"] }],
|
||||
["./A\\/B/C", { kind: "node", path: ["A/B", "C"], rel: true }],
|
||||
['/Minds/Arms ^"tastes what"', { kind: "node", path: ["Minds", "Arms"], quote: "tastes what" }],
|
||||
["/", { kind: "node", path: [] }],
|
||||
['https://example.org/a?b=c "A title"', { kind: "url", url: "https://example.org/a?b=c", title: "A title" }],
|
||||
];
|
||||
for (const [text, ref] of cases) {
|
||||
@@ -261,9 +275,17 @@ describe("the text form of a target", () => {
|
||||
describe("the editor agent's tools", () => {
|
||||
it("create a link and set or remove a target, with node paths checked against the library", async () => {
|
||||
const { execTool } = await import("../src/llm/tasks");
|
||||
const { doc, fixed, arms } = library();
|
||||
const made = JSON.parse(execTool(doc, "create_node", { parent: fixed, title: "", body: "", quote: "Octopus", target: "/minds/Arms" })).created as NodeId;
|
||||
expect(doc.snap().nodes[made].ref).toMatchObject({ kind: "node", id: arms, doc: "minds", path: ["Arms"] });
|
||||
const { doc, fixed, recursion, arms } = library();
|
||||
const made = JSON.parse(execTool(doc, "create_node", { parent: fixed, title: "", body: "", quote: "Octopus", target: "/Minds/Arms" })).created as NodeId;
|
||||
expect(doc.snap().nodes[made].ref).toEqual({ kind: "node", id: arms, path: ["Minds", "Arms"] });
|
||||
expect(JSON.parse(execTool(doc, "read_node", { id: fixed })).notes[0].target).toBe("/Minds/Arms");
|
||||
// A node's id, or a path below the top of the node written in, does as well.
|
||||
execTool(doc, "update_node", { id: made, target: recursion });
|
||||
expect(doc.snap().nodes[made].ref).toEqual({ kind: "node", id: recursion, path: ["Fixed points", "Recursion"] });
|
||||
execTool(doc, "update_node", { id: made, target: "./Recursion" });
|
||||
expect(doc.snap().nodes[made].ref).toMatchObject({ id: recursion });
|
||||
const found = JSON.parse(execTool(doc, "find", { query: "tastes" })).matches[0];
|
||||
expect(found).toMatchObject({ id: arms, top: "Minds", path: "Minds › Arms" });
|
||||
execTool(doc, "update_node", { id: made, target: "w:Octopus" });
|
||||
expect(doc.snap().nodes[made].ref).toEqual(W("Octopus"));
|
||||
expect(JSON.parse(execTool(doc, "read_node", { id: fixed })).notes[0].target).toBe("w:Octopus");
|
||||
@@ -271,7 +293,7 @@ describe("the editor agent's tools", () => {
|
||||
expect(doc.snap().nodes[fixed].ref).toEqual({ kind: "url", url: "https://example.org/fp" });
|
||||
execTool(doc, "update_node", { id: fixed, target: "" });
|
||||
expect(doc.snap().nodes[fixed].ref).toBeUndefined();
|
||||
expect(() => execTool(doc, "update_node", { id: made, target: "/minds/No such section" })).toThrow(OpError);
|
||||
expect(() => execTool(doc, "update_node", { id: made, target: "/Minds/No such section" })).toThrow(OpError);
|
||||
expect(() => execTool(doc, "update_node", { id: made, target: "javascript:alert(1)" })).toThrow(OpError);
|
||||
});
|
||||
});
|
||||
+11
-11
@@ -9,7 +9,7 @@ import { tmpdir } from "node:os";
|
||||
import { join, relative } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { LibraryStore } from "../server/library";
|
||||
import { Doc, descendants, findDoc, isStale, type NodeId } from "../src/core/model";
|
||||
import { Doc, descendants, isStale, tops, type NodeId } from "../src/core/model";
|
||||
import { at, history, mergeBranch, revertDocTo, revertTo, verifyHistory } from "../src/core/repo";
|
||||
|
||||
const temp = () => mkdtempSync(join(tmpdir(), "ie-migrate-"));
|
||||
@@ -86,11 +86,11 @@ describe("migration from the per-document layout", () => {
|
||||
const lib = store.main;
|
||||
const snap = lib.snap();
|
||||
|
||||
// One library: the first document first, then most recently changed first, each under its old id as slug.
|
||||
// One library: the first document first, then most recently changed first.
|
||||
expect(snap.library).toBe(true);
|
||||
expect(store.list().map((d) => d.slug)).toEqual(["infinite-expand", "tides", "tides-copy"]);
|
||||
for (const [id, old] of [["infinite-expand", first], ["tides", tides], ["tides-copy", copy]] as const) {
|
||||
const node = findDoc(snap, id)!;
|
||||
expect(store.list().map((d) => d.title)).toEqual(["Infinite Expand", "The tides", "The tides (copy)"]);
|
||||
const [nFirst, nTides, nCopy] = tops(snap);
|
||||
for (const [node, old] of [[nFirst, first], [nTides, tides], [nCopy, copy]] as const) {
|
||||
expect(lib.shape(snap, node)).toBe(old.shape());
|
||||
// Exactly what was stale before is stale now (the first document's edits left its root out of date).
|
||||
const was = old.snap();
|
||||
@@ -98,9 +98,9 @@ describe("migration from the per-document layout", () => {
|
||||
}
|
||||
expect(isStale(snap, snap.root)).toBe(false);
|
||||
// Kept documents keep their node ids, so anchors and conflict records still point at them.
|
||||
expect(findDoc(snap, "infinite-expand")).toBe(first.snap().root);
|
||||
expect(findDoc(snap, "tides")).toBe(tides.snap().root);
|
||||
expect(findDoc(snap, "tides-copy")).not.toBe(copy.snap().root);
|
||||
expect(nFirst).toBe(first.snap().root);
|
||||
expect(nTides).toBe(tides.snap().root);
|
||||
expect(nCopy).not.toBe(copy.snap().root);
|
||||
expect(lib.conflicts().filter((c) => c.status === "open").map((c) => c.node)).toEqual([one]);
|
||||
expect(snap.nodes[one].pinned).toBe(true);
|
||||
|
||||
@@ -119,7 +119,7 @@ describe("migration from the per-document layout", () => {
|
||||
expect(() => revertTo(lib, humanEdit)).toThrow(/before the library existed/);
|
||||
revertDocTo(lib, humanEdit, first.snap().root);
|
||||
expect(lib.snap().nodes[one].title).toBe("One");
|
||||
expect(lib.shape(lib.snap(), findDoc(lib.snap(), "tides")!)).toBe(tides.shape());
|
||||
expect(lib.shape(lib.snap(), nTides)).toBe(tides.shape());
|
||||
expect(verifyHistory(lib).mismatches).toEqual([]);
|
||||
|
||||
// The old directory is renamed, every byte as it was; the record says what was and was not carried.
|
||||
@@ -155,8 +155,8 @@ describe("migration from the per-document layout", () => {
|
||||
const logs: string[] = [];
|
||||
const store = new LibraryStore(data, (m) => logs.push(m)).open();
|
||||
const snap = store.main.snap();
|
||||
expect(store.list().map((d) => d.slug)).toEqual(["infinite-expand"]);
|
||||
expect(store.main.shape(snap, findDoc(snap, "infinite-expand")!)).toBe(main.shape());
|
||||
expect(store.list().map((d) => d.title)).toEqual(["Infinite Expand"]);
|
||||
expect(store.main.shape(snap, tops(snap)[0])).toBe(main.shape());
|
||||
expect(readdirSync(data).filter((f) => f.endsWith(".loro"))).toEqual([]);
|
||||
expect(existsSync(join(data, "notes.txt"))).toBe(true); // anything else is left alone
|
||||
const flat = readdirSync(data).find((f) => f.startsWith("flat.migrated-"))!;
|
||||
|
||||
@@ -147,7 +147,7 @@ describe("the reviewer", () => {
|
||||
return { p, list: out };
|
||||
}
|
||||
|
||||
it("judges many proposals a call, grouped by document and section, with what it takes to judge each", async () => {
|
||||
it("judges many proposals a call, grouped by tree 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();
|
||||
@@ -163,7 +163,7 @@ describe("the reviewer", () => {
|
||||
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("# Tree: 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.”");
|
||||
|
||||
+5
-5
@@ -1,9 +1,9 @@
|
||||
/** The seed tree against the prompt it was grown from: the first document of a new library. */
|
||||
/** The seed tree against the prompt it was grown from: the first tree of a new library. */
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Doc, descendants, isStale, notesOf, sections } from "../src/core/model";
|
||||
import { verifyHistory } from "../src/core/repo";
|
||||
import { SEED_SLUG, writeSeed } from "../src/core/seed";
|
||||
import { SEED_TITLE, writeSeed } from "../src/core/seed";
|
||||
import { overlaps, sentences, wordCount } from "../src/core/text";
|
||||
import { seed } from "../src/seed/tree";
|
||||
|
||||
@@ -14,9 +14,9 @@ const snap = doc.snap();
|
||||
const root = snap.nodes[first];
|
||||
|
||||
describe("seed tree", () => {
|
||||
it("keeps the prompt verbatim as the document's text, written by a human and pinned, as a section of the library", () => {
|
||||
it("keeps the prompt verbatim as the text of its top, written by a human and pinned, as a section of the library", () => {
|
||||
expect(root.body).toBe(prompt.trim());
|
||||
expect(root).toMatchObject({ by: "human", pinned: true, parent: snap.root, slug: SEED_SLUG });
|
||||
expect(root).toMatchObject({ by: "human", pinned: true, parent: snap.root, title: SEED_TITLE });
|
||||
expect(snap.library).toBe(true);
|
||||
});
|
||||
|
||||
@@ -47,7 +47,7 @@ describe("seed tree", () => {
|
||||
expect(Object.keys(snap.nodes).filter((id) => isStale(snap, id as never))).toEqual([]);
|
||||
const v = verifyHistory(doc);
|
||||
expect(v.mismatches).toEqual([]);
|
||||
// The library, the document, and one commit per top-level section.
|
||||
// The library, the tree's top, and one commit per section under it.
|
||||
expect(v.checked).toBe(seed.length + 2);
|
||||
});
|
||||
});
|
||||
+40
-39
@@ -1,4 +1,4 @@
|
||||
/** The library on disk: seeding, starter documents, documents as subtrees, and slugs that cannot escape. */
|
||||
/** The library on disk: seeding and starter files; and (until step 2 removes them) the UI's document features: the root's children made, listed and addressed. */
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
@@ -6,9 +6,9 @@ import { UndoManager } from "loro-crdt";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { LibraryStore } from "../server/library";
|
||||
import { FormatError, serializeDoc } from "../src/core/format";
|
||||
import { address, createDoc, deleteDoc, duplicateDoc, importDoc, listDocs, renameDoc, resolve } from "../src/core/library";
|
||||
import { Doc, OpError, SYSTEM_ORIGIN, descendants, findDoc, sections } from "../src/core/model";
|
||||
import { SEED_SLUG, writeSeed } from "../src/core/seed";
|
||||
import { address, createDoc, deleteDoc, duplicateDoc, findTop, importDoc, listDocs, renameDoc, resolve } from "../src/core/library";
|
||||
import { Doc, SYSTEM_ORIGIN, descendants, sections } from "../src/core/model";
|
||||
import { SEED_TITLE, writeSeed } from "../src/core/seed";
|
||||
import { seed } from "../src/seed/tree";
|
||||
|
||||
const prompt = readFileSync(new URL("../src/seed/prompt.txt", import.meta.url), "utf8");
|
||||
@@ -17,13 +17,13 @@ const quiet = () => {};
|
||||
const MD = (title: string) => `# ${title}\n\nA root body with a phrase.\n\n## One\n\nSection text.\n\n^ "Section" gloss: a note\n`;
|
||||
|
||||
describe("the library on disk", () => {
|
||||
it("starts an empty data directory as one library with the first document, written once", () => {
|
||||
it("starts an empty data directory as one library with the first tree, written once", () => {
|
||||
const data = temp();
|
||||
const store = new LibraryStore(data, quiet).open();
|
||||
store.seedFirst((doc) => writeSeed(doc, prompt, seed));
|
||||
expect(store.list().map((d) => d.slug)).toEqual([SEED_SLUG]);
|
||||
expect(store.list().map((d) => d.title)).toEqual([SEED_TITLE]);
|
||||
expect(store.main.snap().library).toBe(true);
|
||||
expect(JSON.parse(readFileSync(join(data, "library.json"), "utf8")).imported).toEqual([SEED_SLUG]);
|
||||
expect(JSON.parse(readFileSync(join(data, "library.json"), "utf8")).imported).toEqual(["infinite-expand"]);
|
||||
store.flush();
|
||||
// A second start loads the same library (same id) and writes nothing new.
|
||||
const again = new LibraryStore(data, quiet).open();
|
||||
@@ -34,7 +34,7 @@ describe("the library on disk", () => {
|
||||
expect(again.main.stateHash()).toBe(store.main.stateHash());
|
||||
});
|
||||
|
||||
it("imports each starter file once, as a document; a deleted one stays deleted and a broken one is skipped", () => {
|
||||
it("imports each starter file once, as a child of the root; a deleted one stays deleted and a broken one is skipped", () => {
|
||||
const data = temp();
|
||||
const lib = temp();
|
||||
writeFileSync(join(lib, "good-one.md"), MD("Good one"));
|
||||
@@ -43,80 +43,76 @@ describe("the library on disk", () => {
|
||||
const logs: string[] = [];
|
||||
const store = new LibraryStore(data, (m) => logs.push(m)).open();
|
||||
store.importLibrary(lib);
|
||||
expect(store.list().map((d) => d.slug)).toEqual(["second-file", "good-one"]); // file-name order: "S" sorts before "g"
|
||||
expect(store.list().map((d) => d.title)).toEqual(["Second", "Good one"]); // file-name order: "S" sorts before "g"
|
||||
expect(logs.join("\n")).toMatch(/skipped broken\.md:\n {2}library\/broken\.md:9: in “One”: quote not found: "Missing"/);
|
||||
|
||||
deleteDoc(store.main, findDoc(store.main.snap(), "good-one")!, "alice");
|
||||
deleteDoc(store.main, findTop(store.main.snap(), "good-one")!, "alice");
|
||||
store.save("main");
|
||||
const again = new LibraryStore(data, quiet).open();
|
||||
again.importLibrary(lib);
|
||||
expect(again.list().map((d) => d.slug)).toEqual(["second-file"]);
|
||||
expect(again.list().map((d) => d.title)).toEqual(["Second"]);
|
||||
// Once fixed, the broken file is picked up.
|
||||
writeFileSync(join(lib, "broken.md"), MD("Broken"));
|
||||
again.importLibrary(lib);
|
||||
expect(again.list().map((d) => d.slug)).toEqual(["second-file", "broken"]);
|
||||
expect(again.list().map((d) => d.title)).toEqual(["Second", "Broken"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("documents", () => {
|
||||
it("are created, renamed, duplicated and deleted as ordinary commits, with slugs that stay inside the data directory", () => {
|
||||
describe("the root's children (the UI's documents, until step 2)", () => {
|
||||
it("are created, renamed, duplicated and deleted as ordinary commits, with names made from their titles", () => {
|
||||
const lib = Doc.library("alice");
|
||||
const a = createDoc(lib, "My notes", "alice");
|
||||
const snap = () => lib.snap();
|
||||
expect(snap().nodes[a]).toMatchObject({ parent: snap().root, title: "My notes", slug: "my-notes", by: "human" });
|
||||
const slugOf = (title: string) => {
|
||||
expect(snap().nodes[a]).toMatchObject({ parent: snap().root, title: "My notes", by: "human" });
|
||||
const nameOf = (title: string) => {
|
||||
const id = createDoc(lib, title, "alice");
|
||||
return snap().nodes[id].slug;
|
||||
return listDocs(snap()).find((d) => d.node === id)!.slug;
|
||||
};
|
||||
expect(slugOf("My notes")).toBe("my-notes-2");
|
||||
expect(slugOf("../../etc/passwd")).toBe("etc-passwd");
|
||||
expect(slugOf("Import")).toBe("import-2"); // a word of the URL scheme, not a document
|
||||
for (const bad of ["..", "../x", "a/b", "A", "", "x".repeat(70)]) {
|
||||
expect(() => lib.apply([{ op: "update", id: a, slug: bad }], "bad slug")).toThrow(OpError);
|
||||
}
|
||||
expect(() => lib.apply([{ op: "update", id: a, slug: "my-notes-2" }], "taken")).toThrow(/another document/);
|
||||
// Only a document has a slug.
|
||||
expect(nameOf("My notes")).toBe("my-notes");
|
||||
expect(nameOf("../../etc/passwd")).toBe("etc-passwd");
|
||||
// A name another child has too finds the first; the id finds each.
|
||||
expect(findTop(snap(), "my-notes")).toBe(a);
|
||||
expect(findTop(snap(), a)).toBe(a);
|
||||
const [inner] = lib.apply([{ op: "create", parent: a, title: "Inside" }], "add").created;
|
||||
expect(snap().nodes[inner].slug).toBeUndefined();
|
||||
expect(() => lib.apply([{ op: "update", id: inner, slug: "inside" }], "x")).toThrow(/only a document/);
|
||||
expect(findTop(snap(), "inside")).toBeUndefined();
|
||||
|
||||
renameDoc(lib, a, "Renamed", "alice");
|
||||
expect(snap().nodes[a]).toMatchObject({ title: "Renamed", slug: "my-notes" }); // the slug, and so links, stay
|
||||
expect(listDocs(snap()).find((d) => d.node === a)).toMatchObject({ title: "Renamed", slug: "renamed" });
|
||||
const copy = duplicateDoc(lib, a, "Renamed (copy)", "alice");
|
||||
expect(snap().nodes[copy]).toMatchObject({ title: "Renamed (copy)", slug: "renamed-copy" });
|
||||
expect(listDocs(snap()).find((d) => d.node === copy)).toMatchObject({ title: "Renamed (copy)", slug: "renamed-copy" });
|
||||
expect(snap().nodes[snap().root].children.indexOf(copy)).toBe(snap().nodes[snap().root].children.indexOf(a) + 1);
|
||||
expect(sections(snap(), copy).map((id) => snap().nodes[id].title)).toEqual(["Inside"]);
|
||||
expect(sections(snap(), copy)[0]).not.toBe(inner); // a copy, not the same nodes
|
||||
|
||||
// Delete is an ordinary delete: undo brings the document back, content, slug and all.
|
||||
// Delete is an ordinary delete: undo brings it back, content and all.
|
||||
const undo = new UndoManager(lib.loro, { mergeInterval: 0, excludeOriginPrefixes: [SYSTEM_ORIGIN] });
|
||||
lib.group = { start: () => undo.groupStart(), end: () => undo.groupEnd() };
|
||||
deleteDoc(lib, copy, "alice");
|
||||
expect(findDoc(snap(), "renamed-copy")).toBeUndefined();
|
||||
expect(findTop(snap(), "renamed-copy")).toBeUndefined();
|
||||
expect(undo.undo()).toBe(true);
|
||||
lib.touch();
|
||||
const back = findDoc(snap(), "renamed-copy")!;
|
||||
const back = findTop(snap(), "renamed-copy")!;
|
||||
expect(snap().nodes[back].title).toBe("Renamed (copy)");
|
||||
expect(sections(snap(), back).map((id) => snap().nodes[id].title)).toEqual(["Inside"]);
|
||||
});
|
||||
|
||||
it("import and export one document in the text format; a file with a bad quote writes nothing", () => {
|
||||
it("import and export one tree in the text format; a file with a bad quote writes nothing", () => {
|
||||
const lib = Doc.library("alice");
|
||||
createDoc(lib, "Something else", "alice");
|
||||
const id = importDoc(lib, MD("Imported thing"), "thing.md", { slug: "thing" });
|
||||
const id = importDoc(lib, MD("Imported thing"), "thing.md");
|
||||
const snap = lib.snap();
|
||||
expect([id, ...descendants(snap, id)].every((n) => snap.nodes[n].by === "llm")).toBe(true);
|
||||
expect(serializeDoc(snap, id).text).toBe(MD("Imported thing"));
|
||||
const before = lib.stateHash();
|
||||
expect(() => importDoc(lib, MD("Bad").replace('"Section"', '"Nowhere"'), "bad.md")).toThrow(FormatError);
|
||||
expect(lib.stateHash()).toBe(before);
|
||||
expect(listDocs(lib.snap()).map((d) => d.slug)).toEqual(["something-else", "thing"]);
|
||||
expect(listDocs(lib.snap()).map((d) => d.slug)).toEqual(["something-else", "imported-thing"]);
|
||||
});
|
||||
|
||||
it("have addresses: /doc/<slug> for a document, /doc/<slug>/<node> for a node in it, / for the library", () => {
|
||||
it("have addresses: /doc/<name> for one, /doc/<name>/<node> for a node under it, / for the library", () => {
|
||||
const lib = Doc.library("alice");
|
||||
const a = importDoc(lib, MD("Tides"), "tides.md", { slug: "tides" });
|
||||
const b = importDoc(lib, MD("Codes"), "codes.md", { slug: "codes" });
|
||||
const a = importDoc(lib, MD("Tides"), "tides.md");
|
||||
const b = importDoc(lib, MD("Codes"), "codes.md");
|
||||
const snap = lib.snap();
|
||||
const one = sections(snap, a)[0];
|
||||
expect(address(snap, snap.root)).toBe("/");
|
||||
@@ -128,6 +124,11 @@ describe("documents", () => {
|
||||
expect(resolve(lib.snap(), `/doc/tides/${encodeURIComponent(one)}`)).toEqual({ node: one });
|
||||
expect(address(lib.snap(), one)).toBe(`/doc/codes/${encodeURIComponent(one)}`);
|
||||
expect(resolve(lib.snap(), `/n/${encodeURIComponent(one)}`)).toEqual({ node: one });
|
||||
expect(resolve(lib.snap(), "/doc/nothing")).toEqual({ missing: "no document “nothing”" });
|
||||
expect(resolve(lib.snap(), "/doc/nothing")).toEqual({ missing: "nothing called “nothing”" });
|
||||
// A child of the root whose name another has too is addressed by its id as well.
|
||||
const twin = importDoc(lib, MD("Tides"), "tides-2.md");
|
||||
expect(address(lib.snap(), twin)).toBe(`/doc/tides/${encodeURIComponent(twin)}`);
|
||||
expect(resolve(lib.snap(), address(lib.snap(), twin))).toEqual({ node: twin });
|
||||
expect(address(lib.snap(), a)).toBe("/doc/tides");
|
||||
});
|
||||
});
|
||||
+37
-14
@@ -132,7 +132,7 @@ describe("link marks in what the model writes", () => {
|
||||
it("are taken out of the stored text and handed over, with the node they belong to", async () => {
|
||||
const { doc, a } = fixture();
|
||||
const marks: [NodeId, string[]][] = [];
|
||||
const hooks = { nearby: async () => [{ handle: a, title: "Leaf A", document: "Root" }], marks: (id: NodeId, m: { phrase: string }[]) => marks.push([id, m.map((x) => x.phrase)]) };
|
||||
const hooks = { nearby: async () => [{ handle: a, title: "Leaf A", top: "Root" }], marks: (id: NodeId, m: { phrase: string }[]) => marks.push([id, m.map((x) => x.phrase)]) };
|
||||
const created = await deepen(llm, doc, a, undefined, undefined, hooks);
|
||||
const bodies = created.map((c) => doc.snap().nodes[c].body);
|
||||
expect(bodies.join(" ")).not.toContain("[[");
|
||||
@@ -155,7 +155,7 @@ describe("link marks in what the model writes", () => {
|
||||
const { doc, a } = fixture();
|
||||
let seen: { context: string; prompt: string } | null = null;
|
||||
const spy = { ...llm, stream: async (r: { context: string; prompt: string }, on: (d: string) => void) => ((seen = r), llm.stream(r as never, on)) } as typeof llm;
|
||||
await deepen(spy, doc, a, undefined, undefined, { nearby: async () => [{ handle: "1@2", title: "Elsewhere", document: "Other" }] });
|
||||
await deepen(spy, doc, a, undefined, undefined, { nearby: async () => [{ handle: "1@2", title: "Elsewhere", top: "Other" }] });
|
||||
expect(seen!.prompt).toContain("Nearby in this library:\n- Elsewhere (in Other) [1@2]");
|
||||
expect(seen!.prompt).toContain("[[phrase]]");
|
||||
expect(seen!.context).not.toContain("Nearby");
|
||||
@@ -235,7 +235,7 @@ describe("context", () => {
|
||||
|
||||
// ---- in a library ----
|
||||
|
||||
/** A library of two model-written documents, Alpha (with a part and two leaves) and Beta. */
|
||||
/** A library of two model-written trees, Alpha (with a part and two leaves) and Beta. */
|
||||
function libraryFixture() {
|
||||
const doc = Doc.library("alice");
|
||||
const lib = doc.snap().root;
|
||||
@@ -270,22 +270,45 @@ function recording() {
|
||||
}
|
||||
|
||||
describe("context in a library", () => {
|
||||
it("is the focused node's document only, and stays byte-for-byte the same while other documents change", () => {
|
||||
it("is the outline of the focused node's top only, and stays byte-for-byte the same while other trees change", () => {
|
||||
const { doc, lib, aLeaf, b, bLeaf } = libraryFixture();
|
||||
const before = renderContext(doc.snap(), aLeaf);
|
||||
expect(before).toContain("# Alpha");
|
||||
expect(before).toMatch(/^<outline>\n# Alpha\n/);
|
||||
expect(before).toContain("Alpha leaf two");
|
||||
expect(before).not.toContain("Beta");
|
||||
doc.apply([{ op: "update", id: bLeaf, body: "Beta changed a great deal." }], "Edit the other document");
|
||||
doc.apply([{ op: "create", parent: lib, title: "Gamma", body: "A third document." }], "New document");
|
||||
doc.apply(retitleOps(doc.snap(), b, "Beta renamed"), "Rename the other document");
|
||||
doc.apply([{ op: "update", id: bLeaf, body: "Beta changed a great deal." }], "Edit the other tree");
|
||||
doc.apply([{ op: "create", parent: lib, title: "Gamma", body: "A third tree." }], "New tree");
|
||||
doc.apply(retitleOps(doc.snap(), b, "Beta renamed"), "Rename the other tree");
|
||||
doc.apply([{ op: "update", id: lib, body: "The library's own text." }], "Write the library");
|
||||
expect(renderContext(doc.snap(), aLeaf)).toBe(before);
|
||||
// On the library itself, which is in no document, the context is the list of documents.
|
||||
// On the library itself, which is under no top, the context is the list of the root's children.
|
||||
expect(renderContext(doc.snap(), lib)).toBe("<library>\n- Alpha\n- Beta renamed\n- Gamma\n</library>");
|
||||
});
|
||||
|
||||
it("every model task sends only the document it works in", async () => {
|
||||
it("over its budget keeps only the bodies on the focus path, then starts lower down the path, under the titles above", () => {
|
||||
const { doc, a, aLeaf } = libraryFixture();
|
||||
const snap = () => doc.snap();
|
||||
doc.apply([{ op: "create", parent: a, title: "Alpha aside", body: "An aside." }, { op: "create", parent: "$0" as NodeId, title: "Aside detail", body: "Detail. ".repeat(20) }], "Aside");
|
||||
const full = renderContext(snap(), aLeaf);
|
||||
expect(full).toContain("Detail. Detail.");
|
||||
// Off the focus path (and its sections), titles only.
|
||||
const lean = renderContext(snap(), aLeaf, { budget: full.length - 50 });
|
||||
expect(lean).toContain("## Aside detail");
|
||||
expect(lean).not.toContain("Detail. Detail.");
|
||||
expect(lean).toContain("The second Alpha leaf says another.");
|
||||
// A big tree beside the focus path: even titles are over the budget, so the outline starts at the part.
|
||||
doc.apply(Array.from({ length: 40 }, (_, i) => ({ op: "create" as const, parent: a, title: `Alpha bulk ${i}`, body: "Bulk." })), "Bulk");
|
||||
const stepped = renderContext(snap(), aLeaf, { budget: 300 });
|
||||
expect(stepped).toMatch(/^<outline>\nLibrary › Alpha ›\n# Alpha part\nThe Alpha part summarises its leaves\.\n\n## Alpha leaf one\n/);
|
||||
expect(stepped).not.toContain("bulk");
|
||||
expect(stepped.length).toBeLessThanOrEqual(300 + "<outline>\n</outline>".length);
|
||||
// Nothing on the path fits: the focus's own outline, cut to the budget.
|
||||
expect(renderContext(snap(), aLeaf, { budget: 40 })).toBe(`<outline>\n${"Library › Alpha › Alpha part ›\n# Alpha leaf one".slice(0, 40)}</outline>`);
|
||||
// With room for everything, it is the whole top again.
|
||||
expect(renderContext(snap(), aLeaf)).toMatch(/^<outline>\n# Alpha\n/);
|
||||
});
|
||||
|
||||
it("every model task sends only the tree it works in", async () => {
|
||||
const { doc, aLeaf, aPart, b } = libraryFixture();
|
||||
const { llm, sent } = recording();
|
||||
const body = doc.snap().nodes[aLeaf].body;
|
||||
@@ -304,11 +327,11 @@ describe("context in a library", () => {
|
||||
expect(doc.snap().nodes[b].title).toBe("Beta");
|
||||
});
|
||||
|
||||
it("a cascade stops at the document: the library above it is never asked about or rewritten", async () => {
|
||||
it("a cascade stops at the top: the library above it is never asked about or rewritten", async () => {
|
||||
const { doc, lib, a, aPart, b } = libraryFixture();
|
||||
const { llm, sent } = recording();
|
||||
const libraryBefore = doc.snap().nodes[lib];
|
||||
// An edit to the document's part: the chain is the document alone, not the library above it.
|
||||
// An edit to the top's part: the chain is the top alone, not the library above it.
|
||||
doc.apply([{ op: "update", id: aPart, body: "The Alpha part says something else now." }], "Edit the part");
|
||||
const events = await cascade(llm, doc, aPart, "edited");
|
||||
expect(sent.find((r) => r.task === "cascade")?.vars?.chain).toBe("1");
|
||||
@@ -317,7 +340,7 @@ describe("context in a library", () => {
|
||||
const snap = doc.snap();
|
||||
expect(snap.nodes[lib].body).toBe(libraryBefore.body);
|
||||
expect(staleness(snap, lib)).toEqual({ up: false, down: false, orphan: false });
|
||||
// Rewriting a document's text leaves the other documents alone.
|
||||
// Rewriting a top's text leaves the other trees alone.
|
||||
expect(isStale(snap, b)).toBe(false);
|
||||
// And the model never writes the library itself.
|
||||
expect(await regenUp(llm, doc, lib)).toBe(false);
|
||||
@@ -325,7 +348,7 @@ describe("context in a library", () => {
|
||||
expect(() => execTool(doc, "update_node", { id: lib, body: "x" })).toThrow(/library itself/);
|
||||
});
|
||||
|
||||
it("settles conflicts one document at a time, each with its own context", async () => {
|
||||
it("settles conflicts one top's tree at a time, each with its own context", async () => {
|
||||
const { doc, aLeaf, bLeaf } = libraryFixture();
|
||||
const other = doc.fork("bob");
|
||||
doc.apply([{ op: "update", id: aLeaf, body: "Alpha: always." }, { op: "update", id: bLeaf, body: "Beta: always." }], "A");
|
||||
|
||||
Reference in new issue
Block a user