npm run migrate: the single-library layout copied into a new library with fresh history, every node reference rewritten, the reviewer's verdicts re-keyed, verified node by node before anything is written; --check writes nothing; old files kept in backup-<time>/

Fixtures written by 626dc19 and c4d6856 (tests/fixtures/migrate/make.ts builds them).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
thalladaandClaude Opus 5.5 committed 2026-11-17 02:25:25 -05:00
1 parent 79aa85e883
commit d5d0d7563c
16 files changed
+1182 -1

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
{
"commit": "c4d6856",
"first": {
"made": {
"rootNote": "55200@6511406945601655",
"top": "55246@6511406945601655",
"first": "55319@6511406945601655",
"second": "55462@6511406945601655",
"deep": "55614@6511406945601655",
"gloss": "55687@6511406945601655",
"passage": "55729@6511406945601655",
"inner": "55796@6511406945601655",
"underNote": "55825@6511406945601655",
"orphan": "55864@6511406945601655",
"toFixed": "55920@6511406945601655",
"toKepler": "55928@6511406945601655",
"toWeb": "55936@6511406945601655",
"toGloss": "55944@6511406945601655",
"noteLink": "55961@6511406945601655",
"card": "55995@6511406945601655",
"fromOcto": "56005@6511406945601655",
"doomed": "56016@6511406945601655",
"toDoomed": "56035@6511406945601655",
"locked": "3667@6511406945601655",
"articles": "56054@6511406945601655",
"article": "56061@6511406945601655",
"annotation": "56068@6511406945601655"
},
"scanned": {
"first": 1,
"approved": 1,
"top": 1,
"listed": 2
}
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"imported": [
"infinite-expand",
"fixed-points",
"octopus-minds"
]
}
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
{"55462@6511406945601655":{"at":1794898907309,"suggestions":[{"id":"78b226f461a797bb","node":"55462@6511406945601655","range":[89,109],"quote":"triple-alpha process","key":"triple alpha process","target":{"kind":"wiki","title":"Triple-alpha process","lang":"en"},"score":1,"tier":"auto","why":"fits the text 1.00; a technical term","source":"wikipedia","title":"Triple-alpha process","description":"Nuclear fusion of helium into carbon in stars","kind":"term","review":{"link":true,"reason":"mock: a name or a term a reader may look up","at":1794898907311},"applied":1794898907311,"decided":{"link":true,"by":"reviewer","at":1794898907314}}]},"55246@6511406945601655":{"at":1794898907323,"suggestions":[{"id":"8d4bbd744746d404","node":"55246@6511406945601655","range":[22,29],"quote":"octopus","key":"octopus","target":{"kind":"wiki","title":"Octopus","lang":"en"},"score":0.939,"tier":"suggest","why":"fits the text 0.94; a fairly uncommon word","source":"wikipedia","title":"Octopus","description":"Soft-bodied eight-limbed order of molluscs","kind":"noun","decided":{"link":false,"by":"fixture","at":1794898907326}}]}}
+246
View File
@@ -0,0 +1,246 @@
/**
* Builds the old-layout data directories that tests/migrateLibraries.test.ts migrates, by running
* the server of an older commit on an empty data directory and editing it over HTTP, as a page or
* an outside agent would. The result is committed beside this file, so the tests need no git and no
* server; run this again only to rebuild them.
*
* npx tsx tests/fixtures/migrate/make.ts <scratch dir>
*
* It makes, in <scratch dir>, a git worktree for each commit (node_modules linked to this
* checkout's), runs each server with IE_LLM=mock IE_WIKI=mock IE_EMBED=fake on ports 4800-4802, and
* writes into tests/fixtures/migrate/:
*
* pre/ written by 626dc19 (before step 1: documents with slugs, node targets with `doc`)
* main/ written by c4d6856 (no documents; node targets by titles from the root)
* mixed/ pre/, then opened and edited by c4d6856 (old and new targets side by side)
*
* Each holds library/main.loro, library.json and links/pending.json; edits.json beside them names
* what was made, for the tests to check by.
*/
import { spawn, execFileSync, type ChildProcess } from "node:child_process";
import { cpSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";
const here = resolve(new URL(".", import.meta.url).pathname);
const repo = resolve(here, "../../..");
const scratch = resolve(process.argv[2] ?? "");
if (!process.argv[2]) throw new Error("give a scratch directory");
mkdirSync(scratch, { recursive: true });
interface Node {
id: string;
parent: string | null;
kind: string;
title: string;
body: string;
slug?: string;
children: string[];
anchors: { text: string }[];
ref?: unknown;
articles?: boolean;
}
interface Tree {
root: string;
nodes: Record<string, Node>;
}
function worktree(commit: string): string {
const dir = join(scratch, `ie-${commit}`);
if (!existsSync(dir)) {
execFileSync("git", ["-C", repo, "worktree", "add", "--detach", dir, commit], { stdio: "inherit" });
symlinkSync(join(repo, "node_modules"), join(dir, "node_modules"));
}
return dir;
}
async function serve(dir: string, data: string, port: number, library: string): Promise<ChildProcess> {
const child = spawn(process.execPath, ["--import", "tsx", "server/index.ts"], {
cwd: dir,
env: { ...process.env, IE_PROD: "1", IE_LLM: "mock", IE_MOCK_DELAY: "0", IE_WIKI: "mock", IE_EMBED: "fake", IE_DATA: data, IE_LIBRARY: library, PORT: String(port), IE_USER: "fixture" },
stdio: ["ignore", "inherit", "inherit"],
});
for (let i = 0; i < 200; i++) {
try {
if ((await fetch(`http://127.0.0.1:${port}/api/state`)).ok) return child;
} catch {
/* not up yet */
}
await new Promise((r) => setTimeout(r, 150));
}
child.kill("SIGTERM");
throw new Error(`the server in ${dir} did not start`);
}
async function stop(child: ChildProcess) {
const done = new Promise((r) => child.once("exit", r));
child.kill("SIGTERM");
await done;
}
function client(port: number) {
const base = `http://127.0.0.1:${port}`;
const call = async (path: string, init?: RequestInit) => {
const res = await fetch(base + path, init);
const body = await res.json();
if (!res.ok) throw new Error(`${path}: ${res.status} ${JSON.stringify(body)}`);
return body;
};
const post = (path: string, body: unknown) => call(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
return {
tree: () => call("/api/tree") as Promise<Tree>,
ops: async (ops: unknown[], actor: "human" | "llm" = "human") => (await post("/api/ops", { ops, actor, author: "fixture", message: "fixture" })).created as string[],
post,
};
}
const byTitle = (t: Tree, parent: string, title: string) => {
const id = t.nodes[parent].children.find((c) => t.nodes[c].title === title);
if (!id) throw new Error(`no “${title}” under ${t.nodes[parent].title}`);
return id;
};
const top = (t: Tree, title: string) => byTitle(t, t.root, title);
/** A node target as each version's page made it: with the document's slug and the titles below it, or the titles from the root. */
function refTo(t: Tree, id: string, old: boolean, quote?: string) {
const path: string[] = [];
let sec = id;
while (t.nodes[sec].kind === "note") sec = t.nodes[sec].parent!;
for (let x = t.nodes[sec]; x.parent; x = t.nodes[x.parent]) path.unshift(x.title);
const r: Record<string, unknown> = { kind: "node", id };
if (old) {
r.doc = t.nodes[top(t, path[0])].slug;
r.path = path.slice(1);
} else r.path = path;
if (quote !== undefined) r.quote = quote;
return r;
}
/** The edits both versions get: a tree of every kind of node, link, flag and decision. */
async function edits(port: number, old: boolean) {
const c = client(port);
let t = await c.tree();
const seed = top(t, "Infinispand");
const octo = top(t, "Octopus minds");
const fixed = top(t, "Fixed points");
const made: Record<string, string> = {};
// The root's own text, and a note on it (anchored in the root's body).
await c.ops([{ op: "update", id: t.root, body: "Everything I keep. Root words worth a note sit here." }]);
[made.rootNote] = await c.ops([{ op: "create", parent: t.root, kind: "note", quote: "Root words", form: "note", lens: "why", body: "A note on the library root itself." }]);
// A new top with sections, notes on notes, a section under a note, a titled note.
[made.top, made.first, made.second, made.deep] = await c.ops(
[
{ op: "create", parent: t.root, index: 1, title: "Migration notes", body: "Alpha beta gamma. The octopus has three hearts. Delta epsilon zeta." },
{ op: "create", parent: "$0", title: "First part", body: "Kepler read about Fixed points. Some plain words here. Freddie Mercury sang while a eukaryote swam past bacteria near the planet Mercury." },
{ op: "create", parent: "$0", title: "Second part", body: "Haskell Curry and Fred Hoyle wrote about recursion and stars. The Hoyle state powers the triple-alpha process in stars, and the eukaryote watches." },
{ op: "create", parent: "$2", title: "Deep part", body: "Deep text that points elsewhere and at the doomed section." },
],
"llm",
);
[made.gloss, made.passage] = await c.ops(
[
{ op: "create", parent: made.top, kind: "note", quote: "three hearts", form: "gloss", lens: "define", body: "Two pump blood through the gills." },
{ op: "create", parent: made.top, kind: "note", quote: "Alpha beta gamma.", form: "passage", body: "A passage about the first letters. It has inner words." },
],
"llm",
);
[made.inner] = await c.ops([{ op: "create", parent: made.passage, kind: "note", quote: "inner words", form: "note", lens: "example", body: "A note on a note." }], "llm");
[made.underNote] = await c.ops([{ op: "create", parent: made.passage, kind: "section", title: "A section under a note", body: "It hangs from the passage." }], "llm");
await c.ops([{ op: "update", id: made.gloss, title: "Hearts, titled" }]);
// An orphan: a note whose words are then deleted.
[made.orphan] = await c.ops([{ op: "create", parent: made.top, kind: "note", quote: "Delta epsilon", form: "note", body: "Its words are about to go." }], "llm");
await c.ops([{ op: "update", id: made.top, body: "Alpha beta gamma. The octopus has three hearts. Zeta." }]);
t = await c.tree();
const octoFirst = t.nodes[octo].children.find((x) => t.nodes[x].kind === "section")!;
// Links of every kind: to another top, to Wikipedia, to the web, a note that also links, a card, to a note.
[made.toFixed, made.toKepler, made.toWeb, made.toGloss] = await c.ops([
{ op: "create", parent: made.first, kind: "note", quote: "Fixed points", ref: refTo(t, fixed, old) },
{ op: "create", parent: made.first, kind: "note", quote: "Kepler", ref: { kind: "wiki", title: "Johannes Kepler", lang: "en" } },
{ op: "create", parent: made.first, kind: "note", quote: "plain words", ref: { kind: "url", url: "https://example.org/page", title: "An example" } },
{ op: "create", parent: made.second, kind: "note", quote: "Haskell Curry", ref: refTo(t, made.gloss, old, "three hearts") },
]);
[made.noteLink] = await c.ops([{ op: "create", parent: made.second, kind: "note", quote: "Fred Hoyle", form: "note", body: "He named the Big Bang.", ref: { kind: "wiki", title: "Fred Hoyle", lang: "en" } }], "llm");
[made.card] = await c.ops([{ op: "create", parent: made.second, title: "A card", body: "", ref: refTo(t, octoFirst, old) }]);
[made.fromOcto] = await c.ops([{ op: "create", parent: octoFirst, kind: "note", quote: t.nodes[octoFirst].body.split(" ").slice(0, 2).join(" "), ref: refTo(t, made.deep, old) }]);
// A broken link: its target deleted, so only its hint is left.
[made.doomed] = await c.ops([{ op: "create", parent: made.second, title: "Doomed", body: "Soon gone." }]);
t = await c.tree();
[made.toDoomed] = await c.ops([{ op: "create", parent: made.deep, kind: "note", quote: "doomed section", ref: refTo(t, made.doomed, old) }]);
await c.ops([{ op: "delete", id: made.doomed }]);
// Locks: one set on a model's node, one taken off a person's.
const seedFirst = t.nodes[seed].children.find((x) => t.nodes[x].kind === "section")!;
made.locked = seedFirst;
await c.ops([{ op: "update", id: seedFirst, pinned: true }]);
await c.ops([{ op: "update", id: made.top, pinned: false }]);
// A declined phrase, by op.
await c.ops([{ op: "update", id: made.second, nolink: ["recursion"] }]);
// A Wikipedia article's node with an annotation on it.
[made.articles, made.article, made.annotation] = await c.ops([
{ op: "create", parent: t.root, kind: "section", title: "Wikipedia", body: "", articles: true },
{ op: "create", parent: "$0", kind: "section", title: "Octopus", body: "", ref: { kind: "wiki", title: "Octopus", lang: "en", pageId: 1200106 } },
{ op: "create", parent: "$1", kind: "note", body: "Two thirds of the neurons are in the arms.", form: "note", wanchor: { sec: ["Description", "Nervous system and senses"], q: "two thirds of their neurons", pre: "with roughly ", post: " in the arms", rev: 1 } },
]);
// The reviewer's verdicts (the mock links names and rejects single words), approved links made,
// a person's decline and decision, and plain pending suggestions.
const scan = await c.post("/api/links/scan", { node: made.second, review: "all" });
const approved = (scan.apply ?? []).map((s: { id: string }) => s.id);
if (approved.length) await c.post("/api/links/accept", { ids: approved, author: "reviewer" });
await c.post("/api/links/scan", { node: made.first });
const pending = await c.post("/api/links/scan", { node: made.top, save: true });
const listed = (await (await fetch(`http://127.0.0.1:${port}/api/links/pending?all=1`)).json()).suggestions as { id: string; quote: string; review?: unknown; decided?: unknown }[];
const open = listed.filter((s) => !s.review && !s.decided);
if (open[0]) await c.post("/api/links/reject", { ids: [open[0].id], author: "fixture" });
if (open[1]) await c.post("/api/links/decide", { ids: [open[1].id], link: false, by: "fixture" });
return { made, scanned: { first: scan.suggestions.length, approved: approved.length, top: pending.suggestions.length, listed: listed.length } };
}
/** What c4d6856 adds to a library pre/ wrote: a new link by root titles, a rename, a new node. */
async function laterEdits(port: number) {
const c = client(port);
const t = await c.tree();
const mig = top(t, "Migration notes");
const second = byTitle(t, mig, "Second part");
const octo = top(t, "Octopus minds");
await c.ops([{ op: "update", id: octo, title: "Octopus minds, renamed" }]);
const t2 = await c.tree();
const [later] = await c.ops([{ op: "create", parent: second, title: "Added later", body: "Written by the newer code, linking stars." }]);
const [laterLink] = await c.ops([{ op: "create", parent: later, kind: "note", quote: "stars", ref: refTo(t2, octo, false) }]);
return { later, laterLink };
}
async function build(name: string, commit: string, port: number, from?: string, then?: string) {
const data = mkdtempSync(join(scratch, `data-${name}-`));
if (from) cpSync(from, data, { recursive: true });
const lib = mkdtempSync(join(scratch, "lib-"));
const dir = worktree(commit);
for (const f of ["octopus-minds.md", "fixed-points.md"]) cpSync(join(dir, "library", f), join(lib, f));
const child = await serve(dir, data, port, lib);
let info: unknown;
try {
info = from ? await laterEdits(port) : await edits(port, commit === "626dc19");
} finally {
await stop(child);
}
const out = join(here, name);
rmSync(out, { recursive: true, force: true });
mkdirSync(out, { recursive: true });
for (const f of ["library", "library.json", "links"]) if (existsSync(join(data, f))) cpSync(join(data, f), join(out, f), { recursive: true });
const prior = then ? JSON.parse(execFileSync("cat", [join(here, then, "edits.json")]).toString()) : {};
writeFileSync(join(out, "edits.json"), JSON.stringify({ commit, ...prior, ...(from ? { later: info } : { first: info }) }, null, 2) + "\n");
rmSync(lib, { recursive: true, force: true });
return data;
}
const pre = await build("pre", "626dc19", 4800);
const main = await build("main", "c4d6856", 4801);
const mixed = await build("mixed", "c4d6856", 4802, pre, "pre");
for (const d of [pre, main, mixed]) rmSync(d, { recursive: true, force: true });
console.log("fixtures written to", here);
+40
View File
@@ -0,0 +1,40 @@
{
"commit": "626dc19",
"first": {
"made": {
"rootNote": "55203@2342252495945464",
"top": "55249@2342252495945464",
"first": "55323@2342252495945464",
"second": "55466@2342252495945464",
"deep": "55618@2342252495945464",
"gloss": "55691@2342252495945464",
"passage": "55733@2342252495945464",
"inner": "55800@2342252495945464",
"underNote": "55829@2342252495945464",
"orphan": "55868@2342252495945464",
"toFixed": "55924@2342252495945464",
"toKepler": "55932@2342252495945464",
"toWeb": "55940@2342252495945464",
"toGloss": "55948@2342252495945464",
"noteLink": "55965@2342252495945464",
"card": "55999@2342252495945464",
"fromOcto": "56009@2342252495945464",
"doomed": "56020@2342252495945464",
"toDoomed": "56039@2342252495945464",
"locked": "3668@2342252495945464",
"articles": "56058@2342252495945464",
"article": "56065@2342252495945464",
"annotation": "56072@2342252495945464"
},
"scanned": {
"first": 1,
"approved": 1,
"top": 1,
"listed": 2
}
},
"later": {
"later": "4@705515326553021",
"laterLink": "54@705515326553021"
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"imported": [
"infinite-expand",
"fixed-points",
"octopus-minds"
]
}
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
{"55466@2342252495945464":{"at":1794898906089,"suggestions":[{"id":"d4c0c680082b5ed5","node":"55466@2342252495945464","range":[89,109],"quote":"triple-alpha process","key":"triple alpha process","target":{"kind":"wiki","title":"Triple-alpha process","lang":"en"},"score":1,"tier":"auto","why":"fits the text 1.00; a technical term","source":"wikipedia","title":"Triple-alpha process","description":"Nuclear fusion of helium into carbon in stars","kind":"term","review":{"link":true,"reason":"mock: a name or a term a reader may look up","at":1794898906091},"applied":1794898906091,"decided":{"link":true,"by":"reviewer","at":1794898906094}}]},"55249@2342252495945464":{"at":1794898906103,"suggestions":[{"id":"f758ba6ad795fb36","node":"55249@2342252495945464","range":[22,29],"quote":"octopus","key":"octopus","target":{"kind":"wiki","title":"Octopus","lang":"en"},"score":0.939,"tier":"suggest","why":"fits the text 0.94; a fairly uncommon word","source":"wikipedia","title":"Octopus","description":"Soft-bodied eight-limbed order of molluscs","kind":"noun","decided":{"link":false,"by":"fixture","at":1794898906107}}]}}
+36
View File
@@ -0,0 +1,36 @@
{
"commit": "626dc19",
"first": {
"made": {
"rootNote": "55203@2342252495945464",
"top": "55249@2342252495945464",
"first": "55323@2342252495945464",
"second": "55466@2342252495945464",
"deep": "55618@2342252495945464",
"gloss": "55691@2342252495945464",
"passage": "55733@2342252495945464",
"inner": "55800@2342252495945464",
"underNote": "55829@2342252495945464",
"orphan": "55868@2342252495945464",
"toFixed": "55924@2342252495945464",
"toKepler": "55932@2342252495945464",
"toWeb": "55940@2342252495945464",
"toGloss": "55948@2342252495945464",
"noteLink": "55965@2342252495945464",
"card": "55999@2342252495945464",
"fromOcto": "56009@2342252495945464",
"doomed": "56020@2342252495945464",
"toDoomed": "56039@2342252495945464",
"locked": "3668@2342252495945464",
"articles": "56058@2342252495945464",
"article": "56065@2342252495945464",
"annotation": "56072@2342252495945464"
},
"scanned": {
"first": 1,
"approved": 1,
"top": 1,
"listed": 2
}
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"imported": [
"infinite-expand",
"fixed-points",
"octopus-minds"
]
}
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
{"55466@2342252495945464":{"at":1794898906089,"suggestions":[{"id":"d4c0c680082b5ed5","node":"55466@2342252495945464","range":[89,109],"quote":"triple-alpha process","key":"triple alpha process","target":{"kind":"wiki","title":"Triple-alpha process","lang":"en"},"score":1,"tier":"auto","why":"fits the text 1.00; a technical term","source":"wikipedia","title":"Triple-alpha process","description":"Nuclear fusion of helium into carbon in stars","kind":"term","review":{"link":true,"reason":"mock: a name or a term a reader may look up","at":1794898906091},"applied":1794898906091,"decided":{"link":true,"by":"reviewer","at":1794898906094}}]},"55249@2342252495945464":{"at":1794898906103,"suggestions":[{"id":"f758ba6ad795fb36","node":"55249@2342252495945464","range":[22,29],"quote":"octopus","key":"octopus","target":{"kind":"wiki","title":"Octopus","lang":"en"},"score":0.939,"tier":"suggest","why":"fits the text 0.94; a fairly uncommon word","source":"wikipedia","title":"Octopus","description":"Soft-bodied eight-limbed order of molluscs","kind":"noun","decided":{"link":false,"by":"fixture","at":1794898906107}}]}}
+371
View File
@@ -0,0 +1,371 @@
/**
* The migration from the single-library layout (server/migrateLibraries.ts), on data directories
* written by older commits (tests/fixtures/migrate, made by make.ts there): pre/ by the code before
* documents went, main/ by the code just before libraries, mixed/ by the first then the second.
* The text, the notes, the flags and every reference must come across exactly; a dry run writes
* nothing; a second run does nothing; a copy that differs leaves the data untouched; the server
* will not open the old layout.
*/
import { spawn, type ChildProcess } from "node:child_process";
import { createHash } from "node:crypto";
import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, relative } from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { Libraries, layout, readIndex } from "../server/libraries";
import { LOCK } from "../server/lock";
import { migrateLibraries, type MigrateResult } from "../server/migrateLibraries";
import { resolveNode, targetKey } from "../src/core/links";
import { Doc, descendants, isStale, type NodeId, type Snap } from "../src/core/model";
import { digest } from "../src/core/text";
const FIXTURES = new URL("./fixtures/migrate/", import.meta.url).pathname;
const temps: string[] = [];
const temp = () => {
const d = mkdtempSync(join(tmpdir(), "ie-migrate-"));
temps.push(d);
return d;
};
const children: ChildProcess[] = [];
afterAll(() => {
for (const c of children) c.kill("SIGKILL");
for (const d of temps) rmSync(d, { recursive: true, force: true });
});
interface Edits {
first: { made: Record<string, NodeId> };
later?: { later: NodeId; laterLink: NodeId };
}
/** A copy of a fixture's data directory, and what was made in it. */
function fixture(name: string): { data: string; edits: Edits } {
const data = temp();
for (const f of ["library", "library.json", "links"]) cpSync(join(FIXTURES, name, f), join(data, f), { recursive: true });
return { data, edits: JSON.parse(readFileSync(join(FIXTURES, name, "edits.json"), "utf8")) };
}
/** Every file under a directory, with a hash of its bytes: to show that nothing was written. */
function files(dir: string): Record<string, string> {
const out: Record<string, string> = {};
const walk = (d: string) => {
for (const f of readdirSync(d)) {
const p = join(d, f);
if (statSync(p).isDirectory()) walk(p);
else out[relative(dir, p)] = createHash("sha256").update(readFileSync(p)).digest("hex");
}
};
walk(dir);
return out;
}
const run = (data: string, o: Parameters<typeof migrateLibraries>[1] = {}) => {
const lines: string[] = [];
const r = migrateLibraries(data, { log: (l) => lines.push(l), ...o });
return { ...r, lines } as MigrateResult & { lines: string[] };
};
/** Titles from the root down to a node, its own last: what identifies a node in both libraries. */
function pathOf(snap: Snap, id: NodeId): string {
const out: string[] = [];
for (let x: NodeId | null = id; x; x = snap.nodes[x].parent) out.unshift(`${snap.nodes[x].kind}:${snap.nodes[x].title}#${snap.nodes[x].parent ? snap.nodes[snap.nodes[x].parent!].children.indexOf(x) : 0}`);
return out.join(" / ");
}
/** The new library, read from its file on disk. */
const opened = (data: string, id: string) => Doc.load(readFileSync(join(data, "libraries", id, "main.loro")), "test");
describe.each(["pre", "main", "mixed"])("migrating data written by %s", (name) => {
const { data, edits } = fixture(name);
const before = files(data);
const old = Doc.load(readFileSync(join(data, "library", "main.loro")), "test");
const a = old.snap();
const made = edits.first.made;
// What the fixture's reviewer did not produce: a suggestion to a node, one rejected and one undecided.
const pending = JSON.parse(readFileSync(join(data, "links", "pending.json"), "utf8"));
const sugg = (quote: string, start: number, extra: object) => ({
id: `old-${quote}`,
node: made.second,
range: [start, start + quote.length],
quote,
key: quote.toLowerCase(),
target: { kind: "node", id: made.deep, path: ["Migration notes", "Second part", "Deep part"] },
score: 0.9,
tier: "suggest",
why: "test",
source: "library",
title: "Deep part",
description: null,
kind: "title",
...extra,
});
const body2 = a.nodes[made.second].body;
pending[made.second] = {
at: 1,
suggestions: [
...(pending[made.second]?.suggestions ?? []),
sugg("Haskell Curry", body2.indexOf("Haskell Curry"), { review: { link: false, reason: "test: no", at: 2 } }),
sugg("stars", body2.indexOf("stars"), {}),
],
};
// A suggestion whose node is gone is dropped.
pending[made.doomed] = { at: 1, suggestions: [sugg("Soon", 0, { node: made.doomed })] };
writeFileSync(join(data, "links", "pending.json"), JSON.stringify(pending));
const withPending = files(data);
it("refuses to open in the server, and a dry run verifies and writes nothing", () => {
expect(layout(data).kind).toBe("old");
expect(() => new Libraries(data, () => {}).open(() => {})).toThrow(/npm run migrate/);
const r = run(data, { check: true });
expect(r.problems).toEqual([]);
expect(r.status).toBe("checked");
expect(r.lines.join("\n")).toMatch(/verified: same tree/);
expect(r.lines.join("\n")).toMatch(/Nothing was written/);
expect(files(data)).toEqual(withPending);
expect(before).not.toEqual(withPending); // (the test's own pending entries, above)
});
it("migrates: the same tree, text, notes, flags and anchors under new ids, in a new library", () => {
const r = run(data);
expect(r.problems).toEqual([]);
expect(r.status).toBe("migrated");
expect(layout(data).kind).toBe("libraries");
const index = readIndex(join(data, "libraries"));
expect(index).toEqual([{ id: r.library, title: "Library", created: expect.any(String) }]);
// The old files, moved aside unchanged.
const backup = files(r.backup!);
for (const [f, h] of Object.entries(withPending)) expect(backup[f], f).toBe(h);
expect(existsSync(join(data, "library"))).toBe(false);
const neu = opened(data, r.library!);
const b = neu.snap();
expect(neu.libraryId).toBe(r.library);
expect(neu.libraryId).not.toBe(old.libraryId);
expect(b.library).toBe(true);
// Node for node, by place: the same titles, bodies, kinds, authors, locks, notes and anchors.
const rows = (s: Snap) =>
Object.keys(s.nodes)
.map((id) => {
const n = s.nodes[id as NodeId];
return [pathOf(s, id as NodeId), n.kind, n.title, n.body, n.by, n.pinned, n.form ?? null, n.lens ?? null, n.articles ?? false, JSON.stringify(n.wanchor ?? null), (n.nolink ?? []).join("|"), n.anchors.filter((x) => x.end > x.start).map((x) => `${x.start}-${x.end}:${x.quote}:${x.text}`).join("|"), isStale(s, id as NodeId)].join("\u0000");
})
.sort();
expect(rows(b)).toEqual(rows(a));
// No old id is left anywhere in the new library's nodes.
const oldIds = new Set(Object.keys(a.nodes));
for (const n of Object.values(b.nodes)) {
expect(oldIds.has(n.id)).toBe(false);
if (n.ref?.kind === "node" && n.ref.id) expect(b.nodes[n.ref.id], `${n.title}'s target`).toBeTruthy();
}
// A history of its own: nothing from before.
expect(neu.loro.getAllChanges().size).toBe(1);
});
it("carries what the tests made: the root's note, locks, the article and its note, the orphan, declines", () => {
const r = migrateLibraries(data, { log: () => {} }); // a second run: nothing to do
expect(r.status).toBe("nothing");
const id = readIndex(join(data, "libraries"))[0].id;
const b = opened(data, id).snap();
const find = (title: string, kind = "section") => Object.values(b.nodes).find((n) => n.title === title && n.kind === kind)!;
const root = b.nodes[b.root];
expect(root.body).toBe("Everything I keep. Root words worth a note sit here.");
const rootNote = root.children.map((c) => b.nodes[c]).find((n) => n.kind === "note")!;
expect(rootNote.anchors.map((x) => x.text)).toEqual(["Root words"]);
expect(rootNote.body).toBe("A note on the library root itself.");
expect(b.nodes[root.children[0]].title).toBe("Infinispand");
expect(b.nodes[root.children[1]].title).toBe("Migration notes");
// Locks: set on a model's node, taken off a person's.
const seed = find("Infinispand");
expect(b.nodes[seed.children.find((c) => b.nodes[c].kind === "section")!].pinned).toBe(true);
expect(find("Migration notes").pinned).toBe(false);
// The Wikipedia container, its article and the note on the article.
const box = root.children.map((c) => b.nodes[c]).find((n) => n.articles)!;
expect(box.title).toBe("Wikipedia");
const art = b.nodes[box.children[0]];
expect(art.ref).toEqual({ kind: "wiki", title: "Octopus", lang: "en", pageId: 1200106 });
expect(b.nodes[art.children[0]].wanchor?.q).toBe("two thirds of their neurons");
// The orphan keeps its text; the titled note its title; the section under a note its place.
const top = find("Migration notes");
const notes = top.children.map((c) => b.nodes[c]).filter((n) => n.kind === "note");
expect(notes.map((n) => n.body)).toContain("Its words are about to go.");
expect(find("Hearts, titled", "note").anchors[0].text).toBe("three hearts");
expect(b.nodes[find("A section under a note").parent!].form).toBe("passage");
expect(find("Second part").nolink).toContain("recursion");
});
it("rewrites every node target to the new ids, and keeps a broken one's hint", () => {
const id = readIndex(join(data, "libraries"))[0].id;
const b = opened(data, id).snap();
const find = (title: string) => Object.values(b.nodes).find((n) => n.title === title)!;
// The links the tests made, in the top they made.
const mine = new Set(descendants(b, find("Migration notes").id));
const linkOn = (quote: string) => Object.values(b.nodes).find((n) => mine.has(n.id) && n.kind === "note" && n.anchors.some((x) => x.text === quote) && n.ref)!;
const target = (quote: string) => {
const n = linkOn(quote);
expect(n.ref?.kind).toBe("node");
return resolveNode(b, n.ref as never, n.id);
};
expect(target("Fixed points")).toBe(Object.values(b.nodes).find((n) => n.parent === b.root && n.title === "Fixed points")!.id);
expect(b.nodes[target("Haskell Curry")!].title).toBe("Hearts, titled");
expect(linkOn("Haskell Curry").ref).toMatchObject({ quote: "three hearts", path: ["Migration notes"] });
expect(linkOn("Fred Hoyle").ref).toEqual({ kind: "wiki", title: "Fred Hoyle", lang: "en" });
expect(linkOn("plain words").ref).toEqual({ kind: "url", url: "https://example.org/page", title: "An example" });
const card = find("A card");
expect(b.nodes[resolveNode(b, card.ref as never, card.id)!].parent).toBe(Object.values(b.nodes).find((n) => n.parent === b.root && n.title.startsWith("Octopus minds"))!.id);
// From a starter tree into the new top.
const octo = Object.values(b.nodes).find((n) => n.parent === b.root && n.title.startsWith("Octopus minds"))!;
const octoFirst = b.nodes[octo.children.find((c) => b.nodes[c].kind === "section")!];
const fromOcto = octoFirst.children.map((c) => b.nodes[c]).find((n) => n.ref?.kind === "node")!;
expect(b.nodes[resolveNode(b, fromOcto.ref as never, fromOcto.id)!].title).toBe("Deep part");
// The link to the deleted section: still naming nothing, with its titles from the root and no id.
const broken = linkOn("doomed section");
expect(broken.ref).toEqual({ kind: "node", path: ["Migration notes", "Second part", "Doomed"] });
expect(resolveNode(b, broken.ref as never, broken.id)).toBeNull();
if (name === "mixed") {
// The link the newer code made, to a top renamed since.
expect(b.nodes[target("stars")!].title).toBe("Octopus minds, renamed");
}
});
it("re-keys the reviewer's verdicts, people's decisions and pending suggestions to the new ids", () => {
const id = readIndex(join(data, "libraries"))[0].id;
const b = opened(data, id).snap();
const carried = JSON.parse(readFileSync(join(data, "libraries", id, "links", "pending.json"), "utf8")) as Record<string, { suggestions: { id: string; node: NodeId; range: [number, number]; quote: string; target: { kind: string; id?: NodeId }; review?: { link: boolean }; decided?: { link: boolean } }[] }>;
const all = Object.entries(carried).flatMap(([k, e]) => e.suggestions.map((s) => ({ k, ...s })));
// Every entry under its new node, its words where they were, its id made from the new ids.
for (const s of all) {
expect(s.k).toBe(s.node);
expect(b.nodes[s.node].body.slice(s.range[0], s.range[1])).toBe(s.quote);
expect(s.id).toBe(digest(`${s.node}\u0000${s.range[0]}\u0000${s.range[1]}\u0000${targetKey(s.target as never)}`));
}
const by = (quote: string) => all.find((s) => s.quote === quote)!;
expect(by("triple-alpha process").review?.link).toBe(true);
expect(by("triple-alpha process").decided?.link).toBe(true);
expect(by("octopus").decided?.link).toBe(false);
expect(by("Haskell Curry").review?.link).toBe(false);
expect(b.nodes[by("Haskell Curry").target.id!].title).toBe("Deep part");
expect(b.nodes[by("stars").target.id!].title).toBe("Deep part");
expect(by("stars").review).toBeUndefined();
expect(all.some((s) => s.quote === "Soon")).toBe(false); // its node was deleted
// And the server opens the result as it is.
const libs = new Libraries(data, () => {}).open(() => {
throw new Error("must not seed a migrated library");
});
expect(libs.first().id).toBe(id);
});
});
describe("the migration's guards", () => {
it("leaves the data untouched when the copy differs, and says where", () => {
const { data } = fixture("pre");
const before = files(data);
const r = run(data, {
tamper: (doc) => {
const snap = doc.snap();
const id = Object.values(snap.nodes).find((n) => n.title === "Deep part")!.id;
doc.apply([{ op: "update", id, body: "Changed." }], "tamper");
},
});
expect(r.status).toBe("failed");
expect(r.problems.some((p) => /“Library › Migration notes › Second part › Deep part”: body differs/.test(p))).toBe(true);
expect(r.lines.join("\n")).toMatch(/FAILED: .*nothing was written/);
expect(files(data)).toEqual(before);
expect(readdirSync(data).sort()).toEqual(["library", "library.json", "links"]);
});
it("finishes a migration that stopped before moving the old files, and cleans a leftover temporary directory", () => {
const { data } = fixture("main");
mkdirSync(join(data, "libraries.tmp-20200101-000000", "x"), { recursive: true });
const first = run(data);
expect(first.status).toBe("migrated");
expect(readdirSync(data).some((f) => f.startsWith("libraries.tmp-"))).toBe(false);
// As if the run had stopped after the commit step: the old files back in place.
cpSync(join(first.backup!, "library"), join(data, "library"), { recursive: true });
cpSync(join(first.backup!, "links"), join(data, "links"), { recursive: true });
expect(layout(data).kind).toBe("unfinished");
expect(() => new Libraries(data, () => {}).open(() => {})).toThrow(/did not finish/);
const check = files(data);
expect(run(data, { check: true }).status).toBe("checked");
expect(files(data)).toEqual(check);
const again = run(data);
expect(again.status).toBe("finished");
expect(layout(data).kind).toBe("libraries");
expect(existsSync(join(again.backup!, "library", "main.loro"))).toBe(true);
expect(run(data).status).toBe("nothing");
});
it("carries open conflicts with their nodes renamed, reports other branches and unknown fields, drops slugs", () => {
const data = temp();
const old = Doc.library("old");
const [top, sec] = old.apply(
[
{ op: "create", parent: old.snap().root, title: "Top", body: "Text." },
{ op: "create", parent: "$0" as NodeId, title: "Section", body: "More." },
],
"make",
).created;
old.begin("raw", "human");
old.tree.getNodeByID(top)!.data.set("slug", "top");
old.tree.getNodeByID(sec)!.data.set("color", "red");
old.conflictMap.set("c1", JSON.stringify({ id: "c1", type: "edit-edit", node: sec, field: "body", title: "Section", base: "b", a: "x", b: "y", merged: "xy", status: "open" }));
old.conflictMap.set("c2", JSON.stringify({ id: "c2", type: "edit-edit", node: sec, field: "title", title: "Section", base: "b", a: "x", b: "y", merged: "xy", status: "resolved" }));
old.commit("raw", "human");
mkdirSync(join(data, "library"));
writeFileSync(join(data, "library", "main.loro"), old.snapshotBytes());
writeFileSync(join(data, "library", "draft.loro"), old.snapshotBytes());
const r = run(data);
expect(r.problems).toEqual([]);
const text = r.lines.join("\n");
expect(text).toMatch(/branches other than main, not carried .*: draft/);
expect(text).toMatch(/fields no version of this program reads, not carried: color \(1\)/);
expect(text).not.toMatch(/slug/);
expect(text).toMatch(/1 open carried, 1 resolved left behind/);
const neu = opened(data, r.library!);
const s = neu.snap();
const newSec = Object.values(s.nodes).find((n) => n.title === "Section")!.id;
expect(neu.conflicts()).toEqual([expect.objectContaining({ id: "c1", node: newSec, status: "open" })]);
expect(existsSync(join(r.backup!, "library", "draft.loro"))).toBe(true);
});
it("does nothing on an empty directory, and refuses the layout from before the single library", () => {
const empty = temp();
expect(run(empty).status).toBe("nothing");
expect(readdirSync(empty)).toEqual([]);
const older = temp();
mkdirSync(join(older, "docs", "tides"), { recursive: true });
const r = run(older);
expect(r.status).toBe("refused");
expect(r.problems[0]).toMatch(/c4d6856/);
});
it("refuses to run while a server has the data open: by its lock, or, for a server from before locks, by its checkout", async () => {
// A stand-in server: a process whose command line names server/index.ts.
const checkout = temp();
const data = join(checkout, ".data");
cpSync(join(FIXTURES, "pre", "library"), join(data, "library"), { recursive: true });
const sleeper = (cwd: string) => {
const c = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)", "server/index.ts"], { cwd, stdio: "ignore" });
children.push(c);
return c;
};
const old = sleeper(checkout);
await new Promise((r) => setTimeout(r, 200));
const r = run(data);
expect(r.status).toBe("refused");
expect(r.problems[0]).toMatch(new RegExp(`pid ${old.pid}`));
// A dry run is allowed: it writes nothing.
expect(run(data, { check: true }).status).toBe("checked");
old.kill("SIGKILL");
await new Promise((r) => setTimeout(r, 200));
// A server with a lock, running from elsewhere.
const elsewhere = temp();
const locked = sleeper(elsewhere);
await new Promise((r) => setTimeout(r, 200));
writeFileSync(join(data, LOCK), JSON.stringify({ pid: locked.pid, port: 4999 }));
expect(run(data).problems[0]).toMatch(new RegExp(`pid ${locked.pid}, port 4999`));
locked.kill("SIGKILL");
await new Promise((r) => setTimeout(r, 200));
// A stale lock is no obstacle.
expect(run(data).status).toBe("migrated");
});
});