import { mkdirSync, writeFileSync, appendFileSync, mkdtempSync, realpathSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; import { createReader } from "../../../../packages/conversation/src/reader.mjs"; const proj = realpathSync(mkdtempSync(join(tmpdir(), "fb-proj-"))); const dir = join(proj, ".pi", "state", "x", "sessions"); mkdirSync(dir, { recursive: true }); const f = join(dir, "s.jsonl"); const L = (o) => JSON.stringify(o) + "\n"; const m = (id, parentId, text) => L({ type: "message", id, parentId, timestamp: "2026-09-26T00:00:00Z", message: { role: "user", content: text } }); writeFileSync(f, L({ type: "session", id: "s", cwd: proj, timestamp: "2026-09-26T00:00:00Z" }) + m("a", null, "A") + m("b", "a", "B") + m("c", "b", "C")); const reader = createReader({ roots: [{ seat: "x", project: "p", projectRoot: proj, dir, harness: "pi", unsupportedReason: null, engineStartedAt: null }] }); const conv = reader.catalogue().conversations[0].conversation; const t = (p) => p.ok ? `${p.page.branch} [${p.page.entries.map((e) => e.content[0].text).join(",")}] default=${p.view.defaultBranch} branches=${p.view.branches.map((b) => b.branch).join("|")}` : JSON.stringify(p.refusal); let main = reader.open({ conversation: conv }); console.log("1 open", t(main)); // Pi navigates back to b and continues: fork from the middle of main. appendFileSync(f, m("x", "b", "X") + m("y", "x", "Y")); let fm = reader.next({ cursor: main.follow.id, conversation: conv, branch: "main" }); console.log("2 main follow", t(fm)); let dx = reader.open({ conversation: conv }); console.log("3 default open", t(dx)); // Pi goes back to c on main and continues; then resetLeaf starts a new root. appendFileSync(f, m("d", "c", "D") + m("r", null, "R")); console.log("4 main follow", t(reader.next({ cursor: fm.follow.id, conversation: conv, branch: "main" }))); console.log("5 b.x follow", t(reader.next({ cursor: dx.follow.id, conversation: conv, branch: dx.page.branch }))); console.log("6 open b.x", t(reader.open({ conversation: conv, branch: "b.x" }))); console.log("7 open default", t(reader.open({ conversation: conv })));