{"version":143,"agent":"codex-capacity-chair","message":"Add inactive disk projection provider and verified transactional readers (#16)","time":1791855032023,"timeIso":"2026-10-13T01:30:32.023Z","changes":63,"change":1284,"files":["src/engine/build.ts","src/engine/experimental/projection-locator.ts","src/engine/experimental/projection-marker.ts","src/engine/experimental/projection-overlay-storage.ts","src/engine/experimental/projection-priority.ts","src/engine/experimental/projection-read-scope.ts","src/engine/experimental/projection-reader.ts","src/engine/experimental/projection-records.ts","src/engine/experimental/projection-root.ts","src/engine/experimental/projection-sequence.ts","src/engine/experimental/projection-snapshots.ts","src/engine/test/projection-locator.test.ts","src/engine/test/projection-marker-cycle.test.ts","src/engine/test/projection-marker-move-failures.test.ts","src/engine/test/projection-marker.test.ts","src/engine/test/projection-overlay-storage.test.ts","src/engine/test/projection-priority.test.ts","src/engine/test/projection-read-scope.test.ts","src/engine/test/projection-reader.test.ts","src/engine/test/projection-records.test.ts","src/engine/test/projection-root.test.ts","src/engine/test/projection-sequence.test.ts","src/engine/test/projection-snapshots.test.ts","src/engine/view.ts","worker/project/add-draft.ts","worker/project/changes-since.ts","worker/project/check-clash.ts","worker/project/collisions.ts","worker/project/definition-rule.ts","worker/project/definitions.ts","worker/project/draft-collisions.ts","worker/project/draft-diff.ts","worker/project/edit.ts","worker/project/express-moves.ts","worker/project/history.ts","worker/project/ingest.ts","worker/project/init.ts","worker/project/land.ts","worker/project/markers.ts","worker/project/merge-identical.ts","worker/project/move.ts","worker/project/news.ts","worker/project/notes.ts","worker/project/overlaps.ts","worker/project/pathindex.ts","worker/project/project-status.ts","worker/project/project-types.ts","worker/project/project.ts","worker/project/projection-provider.ts","worker/project/publish.ts","worker/project/queue.ts","worker/project/record-file.ts","worker/project/record.ts","worker/project/restore.ts","worker/project/spelling.ts","worker/project/switch-to.ts","worker/project/sync.ts","worker/project/test/projection-integration.test.ts","worker/project/test/view-cache.test.ts","worker/project/version-log.ts","worker/project/view-changes.ts","worker/project/views.ts","worker/project/whole-files.ts"],"draft":null,"diff":[{"path":"src/engine/build.ts","added":14,"removed":9,"diff":"--- a/src/engine/build.ts\n+++ b/src/engine/build.ts\n@@ -23,6 +23,11 @@\n } from \"./types.ts\";\n import { View } from \"./view.ts\";\n \n+/** Exact read surface used to build atoms; membership requires point lookup only. */\n+export type AtomBuildView = Pick<View, \"graph\" | \"lines\" | \"sequence\" | \"sequenceIndex\" | \"parentOf\"> & {\n+\treadonly set: Pick<ReadonlySet<AtomId>, \"has\">;\n+};\n+\n /** Replace the one exact occurrence of `old` in `file` with `new`. */\n export interface TextEdit {\n \treadonly file: string;\n@@ -108,7 +113,7 @@\n  * the graph's next id; accept it with `graph.add(atom)` and put it in a set.\n  * Its dependencies are derived from what it touched in the view (see deriveDeps).\n  */\n-export function buildAtom(view: View, input: AtomInput): Atom {\n+export function buildAtom(view: AtomBuildView, input: AtomInput): Atom {\n \treturn build(view, input, false);\n }\n \n@@ -126,7 +131,7 @@\n \treturn build(view, { ...meta, edits, attrs }, true);\n }\n \n-function build(view: View, input: AtomInput, allowEmpty: boolean): Atom {\n+function build(view: AtomBuildView, input: AtomInput, allowEmpty: boolean): Atom {\n \tconst graph = view.graph;\n \tconst id = graph.nextId();\n \tif (typeof input.author !== \"string\" || typeof input.message !== \"string\") {\n@@ -275,7 +280,7 @@\n  * lines into each other collide in all but the rarest cases (the view breaks\n  * any loop that is left).\n  */\n-function planMove(view: View, move: MoveInput, writes: Set<Key>, reads: Set<Key>): Relocation[] {\n+function planMove(view: AtomBuildView, move: MoveInput, writes: Set<Key>, reads: Set<Key>): Relocation[] {\n \tfor (const path of [move.file, move.to]) {\n \t\tif (typeof path !== \"string\" || path === \"\" || /[\\n\\r]/.test(path))\n \t\t\tthrow new EngineError(\"bad-edit\", `bad file path ${JSON.stringify(path)}`);\n@@ -341,7 +346,7 @@\n  * the semantic contract. A missing tip still implies its required ancestors.\n  */\n function deriveDeps(\n-\tview: View,\n+\tview: AtomBuildView,\n \tparts: {\n \t\twrites: readonly Key[];\n \t\treads: readonly Key[];\n@@ -390,7 +395,7 @@\n \t});\n }\n \n-function rangeLines(view: View, range: LineRange): LineId[] {\n+function rangeLines(view: AtomBuildView, range: LineRange): LineId[] {\n \tconst visible = view.lines(range.file);\n \tif (\n \t\t!Number.isInteger(range.start) ||\n@@ -407,7 +412,7 @@\n \treturn visible.slice(range.start, range.end).map((l) => l.id);\n }\n \n-function uniqueAtoms(view: View, ids: readonly AtomId[], what: string): AtomId[] {\n+function uniqueAtoms(view: AtomBuildView, ids: readonly AtomId[], what: string): AtomId[] {\n \tconst out: AtomId[] = [];\n \tfor (const id of ids) {\n \t\tif (!view.graph.has(id)) throw new EngineError(\"unknown-atom\", `${what} names unknown atom ${id}`);\n@@ -419,7 +424,7 @@\n \n // Matching edits ---------------------------------------------------------------\n \n-function resolveRegions(view: View, edits: readonly EditInput[]): Region[] {\n+function resolveRegions(view: AtomBuildView, edits: readonly EditInput[]): Region[] {\n \tconst regions = edits.map((edit, order) => {\n \t\tconst mode = edit.mode ?? \"both\";\n \t\tif (!MODES.includes(mode)) throw new EngineError(\"bad-edit\", `mode must be one of ${MODES.join(\", \")}`);\n@@ -455,7 +460,7 @@\n  * whole lines. If the replacement would leave a line without its newline, the\n  * next line joins the region (that is what the plain-text edit does).\n  */\n-function matchText(view: View, edit: TextEdit, mode: Mode, order: number): Region {\n+function matchText(view: AtomBuildView, edit: TextEdit, mode: Mode, order: number): Region {\n \tif (typeof edit.old !== \"string\" || typeof edit.new !== \"string\") {\n \t\tthrow new EngineError(\"bad-edit\", \"a text edit needs old and new strings\");\n \t}\n@@ -514,7 +519,7 @@\n \treturn { file, start: startLine, end: endLine + 1, lines: splitLines(replacement), mode, order };\n }\n \n-function matchSplice(view: View, edit: SpliceEdit, mode: Mode, order: number): Region {\n+function matchSplice(view: AtomBuildView, edit: SpliceEdit, mode: Mode, order: number): Region {\n \tconst count = view.lines(edit.file).length;\n \tif (\n \t\t!Number.isInteger(edit.start) ||"},{"path":"src/engine/experimental/projection-locator.ts","added":111,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/experimental/projection-locator.ts\n@@ -0,0 +1,111 @@\n+import type { GraphStateStorage } from \"../state-source.ts\";\n+\n+type Page = number | null;\n+interface Leaf {\n+\tformat: 1;\n+\tkind: \"leaf\";\n+\tprefix: string;\n+\tvalue: unknown;\n+}\n+interface Branch {\n+\tformat: 1;\n+\tkind: \"branch\";\n+\tprefix: string;\n+\tchildren: Record<string, number>;\n+}\n+type Node = Leaf | Branch;\n+const safe = (n: unknown): n is number => Number.isSafeInteger(n) && Number(n) >= 0;\n+const object = (value: unknown): value is Record<string, unknown> =>\n+\tvalue !== null && typeof value === \"object\" && !Array.isArray(value);\n+function page(id: unknown): asserts id is Page {\n+\tif (id !== null && !safe(id)) throw Error(\"invalid locator page reference\");\n+}\n+function keyOf(id: number): string {\n+\tif (!safe(id) || id >= 2 ** 32) throw Error(\"experimental locator identity limit\");\n+\treturn id.toString(16).padStart(8, \"0\");\n+}\n+/** Internal immutable experiment. Hosts bind roots through ProjectionIdentity. */\n+export class ProjectionLocator<T> {\n+\treadonly #storage: GraphStateStorage;\n+\treadonly #collection: string;\n+\treadonly #decode: (value: unknown) => T;\n+\tconstructor(storage: GraphStateStorage, namespace: string, decode: (value: unknown) => T) {\n+\t\tif (!namespace || namespace.length > 4096) throw Error(\"invalid locator namespace\");\n+\t\tthis.#storage = storage;\n+\t\tthis.#collection = `experimental-locator:${JSON.stringify(namespace)}`;\n+\t\tthis.#decode = decode;\n+\t}\n+\t#read(id: number, parent?: string, digit?: string): Node {\n+\t\tpage(id);\n+\t\tconst row = this.#storage.read(this.#collection, String(id));\n+\t\tif (!object(row) || row.format !== 1 || typeof row.prefix !== \"string\" || !/^[0-9a-f]{0,8}$/.test(row.prefix))\n+\t\t\tthrow Error(\"invalid locator node\");\n+\t\tif (parent !== undefined && (row.prefix.length <= parent.length || !row.prefix.startsWith(parent + digit)))\n+\t\t\tthrow Error(\"invalid locator edge\");\n+\t\tif (row.kind === \"leaf\") {\n+\t\t\tif (row.prefix.length !== 8 || Object.keys(row).length !== 4 || !(\"value\" in row))\n+\t\t\t\tthrow Error(\"invalid locator leaf\");\n+\t\t\treturn row as unknown as Leaf;\n+\t\t}\n+\t\tif (row.kind !== \"branch\" || row.prefix.length >= 8 || Object.keys(row).length !== 4 || !object(row.children))\n+\t\t\tthrow Error(\"invalid locator branch\");\n+\t\tconst children = Object.entries(row.children);\n+\t\tif (children.length < 2 || children.length > 16) throw Error(\"invalid locator fanout\");\n+\t\tfor (const [digit, child] of children)\n+\t\t\tif (!/^[0-9a-f]$/.test(digit) || !safe(child) || child === id) throw Error(\"invalid locator child\");\n+\t\treturn row as unknown as Branch;\n+\t}\n+\t#write(node: Node): number {\n+\t\tconst next = this.#storage.read(this.#collection, \"next\") ?? 0;\n+\t\tif (!safe(next) || !Number.isSafeInteger(next + 1)) throw Error(\"invalid locator allocation\");\n+\t\tif (this.#storage.read(this.#collection, String(next)) !== undefined) throw Error(\"locator allocation collision\");\n+\t\tthis.#storage.write(this.#collection, String(next), node);\n+\t\tthis.#storage.write(this.#collection, \"next\", next + 1);\n+\t\treturn next;\n+\t}\n+\tget(root: Page, id: number): T | undefined {\n+\t\tpage(root);\n+\t\tconst key = keyOf(id);\n+\t\tlet current = root,\n+\t\t\tparent: string | undefined,\n+\t\t\tdigit: string | undefined;\n+\t\tfor (let depth = 0; current !== null; depth++) {\n+\t\t\tif (depth > 8) throw Error(\"invalid locator depth\");\n+\t\t\tconst node = this.#read(current, parent, digit);\n+\t\t\tif (!key.startsWith(node.prefix)) return undefined;\n+\t\t\tif (node.kind === \"leaf\") return this.#decode(structuredClone(node.value));\n+\t\t\tparent = node.prefix;\n+\t\t\tdigit = key[parent.length]!;\n+\t\t\tcurrent = node.children[digit] ?? null;\n+\t\t}\n+\t\treturn undefined;\n+\t}\n+\tset(root: Page, id: number, value: T): number {\n+\t\tpage(root);\n+\t\tconst key = keyOf(id),\n+\t\t\tchecked = structuredClone(this.#decode(structuredClone(value)));\n+\t\treturn this.#storage.transaction(() => {\n+\t\t\tconst visit = (current: Page, parent?: string, digit?: string, depth = 0): number => {\n+\t\t\t\tif (depth > 8) throw Error(\"invalid locator depth\");\n+\t\t\t\tif (current === null) return this.#write({ format: 1, kind: \"leaf\", prefix: key, value: checked });\n+\t\t\t\tconst node = this.#read(current, parent, digit);\n+\t\t\t\tlet common = 0;\n+\t\t\t\twhile (common < node.prefix.length && node.prefix[common] === key[common]) common++;\n+\t\t\t\tif (common < node.prefix.length) {\n+\t\t\t\t\tconst leaf = this.#write({ format: 1, kind: \"leaf\", prefix: key, value: checked });\n+\t\t\t\t\treturn this.#write({\n+\t\t\t\t\t\tformat: 1,\n+\t\t\t\t\t\tkind: \"branch\",\n+\t\t\t\t\t\tprefix: key.slice(0, common),\n+\t\t\t\t\t\tchildren: { [node.prefix[common]!]: current, [key[common]!]: leaf },\n+\t\t\t\t\t});\n+\t\t\t\t}\n+\t\t\t\tif (node.kind === \"leaf\") return this.#write({ format: 1, kind: \"leaf\", prefix: key, value: checked });\n+\t\t\t\tconst nextDigit = key[common]!;\n+\t\t\t\tconst child = visit(node.children[nextDigit] ?? null, node.prefix, nextDigit, depth + 1);\n+\t\t\t\treturn this.#write({ ...node, children: { ...node.children, [nextDigit]: child } });\n+\t\t\t};\n+\t\t\treturn visit(root);\n+\t\t});\n+\t}\n+}"},{"path":"src/engine/experimental/projection-marker.ts","added":428,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/experimental/projection-marker.ts\n@@ -0,0 +1,428 @@\n+import type { Graph } from \"../graph.ts\";\n+import { orderedChildKey } from \"../ordered-index.ts\";\n+import { resolveScratchMoves } from \"../relocation-scratch.ts\";\n+import type { GraphStateStorage } from \"../state-source.ts\";\n+import type { Atom, AtomId } from \"../types.ts\";\n+import { ProjectionLocator } from \"./projection-locator.ts\";\n+import { ProjectionPriority } from \"./projection-priority.ts\";\n+import {\n+\ttype ProjectionAttributeName,\n+\ttype ProjectionAttributes,\n+\ttype ProjectionAttributeValue,\n+\ttype ProjectionChildRoot,\n+\ttype ProjectionMarker,\n+\ttype ProjectionMembership,\n+\tprojectionAttributes,\n+\tprojectionAttributeValue,\n+\tprojectionChildRoot,\n+\tprojectionMarker,\n+\tprojectionMembership,\n+} from \"./projection-records.ts\";\n+import { ProjectionSequence, type SequenceState } from \"./projection-sequence.ts\";\n+\n+type Page = number | null;\n+export interface MarkerState {\n+\treadonly context: string;\n+\tsequence: SequenceState;\n+\tlocator: Page;\n+\tmembership: Page;\n+\tchildren: Page;\n+\tattributeFiles: Page;\n+}\n+interface Plan {\n+\tn: number;\n+\tparentKey: number;\n+\tkey: string;\n+}\n+function relocationPlan(value: unknown): Plan {\n+\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw Error(\"invalid relocation plan\");\n+\tconst row = value as Record<string, unknown>;\n+\tif (\n+\t\tObject.keys(row).length !== 3 ||\n+\t\t!Number.isSafeInteger(row.n) ||\n+\t\tNumber(row.n) < 0 ||\n+\t\tNumber(row.n) >= 0x7fffffff ||\n+\t\t!Number.isSafeInteger(row.parentKey) ||\n+\t\tNumber(row.parentKey) < 0 ||\n+\t\tNumber(row.parentKey) >= 2 ** 32 ||\n+\t\ttypeof row.key !== \"string\" ||\n+\t\t!/^[0-9a-f]{57}$/.test(row.key)\n+\t)\n+\t\tthrow Error(\"invalid relocation plan\");\n+\treturn { n: row.n as number, parentKey: row.parentKey as number, key: row.key };\n+}\n+const numeric = (value: unknown): number => {\n+\tif (!Number.isSafeInteger(value) || Number(value) < 0) throw Error(\"invalid projection number\");\n+\treturn value as number;\n+};\n+function required<T>(value: T | undefined): T {\n+\tif (value === undefined) throw Error(\"missing projection record\");\n+\treturn value;\n+}\n+/** Internal typed experiment; root binding wrapper is still required before integration. */\n+export class ExperimentalMarkerProjection {\n+\treadonly context: string;\n+\treadonly storage: GraphStateStorage;\n+\treadonly graph: Graph;\n+\treadonly path: string;\n+\treadonly sequence: ProjectionSequence;\n+\treadonly markers: ProjectionLocator<ProjectionMarker>;\n+\treadonly members: ProjectionLocator<ProjectionMembership>;\n+\treadonly childRoots: ProjectionLocator<ProjectionChildRoot>;\n+\treadonly attributeRoots: ProjectionLocator<ProjectionAttributes>;\n+\treadonly priorities: ProjectionPriority<number>;\n+\treadonly attributePriorities: ProjectionPriority<ProjectionAttributeValue>;\n+\tconstructor(storage: GraphStateStorage, graph: Graph, path: string, namespace: string) {\n+\t\tif (!namespace || namespace.length > 4096) throw Error(\"invalid projection namespace\");\n+\t\tthis.context = JSON.stringify([namespace, path]);\n+\t\tconst prefix = `experimental-marker:${JSON.stringify(namespace)}:`;\n+\t\tthis.storage = {\n+\t\t\tread: (collection, key) => storage.read(prefix + collection, key),\n+\t\t\twrite: (collection, key, value) => storage.write(prefix + collection, key, value),\n+\t\t\tremove: (collection, key) => storage.remove(prefix + collection, key),\n+\t\t\tentries: (collection) => storage.entries(prefix + collection),\n+\t\t\ttransaction: (body) => storage.transaction(body),\n+\t\t};\n+\t\tthis.graph = graph;\n+\t\tthis.path = path;\n+\t\tthis.sequence = new ProjectionSequence(storage, namespace + \":sequence\");\n+\t\tthis.markers = new ProjectionLocator(storage, namespace + \":markers\", projectionMarker);\n+\t\tthis.members = new ProjectionLocator(storage, namespace + \":membership\", projectionMembership);\n+\t\tthis.childRoots = new ProjectionLocator(storage, namespace + \":children\", projectionChildRoot);\n+\t\tthis.attributeRoots = new ProjectionLocator(storage, namespace + \":attributes\", projectionAttributes);\n+\t\tthis.priorities = new ProjectionPriority(storage, namespace + \":priorities\", numeric);\n+\t\tthis.attributePriorities = new ProjectionPriority(\n+\t\t\tstorage,\n+\t\t\tnamespace + \":attribute-priorities\",\n+\t\t\tprojectionAttributeValue,\n+\t\t);\n+\t}\n+\tassertContext(state: MarkerState): void {\n+\t\tif (!state || state.context !== this.context) throw Error(\"projection constructor context mismatch\");\n+\t}\n+\tempty(): MarkerState {\n+\t\treturn {\n+\t\t\tcontext: this.context,\n+\t\t\tsequence: this.sequence.empty(),\n+\t\t\tlocator: null,\n+\t\t\tmembership: null,\n+\t\t\tchildren: null,\n+\t\t\tattributeFiles: null,\n+\t\t};\n+\t}\n+\tapply(previous: MarkerState, atom: Atom): MarkerState {\n+\t\tthis.assertContext(previous);\n+\t\tif (JSON.stringify(this.graph.atom(atom.id)) !== JSON.stringify(atom)) throw Error(\"canonical atom mismatch\");\n+\t\tif (this.members.get(previous.membership, atom.seq)?.present) return previous;\n+\t\tfor (const id of atom.deps)\n+\t\t\tif (!this.members.get(previous.membership, this.graph.atom(id).seq)?.present) throw Error(\"missing dependency\");\n+\t\treturn this.storage.transaction(() => {\n+\t\t\tconst state = { ...previous };\n+\t\t\tconst sequence = this.sequence;\n+\t\t\tconst insert = (rank: number, text: string, hidden = false): number => {\n+\t\t\t\tconst id = state.sequence.next;\n+\t\t\t\tstate.sequence = sequence.update(state.sequence, { kind: \"insert\", rank, text });\n+\t\t\t\tif (hidden) state.sequence = sequence.update(state.sequence, { kind: \"visibility\", id, delta: 1 });\n+\t\t\t\treturn id;\n+\t\t\t};\n+\t\t\tthis.ensureFile(state, this.path);\n+\t\t\tfor (const run of atom.inserts) this.ensureFile(state, run.file);\n+\t\t\tlet k = 0;\n+\t\t\tfor (const run of atom.inserts)\n+\t\t\t\tfor (const text of run.lines) {\n+\t\t\t\t\tconst line = `${atom.id}.${k++}`,\n+\t\t\t\t\t\tn = this.graph.lineN(line),\n+\t\t\t\t\t\tparent = this.graph.parentCodeOf(n);\n+\t\t\t\t\tif (n + 1 >= 0x80000000) throw Error(\"prototype line identity limit\");\n+\t\t\t\t\tconst existing = this.markers.get(state.locator, n + 1);\n+\t\t\t\t\tif (existing) {\n+\t\t\t\t\t\tstate.sequence = sequence.update(state.sequence, { kind: \"visibility\", id: existing.enter, delta: -1 });\n+\t\t\t\t\t\tcontinue;\n+\t\t\t\t\t}\n+\t\t\t\t\tconst parentMarker = this.markers.get(state.locator, this.parentKey(parent));\n+\t\t\t\t\tif (!parentMarker) throw Error(\"missing parent marker\");\n+\t\t\t\t\tconst parentKey = this.parentKey(parent);\n+\t\t\t\t\tconst index = this.priorities;\n+\t\t\t\t\tconst root = this.childRoots.get(state.children, parentKey)?.root ?? null;\n+\t\t\t\t\tconst seq = this.graph.writerSeqOf(n);\n+\t\t\t\t\tconst key = orderedChildKey({\n+\t\t\t\t\t\tn,\n+\t\t\t\t\t\treplaces: this.graph.replacesN(n) ? 1 : 0,\n+\t\t\t\t\t\tlamport: this.graph.lamportOfSeq(seq),\n+\t\t\t\t\t\tseq,\n+\t\t\t\t\t\tk: this.graph.kOf(n),\n+\t\t\t\t\t});\n+\t\t\t\t\tconst preceding = index.before(root, key);\n+\t\t\t\t\tconst anchor =\n+\t\t\t\t\t\tpreceding === undefined\n+\t\t\t\t\t\t\t? parentMarker.enter\n+\t\t\t\t\t\t\t: required(this.markers.get(state.locator, preceding + 1)).exit;\n+\t\t\t\t\tstate.children = this.childRoots.set(state.children, parentKey, { root: index.insert(root, key, n) });\n+\t\t\t\t\tconst at = sequence.rank(state.sequence, anchor) + 1;\n+\t\t\t\t\tconst enter = insert(at, line),\n+\t\t\t\t\t\texit = insert(at + 1, `${line}:end`, true);\n+\t\t\t\t\tstate.locator = this.markers.set(state.locator, n + 1, { kind: \"line\", enter, exit, parentKey, key });\n+\t\t\t\t}\n+\t\t\tfor (const line of atom.deletes) {\n+\t\t\t\tconst marker = this.markers.get(state.locator, this.graph.lineN(line) + 1);\n+\t\t\t\tif (!marker) throw Error(\"missing deleted marker\");\n+\t\t\t\tstate.sequence = sequence.update(state.sequence, { kind: \"visibility\", id: marker.enter, delta: 1 });\n+\t\t\t}\n+\t\t\tfor (const id of atom.deps) {\n+\t\t\t\tconst seq = this.graph.atom(id).seq,\n+\t\t\t\t\tmember = required(this.members.get(state.membership, seq));\n+\t\t\t\tstate.membership = this.members.set(state.membership, seq, { ...member, dependents: member.dependents + 1 });\n+\t\t\t}\n+\t\t\tthis.updateAttributes(state, atom, true);\n+\t\t\tthis.updateFiles(state, atom, 1);\n+\t\t\tstate.membership = this.members.set(state.membership, atom.seq, { present: true, dependents: 0 });\n+\t\t\treturn atom.moves?.length ? this.reconcileMoves(state) : state;\n+\t\t});\n+\t}\n+\tremoveDeleter(previous: MarkerState, atom: Atom): MarkerState {\n+\t\treturn this.removeAtom(previous, atom);\n+\t}\n+\tremoveAtom(previous: MarkerState, atom: Atom): MarkerState {\n+\t\tthis.assertContext(previous);\n+\t\tif (JSON.stringify(this.graph.atom(atom.id)) !== JSON.stringify(atom)) throw Error(\"canonical atom mismatch\");\n+\t\tif (!this.members.get(previous.membership, atom.seq)?.present) return previous;\n+\t\tif (required(this.members.get(previous.membership, atom.seq)).dependents)\n+\t\t\tthrow Error(\"included dependent prevents removal\");\n+\t\treturn this.storage.transaction(() => {\n+\t\t\tconst state = { ...previous };\n+\t\t\tlet k = 0;\n+\t\t\tfor (const run of atom.inserts)\n+\t\t\t\tfor (const text of run.lines) {\n+\t\t\t\t\tconst marker = this.markers.get(state.locator, this.graph.lineN(`${atom.id}.${k++}`) + 1);\n+\t\t\t\t\tif (!marker) throw Error(\"missing inserted marker\");\n+\t\t\t\t\tstate.sequence = this.sequence.update(state.sequence, { kind: \"visibility\", id: marker.enter, delta: 1 });\n+\t\t\t\t}\n+\t\t\tfor (const line of atom.deletes) {\n+\t\t\t\tconst marker = this.markers.get(state.locator, this.graph.lineN(line) + 1);\n+\t\t\t\tif (!marker) throw Error(\"missing deleted marker\");\n+\t\t\t\tstate.sequence = this.sequence.update(state.sequence, { kind: \"visibility\", id: marker.enter, delta: -1 });\n+\t\t\t}\n+\t\t\tfor (const id of atom.deps) {\n+\t\t\t\tconst seq = this.graph.atom(id).seq,\n+\t\t\t\t\tmember = required(this.members.get(state.membership, seq));\n+\t\t\t\tif (!member?.present || member.dependents < 1) throw Error(\"invalid dependency count\");\n+\t\t\t\tstate.membership = this.members.set(state.membership, seq, { ...member, dependents: member.dependents - 1 });\n+\t\t\t}\n+\t\t\tthis.updateAttributes(state, atom, false);\n+\t\t\tthis.updateFiles(state, atom, -1);\n+\t\t\tstate.membership = this.members.set(state.membership, atom.seq, { present: false, dependents: 0 });\n+\t\t\treturn atom.moves?.length ? this.reconcileMoves(state) : state;\n+\t\t});\n+\t}\n+\treconcileMoves(previous: MarkerState): MarkerState {\n+\t\tthis.assertContext(previous);\n+\t\treturn this.storage.transaction(() => {\n+\t\t\tconst scope = numeric(this.storage.read(\"sequence-meta\", \"work-scope\") ?? 0);\n+\t\t\tthis.storage.write(\"sequence-meta\", \"work-scope\", scope + 1);\n+\t\t\tconst prefix = `sequence-resolver:${scope}:`,\n+\t\t\t\tcollections = new Set<string>();\n+\t\t\tconst scratch: GraphStateStorage = {\n+\t\t\t\tread: (c, k) => this.storage.read(prefix + c, k),\n+\t\t\t\twrite: (c, k, v) => {\n+\t\t\t\t\tcollections.add(c);\n+\t\t\t\t\tthis.storage.write(prefix + c, k, v);\n+\t\t\t\t},\n+\t\t\t\tremove: (c, k) => this.storage.remove(prefix + c, k),\n+\t\t\t\tentries: (c) => this.storage.entries(prefix + c),\n+\t\t\t\ttransaction: (body) => this.storage.transaction(body),\n+\t\t\t};\n+\t\t\tconst has = (id: AtomId) => this.members.get(previous.membership, this.graph.atom(id).seq)?.present ?? false;\n+\t\t\tprevious = { ...previous };\n+\t\t\tfor (const id of this.graph.movers())\n+\t\t\t\tfor (const move of this.graph.atom(id).moves ?? [])\n+\t\t\t\t\tif (move.parent.startsWith(\"^\")) this.ensureFile(previous, move.parent.slice(1));\n+\t\t\tconst resolved = resolveScratchMoves(this.graph, has, scratch),\n+\t\t\t\tself = this;\n+\t\t\tfunction* plans(): IterableIterator<Plan> {\n+\t\t\t\tfor (const id of self.graph.movers())\n+\t\t\t\t\tfor (const move of self.graph.atom(id).moves ?? []) {\n+\t\t\t\t\t\tif (scratch.read(\"planned\", move.line)) continue;\n+\t\t\t\t\t\tscratch.write(\"planned\", move.line, true);\n+\t\t\t\t\t\tconst n = self.graph.lineN(move.line);\n+\t\t\t\t\t\tif (!has(self.graph.idOfSeq(self.graph.writerSeqOf(n)))) continue;\n+\t\t\t\t\t\tconst marker = self.markers.get(previous.locator, n + 1);\n+\t\t\t\t\t\tif (!marker || marker.kind !== \"line\") throw Error(\"missing selected relocation marker\");\n+\t\t\t\t\t\tconst selected = resolved.selected(move.line),\n+\t\t\t\t\t\t\tparent = resolved.parent(move.line);\n+\t\t\t\t\t\tconst parentKey = parent.startsWith(\"^\")\n+\t\t\t\t\t\t\t? required(self.fileKey(parent.slice(1)))\n+\t\t\t\t\t\t\t: self.graph.lineN(parent) + 1;\n+\t\t\t\t\t\tconst seq = selected ? self.graph.atom(selected.atom).seq : self.graph.writerSeqOf(n);\n+\t\t\t\t\t\tconst key = orderedChildKey({\n+\t\t\t\t\t\t\tn,\n+\t\t\t\t\t\t\treplaces: selected ? 0 : Number(self.graph.replacesN(n)),\n+\t\t\t\t\t\t\tlamport: self.graph.lamportOfSeq(seq),\n+\t\t\t\t\t\t\tseq,\n+\t\t\t\t\t\t\tk: selected ? selected.k : self.graph.kOf(n),\n+\t\t\t\t\t\t});\n+\t\t\t\t\t\tif (parentKey !== marker.parentKey || key !== marker.key) yield { n, parentKey, key };\n+\t\t\t\t\t}\n+\t\t\t}\n+\t\t\tconst state = this.relocateBatch(previous, plans());\n+\t\t\tfor (const collection of collections)\n+\t\t\t\tfor (const [key] of this.storage.entries(prefix + collection)) this.storage.remove(prefix + collection, key);\n+\t\t\treturn state;\n+\t\t});\n+\t}\n+\trelocateBatch(previous: MarkerState, plans: Iterable<Plan>): MarkerState {\n+\t\tthis.assertContext(previous);\n+\t\treturn this.storage.transaction(() => {\n+\t\t\tconst scope = numeric(this.storage.read(\"sequence-meta\", \"work-scope\") ?? 0);\n+\t\t\tthis.storage.write(\"sequence-meta\", \"work-scope\", scope + 1);\n+\t\t\tconst name = `sequence-relocation-work:${scope}`;\n+\t\t\tlet count = 0,\n+\t\t\t\tstate = previous;\n+\t\t\tfor (const candidate of plans) {\n+\t\t\t\tconst plan = relocationPlan(candidate);\n+\t\t\t\tif (this.storage.read(name, `seen:${plan.n}`)) throw Error(\"duplicate relocation plan\");\n+\t\t\t\tthis.storage.write(name, `seen:${plan.n}`, true);\n+\t\t\t\tthis.storage.write(name, String(count++), plan);\n+\t\t\t}\n+\t\t\t// A file root is the temporary parking parent. All phases are invisible\n+\t\t\t// outside this transaction; no history-sized plan array is retained.\n+\t\t\tfor (let i = 0; i < count; i++) {\n+\t\t\t\tconst plan = relocationPlan(this.storage.read(name, String(i)));\n+\t\t\t\tconst marker = this.markers.get(state.locator, plan.n + 1);\n+\t\t\t\tif (!marker || marker.kind !== \"line\") throw Error(\"missing relocation marker\");\n+\t\t\t\tstate = this.relocate(state, plan.n, 0, marker.key);\n+\t\t\t}\n+\t\t\tfor (let i = 0; i < count; i++) {\n+\t\t\t\tconst plan = relocationPlan(this.storage.read(name, String(i)));\n+\t\t\t\tstate = this.relocate(state, plan.n, plan.parentKey, plan.key);\n+\t\t\t}\n+\t\t\tfor (let i = 0; i < count; i++) {\n+\t\t\t\tconst plan = relocationPlan(this.storage.read(name, String(i)));\n+\t\t\t\tthis.storage.remove(name, `seen:${plan.n}`);\n+\t\t\t\tthis.storage.remove(name, String(i));\n+\t\t\t}\n+\t\t\treturn state;\n+\t\t});\n+\t}\n+\trelocate(previous: MarkerState, n: number, parentKey: number, key: string): MarkerState {\n+\t\tthis.assertContext(previous);\n+\t\treturn this.storage.transaction(() => {\n+\t\t\tconst state = { ...previous },\n+\t\t\t\tseq = this.sequence,\n+\t\t\t\tindex = this.priorities;\n+\t\t\tconst marker = this.markers.get(state.locator, n + 1),\n+\t\t\t\ttarget = this.markers.get(state.locator, parentKey);\n+\t\t\tif (!marker || marker.kind !== \"line\" || !target) throw Error(\"missing relocation marker\");\n+\t\t\tconst oldRoot = this.childRoots.get(state.children, marker.parentKey)?.root ?? null;\n+\t\t\tstate.children = this.childRoots.set(state.children, marker.parentKey, {\n+\t\t\t\troot: index.remove(oldRoot, marker.key),\n+\t\t\t});\n+\t\t\tconst newRoot = this.childRoots.get(state.children, parentKey)?.root ?? null;\n+\t\t\tconst sibling = index.before(newRoot, key);\n+\t\t\tconst anchor = sibling === undefined ? target.enter : required(this.markers.get(state.locator, sibling + 1)).exit;\n+\t\t\tconst from = seq.rank(state.sequence, marker.enter),\n+\t\t\t\tend = seq.rank(state.sequence, marker.exit);\n+\t\t\tconst anchorRank = seq.rank(state.sequence, anchor),\n+\t\t\t\tlength = end - from + 1;\n+\t\t\tif (anchorRank >= from && anchorRank <= end) throw Error(\"relocation would cycle\");\n+\t\t\tconst to = anchorRank + 1 - (anchorRank > end ? length : 0);\n+\t\t\tstate.sequence = seq.update(state.sequence, { kind: \"move\", from, length, to });\n+\t\t\tstate.children = this.childRoots.set(state.children, parentKey, { root: index.insert(newRoot, key, n) });\n+\t\t\tstate.locator = this.markers.set(state.locator, n + 1, { ...marker, parentKey, key });\n+\t\t\treturn state;\n+\t\t});\n+\t}\n+\tfileKey(path: string): number | undefined {\n+\t\tif (path === this.path) return 0;\n+\t\tconst id = this.storage.read(\"sequence-file-identities\", path);\n+\t\treturn id === undefined ? undefined : numeric(id);\n+\t}\n+\tparentKey(code: number): number {\n+\t\treturn code < 0 ? this.fileKey(this.graph.nodeOf(code).slice(1))! : code + 1;\n+\t}\n+\tensureFile(state: MarkerState, path: string): void {\n+\t\tthis.assertContext(state);\n+\t\tlet key = this.fileKey(path);\n+\t\tif (key === undefined) {\n+\t\t\tkey = numeric(this.storage.read(\"sequence-meta\", \"next-file\") ?? 0x80000000);\n+\t\t\tif (key >= 2 ** 32) throw Error(\"file identity limit\");\n+\t\t\tthis.storage.write(\"sequence-file-identities\", path, key);\n+\t\t\tthis.storage.write(\"sequence-meta\", \"next-file\", key + 1);\n+\t\t}\n+\t\tif (this.markers.get(state.locator, key)) return;\n+\t\tconst seq = this.sequence;\n+\t\tconst insert = (text: string): number => {\n+\t\t\tconst id = state.sequence.next,\n+\t\t\t\trank = state.sequence.root === null ? 0 : seq.get(state.sequence.map, state.sequence.root).count;\n+\t\t\tstate.sequence = seq.update(state.sequence, { kind: \"insert\", rank, text });\n+\t\t\tstate.sequence = seq.update(state.sequence, { kind: \"visibility\", id, delta: 1 });\n+\t\t\treturn id;\n+\t\t};\n+\t\tconst enter = insert(`root:${path}`),\n+\t\t\texit = insert(`end:${path}`);\n+\t\tstate.locator = this.markers.set(state.locator, key, { kind: \"file\", enter, exit, contributions: 0 });\n+\t}\n+\tupdateFiles(state: MarkerState, atom: Atom, delta: 1 | -1): void {\n+\t\tfor (const path of this.graph.filesOf(atom.id)) {\n+\t\t\tthis.ensureFile(state, path);\n+\t\t\tconst key = required(this.fileKey(path));\n+\t\t\tconst marker = this.markers.get(state.locator, key);\n+\t\t\tif (marker?.kind !== \"file\" || marker.contributions + delta < 0) throw Error(\"invalid file contribution count\");\n+\t\t\tstate.locator = this.markers.set(state.locator, key, { ...marker, contributions: marker.contributions + delta });\n+\t\t}\n+\t}\n+\tknownPaths(state: MarkerState): string[] {\n+\t\tthis.assertContext(state);\n+\t\tconst paths: string[] = [];\n+\t\tfor (const path of this.graph.knownFiles()) {\n+\t\t\tconst key = this.fileKey(path),\n+\t\t\t\tmarker = key === undefined ? undefined : this.markers.get(state.locator, key);\n+\t\t\tif (marker?.kind === \"file\" && marker.contributions > 0) paths.push(path);\n+\t\t}\n+\t\treturn paths.sort();\n+\t}\n+\tupdateAttributes(state: MarkerState, atom: Atom, adding: boolean): void {\n+\t\tthis.assertContext(state);\n+\t\tconst index = this.attributePriorities,\n+\t\t\thex = (n: number) => n.toString(16).padStart(14, \"0\");\n+\t\tconst key = `0${hex(this.graph.lamportOfSeq(atom.seq))}${hex(atom.seq)}${hex(0)}${hex(0)}`;\n+\t\tconst names = new Set<string>();\n+\t\tfor (const attr of atom.attrs ?? []) {\n+\t\t\tif (![\"exists\", \"exec\", \"link\", \"blob\"].includes(attr.name)) throw Error(\"unsupported attribute\");\n+\t\t\tconst identity = JSON.stringify([attr.file, attr.name]);\n+\t\t\tif (names.has(identity)) continue;\n+\t\t\tnames.add(identity);\n+\t\t\tthis.ensureFile(state, attr.file);\n+\t\t\tconst file = required(this.fileKey(attr.file)),\n+\t\t\t\troots = this.attributeRoots.get(state.attributeFiles, file) ?? {};\n+\t\t\tconst root = roots[attr.name] ?? null;\n+\t\t\tstate.attributeFiles = this.attributeRoots.set(state.attributeFiles, file, {\n+\t\t\t\t...roots,\n+\t\t\t\t[attr.name]: adding ? index.insert(root, key, { value: attr.value }) : index.remove(root, key),\n+\t\t\t});\n+\t\t}\n+\t}\n+\tattrs(state: MarkerState, path = this.path) {\n+\t\tthis.assertContext(state);\n+\t\tconst index = this.attributePriorities,\n+\t\t\tfile = this.fileKey(path);\n+\t\tconst roots = file === undefined ? {} : (this.attributeRoots.get(state.attributeFiles, file) ?? {});\n+\t\tconst value = (name: ProjectionAttributeName) => index.before(roots[name] ?? null, \"f\".repeat(57))?.value ?? null;\n+\t\treturn { exists: value(\"exists\") === \"1\", exec: value(\"exec\") === \"1\", link: value(\"link\"), blob: value(\"blob\") };\n+\t}\n+\tlines(state: MarkerState, path = this.path): string[] {\n+\t\treturn [...this.lineIds(state, path)];\n+\t}\n+\t*lineIds(state: MarkerState, path = this.path): IterableIterator<string> {\n+\t\tthis.assertContext(state);\n+\t\tconst key = this.fileKey(path);\n+\t\tif (key === undefined) return;\n+\t\tconst marker = this.markers.get(state.locator, key);\n+\t\tif (!marker) return;\n+\t\tfor (const line of this.sequence.range(\n+\t\t\tstate.sequence,\n+\t\t\tthis.sequence.rank(state.sequence, marker.enter) + 1,\n+\t\t\tthis.sequence.rank(state.sequence, marker.exit),\n+\t\t))\n+\t\t\tyield line.text;\n+\t}\n+}"},{"path":"src/engine/experimental/projection-overlay-storage.ts","added":71,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/experimental/projection-overlay-storage.ts\n@@ -0,0 +1,71 @@\n+import type { GraphStateStorage } from \"../state-source.ts\";\n+\n+type OverlayRow = { collection: string; key: string; present: boolean; value?: unknown };\n+\n+/** Disk-backed temporary pages over immutable committed projection pages. */\n+export class ProjectionOverlayStorage implements GraphStateStorage {\n+\treadonly #base: GraphStateStorage;\n+\treadonly #collection: string;\n+\t#open = true;\n+\tconstructor(base: GraphStateStorage, namespace: string) {\n+\t\tif (!namespace) throw Error(\"missing projection overlay namespace\");\n+\t\tthis.#base = base;\n+\t\tthis.#collection = `projection:temporary:${namespace}`;\n+\t\tfor (const _ of base.entries(this.#collection)) throw Error(\"projection overlay namespace is occupied\");\n+\t}\n+\t#check(): void {\n+\t\tif (!this.#open) throw Error(\"closed projection overlay\");\n+\t}\n+\t#key(collection: string, key: string): string {\n+\t\treturn JSON.stringify([collection, key]);\n+\t}\n+\tread(collection: string, key: string): unknown {\n+\t\tthis.#check();\n+\t\tconst row = this.#base.read(this.#collection, this.#key(collection, key)) as OverlayRow | undefined;\n+\t\treturn row ? (row.present ? row.value : undefined) : this.#base.read(collection, key);\n+\t}\n+\twrite(collection: string, key: string, value: unknown): void {\n+\t\tthis.#check();\n+\t\tthis.#base.write(this.#collection, this.#key(collection, key), { collection, key, present: true, value });\n+\t}\n+\tremove(collection: string, key: string): void {\n+\t\tthis.#check();\n+\t\tthis.#base.write(this.#collection, this.#key(collection, key), { collection, key, present: false });\n+\t}\n+\t*entries(collection: string): Iterable<readonly [string, unknown]> {\n+\t\tthis.#check();\n+\t\tfor (const [key, value] of this.#rows(collection)) {\n+\t\t\tthis.#check();\n+\t\t\tif (!this.#base.read(this.#collection, this.#key(collection, key))) yield [key, value];\n+\t\t}\n+\t\tfor (const [, value] of this.#rows(this.#collection)) {\n+\t\t\tthis.#check();\n+\t\t\tconst row = value as OverlayRow;\n+\t\t\tif (row.collection === collection && row.present) yield [row.key, row.value];\n+\t\t}\n+\t\tthis.#check();\n+\t}\n+\t*#rows(collection: string): Iterable<readonly [string, unknown]> {\n+\t\tthis.#check();\n+\t\tconst iterator = this.#base.entries(collection)[Symbol.iterator]();\n+\t\twhile (true) {\n+\t\t\tthis.#check();\n+\t\t\tconst next = iterator.next();\n+\t\t\tthis.#check();\n+\t\t\tif (next.done) return;\n+\t\t\tyield next.value;\n+\t\t}\n+\t}\n+\ttransaction<T>(body: () => T): T {\n+\t\tthis.#check();\n+\t\treturn this.#base.transaction(body);\n+\t}\n+\t/** Invoke before the owning outer transaction commits; failed cleanup must abort it. */\n+\tclose(): void {\n+\t\tif (!this.#open) return;\n+\t\tthis.#base.transaction(() => {\n+\t\t\tfor (const [key] of this.#base.entries(this.#collection)) this.#base.remove(this.#collection, key);\n+\t\t});\n+\t\tthis.#open = false;\n+\t}\n+}"},{"path":"src/engine/experimental/projection-priority.ts","added":115,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/experimental/projection-priority.ts\n@@ -0,0 +1,115 @@\n+import type { GraphStateStorage } from \"../state-source.ts\";\n+\n+type Page = number | null;\n+interface Leaf {\n+\tformat: 1;\n+\tkind: \"leaf\";\n+\tdepth: 57;\n+\tvalue: unknown;\n+}\n+interface Branch {\n+\tformat: 1;\n+\tkind: \"branch\";\n+\tdepth: number;\n+\tchildren: Record<string, number>;\n+}\n+type Node = Leaf | Branch;\n+const safe = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;\n+const object = (value: unknown): value is Record<string, unknown> =>\n+\tvalue !== null && typeof value === \"object\" && !Array.isArray(value);\n+function check(root: Page, key: string): void {\n+\tif ((root !== null && !safe(root)) || !/^[0-9a-f]{57}$/.test(key)) throw Error(\"invalid priority lookup\");\n+}\n+/** Internal immutable priority experiment. At most 57 levels and 16 children. */\n+export class ProjectionPriority<T> {\n+\treadonly #storage: GraphStateStorage;\n+\treadonly #collection: string;\n+\treadonly #decode: (value: unknown) => T;\n+\tconstructor(storage: GraphStateStorage, namespace: string, decode: (value: unknown) => T) {\n+\t\tif (!namespace || namespace.length > 4096) throw Error(\"invalid priority namespace\");\n+\t\tthis.#storage = storage;\n+\t\tthis.#collection = `experimental-priority:${JSON.stringify(namespace)}`;\n+\t\tthis.#decode = decode;\n+\t}\n+\t#read(id: number, depth: number): Node {\n+\t\tif (!safe(id) || !safe(depth) || depth > 57) throw Error(\"invalid priority reference\");\n+\t\tconst row = this.#storage.read(this.#collection, String(id));\n+\t\tif (!object(row) || row.format !== 1 || row.depth !== depth || Object.keys(row).length !== 4)\n+\t\t\tthrow Error(\"invalid priority node\");\n+\t\tif (depth === 57) {\n+\t\t\tif (row.kind !== \"leaf\" || !(\"value\" in row)) throw Error(\"invalid priority leaf\");\n+\t\t\treturn row as unknown as Leaf;\n+\t\t}\n+\t\tif (row.kind !== \"branch\" || !object(row.children)) throw Error(\"invalid priority branch\");\n+\t\tconst entries = Object.entries(row.children);\n+\t\tif (!entries.length || entries.length > 16) throw Error(\"invalid priority fanout\");\n+\t\tfor (const [digit, child] of entries)\n+\t\t\tif (!/^[0-9a-f]$/.test(digit) || !safe(child) || child === id) throw Error(\"invalid priority child\");\n+\t\treturn row as unknown as Branch;\n+\t}\n+\t#write(node: Node): number {\n+\t\tconst next = this.#storage.read(this.#collection, \"next\") ?? 0;\n+\t\tif (!safe(next) || !Number.isSafeInteger(next + 1)) throw Error(\"invalid priority allocation\");\n+\t\tif (this.#storage.read(this.#collection, String(next)) !== undefined) throw Error(\"priority allocation collision\");\n+\t\tthis.#storage.write(this.#collection, String(next), node);\n+\t\tthis.#storage.write(this.#collection, \"next\", next + 1);\n+\t\treturn next;\n+\t}\n+\tinsert(root: Page, key: string, value: T): number {\n+\t\tcheck(root, key);\n+\t\tconst checked = structuredClone(this.#decode(structuredClone(value)));\n+\t\treturn this.#storage.transaction(() => {\n+\t\t\tconst visit = (id: Page, depth: number): number => {\n+\t\t\t\tconst node = id === null ? undefined : this.#read(id, depth);\n+\t\t\t\tif (depth === 57) return this.#write({ format: 1, kind: \"leaf\", depth: 57, value: checked });\n+\t\t\t\tif (node?.kind === \"leaf\") throw Error(\"invalid priority depth\");\n+\t\t\t\tconst children = node?.children ?? {},\n+\t\t\t\t\tdigit = key[depth]!;\n+\t\t\t\tconst child = visit(children[digit] ?? null, depth + 1);\n+\t\t\t\treturn this.#write({ format: 1, kind: \"branch\", depth, children: { ...children, [digit]: child } });\n+\t\t\t};\n+\t\t\treturn visit(root, 0);\n+\t\t});\n+\t}\n+\tremove(root: Page, key: string): Page {\n+\t\tcheck(root, key);\n+\t\treturn this.#storage.transaction(() => {\n+\t\t\tconst visit = (id: Page, depth: number): Page => {\n+\t\t\t\tif (id === null) throw Error(\"missing priority key\");\n+\t\t\t\tconst node = this.#read(id, depth);\n+\t\t\t\tif (node.kind === \"leaf\") return null;\n+\t\t\t\tconst digit = key[depth]!,\n+\t\t\t\t\tchild = visit(node.children[digit] ?? null, depth + 1),\n+\t\t\t\t\tchildren = { ...node.children };\n+\t\t\t\tif (child === null) delete children[digit];\n+\t\t\t\telse children[digit] = child;\n+\t\t\t\treturn Object.keys(children).length ? this.#write({ ...node, children }) : null;\n+\t\t\t};\n+\t\t\treturn visit(root, 0);\n+\t\t});\n+\t}\n+\tbefore(root: Page, key: string): T | undefined {\n+\t\tcheck(root, key);\n+\t\tlet current = root;\n+\t\tlet candidate: { id: number; depth: number } | undefined;\n+\t\tfor (let depth = 0; current !== null && depth < 57; depth++) {\n+\t\t\tconst node = this.#read(current, depth);\n+\t\t\tif (node.kind !== \"branch\") throw Error(\"invalid priority depth\");\n+\t\t\tconst digit = key[depth]!,\n+\t\t\t\tlower = Object.keys(node.children)\n+\t\t\t\t\t.filter((item) => item < digit)\n+\t\t\t\t\t.sort()\n+\t\t\t\t\t.at(-1);\n+\t\t\tif (lower !== undefined) candidate = { id: node.children[lower]!, depth: depth + 1 };\n+\t\t\tcurrent = node.children[digit] ?? null;\n+\t\t}\n+\t\tif (!candidate) return undefined;\n+\t\tlet { id, depth } = candidate;\n+\t\tfor (; depth <= 57; depth++) {\n+\t\t\tconst node = this.#read(id, depth);\n+\t\t\tif (node.kind === \"leaf\") return this.#decode(structuredClone(node.value));\n+\t\t\tid = node.children[Object.keys(node.children).sort().at(-1)!]!;\n+\t\t}\n+\t\tthrow Error(\"invalid priority depth\");\n+\t}\n+}"},{"path":"src/engine/experimental/projection-read-scope.ts","added":59,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/experimental/projection-read-scope.ts\n@@ -0,0 +1,59 @@\n+import type { Graph } from \"../graph.ts\";\n+\n+/** Private host-owned lifetime. The host closes it in commit/rollback finally blocks. */\n+export class ProjectionReadScope {\n+\treadonly #graph: Graph;\n+\treadonly #source: () => unknown;\n+\treadonly #identity: unknown;\n+\treadonly #parent: () => void;\n+\treadonly #onClose: () => void;\n+\t#active = true;\n+\t#epoch = 0;\n+\t#child = false;\n+\tconstructor(graph: Graph, source: () => unknown, parent = () => {}, onClose = () => {}) {\n+\t\tthis.#graph = graph;\n+\t\tthis.#source = source;\n+\t\tthis.#identity = source();\n+\t\tthis.#parent = parent;\n+\t\tthis.#onClose = onClose;\n+\t}\n+\t#check(): void {\n+\t\tthis.#parent();\n+\t\tif (!this.#active || this.#source() !== this.#identity) throw Error(\"expired projection read scope\");\n+\t}\n+\t/** Capture this exact graph revision and scope generation, not a mutable validity flag. */\n+\tguard(graph: Graph): () => void {\n+\t\tthis.#check();\n+\t\tif (graph !== this.#graph || this.#child) throw Error(\"projection read scope mismatch\");\n+\t\tconst epoch = this.#epoch,\n+\t\t\tsize = graph.size;\n+\t\treturn () => {\n+\t\t\tthis.#check();\n+\t\t\tif (this.#child || this.#epoch !== epoch || graph.size !== size) throw Error(\"stale projection reader\");\n+\t\t};\n+\t}\n+\tnested(): ProjectionReadScope {\n+\t\tthis.#check();\n+\t\tif (this.#child) throw Error(\"projection child scope already active\");\n+\t\tthis.#child = true;\n+\t\tconst epoch = ++this.#epoch;\n+\t\treturn new ProjectionReadScope(\n+\t\t\tthis.#graph,\n+\t\t\tthis.#source,\n+\t\t\t() => {\n+\t\t\t\tthis.#check();\n+\t\t\t\tif (this.#epoch !== epoch) throw Error(\"expired projection parent scope\");\n+\t\t\t},\n+\t\t\t() => {\n+\t\t\t\tthis.#child = false;\n+\t\t\t\tthis.#epoch++;\n+\t\t\t},\n+\t\t);\n+\t}\n+\tclose(): void {\n+\t\tif (!this.#active) return;\n+\t\tthis.#active = false;\n+\t\tthis.#epoch++;\n+\t\tthis.#onClose();\n+\t}\n+}"},{"path":"src/engine/experimental/projection-reader.ts","added":183,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/experimental/projection-reader.ts\n@@ -0,0 +1,183 @@\n+import { startNode } from \"../keys.ts\";\n+import { StableSet } from \"../state-source.ts\";\n+import { joinLines } from \"../text.ts\";\n+import type { FileAttrs, ReadView, SeqLine, VisibleLine } from \"../view.ts\";\n+import type { ExperimentalMarkerProjection, MarkerState } from \"./projection-marker.ts\";\n+\n+/** Private reader for a host-verified immutable projection. Not a production View replacement. */\n+export class ProjectionReader implements ReadView {\n+\treadonly #adapter: ExperimentalMarkerProjection;\n+\treadonly #state: MarkerState;\n+\treadonly #assertLive: () => void;\n+\tconstructor(adapter: ExperimentalMarkerProjection, state: MarkerState, assertLive: () => void) {\n+\t\tassertLive();\n+\t\tthis.#assertLive = assertLive;\n+\t\tadapter.assertContext(state);\n+\t\tthis.#adapter = adapter;\n+\t\tthis.#state = structuredClone(state);\n+\t}\n+\tget graph() {\n+\t\tthis.#assertLive();\n+\t\treturn this.#adapter.graph;\n+\t}\n+\tget set(): ReadonlySet<string> {\n+\t\tthis.#assertLive();\n+\t\tconst has = (id: string) =>\n+\t\t\tthis.graph.has(id) &&\n+\t\t\t(this.#adapter.members.get(this.#state.membership, this.graph.atom(id).seq)?.present ?? false);\n+\t\tconst assertLive = this.#assertLive;\n+\t\treturn new (class extends StableSet<string> {\n+\t\t\treadonly retainedBytes = 64;\n+\t\t\thas(id: string): boolean {\n+\t\t\t\tassertLive();\n+\t\t\t\treturn has(id);\n+\t\t\t}\n+\t\t\tvalues(): SetIterator<string> {\n+\t\t\t\tassertLive();\n+\t\t\t\tthrow Error(\"unsupported projected membership enumeration\");\n+\t\t\t}\n+\t\t})();\n+\t}\n+\tpaths(): string[] {\n+\t\tthis.#assertLive();\n+\t\treturn this.knownPaths().filter((path) => this.hasFile(path));\n+\t}\n+\tfiles(): Record<string, string> {\n+\t\tthis.#assertLive();\n+\t\treturn Object.fromEntries(\n+\t\t\tthis.paths()\n+\t\t\t\t.filter((path) => this.attrs(path).blob === null)\n+\t\t\t\t.map((path) => [path, this.text(path)]),\n+\t\t);\n+\t}\n+\tblobs(): Record<string, string> {\n+\t\tthis.#assertLive();\n+\t\tconst result: Record<string, string> = {};\n+\t\tfor (const path of this.paths()) {\n+\t\t\tconst blob = this.attrs(path).blob;\n+\t\t\tif (blob !== null) result[path] = blob;\n+\t\t}\n+\t\treturn result;\n+\t}\n+\tlineNumber(path: string, line: string): number {\n+\t\tthis.#assertLive();\n+\t\treturn this.lines(path).findIndex((item) => item.id === line);\n+\t}\n+\tsameText(path: string, other: ReadView): boolean {\n+\t\tthis.#assertLive();\n+\t\tconst a = this.lines(path),\n+\t\t\tb = other.lines(path);\n+\t\treturn a.length === b.length && a.every((line, index) => line.text === b[index]!.text);\n+\t}\n+\tvisibleNeighbours(_path: string, _line: string): string[] {\n+\t\tthis.#assertLive();\n+\t\tthrow Error(\"unsupported projected visibleNeighbours\");\n+\t}\n+\tweight(): number {\n+\t\tthis.#assertLive();\n+\t\tthrow Error(\"transaction projections cannot enter historical View cache\");\n+\t}\n+\n+\tattrs(path: string): FileAttrs {\n+\t\tthis.#assertLive();\n+\t\treturn this.#adapter.attrs(this.#state, path);\n+\t}\n+\tknownPaths(): string[] {\n+\t\tthis.#assertLive();\n+\t\treturn this.#adapter.knownPaths(this.#state);\n+\t}\n+\thasMoves(): boolean {\n+\t\tthis.#assertLive();\n+\t\tfor (const id of this.graph.movers()) if (this.set.has(id)) return true;\n+\t\treturn false;\n+\t}\n+\t*visibleLines(path: string): IterableIterator<VisibleLine> {\n+\t\tthis.#assertLive();\n+\t\tconst graph = this.#adapter.graph;\n+\t\tconst iterator = this.#adapter.lineIds(this.#state, path);\n+\t\twhile (true) {\n+\t\t\tthis.#assertLive();\n+\t\t\tconst next = iterator.next();\n+\t\t\tthis.#assertLive();\n+\t\t\tif (next.done) return;\n+\t\t\tconst id = next.value;\n+\t\t\tconst n = graph.lineN(id);\n+\t\t\tyield { id, text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };\n+\t\t}\n+\t}\n+\tlines(path: string): readonly VisibleLine[] {\n+\t\tthis.#assertLive();\n+\t\treturn [...this.visibleLines(path)];\n+\t}\n+\tsequence(path: string): readonly SeqLine[] {\n+\t\tthis.#assertLive();\n+\t\tconst adapter = this.#adapter,\n+\t\t\tstate = this.#state,\n+\t\t\tgraph = adapter.graph;\n+\t\tconst key = adapter.fileKey(path);\n+\t\tconst file = key === undefined ? undefined : adapter.markers.get(state.locator, key);\n+\t\tif (!file) return [];\n+\t\tconst result: SeqLine[] = [];\n+\t\tfor (const node of adapter.sequence.range(\n+\t\t\tstate.sequence,\n+\t\t\tadapter.sequence.rank(state.sequence, file.enter) + 1,\n+\t\t\tadapter.sequence.rank(state.sequence, file.exit),\n+\t\t\tfalse,\n+\t\t)) {\n+\t\t\tif (node.text.endsWith(\":end\")) continue;\n+\t\t\tconst n = graph.lineN(node.text),\n+\t\t\t\twriter = graph.writerSeqOf(n);\n+\t\t\tif (!adapter.members.get(state.membership, writer)?.present) continue;\n+\t\t\tconst deletedBy = [...graph.eachDeleterSeqOf(n)]\n+\t\t\t\t.filter((seq) => adapter.members.get(state.membership, seq)?.present)\n+\t\t\t\t.sort((a, b) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b)\n+\t\t\t\t.map((seq) => graph.idOfSeq(seq));\n+\t\t\tresult.push({\n+\t\t\t\tid: node.text,\n+\t\t\t\ttext: graph.textOf(n),\n+\t\t\t\tatom: graph.idOfSeq(writer),\n+\t\t\t\tdeletedBy,\n+\t\t\t\tvisible: deletedBy.length === 0,\n+\t\t\t});\n+\t\t}\n+\t\treturn result;\n+\t}\n+\tsequenceIndex(path: string, line: string): number {\n+\t\tthis.#assertLive();\n+\t\treturn this.sequence(path).findIndex((item) => item.id === line);\n+\t}\n+\tparentOf(line: string): string {\n+\t\tthis.#assertLive();\n+\t\tconst adapter = this.#adapter,\n+\t\t\tstate = this.#state;\n+\t\tconst marker = adapter.markers.get(state.locator, adapter.graph.lineN(line) + 1);\n+\t\tif (marker?.kind !== \"line\") throw Error(\"missing projected line\");\n+\t\tif (marker.parentKey > 0 && marker.parentKey < 0x80000000) return adapter.graph.lineIdOf(marker.parentKey - 1);\n+\t\tconst parent = adapter.markers.get(state.locator, marker.parentKey);\n+\t\tif (parent?.kind !== \"file\") throw Error(\"missing projected file parent\");\n+\t\tconst text = adapter.sequence.get(state.sequence.map, parent.enter).text;\n+\t\tif (!text.startsWith(\"root:\")) throw Error(\"invalid projected file parent\");\n+\t\treturn startNode(text.slice(5));\n+\t}\n+\tfileOf(line: string): string {\n+\t\tthis.#assertLive();\n+\t\tif (line.startsWith(\"^\")) return line.slice(1);\n+\t\tconst marker = this.#adapter.markers.get(this.#state.locator, this.graph.lineN(line) + 1);\n+\t\tif (marker?.kind !== \"line\") throw Error(\"missing projected line\");\n+\t\treturn this.#adapter.sequence.fileAt(this.#state.sequence, marker.enter);\n+\t}\n+\ttext(path: string): string {\n+\t\tthis.#assertLive();\n+\t\treturn joinLines([...this.visibleLines(path)].map((line) => line.text));\n+\t}\n+\thasFile(path: string): boolean {\n+\t\tthis.#assertLive();\n+\t\tconst attrs = this.attrs(path);\n+\t\treturn (\n+\t\t\tattrs.exists ||\n+\t\t\tattrs.link !== null ||\n+\t\t\tattrs.blob !== null ||\n+\t\t\t!this.#adapter.lineIds(this.#state, path).next().done\n+\t\t);\n+\t}\n+}"},{"path":"src/engine/experimental/projection-records.ts","added":79,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/experimental/projection-records.ts\n@@ -0,0 +1,79 @@\n+/** Persisted records for the internal projection experiment; not a production format. */\n+export type ProjectionPage = number | null;\n+export interface FileMarker {\n+\treadonly contributions: number;\n+\treadonly kind: \"file\";\n+\treadonly enter: number;\n+\treadonly exit: number;\n+}\n+export interface LineMarker {\n+\treadonly kind: \"line\";\n+\treadonly enter: number;\n+\treadonly exit: number;\n+\treadonly parentKey: number;\n+\treadonly key: string;\n+}\n+export type ProjectionMarker = FileMarker | LineMarker;\n+export interface ProjectionMembership {\n+\treadonly present: boolean;\n+\treadonly dependents: number;\n+}\n+export interface ProjectionChildRoot {\n+\treadonly root: ProjectionPage;\n+}\n+export type ProjectionAttributeName = \"exists\" | \"exec\" | \"link\" | \"blob\";\n+export type ProjectionAttributes = Partial<Record<ProjectionAttributeName, ProjectionPage>>;\n+export interface ProjectionAttributeValue {\n+\treadonly value: string | null;\n+}\n+const safe = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;\n+const record = (value: unknown): value is Record<string, unknown> =>\n+\tvalue !== null && typeof value === \"object\" && !Array.isArray(value);\n+const markerId = (value: unknown): value is number => safe(value) && value < 2 ** 32;\n+const page = (value: unknown): value is ProjectionPage => value === null || safe(value);\n+export function projectionMarker(value: unknown): ProjectionMarker {\n+\tif (!record(value) || !markerId(value.enter) || !markerId(value.exit) || value.enter === value.exit)\n+\t\tthrow Error(\"invalid projection marker endpoints\");\n+\tif (value.kind === \"file\" && Object.keys(value).length === 4 && safe(value.contributions))\n+\t\treturn { kind: \"file\", enter: value.enter, exit: value.exit, contributions: value.contributions };\n+\tif (\n+\t\tvalue.kind !== \"line\" ||\n+\t\tObject.keys(value).length !== 5 ||\n+\t\t!markerId(value.parentKey) ||\n+\t\ttypeof value.key !== \"string\" ||\n+\t\t!/^[0-9a-f]{57}$/.test(value.key)\n+\t)\n+\t\tthrow Error(\"invalid projection line marker\");\n+\treturn { kind: \"line\", enter: value.enter, exit: value.exit, parentKey: value.parentKey, key: value.key };\n+}\n+export function projectionMembership(value: unknown): ProjectionMembership {\n+\tif (\n+\t\t!record(value) ||\n+\t\tObject.keys(value).length !== 2 ||\n+\t\ttypeof value.present !== \"boolean\" ||\n+\t\t!safe(value.dependents) ||\n+\t\t(!value.present && value.dependents !== 0)\n+\t)\n+\t\tthrow Error(\"invalid projection membership\");\n+\treturn { present: value.present, dependents: value.dependents };\n+}\n+export function projectionChildRoot(value: unknown): ProjectionChildRoot {\n+\tif (!record(value) || Object.keys(value).length !== 1 || !page(value.root))\n+\t\tthrow Error(\"invalid projection child root\");\n+\treturn { root: value.root };\n+}\n+export function projectionAttributes(value: unknown): ProjectionAttributes {\n+\tif (!record(value) || Object.keys(value).length > 4) throw Error(\"invalid projection attributes\");\n+\tconst out: ProjectionAttributes = {};\n+\tfor (const [name, root] of Object.entries(value)) {\n+\t\tif (![\"exists\", \"exec\", \"link\", \"blob\"].includes(name) || !page(root))\n+\t\t\tthrow Error(\"invalid projection attribute root\");\n+\t\tout[name as ProjectionAttributeName] = root;\n+\t}\n+\treturn out;\n+}\n+export function projectionAttributeValue(value: unknown): ProjectionAttributeValue {\n+\tif (!record(value) || Object.keys(value).length !== 1 || (value.value !== null && typeof value.value !== \"string\"))\n+\t\tthrow Error(\"invalid projection attribute value\");\n+\treturn { value: value.value };\n+}"},{"path":"src/engine/experimental/projection-root.ts","added":121,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/experimental/projection-root.ts\n@@ -0,0 +1,121 @@\n+import type { GraphStateStorage } from \"../state-source.ts\";\n+\n+/** Internal experiment only. No production writer selects this format. */\n+export interface ProjectionIdentity {\n+\treadonly database: string;\n+\treadonly namespace: string;\n+\treadonly sourceGeneration: number;\n+\treadonly sourceLength: number;\n+\treadonly sourceDigest: string;\n+\treadonly membership: string;\n+\treadonly registry: string;\n+\treadonly defaultFile: string;\n+}\n+export interface ProjectionRoots {\n+\treadonly sequence: number | null;\n+\treadonly sequenceRoot: number | null;\n+\treadonly sequenceNext: number;\n+\treadonly locator: number | null;\n+\treadonly children: number | null;\n+\treadonly membership: number | null;\n+\treadonly attributes: number | null;\n+}\n+export interface ProjectionHandle {\n+\treadonly format: 1;\n+\treadonly id: number;\n+\treadonly identity: ProjectionIdentity;\n+}\n+interface RootRecord extends ProjectionHandle {\n+\treadonly roots: ProjectionRoots;\n+}\n+const fields = [\n+\t\"database\",\n+\t\"namespace\",\n+\t\"sourceGeneration\",\n+\t\"sourceLength\",\n+\t\"sourceDigest\",\n+\t\"membership\",\n+\t\"registry\",\n+\t\"defaultFile\",\n+] as const;\n+const rootFields = [\n+\t\"sequence\",\n+\t\"sequenceRoot\",\n+\t\"sequenceNext\",\n+\t\"locator\",\n+\t\"children\",\n+\t\"membership\",\n+\t\"attributes\",\n+] as const;\n+const integer = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;\n+const object = (value: unknown): value is Record<string, unknown> =>\n+\tvalue !== null && typeof value === \"object\" && !Array.isArray(value);\n+function identity(value: unknown): asserts value is ProjectionIdentity {\n+\tif (!object(value) || Object.keys(value).length !== fields.length) throw Error(\"invalid projection identity\");\n+\tfor (const field of fields) {\n+\t\tconst item = value[field];\n+\t\tif (field === \"sourceGeneration\" || field === \"sourceLength\") {\n+\t\t\tif (!integer(item)) throw Error(\"invalid projection source position\");\n+\t\t} else if (typeof item !== \"string\" || item.length === 0 || item.length > 4096)\n+\t\t\tthrow Error(\"invalid projection identity field\");\n+\t}\n+\tif (!/^[a-f0-9]{64}$/.test(value.sourceDigest as string)) throw Error(\"invalid projection source digest\");\n+}\n+function roots(value: unknown): asserts value is ProjectionRoots {\n+\tif (!object(value) || Object.keys(value).length !== rootFields.length) throw Error(\"invalid projection roots\");\n+\tfor (const field of rootFields)\n+\t\tif (value[field] !== null && !integer(value[field])) throw Error(\"invalid projection page reference\");\n+\tif (\n+\t\t!integer(value.sequenceNext) ||\n+\t\tvalue.sequenceNext > 2 ** 32 ||\n+\t\t(value.sequenceRoot !== null && (!integer(value.sequenceRoot) || value.sequenceRoot >= value.sequenceNext)) ||\n+\t\t(value.sequenceRoot === null) !== (value.sequenceNext === 0) ||\n+\t\t(value.sequence === null) !== (value.sequenceRoot === null)\n+\t)\n+\t\tthrow Error(\"invalid projection sequence state\");\n+}\n+export function assertProjectionIdentity(actual: ProjectionIdentity, expected: ProjectionIdentity): void {\n+\tidentity(actual);\n+\tidentity(expected);\n+\tfor (const field of fields)\n+\t\tif (actual[field] !== expected[field]) throw Error(`projection identity mismatch: ${field}`);\n+}\n+function collection(expected: ProjectionIdentity): string {\n+\treturn `experimental-projection:${JSON.stringify([expected.database, expected.namespace])}:roots`;\n+}\n+/** Identity checks precede storage access. The host supplies trusted expected identity. */\n+export function readProjectionRoot(\n+\tstorage: GraphStateStorage,\n+\thandle: ProjectionHandle,\n+\texpected: ProjectionIdentity,\n+): ProjectionRoots {\n+\tif (!object(handle) || handle.format !== 1 || !integer(handle.id)) throw Error(\"invalid projection handle\");\n+\tassertProjectionIdentity(handle.identity, expected);\n+\tconst record = storage.read(collection(expected), String(handle.id));\n+\tif (!object(record) || record.format !== 1 || record.id !== handle.id || Object.keys(record).length !== 4)\n+\t\tthrow Error(\"invalid projection root record\");\n+\tidentity(record.identity);\n+\tassertProjectionIdentity(record.identity, expected);\n+\troots(record.roots);\n+\treturn structuredClone(record.roots);\n+}\n+/** The caller's enclosing transaction must include canonical state and its receipt. */\n+export function createProjectionRoot(\n+\tstorage: GraphStateStorage,\n+\texpected: ProjectionIdentity,\n+\tid: number,\n+\tpages: ProjectionRoots,\n+): ProjectionHandle {\n+\tidentity(expected);\n+\troots(pages);\n+\tif (!integer(id)) throw Error(\"invalid projection root id\");\n+\tconst frozenIdentity = structuredClone(expected),\n+\t\tfrozenPages = structuredClone(pages);\n+\treturn storage.transaction(() => {\n+\t\tconst name = collection(frozenIdentity);\n+\t\tif (storage.read(name, String(id)) !== undefined) throw Error(\"projection root already exists\");\n+\t\tconst record: RootRecord = { format: 1, id, identity: frozenIdentity, roots: frozenPages };\n+\t\tstorage.write(name, String(id), record);\n+\t\treturn { format: 1, id, identity: structuredClone(frozenIdentity) };\n+\t});\n+}"},{"path":"src/engine/experimental/projection-sequence.ts","added":343,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/experimental/projection-sequence.ts\n@@ -0,0 +1,343 @@\n+import type { GraphStateStorage } from \"../state-source.ts\";\n+import { ProjectionLocator } from \"./projection-locator.ts\";\n+\n+type Page = number | null;\n+interface SequenceNode {\n+\tid: number;\n+\tparent: Page;\n+\tleft: Page;\n+\tright: Page;\n+\ttext: string;\n+\tdeletions: number;\n+\theight: number;\n+\tcount: number;\n+\tvisible: number;\n+\tfileStarts: number;\n+}\n+export interface SequenceState {\n+\treadonly map: Page;\n+\treadonly root: Page;\n+\treadonly next: number;\n+}\n+export type SequenceOperation =\n+\t| { kind: \"insert\"; rank: number; text: string }\n+\t| { kind: \"visibility\"; id: number; delta: number }\n+\t| { kind: \"move\"; from: number; length: number; to: number };\n+const safe = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;\n+function decode(value: unknown): SequenceNode {\n+\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw Error(\"invalid sequence node\");\n+\tconst row = value as Record<string, unknown>;\n+\tif (Object.keys(row).length !== 10 || !safe(row.id) || row.id >= 2 ** 32 || typeof row.text !== \"string\")\n+\t\tthrow Error(\"invalid sequence node fields\");\n+\tfor (const name of [\"parent\", \"left\", \"right\"])\n+\t\tif (row[name] !== null && (!safe(row[name]) || Number(row[name]) >= 2 ** 32 || row[name] === row.id))\n+\t\t\tthrow Error(\"invalid sequence edge\");\n+\tfor (const name of [\"deletions\", \"height\", \"count\", \"visible\", \"fileStarts\"])\n+\t\tif (!safe(row[name])) throw Error(\"invalid sequence aggregate\");\n+\tif (\n+\t\tNumber(row.height) < 1 ||\n+\t\tNumber(row.height) > 64 ||\n+\t\tNumber(row.count) < 1 ||\n+\t\tNumber(row.visible) > Number(row.count) ||\n+\t\tNumber(row.fileStarts) > Number(row.count)\n+\t)\n+\t\tthrow Error(\"invalid sequence aggregate bounds\");\n+\treturn row as unknown as SequenceNode;\n+}\n+export class ProjectionSequence {\n+\treadonly storage: GraphStateStorage;\n+\treadonly #locator: ProjectionLocator<SequenceNode>;\n+\tconstructor(storage: GraphStateStorage, namespace: string) {\n+\t\tthis.storage = storage;\n+\t\tthis.#locator = new ProjectionLocator(storage, namespace, decode);\n+\t}\n+\tempty(): SequenceState {\n+\t\treturn { map: null, root: null, next: 0 };\n+\t}\n+\tget(map: Page, id: number): SequenceNode {\n+\t\tconst node = this.#locator.get(map, id);\n+\t\tif (!node || node.id !== id) throw Error(\"missing sequence node\");\n+\t\tconst child = (key: Page): SequenceNode | undefined => {\n+\t\t\tif (key === null) return undefined;\n+\t\t\tconst value = this.#locator.get(map, key);\n+\t\t\tif (!value || value.id !== key || value.parent !== id) throw Error(\"invalid sequence child identity\");\n+\t\t\treturn value;\n+\t\t};\n+\t\tconst left = child(node.left),\n+\t\t\tright = child(node.right);\n+\t\tif (\n+\t\t\tnode.height !== 1 + Math.max(left?.height ?? 0, right?.height ?? 0) ||\n+\t\t\tMath.abs((left?.height ?? 0) - (right?.height ?? 0)) > 1 ||\n+\t\t\tnode.count !== 1 + (left?.count ?? 0) + (right?.count ?? 0) ||\n+\t\t\tnode.visible !== (node.deletions === 0 ? 1 : 0) + (left?.visible ?? 0) + (right?.visible ?? 0) ||\n+\t\t\tnode.fileStarts !== (node.text.startsWith(\"root:\") ? 1 : 0) + (left?.fileStarts ?? 0) + (right?.fileStarts ?? 0)\n+\t\t)\n+\t\t\tthrow Error(\"inconsistent sequence aggregate\");\n+\t\treturn node;\n+\t}\n+\t#state(state: SequenceState): void {\n+\t\tif (\n+\t\t\t!state ||\n+\t\t\t!safe(state.next) ||\n+\t\t\tstate.next > 2 ** 32 ||\n+\t\t\t(state.map !== null && !safe(state.map)) ||\n+\t\t\t(state.root !== null && (!safe(state.root) || state.root >= state.next)) ||\n+\t\t\t(state.root === null) !== (state.next === 0) ||\n+\t\t\t(state.map === null) !== (state.root === null)\n+\t\t)\n+\t\t\tthrow Error(\"invalid sequence state\");\n+\t\tif (state.root !== null && this.get(state.map, state.root).parent !== null)\n+\t\t\tthrow Error(\"invalid sequence root parent\");\n+\t}\n+\tset(map: Page, id: number, node: SequenceNode): number {\n+\t\tif (node.id !== id) throw Error(\"sequence node identity mismatch\");\n+\t\treturn this.#locator.set(map, id, node);\n+\t}\n+\trank(state: SequenceState, id: number): number {\n+\t\tthis.#state(state);\n+\t\tlet node = this.get(state.map, id);\n+\t\tif (!node) throw Error(\"unknown marker\");\n+\t\tconst count = (id: Page): number => (id === null ? 0 : this.get(state.map, id).count);\n+\t\tlet rank = count(node.left),\n+\t\t\tsteps = 0;\n+\t\twhile (node.parent !== null) {\n+\t\t\tif (++steps > 64) throw Error(\"invalid parent chain\");\n+\t\t\tconst parent = this.get(state.map, node.parent);\n+\t\t\tif (parent.right === node.id) rank += count(parent.left) + 1;\n+\t\t\telse if (parent.left !== node.id) throw Error(\"broken parent edge\");\n+\t\t\tnode = parent;\n+\t\t}\n+\t\tif (node.id !== state.root) throw Error(\"wrong root\");\n+\t\treturn rank;\n+\t}\n+\t/** Nearest file start before a marker, using subtree counts instead of line ancestry. */\n+\tfileAt(state: SequenceState, id: number): string {\n+\t\tconst target = this.rank(state, id);\n+\t\tconst seek = (id: Page, offset: number, depth: number): string | undefined => {\n+\t\t\tif (id === null || offset > target) return undefined;\n+\t\t\tif (depth > 64) throw Error(\"invalid file lookup depth\");\n+\t\t\tconst node = this.get(state.map, id);\n+\t\t\tif (!node.fileStarts) return undefined;\n+\t\t\tconst leftCount = node.left === null ? 0 : this.get(state.map, node.left).count;\n+\t\t\tconst at = offset + leftCount;\n+\t\t\tif (at <= target) {\n+\t\t\t\tconst right = seek(node.right, at + 1, depth + 1);\n+\t\t\t\tif (right !== undefined) return right;\n+\t\t\t\tif (node.text.startsWith(\"root:\")) return node.text.slice(5);\n+\t\t\t}\n+\t\t\treturn seek(node.left, offset, depth + 1);\n+\t\t};\n+\t\tconst file = seek(state.root, 0, 0);\n+\t\tif (file === undefined) throw Error(\"missing projected file start\");\n+\t\treturn file;\n+\t}\n+\tupdate(state: SequenceState, operation: SequenceOperation): SequenceState {\n+\t\tthis.#state(state);\n+\t\treturn this.storage.transaction(() => {\n+\t\t\tlet map = state.map;\n+\t\t\t// One operation changes an AVL path plus rotation neighbors, not history.\n+\t\t\t// Keep only those decoded records and persist each final record once.\n+\t\t\tconst changed = new Map<number, SequenceNode>();\n+\t\t\tconst get = (id: number): SequenceNode => changed.get(id) ?? this.get(map, id);\n+\t\t\tconst put = (node: SequenceNode): number => {\n+\t\t\t\tchanged.set(node.id, node);\n+\t\t\t\treturn node.id;\n+\t\t\t};\n+\t\t\tconst height = (id: Page): number => (id === null ? 0 : get(id).height);\n+\t\t\tconst count = (id: Page): number => (id === null ? 0 : get(id).count);\n+\t\t\tconst visible = (id: Page): number => (id === null ? 0 : get(id).visible);\n+\t\t\tconst fileStarts = (id: Page): number => (id === null ? 0 : get(id).fileStarts);\n+\t\t\tconst parent = (id: Page, p: Page): void => {\n+\t\t\t\tif (id !== null) {\n+\t\t\t\t\tconst node = get(id);\n+\t\t\t\t\tif (node.parent !== p) put({ ...node, parent: p });\n+\t\t\t\t}\n+\t\t\t};\n+\t\t\tconst save = (node: SequenceNode): number => {\n+\t\t\t\tparent(node.left, node.id);\n+\t\t\t\tparent(node.right, node.id);\n+\t\t\t\treturn put({\n+\t\t\t\t\t...node,\n+\t\t\t\t\theight: 1 + Math.max(height(node.left), height(node.right)),\n+\t\t\t\t\tcount: 1 + count(node.left) + count(node.right),\n+\t\t\t\t\tvisible: (node.deletions === 0 ? 1 : 0) + visible(node.left) + visible(node.right),\n+\t\t\t\t\tfileStarts: (node.text.startsWith(\"root:\") ? 1 : 0) + fileStarts(node.left) + fileStarts(node.right),\n+\t\t\t\t});\n+\t\t\t};\n+\t\t\tconst rotateLeft = (id: number): number => {\n+\t\t\t\tconst a = get(id),\n+\t\t\t\t\tb = get(a.right!);\n+\t\t\t\tsave({ ...a, right: b.left, parent: b.id });\n+\t\t\t\treturn save({ ...b, left: a.id, parent: a.parent });\n+\t\t\t};\n+\t\t\tconst rotateRight = (id: number): number => {\n+\t\t\t\tconst a = get(id),\n+\t\t\t\t\tb = get(a.left!);\n+\t\t\t\tsave({ ...a, left: b.right, parent: b.id });\n+\t\t\t\treturn save({ ...b, right: a.id, parent: a.parent });\n+\t\t\t};\n+\t\t\tconst balance = (id: number): number => {\n+\t\t\t\tconst node = get(id);\n+\t\t\t\tif (height(node.left) - height(node.right) > 1) {\n+\t\t\t\t\tconst left = get(node.left!);\n+\t\t\t\t\tif (height(left.left) < height(left.right)) save({ ...node, left: rotateLeft(left.id) });\n+\t\t\t\t\treturn rotateRight(id);\n+\t\t\t\t}\n+\t\t\t\tif (height(node.right) - height(node.left) > 1) {\n+\t\t\t\t\tconst right = get(node.right!);\n+\t\t\t\t\tif (height(right.right) < height(right.left)) save({ ...node, right: rotateRight(right.id) });\n+\t\t\t\t\treturn rotateLeft(id);\n+\t\t\t\t}\n+\t\t\t\treturn id;\n+\t\t\t};\n+\t\t\tlet root = state.root,\n+\t\t\t\tnext = state.next;\n+\t\t\tif (operation.kind === \"insert\") {\n+\t\t\t\tconst { rank, text } = operation;\n+\t\t\t\tif (!Number.isInteger(rank) || rank < 0 || rank > count(root) || next >= 2 ** 32) throw Error(\"invalid insert\");\n+\t\t\t\tconst added = next++;\n+\t\t\t\tconst insert = (id: Page, at: number, p: Page): number => {\n+\t\t\t\t\tif (id === null)\n+\t\t\t\t\t\treturn put({\n+\t\t\t\t\t\t\tid: added,\n+\t\t\t\t\t\t\tparent: p,\n+\t\t\t\t\t\t\tleft: null,\n+\t\t\t\t\t\t\tright: null,\n+\t\t\t\t\t\t\ttext,\n+\t\t\t\t\t\t\tdeletions: 0,\n+\t\t\t\t\t\t\theight: 1,\n+\t\t\t\t\t\t\tcount: 1,\n+\t\t\t\t\t\t\tvisible: 1,\n+\t\t\t\t\t\t\tfileStarts: text.startsWith(\"root:\") ? 1 : 0,\n+\t\t\t\t\t\t});\n+\t\t\t\t\tconst node = get(id),\n+\t\t\t\t\t\tleftCount = count(node.left);\n+\t\t\t\t\tif (at <= leftCount) save({ ...node, left: insert(node.left, at, id) });\n+\t\t\t\t\telse save({ ...node, right: insert(node.right, at - leftCount - 1, id) });\n+\t\t\t\t\treturn balance(id);\n+\t\t\t\t};\n+\t\t\t\troot = insert(root, rank, null);\n+\t\t\t\tparent(root, null);\n+\t\t\t} else if (operation.kind === \"move\") {\n+\t\t\t\tconst { from, length, to } = operation;\n+\t\t\t\tconst total = count(root);\n+\t\t\t\tif (\n+\t\t\t\t\t![from, length, to].every(Number.isSafeInteger) ||\n+\t\t\t\t\tfrom < 0 ||\n+\t\t\t\t\tlength < 0 ||\n+\t\t\t\t\tfrom + length > total ||\n+\t\t\t\t\tto < 0 ||\n+\t\t\t\t\tto > total - length\n+\t\t\t\t)\n+\t\t\t\t\tthrow Error(\"invalid move range\");\n+\t\t\t\t// Join two AVL trees around one existing stable marker.\n+\t\t\t\tconst join = (left: Page, pivot: number, right: Page): number => {\n+\t\t\t\t\tif (height(left) > height(right) + 1) {\n+\t\t\t\t\t\tconst node = get(left!);\n+\t\t\t\t\t\tsave({ ...node, right: join(node.right, pivot, right) });\n+\t\t\t\t\t\tconst result = balance(left!);\n+\t\t\t\t\t\tparent(result, null);\n+\t\t\t\t\t\treturn result;\n+\t\t\t\t\t}\n+\t\t\t\t\tif (height(right) > height(left) + 1) {\n+\t\t\t\t\t\tconst node = get(right!);\n+\t\t\t\t\t\tsave({ ...node, left: join(left, pivot, node.left) });\n+\t\t\t\t\t\tconst result = balance(right!);\n+\t\t\t\t\t\tparent(result, null);\n+\t\t\t\t\t\treturn result;\n+\t\t\t\t\t}\n+\t\t\t\t\treturn save({ ...get(pivot), left, right, parent: null });\n+\t\t\t\t};\n+\t\t\t\tconst split = (id: Page, at: number): [Page, Page] => {\n+\t\t\t\t\tif (id === null) return [null, null];\n+\t\t\t\t\tconst node = get(id),\n+\t\t\t\t\t\tsize = count(node.left);\n+\t\t\t\t\tif (at <= size) {\n+\t\t\t\t\t\tconst [left, middle] = split(node.left, at);\n+\t\t\t\t\t\tconst right = join(middle, id, node.right);\n+\t\t\t\t\t\tparent(left, null);\n+\t\t\t\t\t\tparent(right, null);\n+\t\t\t\t\t\treturn [left, right];\n+\t\t\t\t\t}\n+\t\t\t\t\tconst [middle, right] = split(node.right, at - size - 1);\n+\t\t\t\t\tconst left = join(node.left, id, middle);\n+\t\t\t\t\tparent(left, null);\n+\t\t\t\t\tparent(right, null);\n+\t\t\t\t\treturn [left, right];\n+\t\t\t\t};\n+\t\t\t\tconst merge = (left: Page, right: Page): Page => {\n+\t\t\t\t\tif (left === null) {\n+\t\t\t\t\t\tparent(right, null);\n+\t\t\t\t\t\treturn right;\n+\t\t\t\t\t}\n+\t\t\t\t\tif (right === null) {\n+\t\t\t\t\t\tparent(left, null);\n+\t\t\t\t\t\treturn left;\n+\t\t\t\t\t}\n+\t\t\t\t\tconst [pivot, rest] = split(right, 1);\n+\t\t\t\t\treturn join(left, pivot!, rest);\n+\t\t\t\t};\n+\t\t\t\tif (length && from !== to) {\n+\t\t\t\t\tconst [left, tail] = split(root, from);\n+\t\t\t\t\tconst [moved, right] = split(tail, length);\n+\t\t\t\t\tconst remaining = merge(left, right);\n+\t\t\t\t\tconst [before, after] = split(remaining, to);\n+\t\t\t\t\troot = merge(merge(before, moved), after);\n+\t\t\t\t\tparent(root, null);\n+\t\t\t\t}\n+\t\t\t} else if (operation.kind === \"visibility\") {\n+\t\t\t\tlet node = get(operation.id);\n+\t\t\t\tif (\n+\t\t\t\t\t!node ||\n+\t\t\t\t\t!Number.isInteger(operation.delta) ||\n+\t\t\t\t\tMath.abs(operation.delta) !== 1 ||\n+\t\t\t\t\tnode.deletions + operation.delta < 0\n+\t\t\t\t)\n+\t\t\t\t\tthrow Error(\"invalid visibility\");\n+\t\t\t\tsave({ ...node, deletions: node.deletions + operation.delta });\n+\t\t\t\twhile (node.parent !== null) {\n+\t\t\t\t\tnode = get(node.parent);\n+\t\t\t\t\tsave(node);\n+\t\t\t\t}\n+\t\t\t} else throw Error(\"unknown operation\");\n+\t\t\tfor (const [id, node] of changed) map = this.set(map, id, node);\n+\t\t\treturn { map, root, next };\n+\t\t});\n+\t}\n+\t*range(\n+\t\tstate: SequenceState,\n+\t\tfrom: number,\n+\t\tto: number,\n+\t\tvisibleOnly = true,\n+\t): IterableIterator<{ id: number; text: string }> {\n+\t\tthis.#state(state);\n+\t\tif (!safe(from) || !safe(to) || from > to) throw Error(\"invalid sequence range\");\n+\t\tconst visit = function* (\n+\t\t\tseq: ProjectionSequence,\n+\t\t\tid: Page,\n+\t\t\toffset: number,\n+\t\t): IterableIterator<{ id: number; text: string }> {\n+\t\t\tif (id === null) return;\n+\t\t\tconst node = seq.get(state.map, id);\n+\t\t\tif ((visibleOnly && !node.visible) || offset >= to || offset + node.count <= from) return;\n+\t\t\tconst leftCount = node.left === null ? 0 : seq.get(state.map, node.left).count;\n+\t\t\tyield* visit(seq, node.left, offset);\n+\t\t\tconst at = offset + leftCount;\n+\t\t\tif (at >= from && at < to && (!visibleOnly || node.deletions === 0)) yield { id: node.id, text: node.text };\n+\t\t\tyield* visit(seq, node.right, at + 1);\n+\t\t};\n+\t\tyield* visit(this, state.root, 0);\n+\t}\n+\t*values(state: SequenceState, visibleOnly = true): IterableIterator<{ id: number; text: string }> {\n+\t\tthis.#state(state);\n+\t\tconst visit = function* (seq: ProjectionSequence, id: Page): IterableIterator<{ id: number; text: string }> {\n+\t\t\tif (id === null) return;\n+\t\t\tconst node = seq.get(state.map, id);\n+\t\t\tif (visibleOnly && node.visible === 0) return;\n+\t\t\tyield* visit(seq, node.left);\n+\t\t\tif (!visibleOnly || node.deletions === 0) yield { id: node.id, text: node.text };\n+\t\t\tyield* visit(seq, node.right);\n+\t\t};\n+\t\tyield* visit(this, state.root);\n+\t}\n+}"},{"path":"src/engine/experimental/projection-snapshots.ts","added":82,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/experimental/projection-snapshots.ts\n@@ -0,0 +1,82 @@\n+import type { GraphStateStorage } from \"../state-source.ts\";\n+import type { ExperimentalMarkerProjection, MarkerState } from \"./projection-marker.ts\";\n+import {\n+\tassertProjectionIdentity,\n+\tcreateProjectionRoot,\n+\ttype ProjectionHandle,\n+\ttype ProjectionIdentity,\n+\treadProjectionRoot,\n+} from \"./projection-root.ts\";\n+\n+type Context = Pick<ProjectionIdentity, \"database\" | \"namespace\" | \"registry\" | \"defaultFile\">;\n+/** Internal snapshot boundary. The host supplies verified canonical and membership identities. */\n+export class ProjectionSnapshots {\n+\treadonly #storage: GraphStateStorage;\n+\treadonly #adapter: ExperimentalMarkerProjection;\n+\treadonly #context: Context;\n+\treadonly #collection: string;\n+\tconstructor(storage: GraphStateStorage, adapter: ExperimentalMarkerProjection, context: Context) {\n+\t\tthis.#storage = storage;\n+\t\tthis.#adapter = adapter;\n+\t\tthis.#context = {\n+\t\t\tdatabase: context.database,\n+\t\t\tnamespace: context.namespace,\n+\t\t\tregistry: context.registry,\n+\t\t\tdefaultFile: context.defaultFile,\n+\t\t};\n+\t\tthis.#collection = `experimental-projection:${JSON.stringify([context.database, context.namespace])}:context`;\n+\t\tif (adapter.context !== JSON.stringify([context.namespace, context.defaultFile]))\n+\t\t\tthrow Error(\"projection snapshot constructor mismatch\");\n+\t}\n+\t#expected(expected: ProjectionIdentity): void {\n+\t\tassertProjectionIdentity(expected, expected);\n+\t\tfor (const field of [\"database\", \"namespace\", \"registry\", \"defaultFile\"] as const)\n+\t\t\tif (expected[field] !== this.#context[field]) throw Error(`projection snapshot context mismatch: ${field}`);\n+\t}\n+\t#registry(create: boolean): void {\n+\t\tconst stored = this.#storage.read(this.#collection, \"binding\");\n+\t\tif (stored === undefined) {\n+\t\t\tif (!create) throw Error(\"missing projection registry binding\");\n+\t\t\tthis.#storage.write(this.#collection, \"binding\", this.#context);\n+\t\t\treturn;\n+\t\t}\n+\t\tif (!stored || typeof stored !== \"object\" || Array.isArray(stored) || Object.keys(stored).length !== 4)\n+\t\t\tthrow Error(\"invalid projection registry binding\");\n+\t\tfor (const field of [\"database\", \"namespace\", \"registry\", \"defaultFile\"] as const)\n+\t\t\tif ((stored as Record<string, unknown>)[field] !== this.#context[field])\n+\t\t\t\tthrow Error(\"projection registry binding mismatch\");\n+\t}\n+\tsave(id: number, expected: ProjectionIdentity, state: MarkerState): ProjectionHandle {\n+\t\tthis.#expected(expected);\n+\t\tthis.#adapter.assertContext(state);\n+\t\treturn this.#storage.transaction(() => {\n+\t\t\tthis.#registry(true);\n+\t\t\tif (state.sequence.root !== null) this.#adapter.sequence.rank(state.sequence, state.sequence.root);\n+\t\t\treturn createProjectionRoot(this.#storage, expected, id, {\n+\t\t\t\tsequence: state.sequence.map,\n+\t\t\t\tsequenceRoot: state.sequence.root,\n+\t\t\t\tsequenceNext: state.sequence.next,\n+\t\t\t\tlocator: state.locator,\n+\t\t\t\tchildren: state.children,\n+\t\t\t\tmembership: state.membership,\n+\t\t\t\tattributes: state.attributeFiles,\n+\t\t\t});\n+\t\t});\n+\t}\n+\tload(handle: ProjectionHandle, expected: ProjectionIdentity): MarkerState {\n+\t\tthis.#expected(expected);\n+\t\tassertProjectionIdentity(handle.identity, expected);\n+\t\tthis.#registry(false);\n+\t\tconst roots = readProjectionRoot(this.#storage, handle, expected);\n+\t\tconst state: MarkerState = {\n+\t\t\tcontext: this.#adapter.context,\n+\t\t\tsequence: { map: roots.sequence, root: roots.sequenceRoot, next: roots.sequenceNext },\n+\t\t\tlocator: roots.locator,\n+\t\t\tchildren: roots.children,\n+\t\t\tmembership: roots.membership,\n+\t\t\tattributeFiles: roots.attributes,\n+\t\t};\n+\t\tif (state.sequence.root !== null) this.#adapter.sequence.rank(state.sequence, state.sequence.root);\n+\t\treturn state;\n+\t}\n+}"},{"path":"src/engine/test/projection-locator.test.ts","added":49,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-locator.test.ts\n@@ -0,0 +1,49 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { ProjectionLocator } from \"../experimental/projection-locator.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+const decode = (value: unknown): number => {\n+\tif (!Number.isSafeInteger(value)) throw Error(\"invalid payload\");\n+\treturn value as number;\n+};\n+test(\"experimental locator preserves sparse old roots and rejects corrupt storage\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst index = new ProjectionLocator(storage, \"test\", decode),\n+\t\t\tkeys = [0, 0xffffffff, 16, 1, 0x80000000, 255, 256];\n+\t\tlet root: number | null = null;\n+\t\tconst versions: number[] = [];\n+\t\tfor (const id of keys) {\n+\t\t\troot = index.set(root, id, id);\n+\t\t\tversions.push(root);\n+\t\t}\n+\t\tfor (let i = 0; i < versions.length; i++)\n+\t\t\tfor (let j = 0; j < keys.length; j++)\n+\t\t\t\tassert.equal(index.get(versions[i]!, keys[j]!), j <= i ? keys[j] : undefined);\n+\t\tconst before = JSON.stringify(storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all());\n+\t\tstorage.failWrite = storage.writes + 3;\n+\t\tassert.throws(() => index.set(root, 42, 42), /injected/);\n+\t\tassert.equal(JSON.stringify(storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all()), before);\n+\t\tstorage.failWrite = Infinity;\n+\t\tfor (const id of [-1, 2 ** 32, 0.5, NaN]) assert.throws(() => index.get(root, id), /identity limit/);\n+\t\tconst collection = 'experimental-locator:\"test\"',\n+\t\t\tsaved = storage.read(collection, String(root));\n+\t\tfor (const corrupt of [\n+\t\t\t{ format: 2, kind: \"leaf\", prefix: \"00000000\", value: 0 },\n+\t\t\t{ format: 1, kind: \"leaf\", prefix: \"0\", value: 0 },\n+\t\t\t{ format: 1, kind: \"branch\", prefix: \"\", children: { \"0\": root, f: 0 } },\n+\t\t\t{ format: 1, kind: \"branch\", prefix: \"\", children: { \"00\": 0, f: 1 } },\n+\t\t]) {\n+\t\t\tstorage.write(collection, String(root), corrupt);\n+\t\t\tassert.throws(() => index.get(root, 0), /invalid locator/);\n+\t\t}\n+\t\tstorage.write(collection, String(root), saved);\n+\t\tassert.equal(index.get(root, 16), 16);\n+\t\tconst leaf = index.set(null, 7, 7);\n+\t\tstorage.write(collection, String(leaf), { format: 1, kind: \"leaf\", prefix: \"00000007\", value: \"bad\" });\n+\t\tassert.throws(() => index.get(leaf, 7), /invalid payload/);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/projection-marker-cycle.test.ts","added":83,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-marker-cycle.test.ts\n@@ -0,0 +1,83 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { ExperimentalMarkerProjection as MarkerProjection } from \"../experimental/projection-marker.ts\";\n+import { Graph } from \"../graph.ts\";\n+import { CachedStateStorage } from \"../state-source.ts\";\n+import { Repo, Rng } from \"./helpers.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"typed marker projection matches competing cyclic moves and removals\", () => {\n+\tconst db = new SqlState();\n+\ttry {\n+\t\tconst repo = Repo.init({ \"f.txt\": Array.from({ length: 12 }, (_, n) => `${n}\\n`).join(\"\") }),\n+\t\t\tgraph = new Graph({ storage: new CachedStateStorage(db) }),\n+\t\t\trng = new Rng(45131);\n+\t\tgraph.add(repo.graph.atom(\"a0\"));\n+\t\tconst p = new MarkerProjection(db, graph, \"f.txt\", \"typed-\" + \"cycle\");\n+\t\tlet state = p.apply(p.empty(), repo.graph.atom(\"a0\")),\n+\t\t\tchecks = 0;\n+\t\tconst atoms = [];\n+\t\tconst check = () => {\n+\t\t\tconst view = repo.view();\n+\t\t\tassert.deepEqual(\n+\t\t\t\tp.lines(state),\n+\t\t\t\tview.lines(\"f.txt\").map((x) => x.id),\n+\t\t\t);\n+\t\t\tfor (let n = 0; n < 12; n++) {\n+\t\t\t\tconst parent = view.parentOf(`a0.${n}`);\n+\t\t\t\tassert.equal(\n+\t\t\t\t\t(p.markers.get(state.locator, n + 1) as { parentKey: number }).parentKey,\n+\t\t\t\t\tparent.startsWith(\"^\") ? 0 : graph.lineN(parent) + 1,\n+\t\t\t\t);\n+\t\t\t}\n+\t\t\tchecks++;\n+\t\t};\n+\t\tfor (let j = 0; j < 24; j++) {\n+\t\t\tconst offset = rng.int(12),\n+\t\t\t\tmoves = Array.from({ length: 3 }, (_, i) => {\n+\t\t\t\t\tconst line = `a0.${(offset + i) % 12}`,\n+\t\t\t\t\t\tcandidate = `a0.${rng.int(12)}`;\n+\t\t\t\t\treturn { line, parent: candidate === line ? \"^f.txt\" : candidate };\n+\t\t\t\t});\n+\t\t\tconst atom = {\n+\t\t\t\tid: repo.graph.nextId(),\n+\t\t\t\tseq: repo.graph.size,\n+\t\t\t\tauthor: \"fixture\",\n+\t\t\t\tmessage: \"move\",\n+\t\t\t\ttime: j,\n+\t\t\t\tinserts: [],\n+\t\t\t\tdeletes: [],\n+\t\t\t\twrites: moves.flatMap((m) => [`P:${m.line}`, `G:${m.parent}`]),\n+\t\t\t\treads: [],\n+\t\t\t\tholds: [],\n+\t\t\t\tneeds: [],\n+\t\t\t\tresolves: [],\n+\t\t\t\treasons: [],\n+\t\t\t\tdeps: [\"a0\"],\n+\t\t\t\tmoves,\n+\t\t\t};\n+\t\t\trepo.graph.add(atom);\n+\t\t\trepo.shared.add(atom.id);\n+\t\t\tgraph.add(atom);\n+\t\t\tatoms.push(atom);\n+\t\t\tstate = p.apply(state, atom);\n+\t\t\tcheck();\n+\t\t}\n+\t\tfor (const atom of atoms.filter((_, i) => i % 2 === 0)) {\n+\t\t\trepo.shared.delete(atom.id);\n+\t\t\tstate = p.removeAtom(state, atom);\n+\t\t\tcheck();\n+\t\t}\n+\t\tassert.equal(\n+\t\t\tdb.db\n+\t\t\t\t.prepare(\n+\t\t\t\t\t\"SELECT count(*) AS n FROM state WHERE collection LIKE '%sequence-resolver:%' OR collection LIKE '%sequence-relocation-work:%'\",\n+\t\t\t\t)\n+\t\t\t\t.get()!.n,\n+\t\t\t0,\n+\t\t);\n+\t\tassert.equal(checks, 36);\n+\t} finally {\n+\t\tdb.db.close();\n+\t}\n+});"},{"path":"src/engine/test/projection-marker-move-failures.test.ts","added":86,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-marker-move-failures.test.ts\n@@ -0,0 +1,86 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { ExperimentalMarkerProjection as MarkerProjection } from \"../experimental/projection-marker.ts\";\n+import { Graph } from \"../graph.ts\";\n+import { CachedStateStorage } from \"../state-source.ts\";\n+import { Repo, Rng } from \"./helpers.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"typed marker move transaction rolls back each selected phase\", () => {\n+\tconst db = new SqlState();\n+\ttry {\n+\t\tconst repo = Repo.init({ \"f.txt\": \"a\\nb\\nc\\n\" }),\n+\t\t\tgraph = new Graph({ storage: new CachedStateStorage(db) });\n+\t\tgraph.add(repo.graph.atom(\"a0\"));\n+\t\tconst p = new MarkerProjection(db, graph, \"f.txt\", \"typed-\" + \"move-failures\"),\n+\t\t\tbefore = p.apply(p.empty(), repo.graph.atom(\"a0\"));\n+\t\tconst atom = repo.edit({ move: { file: \"f.txt\", start: 0, end: 1, to: \"f.txt\", at: 3 } });\n+\t\tgraph.add(atom);\n+\t\tconst originalWrite = db.write.bind(db),\n+\t\t\toriginalRemove = db.remove.bind(db),\n+\t\t\tevents: { kind: string; collection: string; key: string }[] = [];\n+\t\tdb.write = (collection, key, value) => {\n+\t\t\tevents.push({ kind: \"write\", collection, key });\n+\t\t\treturn originalWrite(collection, key, value);\n+\t\t};\n+\t\tdb.remove = (collection, key) => {\n+\t\t\tevents.push({ kind: \"remove\", collection, key });\n+\t\t\treturn originalRemove(collection, key);\n+\t\t};\n+\t\tconst sentinel = Error(\"rollback measured success\");\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\tdb.transaction(() => {\n+\t\t\t\t\tp.apply(before, atom);\n+\t\t\t\t\tthrow sentinel;\n+\t\t\t\t}),\n+\t\t\t(e) => e === sentinel,\n+\t\t);\n+\t\tdb.write = originalWrite;\n+\t\tdb.remove = originalRemove;\n+\t\tconst offsets = new Set([0, events.length - 1]);\n+\t\tfor (const prefix of [\"sequence-resolver:\", \"sequence-relocation-work:\"]) {\n+\t\t\toffsets.add(events.findIndex((e) => e.collection.includes(prefix)));\n+\t\t\toffsets.add(events.findIndex((e) => e.kind === \"remove\" && e.collection.includes(prefix)));\n+\t\t}\n+\t\tconst plan = events.findIndex((e) => e.collection.includes(\"sequence-relocation-work:\"));\n+\t\toffsets.add(events.findIndex((e, i) => i > plan && e.collection.includes(\":sequence\")));\n+\t\tconst rows = () => JSON.stringify(db.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all());\n+\t\tconst baseline = rows(),\n+\t\t\tresults = [];\n+\t\tfor (const offset of [...offsets].filter((n) => n >= 0).sort((a, b) => a - b)) {\n+\t\t\tlet cursor = 0;\n+\t\t\tconst fail = () => {\n+\t\t\t\tif (cursor++ === offset) throw Error(\"injected phase failure\");\n+\t\t\t};\n+\t\t\tdb.write = (c, k, v) => {\n+\t\t\t\tfail();\n+\t\t\t\treturn originalWrite(c, k, v);\n+\t\t\t};\n+\t\t\tdb.remove = (c, k) => {\n+\t\t\t\tfail();\n+\t\t\t\treturn originalRemove(c, k);\n+\t\t\t};\n+\t\t\tassert.throws(() => p.apply(before, atom), /injected phase failure/);\n+\t\t\tdb.write = originalWrite;\n+\t\t\tdb.remove = originalRemove;\n+\t\t\tassert.equal(rows(), baseline);\n+\t\t\tassert.deepEqual(p.lines(before), [\"a0.0\", \"a0.1\", \"a0.2\"]);\n+\t\t\tresults.push({ offset, ...events[offset] });\n+\t\t}\n+\t\tconst state = p.apply(before, atom);\n+\t\tassert.deepEqual(\n+\t\t\tp.lines(state),\n+\t\t\trepo\n+\t\t\t\t.view()\n+\t\t\t\t.lines(\"f.txt\")\n+\t\t\t\t.map((x) => x.id),\n+\t\t);\n+\t\tconst writes = db.writes;\n+\t\tassert.equal(p.apply(state, atom), state);\n+\t\tassert.equal(db.writes, writes);\n+\t\tassert.equal(results.length, 7);\n+\t} finally {\n+\t\tdb.db.close();\n+\t}\n+});"},{"path":"src/engine/test/projection-marker.test.ts","added":120,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-marker.test.ts\n@@ -0,0 +1,120 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { ExperimentalMarkerProjection as MarkerProjection } from \"../experimental/projection-marker.ts\";\n+import { Graph } from \"../graph.ts\";\n+import { CachedStateStorage } from \"../state-source.ts\";\n+import { Repo } from \"./helpers.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"typed marker projection matches mixed multi-file edits and reverse removals\", () => {\n+\tconst db = new SqlState();\n+\ttry {\n+\t\tconst repo = Repo.init({ \"f.txt\": \"a\\nb\\nc\\n\", \"g.txt\": \"x\\ny\\n\" }),\n+\t\t\tgraph = new Graph({ storage: new CachedStateStorage(db) });\n+\t\tgraph.add(repo.graph.atom(\"a0\"));\n+\t\tconst p = new MarkerProjection(db, graph, \"f.txt\", \"typed-mixed\");\n+\t\tlet state = p.apply(p.empty(), repo.graph.atom(\"a0\")),\n+\t\t\tchecks = 0;\n+\t\tconst atoms = [],\n+\t\t\troots = [];\n+\t\tconst check = () => {\n+\t\t\tconst view = repo.view();\n+\t\t\tfor (const path of [\"f.txt\", \"g.txt\"]) {\n+\t\t\t\tassert.deepEqual(\n+\t\t\t\t\tp.lines(state, path),\n+\t\t\t\t\tview.lines(path).map((x) => x.id),\n+\t\t\t\t);\n+\t\t\t\tassert.deepEqual(p.attrs(state, path), view.attrs(path));\n+\t\t\t}\n+\t\t\tchecks++;\n+\t\t};\n+\t\tfor (let i = 0; i < 36; i++) {\n+\t\t\tconst file = i % 2 ? \"f.txt\" : \"g.txt\",\n+\t\t\t\tother = i % 2 ? \"g.txt\" : \"f.txt\",\n+\t\t\t\tview = repo.view();\n+\t\t\tlet input: Parameters<Repo[\"edit\"]>[0];\n+\t\t\tif (i % 3 === 0 && view.lines(file).length) input = { move: { file, start: 0, end: 1, to: other, at: 0 } };\n+\t\t\telse if (i % 3 === 1)\n+\t\t\t\tinput = {\n+\t\t\t\t\tedits: [{ file, old: view.text(file), new: `new ${i}\\n${view.text(file)}` }],\n+\t\t\t\t\tattrs: [{ file, name: \"exec\", value: i % 2 ? \"1\" : null }],\n+\t\t\t\t};\n+\t\t\telse input = { edits: [{ file, old: view.text(file), new: `rewrite ${i}\\n` }] };\n+\t\t\tconst atom = repo.edit(input);\n+\t\t\tgraph.add(atom);\n+\t\t\tatoms.push(atom);\n+\t\t\tstate = p.apply(state, atom);\n+\t\t\tcheck();\n+\t\t\tif (i % 9 === 0) roots.push({ state, f: p.lines(state, \"f.txt\"), g: p.lines(state, \"g.txt\") });\n+\t\t}\n+\t\tfor (const atom of atoms.toReversed()) {\n+\t\t\trepo.shared.delete(atom.id);\n+\t\t\tstate = p.removeAtom(state, atom);\n+\t\t\tcheck();\n+\t\t}\n+\t\tfor (const root of roots) {\n+\t\t\tassert.deepEqual(p.lines(root.state, \"f.txt\"), root.f);\n+\t\t\tassert.deepEqual(p.lines(root.state, \"g.txt\"), root.g);\n+\t\t}\n+\t\tassert.equal(checks, 72);\n+\t} finally {\n+\t\tdb.db.close();\n+\t}\n+});\n+\n+test(\"typed marker namespaces isolate file identities and temporary metadata\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst repo = Repo.init({ \"f.txt\": \"f\\n\", \"g.txt\": \"g\\n\" });\n+\t\tconst graph = new Graph({ storage: new CachedStateStorage(storage) });\n+\t\tgraph.add(repo.graph.atom(\"a0\"));\n+\t\tconst alpha = new MarkerProjection(storage, graph, \"f.txt\", \"alpha\");\n+\t\tconst beta = new MarkerProjection(storage, graph, \"g.txt\", \"beta\");\n+\t\tconst a = alpha.apply(alpha.empty(), repo.graph.atom(\"a0\"));\n+\t\tconst b = beta.apply(beta.empty(), repo.graph.atom(\"a0\"));\n+\t\tconst wrongFile = new MarkerProjection(storage, graph, \"g.txt\", \"alpha\");\n+\t\tfor (const other of [beta, wrongFile]) {\n+\t\t\tconst reads = storage.reads,\n+\t\t\t\twrites = storage.writes;\n+\t\t\tassert.throws(() => other.lines(a, \"f.txt\"), /constructor context mismatch/);\n+\t\t\tassert.throws(() => other.apply(a, repo.graph.atom(\"a0\")), /constructor context mismatch/);\n+\t\t\tassert.equal(storage.reads, reads);\n+\t\t\tassert.equal(storage.writes, writes);\n+\t\t}\n+\n+\t\tfor (const path of [\"f.txt\", \"g.txt\"]) {\n+\t\t\tassert.deepEqual(\n+\t\t\t\talpha.lines(a, path),\n+\t\t\t\trepo\n+\t\t\t\t\t.view()\n+\t\t\t\t\t.lines(path)\n+\t\t\t\t\t.map((x) => x.id),\n+\t\t\t);\n+\t\t\tassert.deepEqual(\n+\t\t\t\tbeta.lines(b, path),\n+\t\t\t\trepo\n+\t\t\t\t\t.view()\n+\t\t\t\t\t.lines(path)\n+\t\t\t\t\t.map((x) => x.id),\n+\t\t\t);\n+\t\t}\n+\t\talpha.storage.write(\"sequence-meta\", \"work-scope\", 91);\n+\t\tassert.equal(beta.storage.read(\"sequence-meta\", \"work-scope\"), undefined);\n+\t\tconst rows = () => JSON.stringify(storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all());\n+\t\tconst before = rows();\n+\t\tassert.throws(\n+\t\t\t() => alpha.relocateBatch(a, [{ n: -1, parentKey: 0, key: \"0\".repeat(57) }]),\n+\t\t\t/invalid relocation plan/,\n+\t\t);\n+\t\tassert.equal(rows(), before);\n+\t\tassert.deepEqual(\n+\t\t\tbeta.lines(b, \"f.txt\"),\n+\t\t\trepo\n+\t\t\t\t.view()\n+\t\t\t\t.lines(\"f.txt\")\n+\t\t\t\t.map((x) => x.id),\n+\t\t);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/projection-overlay-storage.test.ts","added":51,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-overlay-storage.test.ts\n@@ -0,0 +1,51 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { ProjectionOverlayStorage } from \"../experimental/projection-overlay-storage.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"temporary projection pages shadow committed pages and cleanup preserves durable writes\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tstorage.write(\"pages\", \"one\", { n: 1 });\n+\t\tstorage.write(\"pages\", \"two\", { n: 2 });\n+\t\tconst overlay = new ProjectionOverlayStorage(storage, \"read-a\");\n+\t\tstorage.transaction(() => {\n+\t\t\toverlay.write(\"pages\", \"one\", { n: 10 });\n+\t\t\toverlay.remove(\"pages\", \"two\");\n+\t\t\toverlay.write(\"pages\", \"three\", { n: 3 });\n+\t\t\tassert.deepEqual(overlay.read(\"pages\", \"one\"), { n: 10 });\n+\t\t\tassert.equal(overlay.read(\"pages\", \"two\"), undefined);\n+\t\t\tassert.deepEqual([...overlay.entries(\"pages\")].sort(), [\n+\t\t\t\t[\"one\", { n: 10 }],\n+\t\t\t\t[\"three\", { n: 3 }],\n+\t\t\t]);\n+\t\t\tassert.throws(() => new ProjectionOverlayStorage(storage, \"read-a\"), /occupied/);\n+\t\t\tassert.throws(\n+\t\t\t\t() =>\n+\t\t\t\t\toverlay.transaction(() => {\n+\t\t\t\t\t\toverlay.write(\"pages\", \"one\", 99);\n+\t\t\t\t\t\tthrow Error(\"fail\");\n+\t\t\t\t\t}),\n+\t\t\t\t/fail/,\n+\t\t\t);\n+\t\t\tassert.deepEqual(overlay.read(\"pages\", \"one\"), { n: 10 });\n+\t\t\tstorage.write(\"roots\", \"committed\", { root: 7 });\n+\t\t\tconst iterator = overlay.entries(\"pages\")[Symbol.iterator]();\n+\t\t\titerator.next();\n+\t\t\toverlay.close();\n+\t\t\tassert.throws(() => iterator.next(), /closed/);\n+\t\t});\n+\t\tassert.deepEqual(\n+\t\t\t[...storage.entries(\"pages\")],\n+\t\t\t[\n+\t\t\t\t[\"one\", { n: 1 }],\n+\t\t\t\t[\"two\", { n: 2 }],\n+\t\t\t],\n+\t\t);\n+\t\tassert.deepEqual(storage.read(\"roots\", \"committed\"), { root: 7 });\n+\t\tassert.deepEqual([...storage.entries(\"projection:temporary:read-a\")], []);\n+\t\tassert.throws(() => overlay.read(\"pages\", \"one\"), /closed/);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/projection-priority.test.ts","added":53,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-priority.test.ts\n@@ -0,0 +1,53 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { ProjectionPriority } from \"../experimental/projection-priority.ts\";\n+import { orderedChildKey } from \"../ordered-index.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+const decode = (value: unknown): number => {\n+\tif (!Number.isSafeInteger(value)) throw Error(\"invalid payload\");\n+\treturn value as number;\n+};\n+test(\"experimental priority retains old roots, removes winners and rejects corrupt pages\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst index = new ProjectionPriority(storage, \"test\", decode),\n+\t\t\toracle: { key: string; value: number }[] = [];\n+\t\tlet root: number | null = null;\n+\t\tfor (let n = 0; n < 96; n++) {\n+\t\t\tconst key = orderedChildKey({ n, replaces: n % 2, lamport: (n * 71) % 97, seq: n, k: 0 });\n+\t\t\tconst expected = oracle.filter((entry) => entry.key < key).at(-1)?.value;\n+\t\t\tassert.equal(index.before(root, key), expected);\n+\t\t\tconst old: number | null = root;\n+\t\t\troot = index.insert(root, key, n);\n+\t\t\tassert.equal(index.before(old, key), expected);\n+\t\t\toracle.push({ key, value: n });\n+\t\t\toracle.sort((a, b) => a.key.localeCompare(b.key));\n+\t\t}\n+\t\tconst full = root;\n+\t\tconst greatest = oracle.pop()!;\n+\t\troot = index.remove(root, greatest.key);\n+\t\tassert.equal(index.before(root, \"f\".repeat(57)), oracle.at(-1)!.value);\n+\t\tassert.equal(index.before(full, \"f\".repeat(57)), greatest.value);\n+\t\tconst rows = () => JSON.stringify(storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all());\n+\t\tconst before = rows();\n+\t\tstorage.failWrite = storage.writes + 3;\n+\t\tassert.throws(() => index.insert(root, \"e\".repeat(57), 100), /injected/);\n+\t\tassert.equal(rows(), before);\n+\t\tstorage.failWrite = Infinity;\n+\t\tconst collection = 'experimental-priority:\"test\"',\n+\t\t\tsaved = storage.read(collection, String(root));\n+\t\tfor (const corrupt of [\n+\t\t\t{ format: 1, kind: \"branch\", depth: 1, children: { \"0\": 0 } },\n+\t\t\t{ format: 1, kind: \"branch\", depth: 0, children: { f: root } },\n+\t\t\t{ format: 1, kind: \"branch\", depth: 0, children: {} },\n+\t\t]) {\n+\t\t\tstorage.write(collection, String(root), corrupt);\n+\t\t\tassert.throws(() => index.before(root, \"f\".repeat(57)), /invalid priority/);\n+\t\t}\n+\t\tstorage.write(collection, String(root), saved);\n+\t\tassert.equal(index.before(root, \"f\".repeat(57)), oracle.at(-1)!.value);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/projection-read-scope.test.ts","added":56,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-read-scope.test.ts\n@@ -0,0 +1,56 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { ExperimentalMarkerProjection } from \"../experimental/projection-marker.ts\";\n+import { ProjectionReadScope } from \"../experimental/projection-read-scope.ts\";\n+import { ProjectionReader } from \"../experimental/projection-reader.ts\";\n+import { Graph } from \"../graph.ts\";\n+import { Repo } from \"./helpers.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+for (const end of [\"commit\", \"rollback\", \"source\", \"nested\", \"graph\"] as const) {\n+\ttest(`projected reads reject stale methods, membership and iterator resume after ${end}`, (t) => {\n+\t\tconst storage = new SqlState();\n+\t\ttry {\n+\t\t\tconst repo = Repo.init({ \"f.txt\": \"one\\ntwo\\n\" });\n+\t\t\tconst graph = new Graph();\n+\t\t\tgraph.add(repo.graph.atom(\"a0\"));\n+\t\t\tconst adapter = new ExperimentalMarkerProjection(storage, graph, \"f.txt\", \"scope-test\");\n+\t\t\tconst state = adapter.apply(adapter.empty(), graph.atom(\"a0\"));\n+\t\t\tlet source = {};\n+\t\t\tconst scope = new ProjectionReadScope(graph, () => source);\n+\t\t\tassert.throws(() => scope.guard(new Graph()), /mismatch/);\n+\t\t\tconst reader = new ProjectionReader(adapter, state, scope.guard(graph));\n+\t\t\tconst membership = reader.set;\n+\t\t\tconst iterator = reader.visibleLines(\"f.txt\");\n+\t\t\tassert.equal(iterator.next().value?.text, \"one\");\n+\t\t\tif (end === \"source\") source = {};\n+\t\t\telse if (end === \"nested\") {\n+\t\t\t\tconst child = scope.nested();\n+\t\t\t\tassert.throws(() => reader.text(\"f.txt\"), /stale/);\n+\t\t\t\tconst childGuard = child.guard(graph);\n+\t\t\t\tchildGuard();\n+\t\t\t\tchild.close();\n+\t\t\t\tassert.throws(childGuard, /expired/);\n+\t\t\t\tscope.guard(graph)();\n+\t\t\t} else if (end === \"graph\") {\n+\t\t\t\trepo.edit({ edits: [{ file: \"f.txt\", old: \"one\\ntwo\\n\", new: \"changed\\n\" }] });\n+\t\t\t\tgraph.add(repo.graph.atom(\"a1\"));\n+\t\t\t} else scope.close();\n+\t\t\tlet touched = false;\n+\t\t\tconst refuseAccess = () => {\n+\t\t\t\ttouched = true;\n+\t\t\t\tthrow Error(\"expired reader touched data\");\n+\t\t\t};\n+\t\t\tt.mock.method(storage, \"read\", refuseAccess);\n+\t\t\tt.mock.method(storage, \"entries\", refuseAccess);\n+\t\t\tt.mock.method(graph, \"lineN\", refuseAccess);\n+\t\t\tt.mock.method(graph, \"textOf\", refuseAccess);\n+\t\t\tassert.throws(() => reader.text(\"f.txt\"), /expired|stale/);\n+\t\t\tassert.throws(() => membership.has(\"a0\"), /expired|stale/);\n+\t\t\tassert.throws(() => iterator.next(), /expired|stale/);\n+\t\t\tassert.equal(touched, false);\n+\t\t} finally {\n+\t\t\tstorage.db.close();\n+\t\t}\n+\t});\n+}"},{"path":"src/engine/test/projection-reader.test.ts","added":113,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-reader.test.ts\n@@ -0,0 +1,113 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildAtom } from \"../build.ts\";\n+import { ExperimentalMarkerProjection } from \"../experimental/projection-marker.ts\";\n+import { ProjectionReadScope } from \"../experimental/projection-read-scope.ts\";\n+import { ProjectionReader } from \"../experimental/projection-reader.ts\";\n+import { Graph } from \"../graph.ts\";\n+import { CachedStateStorage } from \"../state-source.ts\";\n+\n+import { Repo } from \"./helpers.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"unchanged atom builder consumes the private reader for replacement and insertion edits\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst repo = Repo.init({ \"f.txt\": \"one\\ntwo\\nthree\\n\" });\n+\t\tconst graph = new Graph({ storage: new CachedStateStorage(storage) });\n+\t\tgraph.add(repo.graph.atom(\"a0\"));\n+\t\tconst adapter = new ExperimentalMarkerProjection(storage, graph, \"f.txt\", \"builder-reader\");\n+\t\tlet state = adapter.apply(adapter.empty(), graph.atom(\"a0\"));\n+\t\tfor (let i = 0; i < 16; i++) {\n+\t\t\tconst input = {\n+\t\t\t\tauthor: \"writer\",\n+\t\t\t\tmessage: `Edit ${i}`,\n+\t\t\t\ttime: i,\n+\t\t\t\tedits: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tfile: \"f.txt\",\n+\t\t\t\t\t\told: repo.view().text(\"f.txt\"),\n+\t\t\t\t\t\tnew: `one\\nrevision ${i}\\nthree\\n${i % 2 ? \"extra\\n\" : \"\"}`,\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t};\n+\t\t\tconst expected = buildAtom(repo.view(), input);\n+\t\t\tconst reader = new ProjectionReader(adapter, state, new ProjectionReadScope(graph, () => graph).guard(graph));\n+\t\t\tconst actual = buildAtom(reader, input);\n+\t\t\tassert.deepEqual(actual, expected);\n+\t\t\tgraph.add(actual);\n+\t\t\trepo.graph.add(expected);\n+\t\t\trepo.shared.add(expected.id);\n+\t\t\tstate = adapter.apply(state, actual);\n+\t\t\tassert.equal(\n+\t\t\t\tnew ProjectionReader(adapter, state, new ProjectionReadScope(graph, () => graph).guard(graph)).text(\"f.txt\"),\n+\t\t\t\trepo.view().text(\"f.txt\"),\n+\t\t\t);\n+\t\t}\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});\n+\n+test(\"private reader builds cross-file moves and resurrects a deleted file\", (t) => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst repo = Repo.init({ \"f.txt\": \"one\\ntwo\\nthree\\n\", \"g.txt\": \"other\\n\" });\n+\t\tconst graph = new Graph({ storage: new CachedStateStorage(storage) });\n+\t\tgraph.add(repo.graph.atom(\"a0\"));\n+\t\tconst adapter = new ExperimentalMarkerProjection(storage, graph, \"f.txt\", \"reader-moves\");\n+\t\tlet state = adapter.apply(adapter.empty(), graph.atom(\"a0\"));\n+\t\tconst inputs: Parameters<typeof buildAtom>[1][] = [\n+\t\t\t{ author: \"writer\", message: \"Move\", move: { file: \"f.txt\", start: 1, end: 2, to: \"g.txt\", at: 1 } },\n+\t\t\t{ author: \"writer\", message: \"Delete file\", edits: [{ file: \"f.txt\", old: \"one\\nthree\\n\", new: \"\" }] },\n+\t\t\t{ author: \"writer\", message: \"Recreate file\", edits: [{ file: \"f.txt\", old: \"\", new: \"reborn\\n\" }] },\n+\t\t\t{ author: \"writer\", message: \"Move back\", move: { file: \"g.txt\", start: 1, end: 2, to: \"f.txt\", at: 0 } },\n+\t\t];\n+\t\tfor (const input of inputs) {\n+\t\t\tconst expected = buildAtom(repo.view(), input),\n+\t\t\t\treader = new ProjectionReader(adapter, state, new ProjectionReadScope(graph, () => graph).guard(graph));\n+\t\t\tconst actual = buildAtom(reader, input);\n+\t\t\tassert.deepEqual(actual, expected);\n+\t\t\tgraph.add(actual);\n+\t\t\trepo.graph.add(expected);\n+\t\t\trepo.shared.add(expected.id);\n+\t\t\tstate = adapter.apply(state, actual);\n+\t\t\tconst projected = new ProjectionReader(adapter, state, new ProjectionReadScope(graph, () => graph).guard(graph));\n+\t\t\tt.mock.method(projected, \"parentOf\", () => {\n+\t\t\t\tthrow Error(\"line ancestry traversal forbidden\");\n+\t\t\t});\n+\t\t\tfor (const path of [\"f.txt\", \"g.txt\"]) {\n+\t\t\t\tassert.deepEqual(projected.sequence(path), repo.view().sequence(path));\n+\t\t\t\tfor (const line of projected.sequence(path))\n+\t\t\t\t\tassert.equal(projected.fileOf(line.id), repo.view().fileOf(line.id));\n+\t\t\t}\n+\t\t}\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});\n+\n+test(\"reader orders deletion contributors by Lamport before sequence and treats unknown membership as absent\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst repo = Repo.init({ \"f.txt\": \"target\\n\", \"g.txt\": \"other\\n\" });\n+\t\tconst chain = repo.edit({ edits: [{ file: \"g.txt\", old: \"other\", new: \"changed\" }] });\n+\t\tconst high = repo.edit({ edits: [{ file: \"f.txt\", old: \"target\\n\", new: \"\" }], needs: [chain.id] });\n+\t\tconst low = repo.edit({ edits: [{ file: \"f.txt\", old: \"target\\n\", new: \"\" }] }, [\"a0\"]);\n+\t\tassert.ok(repo.graph.lamportOfSeq(high.seq) > repo.graph.lamportOfSeq(low.seq));\n+\t\tassert.ok(high.seq < low.seq);\n+\t\tconst graph = new Graph({ storage: new CachedStateStorage(storage) });\n+\t\tconst adapter = new ExperimentalMarkerProjection(storage, graph, \"f.txt\", \"reader-priority\");\n+\t\tlet state = adapter.empty();\n+\t\tfor (const id of [\"a0\", chain.id, high.id, low.id]) {\n+\t\t\tconst atom = repo.graph.atom(id);\n+\t\t\tgraph.add(atom);\n+\t\t\tstate = adapter.apply(state, atom);\n+\t\t}\n+\t\tconst reader = new ProjectionReader(adapter, state, new ProjectionReadScope(graph, () => graph).guard(graph));\n+\t\tassert.deepEqual(reader.sequence(\"f.txt\"), repo.view().sequence(\"f.txt\"));\n+\t\tassert.equal(reader.set.has(\"unknown-atom\"), false);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/projection-records.test.ts","added":41,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-records.test.ts\n@@ -0,0 +1,41 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import {\n+\tprojectionAttributes,\n+\tprojectionAttributeValue,\n+\tprojectionChildRoot,\n+\tprojectionMarker,\n+\tprojectionMembership,\n+} from \"../experimental/projection-records.ts\";\n+\n+test(\"experimental projection record decoders reject contradictory persisted state\", () => {\n+\tconst file = { kind: \"file\", enter: 1, exit: 2, contributions: 0 };\n+\tassert.deepEqual(projectionMarker(file), file);\n+\tconst line = { kind: \"line\", enter: 3, exit: 4, parentKey: 0, key: \"0\".repeat(57) };\n+\tassert.deepEqual(projectionMarker(line), line);\n+\tfor (const value of [\n+\t\t{ ...file, exit: 1 },\n+\t\t{ ...file, parentKey: 0 },\n+\t\t{ ...line, key: \"f\" },\n+\t\t{ ...line, parentKey: 2 ** 32 },\n+\t\t{ ...line, enter: -1 },\n+\t])\n+\t\tassert.throws(() => projectionMarker(value), /invalid projection/);\n+\tassert.deepEqual(projectionMembership({ present: true, dependents: 2 }), { present: true, dependents: 2 });\n+\tfor (const value of [\n+\t\t{ present: false, dependents: 1 },\n+\t\t{ present: true, dependents: -1 },\n+\t\t{ present: true, dependents: 0.5 },\n+\t\t{ present: 1, dependents: 0 },\n+\t])\n+\t\tassert.throws(() => projectionMembership(value), /invalid projection/);\n+\tassert.deepEqual(projectionChildRoot({ root: null }), { root: null });\n+\tassert.throws(() => projectionChildRoot({ root: NaN }), /invalid projection/);\n+\tconst roots = { exec: 4, link: null };\n+\tassert.deepEqual(projectionAttributes(roots), roots);\n+\tassert.notEqual(projectionAttributes(roots), roots);\n+\tassert.throws(() => projectionAttributes({ unknown: 0 }), /invalid projection/);\n+\tassert.throws(() => projectionAttributes({ exec: -1 }), /invalid projection/);\n+\tassert.deepEqual(projectionAttributeValue({ value: null }), { value: null });\n+\tassert.throws(() => projectionAttributeValue({ value: 4 }), /invalid projection/);\n+});"},{"path":"src/engine/test/projection-root.test.ts","added":74,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-root.test.ts\n@@ -0,0 +1,74 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import {\n+\tcreateProjectionRoot,\n+\ttype ProjectionIdentity,\n+\ttype ProjectionRoots,\n+\treadProjectionRoot,\n+} from \"../experimental/projection-root.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"experimental roots bind identity before storage access and remain immutable\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst expected: ProjectionIdentity = {\n+\t\t\tdatabase: \"db\",\n+\t\t\tnamespace: \"index\",\n+\t\t\tsourceGeneration: 1,\n+\t\t\tsourceLength: 2,\n+\t\t\tsourceDigest: \"a\".repeat(64),\n+\t\t\tmembership: \"closed:2\",\n+\t\t\tregistry: \"files:1\",\n+\t\t\tdefaultFile: \"f.txt\",\n+\t\t};\n+\t\tconst pages: ProjectionRoots = {\n+\t\t\tsequence: 3,\n+\t\t\tsequenceRoot: 0,\n+\t\t\tsequenceNext: 1,\n+\t\t\tlocator: 4,\n+\t\t\tchildren: 5,\n+\t\t\tmembership: 6,\n+\t\t\tattributes: null,\n+\t\t};\n+\t\tconst handle = createProjectionRoot(storage, expected, 0, pages);\n+\t\tassert.deepEqual(readProjectionRoot(storage, handle, expected), pages);\n+\t\tfor (const field of Object.keys(expected) as (keyof ProjectionIdentity)[]) {\n+\t\t\tconst changed = {\n+\t\t\t\t...expected,\n+\t\t\t\t[field]:\n+\t\t\t\t\ttypeof expected[field] === \"number\"\n+\t\t\t\t\t\t? Number(expected[field]) + 1\n+\t\t\t\t\t\t: field === \"sourceDigest\"\n+\t\t\t\t\t\t\t? \"b\".repeat(64)\n+\t\t\t\t\t\t\t: `${expected[field]}:other`,\n+\t\t\t};\n+\t\t\tconst reads = storage.reads,\n+\t\t\t\twrites = storage.writes;\n+\t\t\tassert.throws(() => readProjectionRoot(storage, handle, changed), /identity mismatch/);\n+\t\t\tassert.equal(storage.reads, reads);\n+\t\t\tassert.equal(storage.writes, writes);\n+\t\t}\n+\t\tassert.throws(() => createProjectionRoot(storage, expected, 0, pages), /already exists/);\n+\t\tconst copy = readProjectionRoot(storage, handle, expected) as { sequence: number | null };\n+\t\tcopy.sequence = 999;\n+\t\tassert.deepEqual(readProjectionRoot(storage, handle, expected), pages);\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\tstorage.transaction(() => {\n+\t\t\t\t\tcreateProjectionRoot(storage, expected, 1, pages);\n+\t\t\t\t\tthrow Error(\"fail after root\");\n+\t\t\t\t}),\n+\t\t\t/fail after root/,\n+\t\t);\n+\t\tassert.throws(() => readProjectionRoot(storage, { ...handle, id: 1 }, expected), /invalid projection root record/);\n+\t\tstorage.write('experimental-projection:[\"db\",\"index\"]:roots', \"0\", {\n+\t\t\tformat: 1,\n+\t\t\tid: 0,\n+\t\t\tidentity: expected,\n+\t\t\troots: { ...pages, locator: -1 },\n+\t\t});\n+\t\tassert.throws(() => readProjectionRoot(storage, handle, expected), /invalid projection page reference/);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/projection-sequence.test.ts","added":49,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-sequence.test.ts\n@@ -0,0 +1,49 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { ProjectionSequence } from \"../experimental/projection-sequence.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"typed sequence preserves ordering, moves, old roots and rollback\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst sequence = new ProjectionSequence(storage, \"test\");\n+\t\tlet state = sequence.empty();\n+\t\tconst oracle: { id: number; text: string }[] = [];\n+\t\tfor (let i = 0; i < 64; i++) {\n+\t\t\tconst rank = i % 2 ? 0 : oracle.length;\n+\t\t\tstate = sequence.update(state, { kind: \"insert\", rank, text: String(i) });\n+\t\t\toracle.splice(rank, 0, { id: i, text: String(i) });\n+\t\t}\n+\t\tconst original = state,\n+\t\t\told = structuredClone(oracle);\n+\t\tfor (let i = 0; i < 32; i++) {\n+\t\t\tconst from = i % 48,\n+\t\t\t\tlength = 1 + (i % 12),\n+\t\t\t\tto = (i * 7) % (65 - length);\n+\t\t\tstate = sequence.update(state, { kind: \"move\", from, length, to });\n+\t\t\tconst block = oracle.splice(from, length);\n+\t\t\toracle.splice(to, 0, ...block);\n+\t\t\tassert.deepEqual([...sequence.values(state)], oracle);\n+\t\t\tfor (let k = 0; k < oracle.length; k++) assert.equal(sequence.rank(state, oracle[k]!.id), k);\n+\t\t}\n+\t\tstate = sequence.update(state, { kind: \"visibility\", id: 0, delta: 1 });\n+\t\tassert.deepEqual(\n+\t\t\t[...sequence.values(state)],\n+\t\t\toracle.filter((x) => x.id !== 0),\n+\t\t);\n+\t\tassert.deepEqual([...sequence.values(original)], old);\n+\t\tconst rows = () => JSON.stringify(storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all());\n+\t\tconst before = rows();\n+\t\tstorage.failWrite = storage.writes + 3;\n+\t\tassert.throws(() => sequence.update(state, { kind: \"insert\", rank: 0, text: \"failure\" }), /injected/);\n+\t\tassert.equal(rows(), before);\n+\t\tstorage.failWrite = Infinity;\n+\t\tassert.throws(() => sequence.rank({ ...state, next: -1 }, 0), /invalid sequence state/);\n+\t\tconst root = sequence.get(state.map, state.root!);\n+\t\tconst corrupt = sequence.set(state.map, root.id, { ...root, count: root.count + 1 });\n+\t\tassert.throws(() => [...sequence.values({ ...state, map: corrupt })], /inconsistent sequence aggregate/);\n+\t\tassert.deepEqual([...sequence.values(original)], old);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/projection-snapshots.test.ts","added":174,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/projection-snapshots.test.ts\n@@ -0,0 +1,174 @@\n+import assert from \"node:assert/strict\";\n+import { mkdtempSync, rmSync } from \"node:fs\";\n+import { tmpdir } from \"node:os\";\n+import { join } from \"node:path\";\n+import { test } from \"node:test\";\n+import { ExperimentalMarkerProjection } from \"../experimental/projection-marker.ts\";\n+import type { ProjectionIdentity } from \"../experimental/projection-root.ts\";\n+import { ProjectionSnapshots } from \"../experimental/projection-snapshots.ts\";\n+import { Graph } from \"../graph.ts\";\n+import { CachedStateStorage } from \"../state-source.ts\";\n+import { Repo } from \"./helpers.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"experimental snapshots reopen and refuse wrong identities before projection reads\", () => {\n+\tconst filename = join(mkdtempSync(join(tmpdir(), \"abso-projection-snapshot-\")), \"state.sqlite\");\n+\tlet storage = new SqlState(filename);\n+\tconst repo = Repo.init({ \"f.txt\": \"hello\\n\", \"g.txt\": \"other\\n\" });\n+\tconst identity: ProjectionIdentity = {\n+\t\tdatabase: \"database-a\",\n+\t\tnamespace: \"index-a\",\n+\t\tregistry: \"registry-a\",\n+\t\tdefaultFile: \"f.txt\",\n+\t\tsourceGeneration: 1,\n+\t\tsourceLength: 1,\n+\t\tsourceDigest: \"a\".repeat(64),\n+\t\tmembership: \"base\",\n+\t};\n+\ttry {\n+\t\tlet graph = new Graph({ storage: new CachedStateStorage(storage) });\n+\t\tgraph.add(repo.graph.atom(\"a0\"));\n+\t\tlet adapter = new ExperimentalMarkerProjection(storage, graph, \"f.txt\", \"index-a\");\n+\t\tlet snapshots = new ProjectionSnapshots(storage, adapter, identity);\n+\t\tconst state = adapter.apply(adapter.empty(), repo.graph.atom(\"a0\"));\n+\t\tconst handle = snapshots.save(0, identity, state);\n+\t\tstorage.db.close();\n+\t\tstorage = new SqlState(filename);\n+\t\tgraph = new Graph({ storage: new CachedStateStorage(storage) });\n+\t\tadapter = new ExperimentalMarkerProjection(storage, graph, \"f.txt\", \"index-a\");\n+\t\tsnapshots = new ProjectionSnapshots(storage, adapter, identity);\n+\t\tconst reopened = snapshots.load(handle, identity);\n+\t\tassert.deepEqual(adapter.lines(reopened), [\"a0.0\"]);\n+\t\tfor (const field of Object.keys(identity) as (keyof ProjectionIdentity)[]) {\n+\t\t\tconst changed = {\n+\t\t\t\t...identity,\n+\t\t\t\t[field]:\n+\t\t\t\t\ttypeof identity[field] === \"number\"\n+\t\t\t\t\t\t? Number(identity[field]) + 1\n+\t\t\t\t\t\t: field === \"sourceDigest\"\n+\t\t\t\t\t\t\t? \"b\".repeat(64)\n+\t\t\t\t\t\t\t: `${identity[field]}:other`,\n+\t\t\t};\n+\t\t\tconst reads = storage.reads,\n+\t\t\t\twrites = storage.writes;\n+\t\t\tassert.throws(() => snapshots.load(handle, changed), /mismatch/);\n+\t\t\tassert.equal(storage.reads, reads);\n+\t\t\tassert.equal(storage.writes, writes);\n+\t\t}\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\tnew ProjectionSnapshots(\n+\t\t\t\t\tstorage,\n+\t\t\t\t\tnew ExperimentalMarkerProjection(storage, graph, \"g.txt\", \"index-a\"),\n+\t\t\t\t\tidentity,\n+\t\t\t\t),\n+\t\t\t/constructor mismatch/,\n+\t\t);\n+\t\tconst rows = () => JSON.stringify(storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all());\n+\t\tconst before = rows();\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\tstorage.transaction(() => {\n+\t\t\t\t\tsnapshots.save(1, identity, reopened);\n+\t\t\t\t\tthrow Error(\"fail after snapshot\");\n+\t\t\t\t}),\n+\t\t\t/fail after snapshot/,\n+\t\t);\n+\t\tassert.equal(rows(), before);\n+\t\tstorage.write('experimental-projection:[\"database-a\",\"index-a\"]:context', \"binding\", {\n+\t\t\t...identity,\n+\t\t\tregistry: \"replaced\",\n+\t\t});\n+\t\tassert.throws(() => snapshots.load(handle, identity), /registry binding/);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});\n+\n+test(\"experimental snapshots preserve mixed files across two reopens and subsequent writes\", () => {\n+\tconst directory = mkdtempSync(join(tmpdir(), \"abso-projection-mixed-\"));\n+\tconst filename = join(directory, \"state.sqlite\");\n+\tlet storage = new SqlState(filename);\n+\tconst repo = Repo.init({ \"f.txt\": \"a\\nb\\n\", \"g.txt\": \"x\\n\" });\n+\tconst identity: ProjectionIdentity = {\n+\t\tdatabase: \"mixed-database\",\n+\t\tnamespace: \"mixed-index\",\n+\t\tregistry: \"mixed-registry\",\n+\t\tdefaultFile: \"f.txt\",\n+\t\tsourceGeneration: 1,\n+\t\tsourceLength: 1,\n+\t\tsourceDigest: \"a\".repeat(64),\n+\t\tmembership: \"base\",\n+\t};\n+\tlet graph = new Graph({ storage: new CachedStateStorage(storage) });\n+\tlet adapter = new ExperimentalMarkerProjection(storage, graph, \"f.txt\", identity.namespace);\n+\tlet snapshots = new ProjectionSnapshots(storage, adapter, identity);\n+\tgraph.add(repo.graph.atom(\"a0\"));\n+\tlet state = adapter.apply(adapter.empty(), repo.graph.atom(\"a0\"));\n+\tconst original = snapshots.save(0, identity, state);\n+\tconst reopen = () => {\n+\t\tstorage.db.close();\n+\t\tstorage = new SqlState(filename);\n+\t\tgraph = new Graph({ storage: new CachedStateStorage(storage) });\n+\t\tadapter = new ExperimentalMarkerProjection(storage, graph, \"f.txt\", identity.namespace);\n+\t\tsnapshots = new ProjectionSnapshots(storage, adapter, identity);\n+\t};\n+\tconst check = () => {\n+\t\tconst view = repo.view();\n+\t\tfor (const path of [\"f.txt\", \"g.txt\", \"empty.txt\"]) {\n+\t\t\tassert.deepEqual(\n+\t\t\t\tadapter.lines(state, path),\n+\t\t\t\tview.lines(path).map((line) => line.id),\n+\t\t\t);\n+\t\t\tassert.deepEqual(adapter.attrs(state, path), view.attrs(path));\n+\t\t}\n+\t};\n+\ttry {\n+\t\tconst move = repo.edit({ move: { file: \"f.txt\", start: 0, end: 1, to: \"g.txt\", at: 0 } });\n+\t\tgraph.add(move);\n+\t\tstate = adapter.apply(state, move);\n+\t\tconst attr = repo.edit({\n+\t\t\tattrs: [\n+\t\t\t\t{ file: \"empty.txt\", name: \"exists\", value: \"1\" },\n+\t\t\t\t{ file: \"g.txt\", name: \"exec\", value: \"1\" },\n+\t\t\t],\n+\t\t});\n+\t\tgraph.add(attr);\n+\t\tstate = adapter.apply(state, attr);\n+\t\tconst mixedIdentity = { ...identity, sourceLength: 3, sourceDigest: \"b\".repeat(64), membership: \"mixed\" };\n+\t\tconst mixed = snapshots.save(1, mixedIdentity, state);\n+\t\treopen();\n+\t\tstate = snapshots.load(mixed, mixedIdentity);\n+\t\tcheck();\n+\t\tconst writes = storage.writes;\n+\t\tassert.equal(adapter.apply(state, attr), state);\n+\t\tassert.equal(storage.writes, writes);\n+\t\tfor (const atom of [attr, move]) {\n+\t\t\trepo.shared.delete(atom.id);\n+\t\t\tstate = adapter.removeAtom(state, atom);\n+\t\t\tcheck();\n+\t\t}\n+\t\tassert.deepEqual(adapter.lines(snapshots.load(original, identity), \"f.txt\"), [\"a0.0\", \"a0.1\"]);\n+\t\tconst edit = repo.edit({ edits: [{ file: \"g.txt\", old: \"x\\n\", new: \"after restart\\n\" }] });\n+\t\tgraph.add(edit);\n+\t\tstate = adapter.apply(state, edit);\n+\t\tcheck();\n+\t\tconst finalIdentity = { ...identity, sourceLength: 4, sourceDigest: \"c\".repeat(64), membership: \"edited\" };\n+\t\tconst final = snapshots.save(2, finalIdentity, state);\n+\t\treopen();\n+\t\tstate = snapshots.load(final, finalIdentity);\n+\t\tcheck();\n+\t\tassert.deepEqual(adapter.lines(snapshots.load(mixed, mixedIdentity), \"g.txt\"), [\"a0.0\", \"a0.2\"]);\n+\t\tassert.equal(\n+\t\t\tstorage.db\n+\t\t\t\t.prepare(\n+\t\t\t\t\t\"SELECT count(*) AS n FROM state WHERE collection LIKE '%sequence-resolver:%' OR collection LIKE '%sequence-relocation-work:%'\",\n+\t\t\t\t)\n+\t\t\t\t.get()!.n,\n+\t\t\t0,\n+\t\t);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t\trmSync(directory, { recursive: true, force: true });\n+\t}\n+});"},{"path":"src/engine/view.ts","added":12,"removed":2,"diff":"--- a/src/engine/view.ts\n+++ b/src/engine/view.ts\n@@ -45,6 +45,11 @@\n \treadonly blob: string | null;\n }\n \n+/** Structural read boundary shared by historical and transaction-bound projections. */\n+export type ReadView = Omit<Pick<View, keyof View>, \"sameText\"> & {\n+\tsameText(path: string, other: ReadView): boolean;\n+};\n+\n const NO_ATTRS: FileAttrs = { exists: false, exec: false, link: null, blob: null };\n const NONE: readonly never[] = Object.freeze([]);\n \n@@ -523,7 +528,12 @@\n \t}\n \n \t/** Whether a file reads the same here and in `other` (of the same graph), compared line by line without joining either (#46). */\n-\tsameText(path: string, other: View): boolean {\n+\tsameText(path: string, other: ReadView): boolean {\n+\t\tif (!(other instanceof View)) {\n+\t\t\tconst a = this.lines(path),\n+\t\t\t\tb = other.lines(path);\n+\t\t\treturn a.length === b.length && a.every((line, i) => line.text === b[i]!.text);\n+\t\t}\n \t\tconst a = this.#file(path).vis;\n \t\tconst b = other.#file(path).vis;\n \t\tif (a.length !== b.length) return false;\n@@ -698,7 +708,7 @@\n }\n \n /** Where a node sits in a file's sequence: the index just after it (0 for a start node). */\n-export function indexAfter(view: View, path: string, node: NodeId): number {\n+export function indexAfter(view: Pick<ReadView, \"sequenceIndex\">, path: string, node: NodeId): number {\n \tif (isStartNode(node)) return 0;\n \tconst i = view.sequenceIndex(path, node);\n \tif (i < 0) throw new EngineError(\"not-in-view\", `line ${node} is not in ${path} in this view`);"},{"path":"worker/project/add-draft.ts","added":3,"removed":3,"diff":"--- a/worker/project/add-draft.ts\n+++ b/worker/project/add-draft.ts\n@@ -11,7 +11,7 @@\n \ttype Graph,\n \ttype MoveInput,\n \tparseKey,\n-\ttype View,\n+\ttype ReadView,\n } from \"../../src/engine/index.ts\";\n import type { Pair } from \"./collisions.ts\";\n import type { AgentState, Entry, Meta } from \"./project-types.ts\";\n@@ -20,7 +20,7 @@\n export interface AddDraftHost {\n \treadonly graph: Graph;\n \topenPairs(agent: AgentState): Pair[];\n-\tmarkersSettled(agent: AgentState, view: View, atom: Atom): AtomId[];\n+\tmarkersSettled(agent: AgentState, view: ReadView, atom: Atom): AtomId[];\n \tapply(entry: Entry): void;\n }\n \n@@ -32,7 +32,7 @@\n export function addDraft(\n \thost: AddDraftHost,\n \tagent: AgentState,\n-\tview: View,\n+\tview: ReadView,\n \tinput: { edits: readonly EditInput[]; attrs?: readonly AttrSet[]; move?: MoveInput },\n \ttime: number,\n \tmeta: Meta,"},{"path":"worker/project/changes-since.ts","added":4,"removed":4,"diff":"--- a/worker/project/changes-since.ts\n+++ b/worker/project/changes-since.ts\n@@ -1,7 +1,7 @@\n // The files whose text in the agent's view differs from before, and its open\n // collisions. Reads go through ChangesSinceHost; today the host is Project.\n \n-import type { AtomId, View } from \"../../src/engine/index.ts\";\n+import type { AtomId, ReadView } from \"../../src/engine/index.ts\";\n import type { Pair } from \"./collisions.ts\";\n import { sortKeys } from \"./project-helpers.ts\";\n import type { AgentState, Blobs, Collision, Files, Modes, SyncAnswer } from \"./project-types.ts\";\n@@ -9,8 +9,8 @@\n \n /** What a changes-since read needs from a project. */\n export interface ChangesSinceHost {\n-\tagentView(agent: AgentState): View;\n-\ttouchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;\n+\tagentView(agent: AgentState): ReadView;\n+\ttouchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>;\n \topenPairs(agent: AgentState): Pair[];\n \tcollision(agent: AgentState, pair: Pair): Collision;\n \tduplicates(agent: AgentState): Collision[];\n@@ -18,7 +18,7 @@\n }\n \n /** The files whose text in the agent's view differs from `before`, and its open collisions. */\n-export function changesSince(host: ChangesSinceHost, agent: AgentState, before: View): SyncAnswer {\n+export function changesSince(host: ChangesSinceHost, agent: AgentState, before: ReadView): SyncAnswer {\n \tconst after = host.agentView(agent);\n \t// Only files that an atom in one view but not the other touches can differ.\n \tconst touched = new Set<string>();"},{"path":"worker/project/check-clash.ts","added":10,"removed":8,"diff":"--- a/worker/project/check-clash.ts\n+++ b/worker/project/check-clash.ts\n@@ -1,7 +1,7 @@\n // Refuse work whose paths would clash in shared. Reads go through\n // CheckClashHost; today the host is Project.\n \n-import type { AtomId, View } from \"../../src/engine/index.ts\";\n+import type { AtomId, ReadView } from \"../../src/engine/index.ts\";\n import { unionOverlay } from \"../../src/engine/state-source.ts\";\n import { ProjectError } from \"./project-error.ts\";\n import { configProblem, PROJECT_FILES } from \"./project-helpers.ts\";\n@@ -12,9 +12,10 @@\n export interface CheckClashHost {\n \tshared(): Space;\n \tsetOf(space: Space): ReadonlySet<AtomId>;\n-\tview(set: ReadonlySet<AtomId>): View;\n-\tsharedView(): View;\n-\ttouchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;\n+\tview(set: ReadonlySet<AtomId>): ReadView;\n+\tsharedView(): ReadView;\n+\tsharedOverlay?(atoms: readonly AtomId[]): ReadView;\n+\ttouchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>;\n }\n \n /**\n@@ -27,14 +28,15 @@\n \tahead: ReadonlySet<AtomId> = new Set(),\n ): void {\n \tif (changes.length === 0) return;\n-\tlet view: View;\n-\tlet now: View;\n+\tlet view: ReadView;\n+\tlet now: ReadView;\n \ttry {\n \t\t// Publishes queued ahead (#39) land first, so they count as shared.\n \t\tconst base = host.setOf(host.shared());\n \t\tconst queued = unionOverlay(base, ahead);\n-\t\tview = host.view(unionOverlay(queued, changes));\n-\t\tnow = ahead.size === 0 ? host.sharedView() : host.view(queued);\n+\t\tview = host.sharedOverlay ? host.sharedOverlay([...ahead, ...changes]) : host.view(unionOverlay(queued, changes));\n+\t\tnow =\n+\t\t\tahead.size === 0 ? host.sharedView() : host.sharedOverlay ? host.sharedOverlay([...ahead]) : host.view(queued);\n \t} catch (e) {\n \t\tif ((e as { code?: string }).code === \"not-closed\") return; // stranded by a drop: the publish says so itself\n \t\tthrow e;"},{"path":"worker/project/collisions.ts","added":8,"removed":8,"diff":"--- a/worker/project/collisions.ts\n+++ b/worker/project/collisions.ts\n@@ -10,7 +10,7 @@\n \ttype Graph,\n \tjoinLines,\n \tparseKey,\n-\ttype View,\n+\ttype ReadView,\n } from \"../../src/engine/index.ts\";\n import { differenceSet, StableOverlaySet } from \"../../src/engine/state-source.ts\";\n import { definedTwice } from \"./definitions.ts\";\n@@ -147,8 +147,8 @@\n \tg: Graph,\n \torigin: (atom: AtomId, spaceName: string) => Origin,\n \tpair: Pair,\n-\tyoursView: View,\n-\ttheirsView: View,\n+\tyoursView: ReadView,\n+\ttheirsView: ReadView,\n \tspaceName: string,\n ): Collision {\n \tconst file = fileOfKey(pair.keys[0]!.key, yoursView);\n@@ -157,7 +157,7 @@\n \tif (attrsOnly.length === fileKeys.length) {\n \t\t// Both set the same attribute of the file: show each side's value.\n \t\tconst name = attrsOnly[0]!.attr!;\n-\t\tconst valueIn = (view: View, atom: AtomId): string => {\n+\t\tconst valueIn = (view: ReadView, atom: AtomId): string => {\n \t\t\tconst set = (g.atom(atom).attrs ?? []).find((a) => a.file === file && a.name === name);\n \t\t\treturn set?.value ?? (name === \"exec\" ? \"\" : String(view.attrs(file)[name] ?? \"\"));\n \t\t};\n@@ -177,7 +177,7 @@\n \t};\n }\n \n-export function fileOfKey(key: string, view: View): string {\n+export function fileOfKey(key: string, view: ReadView): string {\n \tconst { kind, node } = parseKey(key);\n \tif (kind === \"attr\") return node;\n \treturn node.startsWith(\"^\") ? node.slice(1) : view.fileOf(node);\n@@ -187,7 +187,7 @@\n  * The files some atoms change: the graph's files of each, and, in views\n  * with moves (#28), wherever the lines they touch are in those views.\n  */\n-export function touchedFiles(g: Graph, ids: Iterable<AtomId>, views: readonly View[]): Set<string> {\n+export function touchedFiles(g: Graph, ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string> {\n \tconst out = new Set<string>();\n \tconst moved = views.filter((v) => v.hasMoves());\n \tfor (const id of ids) {\n@@ -206,7 +206,7 @@\n }\n \n /** The atom's visible lines in a file of a view, or where it acted when none are left. */\n-export function describeSide(view: View, atom: AtomId, file: string, keys: readonly string[]): CollisionSide {\n+export function describeSide(view: ReadView, atom: AtomId, file: string, keys: readonly string[]): CollisionSide {\n \tconst visible = view.lines(file);\n \tlet first = -1;\n \tlet lastLine = -1;\n@@ -238,7 +238,7 @@\n \tspaceOf(agent: AgentState): Space;\n \tagentSet(agent: AgentState): ReadonlySet<AtomId>;\n \tdraft(agent: AgentState): AtomId[];\n-\tagentView(agent: AgentState): View;\n+\tagentView(agent: AgentState): ReadView;\n \tat(space: Space, version: number): ReadonlySet<AtomId>;\n \tshared(): Space;\n }"},{"path":"worker/project/definition-rule.ts","added":5,"removed":5,"diff":"--- a/worker/project/definition-rule.ts\n+++ b/worker/project/definition-rule.ts\n@@ -4,7 +4,7 @@\n // views; the project hands in who published an atom, and keeps the rule's\n // cache for its life.\n \n-import { type AtomId, type Graph, joinLines, type LineId, type View } from \"../../src/engine/index.ts\";\n+import { type AtomId, type Graph, joinLines, type LineId, type ReadView } from \"../../src/engine/index.ts\";\n import { type Origin, touchedFiles } from \"./collisions.ts\";\n import { type Definition, definitionsIn, importsOf, usedNames } from \"./definitions.ts\";\n import { codeOfLines, declaredIn, holdsNoCode } from \"./names.ts\";\n@@ -52,7 +52,7 @@\n \t * replaced the block of lines the atom deleted just before it in `base`.\n \t * A pure insertion replaced nothing.\n \t */\n-\t#replacedNames(line: LineId, base: View, runsOf: Map<AtomId, readonly RunEnd[]>): ReadonlySet<string> {\n+\t#replacedNames(line: LineId, base: ReadView, runsOf: Map<AtomId, readonly RunEnd[]>): ReadonlySet<string> {\n \t\tconst g = this.#graph;\n \t\tconst info = g.line(line);\n \t\tif (!info) return EMPTY_NAMES;\n@@ -97,9 +97,9 @@\n \t */\n \tcollisions(\n \t\tdraft: ReadonlySet<AtomId>,\n-\t\tview: View,\n-\t\tbaseView: View,\n-\t\tnowView: View,\n+\t\tview: ReadView,\n+\t\tbaseView: ReadView,\n+\t\tnowView: ReadView,\n \t\tnewer: ReadonlySet<AtomId>,\n \t\tspaceName: string,\n \t): DefinitionCollision[] {"},{"path":"worker/project/definitions.ts","added":9,"removed":9,"diff":"--- a/worker/project/definitions.ts\n+++ b/worker/project/definitions.ts\n@@ -19,7 +19,7 @@\n // A use means a definition only through an import of it, or in the file\n // that defines it (project.ts, #definitionCore).\n \n-import type { LineId, View } from \"../../src/engine/index.ts\";\n+import type { LineId, ReadView } from \"../../src/engine/index.ts\";\n import { codeOfLines, holdsNoCode, isCommonName } from \"./names.ts\";\n \n export interface Definition {\n@@ -90,13 +90,13 @@\n const TOP_ASSIGN = new RegExp(`^(${NAME})\\\\s*(?::[^=]*)?=(?![=>])`);\n const MAX_HEADER = 30;\n \n-const cache = new WeakMap<View, Map<string, readonly Definition[]>>();\n+const cache = new WeakMap<ReadView, Map<string, readonly Definition[]>>();\n \n /**\n  * Every definition in the view's code files (or only in `files`), by name.\n  * Each file's definitions are cached per view.\n  */\n-export function definitionsIn(view: View, files?: Iterable<string>): Map<string, Definition[]> {\n+export function definitionsIn(view: ReadView, files?: Iterable<string>): Map<string, Definition[]> {\n \tlet perFile = cache.get(view);\n \tif (!perFile) {\n \t\tperFile = new Map();\n@@ -118,7 +118,7 @@\n \treturn out;\n }\n \n-function definitionsInFile(view: View, file: string, keepCommon = false): Definition[] {\n+function definitionsInFile(view: ReadView, file: string, keepCommon = false): Definition[] {\n \tif (holdsNoCode(file) || !view.hasFile(file)) return [];\n \tconst out: Definition[] = [];\n \tconst visible = view.lines(file);\n@@ -149,7 +149,7 @@\n  * included (two `parse` functions in a file are a mistake whatever the name).\n  * Each spans its whole block, body and all, for showing to the agent.\n  */\n-export function definedTwice(view: View, file: string): Map<string, Definition[]> {\n+export function definedTwice(view: ReadView, file: string): Map<string, Definition[]> {\n \tconst out = new Map<string, Definition[]>();\n \tconst all = definitionsInFile(view, file, true);\n \tconst count = new Map<string, number>();\n@@ -306,7 +306,7 @@\n \treturn i + 1;\n }\n \n-const importCache = new WeakMap<View, Map<string, ReadonlyMap<string, string>>>();\n+const importCache = new WeakMap<ReadView, Map<string, ReadonlyMap<string, string>>>();\n \n /**\n  * Names a file imports by name, and the project file each comes from, when\n@@ -316,7 +316,7 @@\n  * x.y import a, b`. Lets a use of a name be matched to the definition it\n  * means instead of every definition with that name.\n  */\n-export function importsOf(view: View, file: string): ReadonlyMap<string, string> {\n+export function importsOf(view: ReadView, file: string): ReadonlyMap<string, string> {\n \tlet perFile = importCache.get(view);\n \tif (!perFile) {\n \t\tperFile = new Map();\n@@ -367,7 +367,7 @@\n \treturn parts.join(\"/\");\n }\n \n-function resolveModule(view: View, from: string, spec: string): string | undefined {\n+function resolveModule(view: ReadView, from: string, spec: string): string | undefined {\n \tif (!spec.startsWith(\".\")) return undefined;\n \tconst base = joinPath(dirOf(from), spec);\n \tconst stem = base.replace(/\\.(?:js|mjs|cjs|jsx)$/, \"\");\n@@ -385,7 +385,7 @@\n \treturn undefined;\n }\n \n-function resolvePython(view: View, from: string, spec: string): string | undefined {\n+function resolvePython(view: ReadView, from: string, spec: string): string | undefined {\n \tconst dots = /^\\.*/.exec(spec)![0].length;\n \tconst rest = spec.slice(dots).replace(/\\./g, \"/\");\n \tlet dir = dots > 0 ? dirOf(from) : \"\";"},{"path":"worker/project/draft-collisions.ts","added":5,"removed":5,"diff":"--- a/worker/project/draft-collisions.ts\n+++ b/worker/project/draft-collisions.ts\n@@ -1,7 +1,7 @@\n // Whether agents' unpublished changes would collide (#41, F22), read through DraftCollisionHost; today the host\n // is the project in memory.\n \n-import { type AtomId, type Graph, parseKey, type View } from \"../../src/engine/index.ts\";\n+import { type AtomId, type Graph, parseKey, type ReadView } from \"../../src/engine/index.ts\";\n import { describeSide, fileOfKey, type Pair } from \"./collisions.ts\";\n import type { DefinitionRule } from \"./definition-rule.ts\";\n import { type Definition, definedTwice } from \"./definitions.ts\";\n@@ -20,13 +20,13 @@\n \treadonly agents: ReadonlyMap<string, Agent>;\n \tneedInit(): void;\n \tshared(): Space;\n-\tsharedView(): View;\n+\tsharedView(): ReadView;\n \tdefinitionRule(): DefinitionRule;\n \tdraft(agent: Agent): AtomId[];\n-\tagentView(agent: Agent): View;\n-\tview(set: ReadonlySet<AtomId>): View;\n+\tagentView(agent: Agent): ReadView;\n+\tview(set: ReadonlySet<AtomId>): ReadView;\n \tpairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[];\n-\ttouchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;\n+\ttouchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>;\n }\n \n /**"},{"path":"worker/project/draft-diff.ts","added":4,"removed":4,"diff":"--- a/worker/project/draft-diff.ts\n+++ b/worker/project/draft-diff.ts\n@@ -1,7 +1,7 @@\n // An agent's unpublished changes, file by file. They read through DraftDiffHost; today the host is the project\n // in memory.\n \n-import type { AtomId, View } from \"../../src/engine/index.ts\";\n+import type { AtomId, ReadView } from \"../../src/engine/index.ts\";\n import { ProjectError } from \"./project-error.ts\";\n import type { DiffAnswer } from \"./project-types.ts\";\n import { SHARED } from \"./spaces.ts\";\n@@ -17,9 +17,9 @@\n \treadonly agents: ReadonlyMap<string, Agent>;\n \tneedInit(): void;\n \tdraft(agent: Agent): AtomId[];\n-\tagentView(agent: Agent): View;\n-\tview(set: ReadonlySet<AtomId>): View;\n-\ttouchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;\n+\tagentView(agent: Agent): ReadView;\n+\tview(set: ReadonlySet<AtomId>): ReadView;\n+\ttouchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>;\n }\n \n /** An agent's draft diff for a reader (#41, the website): never creates the agent, never writes. */"},{"path":"worker/project/edit.ts","added":6,"removed":6,"diff":"--- a/worker/project/edit.ts\n+++ b/worker/project/edit.ts\n@@ -7,7 +7,7 @@\n \tEngineError,\n \ttype Hunk,\n \tnormalizeText,\n-\ttype View,\n+\ttype ReadView,\n } from \"../../src/engine/index.ts\";\n import { checkPath } from \"./path-rules.ts\";\n import { isComposed } from \"./pathkey.ts\";\n@@ -32,9 +32,9 @@\n \treadonly agents: ReadonlyMap<string, AgentState>;\n \treadonly whole: ProjectOptions[\"whole\"];\n \tinitialized(): boolean;\n-\tagentView(agent: AgentState): View;\n-\tsharedView(): View;\n-\tisWhole(path: string, length: number, view: View | undefined, rules: readonly string[]): boolean;\n+\tagentView(agent: AgentState): ReadView;\n+\tsharedView(): ReadView;\n+\tisWhole(path: string, length: number, view: ReadView | undefined, rules: readonly string[]): boolean;\n \twholeRules(config?: string): string[];\n \trecord(\n \t\tagentName: string,\n@@ -48,7 +48,7 @@\n \tdraftFiles(agent: AgentState): Set<string>;\n \trecordFile(\n \t\tagent: AgentState,\n-\t\tview: View,\n+\t\tview: ReadView,\n \t\tpath: string,\n \t\ttext: string | null | undefined,\n \t\ttime: number,\n@@ -60,7 +60,7 @@\n \t): boolean;\n \taddDraft(\n \t\tagent: AgentState,\n-\t\tview: View,\n+\t\tview: ReadView,\n \t\tinput: { edits: readonly EditInput[] },\n \t\ttime: number,\n \t\tmeta: Meta,"},{"path":"worker/project/express-moves.ts","added":15,"removed":9,"diff":"--- a/worker/project/express-moves.ts\n+++ b/worker/project/express-moves.ts\n@@ -2,7 +2,7 @@\n // text that arrives somewhere else is the same line. Before a publish, those matches become move\n // atoms so the lines keep their ids. Writes go through ExpressMovesHost; today the host is Project.\n \n-import type { AtomId, AttrSet, EditInput, Graph, LineId, MoveInput, View } from \"../../src/engine/index.ts\";\n+import type { AtomId, AttrSet, EditInput, Graph, LineId, MoveInput, ReadView } from \"../../src/engine/index.ts\";\n import { differenceSet, StableOverlaySet } from \"../../src/engine/state-source.ts\";\n import { PLAIN_LINE } from \"./collisions.ts\";\n import type { AgentState, Entry, Meta, Mode } from \"./project-types.ts\";\n@@ -18,12 +18,13 @@\n export interface ExpressMovesHost {\n \treadonly graph: Graph;\n \tdraft(agent: AgentState): AtomId[];\n-\tagentView(agent: AgentState): View;\n-\tview(set: ReadonlySet<AtomId>): View;\n+\tagentView(agent: AgentState): ReadView;\n+\tbeforeDraft?(agent: AgentState, draft: readonly AtomId[]): ReadView;\n+\tview(set: ReadonlySet<AtomId>): ReadView;\n \tapply(entry: Entry): void;\n \taddDraft(\n \t\tagent: AgentState,\n-\t\tview: View,\n+\t\tview: ReadView,\n \t\tinput: { edits: readonly EditInput[]; attrs?: readonly AttrSet[]; move?: MoveInput },\n \t\ttime: number,\n \t\tmeta: Meta,\n@@ -31,7 +32,7 @@\n \t): void;\n \trecordFile(\n \t\tagent: AgentState,\n-\t\tview: View,\n+\t\tview: ReadView,\n \t\tpath: string,\n \t\ttext: string | null | undefined,\n \t\ttime: number,\n@@ -59,7 +60,9 @@\n \tconst g = host.graph;\n \tconst mine = new Set(draft);\n \tconst after = host.agentView(agent);\n-\tconst before = host.view(differenceSet(after.set, new StableOverlaySet(draft)));\n+\tconst before = host.beforeDraft\n+\t\t? host.beforeDraft(agent, draft)\n+\t\t: host.view(differenceSet(after.set, new StableOverlaySet(draft)));\n \tconst touched = new Set<string>();\n \tfor (const id of draft) for (const file of g.filesOf(id)) touched.add(file);\n \n@@ -171,6 +174,8 @@\n \t\t\t}\n \t\t}\n \t}\n+\t// Keep the intended membership, but reacquire its reader after each graph mutation.\n+\tconst finalAgent = { ...agent, mine: [...agent.mine] };\n \tconst discard: Entry = { type: \"discard\", agent: agent.name, atoms: draft.filter((id) => drop.has(id)) };\n \tentries.push(discard);\n \thost.apply(discard);\n@@ -180,7 +185,7 @@\n \t\tconst start = view.lineNumber(m.from, m.ids[0]!);\n \t\tif (start < 0 || m.ids.some((id, k) => view.lineNumber(m.from, id) !== start + k)) continue;\n \t\t// Land after the nearest line above it in the final text that is already there.\n-\t\tconst finalLines = after.lines(m.to);\n+\t\tconst finalLines = host.agentView(finalAgent).lines(m.to);\n \t\tlet at = 0;\n \t\tfor (let i = m.at - 1; i >= 0; i--) {\n \t\t\tconst n = view.lineNumber(m.to, finalLines[i]!.id);\n@@ -200,12 +205,13 @@\n \t\t);\n \t}\n \tfor (const path of [...involved].toSorted()) {\n-\t\tconst was = after.attrs(path);\n+\t\tconst finalView = host.agentView(finalAgent);\n+\t\tconst was = finalView.attrs(path);\n \t\thost.recordFile(\n \t\t\tagent,\n \t\t\thost.agentView(agent),\n \t\t\tpath,\n-\t\t\tafter.hasFile(path) ? after.text(path) : null,\n+\t\t\tfinalView.hasFile(path) ? finalView.text(path) : null,\n \t\t\ttime,\n \t\t\t{},\n \t\t\tentries,"},{"path":"worker/project/history.ts","added":4,"removed":4,"diff":"--- a/worker/project/history.ts\n+++ b/worker/project/history.ts\n@@ -2,7 +2,7 @@\n // (pathLife), and where lines went (follow). They read through HistoryHost, the one seam the derived tables\n // (abso issues 48 and 79) plug into: today the host is the project in memory.\n \n-import type { Graph, LineId, View } from \"../../src/engine/index.ts\";\n+import type { Graph, LineId, ReadView } from \"../../src/engine/index.ts\";\n import { pathKey } from \"./pathkey.ts\";\n import { checkReadPath, differs, type LastChange, ProjectError, utf8Bytes } from \"./project.ts\";\n import { last, SHARED, type Space } from \"./spaces.ts\";\n@@ -15,9 +15,9 @@\n \tneedInit(): void;\n \tspaceNamed(name: string | null): Space;\n \tcheckVersion(space: Space, version: number): void;\n-\tviewAt(space: Space, version: number): View;\n-\tagentView(agent: { readonly name: string; readonly space: string; readonly base: number }): View;\n-\tspellingIn(view: View, asked: string): string;\n+\tviewAt(space: Space, version: number): ReadView;\n+\tagentView(agent: { readonly name: string; readonly space: string; readonly base: number }): ReadView;\n+\tspellingIn(view: ReadView, asked: string): string;\n \tpathsOf(space: Space): Map<string, PathLifeRecord>;\n \tlastChange(space: Space, version: number): LastChange;\n \tatOrBefore(list: readonly number[], version: number): number | undefined;"},{"path":"worker/project/ingest.ts","added":4,"removed":4,"diff":"--- a/worker/project/ingest.ts\n+++ b/worker/project/ingest.ts\n@@ -1,6 +1,6 @@\n // Take in commits a person pushed with plain git. Writes go through IngestHost; today the host is Project.\n \n-import { type AtomId, canonicalText, type Hunk, type View } from \"../../src/engine/index.ts\";\n+import { type AtomId, canonicalText, type Hunk, type ReadView } from \"../../src/engine/index.ts\";\n import { checkPath } from \"./path-rules.ts\";\n import { ProjectError } from \"./project-error.ts\";\n import { configProblem, PROJECT_FILES } from \"./project-helpers.ts\";\n@@ -20,13 +20,13 @@\n \twholeOut(\n \t\tfiles: Readonly<Record<string, string | null>>,\n \t\tblobs: Readonly<Record<string, string>>,\n-\t\tview: View | undefined,\n+\t\tview: ReadView | undefined,\n \t\tconfig?: string,\n \t): { files: Record<string, string | null>; blobs: Record<string, string> };\n-\tagentView(agent: AgentState): View;\n+\tagentView(agent: AgentState): ReadView;\n \trecordFile(\n \t\tagent: AgentState,\n-\t\tview: View,\n+\t\tview: ReadView,\n \t\tpath: string,\n \t\ttext: string | null | undefined,\n \t\ttime: number,"},{"path":"worker/project/init.ts","added":2,"removed":2,"diff":"--- a/worker/project/init.ts\n+++ b/worker/project/init.ts\n@@ -1,7 +1,7 @@\n // Create the project from its first files. Writes go through InitHost; today\n // the host is Project.\n \n-import { type AttrSet, buildBase, canonicalText, type View } from \"../../src/engine/index.ts\";\n+import { type AttrSet, buildBase, canonicalText, type ReadView } from \"../../src/engine/index.ts\";\n import { checkPath } from \"./path-rules.ts\";\n import { ProjectError } from \"./project-error.ts\";\n import { configProblem, PROJECT_FILES, projectFileOf } from \"./project-helpers.ts\";\n@@ -16,7 +16,7 @@\n \twholeOut(\n \t\tfiles: Readonly<Record<string, string | null>>,\n \t\tblobs: Readonly<Record<string, string>>,\n-\t\tview: View | undefined,\n+\t\tview: ReadView | undefined,\n \t\tconfig?: string,\n \t): { files: Record<string, string | null>; blobs: Record<string, string> };\n \tcheckBlobs(blobs: unknown, files: object): Record<string, string>;"},{"path":"worker/project/land.ts","added":4,"removed":4,"diff":"--- a/worker/project/land.ts\n+++ b/worker/project/land.ts\n@@ -1,7 +1,7 @@\n // Land a named draft in shared as one unit. Writes go through LandHost; today\n // the host is Project. Ingest and pluck call landDraft, the inner step.\n \n-import { type AtomId, buildAtom, type Graph, type View } from \"../../src/engine/index.ts\";\n+import { type AtomId, buildAtom, type Graph, type ReadView } from \"../../src/engine/index.ts\";\n import type { Pair } from \"./collisions.ts\";\n import type { DefinitionRule } from \"./definition-rule.ts\";\n import { ProjectError } from \"./project-error.ts\";\n@@ -22,10 +22,10 @@\n \tshared(): Space;\n \tsetOf(space: Space): ReadonlySet<AtomId>;\n \tat(space: Space, version: number): ReadonlySet<AtomId>;\n-\tview(set: ReadonlySet<AtomId>): View;\n-\tsharedView(): View;\n+\tview(set: ReadonlySet<AtomId>): ReadView;\n+\tsharedView(): ReadView;\n \tpairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[];\n-\tdescribe(pair: Pair, yoursView: View, theirsView: View, spaceName: string): Collision;\n+\tdescribe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision;\n \tdefinitionRule(): DefinitionRule;\n \trefuse(\n \t\tagent: AgentState,"},{"path":"worker/project/markers.ts","added":3,"removed":3,"diff":"--- a/worker/project/markers.ts\n+++ b/worker/project/markers.ts\n@@ -14,7 +14,7 @@\n // Settled means the block is gone. These helpers also say what an agent kept\n // once it settled one.\n \n-import { type Atom, type AtomId, diffLines, type Graph, type Hunk, type View } from \"../../src/engine/index.ts\";\n+import { type Atom, type AtomId, diffLines, type Graph, type Hunk, type ReadView } from \"../../src/engine/index.ts\";\n import type { AgentState, AgentStatus, Collision } from \"./project-types.ts\";\n \n export const YOURS = \"<<<<<<< yours (unpublished)\";\n@@ -263,7 +263,7 @@\n /** What the marker reads need from a project. */\n export interface MarkerHost {\n \treadonly graph: Graph;\n-\tagentView(agent: AgentState): View;\n+\tagentView(agent: AgentState): ReadView;\n \tdraft(agent: AgentState): AtomId[];\n \tdraftFiles(agent: AgentState): Set<string>;\n }\n@@ -309,7 +309,7 @@\n }\n \n /** The collided changes behind each block whose marker lines `atom` deletes (#11). */\n-export function markersSettled(host: MarkerHost, agent: AgentState, view: View, atom: Atom): AtomId[] {\n+export function markersSettled(host: MarkerHost, agent: AgentState, view: ReadView, atom: Atom): AtomId[] {\n \tif (agent.marked.length === 0) return [];\n \tconst out = new Set<AtomId>();\n \tconst blocksBy = new Map<string, Block[]>();"},{"path":"worker/project/merge-identical.ts","added":7,"removed":7,"diff":"--- a/worker/project/merge-identical.ts\n+++ b/worker/project/merge-identical.ts\n@@ -8,8 +8,8 @@\n \tjoinLines,\n \tmergeLines,\n \tmergeWords,\n+\ttype ReadView,\n \tsplitLines,\n-\ttype View,\n } from \"../../src/engine/index.ts\";\n import type { Origin, Pair } from \"./collisions.ts\";\n import { type MarkedRegion, markedHunks, markerBlock } from \"./markers.ts\";\n@@ -22,14 +22,14 @@\n \topenPairs(agent: AgentState): Pair[];\n \tdraft(agent: AgentState): AtomId[];\n \torigin(atom: AtomId, spaceName: string): Origin;\n-\tview(set: ReadonlySet<AtomId>): View;\n-\tviewAt(space: Space, version: number): View;\n+\tview(set: ReadonlySet<AtomId>): ReadView;\n+\tviewAt(space: Space, version: number): ReadView;\n \tspaceOf(agent: AgentState): Space;\n \tapply(entry: Entry): void;\n-\tagentView(agent: AgentState): View;\n+\tagentView(agent: AgentState): ReadView;\n \trecordFile(\n \t\tagent: AgentState,\n-\t\tview: View,\n+\t\tview: ReadView,\n \t\tpath: string,\n \t\ttext: string | null | undefined,\n \t\ttime: number,\n@@ -53,7 +53,7 @@\n export function mergeIdentical(\n \thost: MergeHost,\n \tagent: AgentState,\n-\tbefore: View,\n+\tbefore: ReadView,\n \toldBase: ReadonlySet<AtomId>,\n \toldVersion: number,\n \ttime: number,\n@@ -91,7 +91,7 @@\n \tif ([...involved].some((f) => shown.has(f))) return [];\n \tconst baseView = host.view(oldBase);\n \tconst theirs = host.viewAt(host.spaceOf(agent), agent.base);\n-\tconst textOf = (v: View, path: string): string | null => (v.hasFile(path) ? v.text(path) : null);\n+\tconst textOf = (v: ReadView, path: string): string | null => (v.hasFile(path) ? v.text(path) : null);\n \tconst merged = new Map<string, { text: string | null; mode: Mode; hunks?: Hunk[] }>();\n \tconst notices: MergedLine[] = [];\n \tconst regions: MarkedRegion[] = [];"},{"path":"worker/project/move.ts","added":5,"removed":5,"diff":"--- a/worker/project/move.ts\n+++ b/worker/project/move.ts\n@@ -1,7 +1,7 @@\n // Move a file in the agent's draft. Writes go through MoveHost; today the\n // host is Project.\n \n-import type { EditInput, Hunk, MoveInput, View } from \"../../src/engine/index.ts\";\n+import type { EditInput, Hunk, MoveInput, ReadView } from \"../../src/engine/index.ts\";\n import { checkPath } from \"./path-rules.ts\";\n import { pathKey } from \"./pathkey.ts\";\n import { ProjectError } from \"./project-error.ts\";\n@@ -11,12 +11,12 @@\n export interface MoveHost {\n \tneedInit(): void;\n \treadonly agents: ReadonlyMap<string, AgentState>;\n-\tagentView(agent: AgentState): View;\n-\tsharedView(): View;\n+\tagentView(agent: AgentState): ReadView;\n+\tsharedView(): ReadView;\n \tagent(name: string, entries: Entry[]): AgentState;\n \taddDraft(\n \t\tagent: AgentState,\n-\t\tview: View,\n+\t\tview: ReadView,\n \t\tinput: { edits: readonly EditInput[]; move?: MoveInput },\n \t\ttime: number,\n \t\tmeta: Meta,\n@@ -24,7 +24,7 @@\n \t): void;\n \trecordFile(\n \t\tagent: AgentState,\n-\t\tview: View,\n+\t\tview: ReadView,\n \t\tpath: string,\n \t\ttext: string | null | undefined,\n \t\ttime: number,"},{"path":"worker/project/news.ts","added":2,"removed":2,"diff":"--- a/worker/project/news.ts\n+++ b/worker/project/news.ts\n@@ -1,7 +1,7 @@\n // How news reads: one sentence for each thing an agent should hear, with the key that makes it heard\n // once, and who hears it after an edit, publish or land. Writes (the news entry) stay on Project.\n \n-import { type AtomId, type Graph, isStartNode, parseKey, type View } from \"../../src/engine/index.ts\";\n+import { type AtomId, type Graph, isStartNode, parseKey, type ReadView } from \"../../src/engine/index.ts\";\n import { unionOverlay } from \"../../src/engine/state-source.ts\";\n import { type Origin, type Pair, pairsIn, touchedFiles } from \"./collisions.ts\";\n import { type DefinitionCollision, signature } from \"./definition-rule.ts\";\n@@ -196,7 +196,7 @@\n \tnewerFor(agent: AgentState): ReadonlySet<AtomId>;\n \tspaceOf(agent: AgentState): Space;\n \tsetOf(space: Space): ReadonlySet<AtomId>;\n-\tviewAt(space: Space, version: number): View;\n+\tviewAt(space: Space, version: number): ReadView;\n \torigin(atom: AtomId, spaceName: string): Origin;\n \tcollision(agent: AgentState, pair: Pair): Collision;\n \tdefinitionCollisions(agent: AgentState, newer: ReadonlySet<AtomId>): DefinitionCollision[];"},{"path":"worker/project/notes.ts","added":12,"removed":12,"diff":"--- a/worker/project/notes.ts\n+++ b/worker/project/notes.ts\n@@ -2,7 +2,7 @@\n // reviews which files by avcs.json, the notes list, every agent's start note, and writing or closing\n // a note. Reads go through NoteHost, writes through NoteWriteHost; today the host is Project.\n \n-import type { AtomId, Graph, LineId, View } from \"../../src/engine/index.ts\";\n+import type { AtomId, Graph, LineId, ReadView } from \"../../src/engine/index.ts\";\n import { matchesPattern } from \"./globs.ts\";\n import { type NewsItem, noteClosedItem, noteSaid } from \"./news.ts\";\n import { checkReadPath } from \"./path-rules.ts\";\n@@ -27,11 +27,11 @@\n \treadonly notes: ReadonlyMap<number, NoteRecord>;\n \tinitialized(): boolean;\n \tshared(): Space;\n-\tsharedView(): View;\n-\tspellingIn(view: View, path: string): string;\n-\tviewAt(space: Space, version: number): View;\n-\tagentView(agent: AgentState): View;\n-\tview(set: ReadonlySet<AtomId>): View;\n+\tsharedView(): ReadView;\n+\tspellingIn(view: ReadView, path: string): string;\n+\tviewAt(space: Space, version: number): ReadView;\n+\tagentView(agent: AgentState): ReadView;\n+\tview(set: ReadonlySet<AtomId>): ReadView;\n \tat(space: Space, version: number): ReadonlySet<AtomId>;\n \tliveNote(agent: AgentState): Starting | undefined;\n }\n@@ -43,9 +43,9 @@\n \treadonly changes: ReadonlyMap<number, ChangeRecord>;\n \treadonly graph: Graph;\n \tlastNote(): number;\n-\tagentView(agent: AgentState): View;\n-\tviewAtVersion(version: number): View;\n-\tsharedView(): View;\n+\tagentView(agent: AgentState): ReadView;\n+\tviewAtVersion(version: number): ReadView;\n+\tsharedView(): ReadView;\n \tchangeOfLines(lines: readonly LineId[]): number | undefined;\n \tapply(entry: Entry): void;\n \tflush(entries: Entry[]): void;\n@@ -99,7 +99,7 @@\n }\n \n /** A note as reads show it, from the view its lines live in (undefined when no space holds them any more). */\n-export function noteAnswerIn(n: NoteRecord, view: View | undefined): NoteAnswer {\n+export function noteAnswerIn(n: NoteRecord, view: ReadView | undefined): NoteAnswer {\n \t// Where the lines are now, found by their ids: a move (#49) can have taken them to another file.\n \tlet lines: [number, number] | null = null;\n \tlet file = n.file;\n@@ -138,7 +138,7 @@\n  * published into; else their author's draft, where it works now or where it\n  * parked it. Undefined when no space holds them any more (a discarded draft).\n  */\n-export function noteView(host: NoteHost, n: NoteRecord): View | undefined {\n+export function noteView(host: NoteHost, n: NoteRecord): ReadView | undefined {\n \tconst writers = new Set(n.lines.map((l) => host.graph.lineAtom(l)).filter((a): a is AtomId => a !== undefined));\n \tconst holds = (set: ReadonlySet<AtomId> | readonly AtomId[]) =>\n \t\t[...writers].some((a) => (set instanceof Set ? set.has(a) : (set as readonly AtomId[]).includes(a)));\n@@ -218,7 +218,7 @@\n \t\t\tthrow new ProjectError(\"bad-request\", \"a note needs {file, from, to}, or {reply}\");\n \t\tfile = body.file;\n \t\tcheckReadPath(file);\n-\t\tlet view: View;\n+\t\tlet view: ReadView;\n \t\tif (typeof body.of === \"string\") {\n \t\t\tconst of = host.agents.get(body.of);\n \t\t\tif (!of) throw new ProjectError(\"not-found\", `there is no agent ${JSON.stringify(body.of)}`);"},{"path":"worker/project/overlaps.ts","added":2,"removed":2,"diff":"--- a/worker/project/overlaps.ts\n+++ b/worker/project/overlaps.ts\n@@ -2,7 +2,7 @@\n // the news when a draft first touches one. Reads and news writes go through\n // OverlapHost; today the host is Project. overlapsOf is the pure match.\n \n-import { type AtomId, type Graph, isStartNode, type View } from \"../../src/engine/index.ts\";\n+import { type AtomId, type Graph, isStartNode, type ReadView } from \"../../src/engine/index.ts\";\n import { matchesPattern, pathsInText, patternsMeet } from \"./globs.ts\";\n import { type NewsItem, overlapItems } from \"./news.ts\";\n import type { AgentState, Entry, Overlap, Starting } from \"./project-types.ts\";\n@@ -22,7 +22,7 @@\n export interface OverlapHost {\n \treadonly graph: Graph;\n \treadonly agents: ReadonlyMap<string, AgentState>;\n-\tagentView(agent: AgentState): View;\n+\tagentView(agent: AgentState): ReadView;\n \tdraft(agent: AgentState): readonly AtomId[];\n \t/** draftFiles below, kept per agent by the host. */\n \tdraftFiles(agent: AgentState): Set<string>;"},{"path":"worker/project/pathindex.ts","added":8,"removed":7,"diff":"--- a/worker/project/pathindex.ts\n+++ b/worker/project/pathindex.ts\n@@ -1,8 +1,9 @@\n+import { View } from \"../../src/engine/index.ts\";\n // Each version's files and shape, and each path's history in a space (#41; #46, disk-first 1). Built the first\n // time it's asked for and kept up as versions land; a version's files are also kept in the shapes table, so a\n // load needn't lay them out again.\n \n-import { type AtomId, type Graph, type LineId, View } from \"../../src/engine/index.ts\";\n+import type { AtomId, Graph, LineId, ReadView } from \"../../src/engine/index.ts\";\n import {\n \tdiffers,\n \ttype LastChange,\n@@ -17,8 +18,8 @@\n export interface PathIndexDeps {\n \treadonly graph: Graph;\n \tat(space: Space, version: number): ReadonlySet<AtomId>;\n-\tviewAt(space: Space, version: number): View;\n-\ttouchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;\n+\tviewAt(space: Space, version: number): ReadView;\n+\ttouchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>;\n \treadonly shapes: ProjectOptions[\"shapes\"];\n }\n \n@@ -44,7 +45,7 @@\n \treadonly #pathIndex = new WeakMap<Space, { upTo: number; paths: Map<string, PathLife> }>();\n \n \t/** The files a version changed. `views` holds views by version, so a run of versions builds each once. */\n-\tversionFiles(space: Space, version: number, views = new Map<number, View>()): string[] {\n+\tversionFiles(space: Space, version: number, views = new Map<number, ReadView>()): string[] {\n \t\tlet cache = this.#filesCache.get(space);\n \t\tif (!cache) this.#filesCache.set(space, (cache = new Map()));\n \t\tconst known = cache.get(version);\n@@ -53,7 +54,7 @@\n \t\tif (kept) return kept;\n \t\tconst shapes = this.#shapeCache.get(space)!;\n \t\tconst p = space.versions[version]!;\n-\t\tconst viewAt = (v: number): View => {\n+\t\tconst viewAt = (v: number): ReadView => {\n \t\t\tlet view = views.get(v);\n \t\t\tif (!view) views.set(v, (view = v < 0 ? new View(this.#deps.graph, []) : this.#deps.viewAt(space, v)));\n \t\t\treturn view;\n@@ -107,7 +108,7 @@\n \t}\n \n \t/** A version's files made and taken out, and moves (#41). */\n-\tversionShape(space: Space, version: number, views?: Map<number, View>): VersionShape {\n+\tversionShape(space: Space, version: number, views?: Map<number, ReadView>): VersionShape {\n \t\tconst known = this.#shapeCache.get(space)?.get(version);\n \t\tif (known) return known;\n \t\tthis.#filesCache.get(space)?.delete(version);\n@@ -124,7 +125,7 @@\n \tpathsOf(space: Space): Map<string, PathLife> {\n \t\tlet index = this.#pathIndex.get(space);\n \t\tif (!index) this.#pathIndex.set(space, (index = { upTo: -1, paths: new Map() }));\n-\t\tconst views = new Map<number, View>();\n+\t\tconst views = new Map<number, ReadView>();\n \t\t// Shared's sets grow version by version, so walk them forward rather than build each from the\n \t\t// start; the views stay out of the cache, which they would only push other views from. A version\n \t\t// whose files are kept (#41) needs no views at all."},{"path":"worker/project/project-status.ts","added":3,"removed":3,"diff":"--- a/worker/project/project-status.ts\n+++ b/worker/project/project-status.ts\n@@ -1,7 +1,7 @@\n // What the project looks like now: status, the paths in a folder, and the labels. They read through\n // SnapshotHost; today the host is the project in memory.\n \n-import type { AtomId, View } from \"../../src/engine/index.ts\";\n+import type { AtomId, ReadView } from \"../../src/engine/index.ts\";\n import { ProjectError } from \"./project-error.ts\";\n import { countRefusals, type projectFileIn } from \"./project-helpers.ts\";\n import type {\n@@ -39,8 +39,8 @@\n \tsetOf(space: Space): ReadonlySet<AtomId>;\n \tspaceNamed(name: string | null): Space;\n \tcheckVersion(space: Space, version: number): void;\n-\tviewAt(space: Space, version: number): View;\n-\tagentView(agent: AgentState): View;\n+\tviewAt(space: Space, version: number): ReadView;\n+\tagentView(agent: AgentState): ReadView;\n \tversion(): number;\n \t/** Shared's project file (224), or undefined before init or without one. */\n \tprojectFile(): ReturnType<typeof projectFileIn>;"},{"path":"worker/project/project-types.ts","added":4,"removed":1,"diff":"--- a/worker/project/project-types.ts\n+++ b/worker/project/project-types.ts\n@@ -1,6 +1,7 @@\n-import type { Atom, AtomId, LineId } from \"../../src/engine/index.ts\";\n+import type { Atom, AtomId, Graph, LineId } from \"../../src/engine/index.ts\";\n import type { GraphStateStorage } from \"../../src/engine/state-source.ts\";\n import type { Kept, MarkedRegion } from \"./markers.ts\";\n+import type { ReadViewProvider } from \"./views.ts\";\n /** Whole files: path -> text, or null for a deleted file. */\n export type Files = Record<string, string | null>;\n \n@@ -566,6 +567,8 @@\n \n /** What the project needs from the store of binary files' bytes. */\n export interface ProjectOptions {\n+\t/** Private experimental reader route; never falls back for unsupported membership. */\n+\treadViewProvider?: (graph: Graph) => ReadViewProvider;\n \t/**\n \t * Writer indexes for a fresh project or adoption into an empty namespace.\n \t * The host must wrap each operation and canonical log append in the same"},{"path":"worker/project/project.ts","added":37,"removed":18,"diff":"--- a/worker/project/project.ts\n+++ b/worker/project/project.ts\n@@ -12,7 +12,7 @@\n // agents publish into under the same rules, and that lands in shared as one\n // unit. Every agent works in one space at a time.\n \n-import { type Atom, type AtomId, EngineError, Graph, type LineId, type View } from \"../../src/engine/index.ts\";\n+import { type Atom, type AtomId, EngineError, Graph, type LineId, type ReadView } from \"../../src/engine/index.ts\";\n import {\n \tCachedStateStorage,\n \tdifferenceSet,\n@@ -406,7 +406,7 @@\n \t\t\t: entryAt\n \t\t\t\t? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })\n \t\t\t\t: new Graph();\n-\t\tthis.#views = new ViewCache(this.#graph);\n+\t\tthis.#views = new ViewCache(this.#graph, options.readViewProvider);\n \t\tthis.#paths = new PathIndex({\n \t\t\tgraph: this.#graph,\n \t\t\tat: (space, version) => this.#at(space, version),\n@@ -606,8 +606,8 @@\n \t\treturn modesOf(this.#sharedView());\n \t}\n \n-\t/** Shared as a View, for reading lines (blame, why). Don't hold on to it across calls. */\n-\tsharedView(): View {\n+\t/** Shared as a ReadView, for reading lines (blame, why). Don't hold on to it across calls. */\n+\tsharedView(): ReadView {\n \t\treturn this.#sharedView();\n \t}\n \n@@ -621,7 +621,7 @@\n \t * The view is laid out on first use: where asks every agent, most have no changes, and a big project has more\n \t * agents than the view cache holds, so building every view cost each call about 0.7 s.\n \t */\n-\tdraftOf(agentName: string): { atoms: AtomId[]; readonly view: View } | undefined {\n+\tdraftOf(agentName: string): { atoms: AtomId[]; readonly view: ReadView } | undefined {\n \t\tconst agent = this.#agents.get(agentName);\n \t\tif (!agent) return undefined;\n \t\tconst view = () => this.#agentView(agent);\n@@ -757,7 +757,7 @@\n \t * last makes it one-way: a file kept whole stays whole while it exists,\n \t * even if it shrinks or the rule changes, so it never flips back and forth.\n \t */\n-\t#isWhole(path: string, length: number, view: View | undefined, rules: readonly string[]): boolean {\n+\t#isWhole(path: string, length: number, view: ReadView | undefined, rules: readonly string[]): boolean {\n \t\treturn hostedIsWhole(this.#wholeHost, path, length, view, rules);\n \t}\n \n@@ -765,7 +765,7 @@\n \t#wholeOut(\n \t\tfiles: Readonly<Record<string, string | null>>,\n \t\tblobs: Readonly<Record<string, string>>,\n-\t\tview: View | undefined,\n+\t\tview: ReadView | undefined,\n \t\tconfig?: string,\n \t): { files: Record<string, string | null>; blobs: Record<string, string> } {\n \t\treturn hostedWholeOut(this.#wholeHost, files, blobs, view, config);\n@@ -1085,7 +1085,7 @@\n \t */\n \t#mergeIdentical(\n \t\tagent: AgentState,\n-\t\tbefore: View,\n+\t\tbefore: ReadView,\n \t\toldBase: ReadonlySet<AtomId>,\n \t\toldVersion: number,\n \t\ttime: number,\n@@ -1172,7 +1172,7 @@\n \t}\n \n \t/** The collided changes behind each block whose marker lines `atom` deletes (#11). */\n-\t#markersSettled(agent: AgentState, view: View, atom: Atom): AtomId[] {\n+\t#markersSettled(agent: AgentState, view: ReadView, atom: Atom): AtomId[] {\n \t\treturn hostedMarkersSettled(this.#markerHost, agent, view, atom);\n \t}\n \n@@ -1418,7 +1418,7 @@\n \t * the one file ever in the view it matches, for a file since taken out.\n \t * A path that matches two files is answered exactly.\n \t */\n-\tspellingIn(view: View, path: string): string {\n+\tspellingIn(view: ReadView, path: string): string {\n \t\tif (view.hasFile(path)) return path;\n \t\tconst key = pathKey(path);\n \t\tconst live = view.knownPaths().filter((p) => pathKey(p) === key && view.hasFile(p));\n@@ -1660,7 +1660,7 @@\n \t\treturn versionCompare(this.#logHost, ...args);\n \t}\n \n-\t/** A version of shared (or of a named draft) as a View (version-log.ts). */\n+\t/** A version of shared (or of a named draft) as a ReadView (version-log.ts). */\n \tviewAt(...args: Tail<Parameters<typeof versionViewAt>>): ReturnType<typeof versionViewAt> {\n \t\treturn versionViewAt(this.#logHost, ...args);\n \t}\n@@ -1725,6 +1725,16 @@\n \t\tthis.#movesHost ??= {\n \t\t\tgraph: this.#graph,\n \t\t\tdraft: (agent) => this.#unqueuedDraft(agent),\n+\t\t\tbeforeDraft: (agent, draft) => {\n+\t\t\t\tconst base = this.#at(this.#spaceOf(agent), agent.base);\n+\t\t\t\tif (draft.some((id) => base.has(id)))\n+\t\t\t\t\treturn this.#view(differenceSet(this.#agentView(agent).set, new StableOverlaySet(draft)));\n+\t\t\t\tconst removed = new Set(draft),\n+\t\t\t\t\tkept = agent.mine.filter((id) => !removed.has(id));\n+\t\t\t\treturn kept.length === 0\n+\t\t\t\t\t? this.#viewAt(this.#spaceOf(agent), agent.base)\n+\t\t\t\t\t: this.#viewKeyed(`a ${agent.space}@${agent.base}+${kept.join(\",\")}`, () => unionOverlay(base, kept));\n+\t\t\t},\n \t\t\tagentView: (agent) => this.#agentView(agent),\n \t\t\tview: (set) => this.#view(set),\n \t\t\tapply: (entry) => this.#apply(entry),\n@@ -1923,6 +1933,10 @@\n \t\t\t\tthis.#enqueue(agent, message, time, draft, resolves, entries),\n \t\t\tview: (set) => this.#view(set),\n \t\t\trequireClosed: (tie, union) => this.#requireClosed(tie, union),\n+\t\t\tspaceOverlay: (space, atoms) =>\n+\t\t\t\tthis.#viewKeyed(`a ${space.name}@${last(space)}+${atoms.join(\",\")}`, () =>\n+\t\t\t\t\tunionOverlay(this.#setOf(space), atoms),\n+\t\t\t\t),\n \t\t\tnewerFor: (agent) => this.#newerFor(agent),\n \t\t\tcurrentChange: (agent, time) => this.#currentChange(agent, time),\n \t\t\tapply: (entry) => this.#apply(entry),\n@@ -2189,6 +2203,10 @@\n \t\t\tsetOf: (space) => this.#setOf(space),\n \t\t\tview: (set) => this.#view(set),\n \t\t\tsharedView: () => this.#sharedView(),\n+\t\t\tsharedOverlay: (atoms) =>\n+\t\t\t\tthis.#viewKeyed(`a @${last(this.#shared)}+${atoms.join(\",\")}`, () =>\n+\t\t\t\t\tunionOverlay(this.#setOf(this.#shared), atoms),\n+\t\t\t\t),\n \t\t\ttouchedFiles: (ids, views) => this.#touchedFiles(ids, views),\n \t\t};\n \t\treturn this.#checkClashes;\n@@ -2475,7 +2493,7 @@\n \t\treturn new Set([...this.#at(this.#spaceOf(agent), agent.base), ...agent.mine]);\n \t}\n \n-\t#agentView(agent: AgentState): View {\n+\t#agentView(agent: AgentState): ReadView {\n \t\treturn this.#viewKeyed(this.#agentViewKey(agent), () => {\n \t\t\tconst base = this.#at(this.#spaceOf(agent), agent.base);\n \t\t\treturn base instanceof StableSet\n@@ -2493,21 +2511,22 @@\n \t}\n \n \t/** A space at a version: published versions never change, so the key is just their names (#46). */\n-\t#viewAt(space: Space, version: number): View {\n+\t#viewAt(space: Space, version: number): ReadView {\n \t\treturn this.#viewKeyed(`v ${space.name}@${version}`, () => this.#at(space, version));\n \t}\n \n-\t#sharedView(): View {\n+\t#sharedView(): ReadView {\n \t\treturn this.#viewAt(this.#shared, last(this.#shared));\n \t}\n \n \t/** A view of a set, cached by the set's exact contents (views.ts). */\n-\t#view(set: ReadonlySet<AtomId>): View {\n+\t#view(set: ReadonlySet<AtomId>): ReadView {\n+\t\tthis.#views.assertUnkeyedAllowed();\n \t\treturn this.#views.view(this.#closed(set));\n \t}\n \n \t/** A view cached under `key` (views.ts). */\n-\t#viewKeyed(key: string, set: () => ReadonlySet<AtomId>): View {\n+\t#viewKeyed(key: string, set: () => ReadonlySet<AtomId>): ReadView {\n \t\treturn this.#views.keyed(key, () => this.#closed(set()));\n \t}\n \n@@ -2672,7 +2691,7 @@\n \t\t);\n \t}\n \n-\t#describe(pair: Pair, yoursView: View, theirsView: View, spaceName: string): Collision {\n+\t#describe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision {\n \t\treturn describePair(\n \t\t\tthis.#graph,\n \t\t\t(atom, space) => this.#origin(atom, space),\n@@ -2683,7 +2702,7 @@\n \t\t);\n \t}\n \n-\t#touchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string> {\n+\t#touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string> {\n \t\treturn touchedFiles(this.#graph, ids, views);\n \t}\n "},{"path":"worker/project/projection-provider.ts","added":80,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/projection-provider.ts\n@@ -0,0 +1,80 @@\n+import { ExperimentalMarkerProjection } from \"../../src/engine/experimental/projection-marker.ts\";\n+import { ProjectionReader } from \"../../src/engine/experimental/projection-reader.ts\";\n+import type { ProjectionHandle, ProjectionIdentity } from \"../../src/engine/experimental/projection-root.ts\";\n+import { ProjectionSnapshots } from \"../../src/engine/experimental/projection-snapshots.ts\";\n+import type { Graph } from \"../../src/engine/graph.ts\";\n+import type { GraphStateStorage } from \"../../src/engine/state-source.ts\";\n+import type { Published } from \"./spaces.ts\";\n+\n+/** Internal host contract; canonical proofs and version authority are independent of saved handles. */\n+export interface ProjectionReadBinding {\n+\treadonly graph: Graph;\n+\treadonly context: Pick<ProjectionIdentity, \"database\" | \"namespace\" | \"registry\" | \"defaultFile\">;\n+\treadonly sourceGeneration: number;\n+\tsourceLength(): number;\n+\tprefixDigest(length: number): string | undefined;\n+\tversion(): number;\n+\tcommitted(): { version: number; handle: ProjectionHandle };\n+\tat(version: number): ProjectionHandle | undefined;\n+\tdelta(version: number): Published | undefined;\n+\t/** Read-through overlay owned and cleaned by the current transaction. */\n+\tallocate(): GraphStateStorage;\n+\t/** Checks this exact transaction, graph revision and verified source binding. */\n+\tguard(): () => void;\n+}\n+\n+/** Explicit private route. Unsupported memberships never fall back to historical View construction. */\n+export function projectedReader(binding: ProjectionReadBinding, key: string): ProjectionReader {\n+\tconst scopeGuard = binding.guard();\n+\tscopeGuard();\n+\tconst sourceLength = binding.sourceLength(),\n+\t\tsourceGeneration = binding.sourceGeneration;\n+\tconst sourceDigest = binding.prefixDigest(sourceLength);\n+\tif (sourceDigest === undefined) throw Error(\"missing verified current canonical prefix\");\n+\tconst assertLive = () => {\n+\t\tscopeGuard();\n+\t\tif (\n+\t\t\tbinding.sourceGeneration !== sourceGeneration ||\n+\t\t\tbinding.sourceLength() !== sourceLength ||\n+\t\t\tbinding.prefixDigest(sourceLength) !== sourceDigest\n+\t\t)\n+\t\t\tthrow Error(\"expired projection source binding\");\n+\t};\n+\tassertLive();\n+\tconst match = /^(v|a) @(0|[1-9]\\d*)(?:\\+(.+))?$/.exec(key);\n+\tif (!match || (match[1] === \"v\" && match[3])) throw Error(`unsupported projection key: ${key}`);\n+\tconst version = Number(match[2]);\n+\tif (!Number.isSafeInteger(version) || version > binding.version())\n+\t\tthrow Error(\"projection version outside authority\");\n+\tconst exact = binding.at(version);\n+\tconst anchor = exact ? { version, handle: exact } : binding.committed();\n+\tif (!Number.isSafeInteger(anchor.version) || anchor.version < 0 || (!exact && version <= anchor.version))\n+\t\tthrow Error(\"missing historical version projection\");\n+\tconst length = anchor.handle.identity.sourceLength;\n+\tif (!Number.isSafeInteger(length) || length < 0 || length > binding.sourceLength())\n+\t\tthrow Error(\"projection source outside authority\");\n+\tconst digest = binding.prefixDigest(length);\n+\tif (digest === undefined) throw Error(\"missing verified canonical prefix\");\n+\tconst storage = binding.allocate();\n+\tconst context = { ...binding.context };\n+\tconst adapter = new ExperimentalMarkerProjection(storage, binding.graph, context.defaultFile, context.namespace);\n+\tconst snapshots = new ProjectionSnapshots(storage, adapter, context);\n+\tlet state = snapshots.load(anchor.handle, {\n+\t\t...context,\n+\t\tsourceGeneration: binding.sourceGeneration,\n+\t\tsourceLength: length,\n+\t\tsourceDigest: digest,\n+\t\tmembership: String(anchor.version),\n+\t});\n+\tfor (let next = anchor.version + 1; next <= version; next++) {\n+\t\tconst delta = binding.delta(next);\n+\t\tif (!delta || delta.version !== next) throw Error(\"missing transaction-local version delta\");\n+\t\tfor (const atom of [...(delta.dropped ?? [])].map((id) => binding.graph.atom(id)).sort((a, b) => b.seq - a.seq))\n+\t\t\tstate = adapter.removeAtom(state, atom);\n+\t\tfor (const atom of delta.atoms.map((id) => binding.graph.atom(id)).sort((a, b) => a.seq - b.seq))\n+\t\t\tstate = adapter.apply(state, atom);\n+\t}\n+\tfor (const id of match[3]?.split(\",\") ?? []) state = adapter.apply(state, binding.graph.atom(id));\n+\tassertLive();\n+\treturn new ProjectionReader(adapter, state, assertLive);\n+}"},{"path":"worker/project/publish.ts","added":7,"removed":5,"diff":"--- a/worker/project/publish.ts\n+++ b/worker/project/publish.ts\n@@ -1,7 +1,7 @@\n // Add the agent's draft to its space. Writes go through PublishHost; today\n // the host is Project. Ingest calls publishDraft, the inner step.\n \n-import { type AtomId, buildAtom, type Hunk, joinLines, type View } from \"../../src/engine/index.ts\";\n+import { type AtomId, buildAtom, type Hunk, joinLines, type ReadView } from \"../../src/engine/index.ts\";\n import { differenceSet, unionOverlay } from \"../../src/engine/state-source.ts\";\n import type { Pair } from \"./collisions.ts\";\n import type { DefinitionCollision } from \"./definition-rule.ts\";\n@@ -23,10 +23,10 @@\n \tstrandedFiles(draft: readonly AtomId[], set: ReadonlySet<AtomId>): string[];\n \tsetOf(space: Space): ReadonlySet<AtomId>;\n \tmarkedFiles(agent: AgentState): string[];\n-\tagentView(agent: AgentState): View;\n+\tagentView(agent: AgentState): ReadView;\n \trecordFile(\n \t\tagent: AgentState,\n-\t\tview: View,\n+\t\tview: ReadView,\n \t\tpath: string,\n \t\ttext: string | null | undefined,\n \t\ttime: number,\n@@ -58,7 +58,8 @@\n \t\tresolves: readonly AtomId[],\n \t\tentries: Entry[],\n \t): PublishAnswer;\n-\tview(set: ReadonlySet<AtomId>): View;\n+\tview(set: ReadonlySet<AtomId>): ReadView;\n+\tspaceOverlay?(space: Space, atoms: readonly AtomId[]): ReadView;\n \trequireClosed(tie: { deps: readonly AtomId[] }, union: ReadonlySet<AtomId>): void;\n \tnewerFor(agent: AgentState): ReadonlySet<AtomId>;\n \tcurrentChange(agent: AgentState, time: number): number | undefined;\n@@ -155,7 +156,8 @@\n \tconst resolves = [...new Set(seen.flatMap((p) => [p.yours, p.theirs]))];\n \tif (space.name === SHARED && !direct && host.queueOn())\n \t\treturn host.enqueue(agent, message, time, draft, resolves, entries);\n-\tconst tie = buildAtom(host.view(union), { author: agent.name, message, time, needs: draft, resolves });\n+\tconst candidate = host.spaceOverlay ? host.spaceOverlay(space, draft) : host.view(union);\n+\tconst tie = buildAtom(candidate, { author: agent.name, message, time, needs: draft, resolves });\n \thost.requireClosed(tie, union);\n \tconst version = last(space) + 1;\n \tconst othersPublished = space.versions.slice(agent.base + 1).some((p) => p.agent !== agent.name);"},{"path":"worker/project/queue.ts","added":6,"removed":6,"diff":"--- a/worker/project/queue.ts\n+++ b/worker/project/queue.ts\n@@ -1,7 +1,7 @@\n // The merge queue: publishes to shared waiting for their batch's check.\n // Writes go through QueueHost; today the host is Project.\n \n-import { type AtomId, buildAtom, type Graph, type View } from \"../../src/engine/index.ts\";\n+import { type AtomId, buildAtom, type Graph, type ReadView } from \"../../src/engine/index.ts\";\n import type { Pair } from \"./collisions.ts\";\n import { definedTwice } from \"./definitions.ts\";\n import { keptOf, lostLines } from \"./markers.ts\";\n@@ -27,7 +27,7 @@\n export interface QueueHost {\n \treadonly graph: Graph;\n \tcheckerReady(): boolean;\n-\tsharedView(): View;\n+\tsharedView(): ReadView;\n \tqueued(): readonly QueuedPublish[];\n \tqueuedId(): number;\n \tcheckingHas(id: number): boolean;\n@@ -36,12 +36,12 @@\n \tneedInit(): void;\n \tshared(): Space;\n \tsetOf(space: Space): ReadonlySet<AtomId>;\n-\tview(set: ReadonlySet<AtomId>): View;\n+\tview(set: ReadonlySet<AtomId>): ReadView;\n \tagentSet(agent: AgentState): Set<AtomId>;\n-\tagentView(agent: AgentState): View;\n+\tagentView(agent: AgentState): ReadView;\n \tpairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[];\n-\tdescribe(pair: Pair, yoursView: View, theirsView: View, spaceName: string): Collision;\n-\ttouchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;\n+\tdescribe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision;\n+\ttouchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>;\n \trefuse(\n \t\tagent: AgentState,\n \t\tspace: Space,"},{"path":"worker/project/record-file.ts","added":3,"removed":3,"diff":"--- a/worker/project/record-file.ts\n+++ b/worker/project/record-file.ts\n@@ -7,9 +7,9 @@\n \tdiffLines,\n \ttype EditInput,\n \ttype Hunk,\n+\ttype ReadView,\n \ttype SpliceEdit,\n \tsplitLines,\n-\ttype View,\n } from \"../../src/engine/index.ts\";\n import type { AgentState, Entry, Meta, Mode } from \"./project-types.ts\";\n \n@@ -17,7 +17,7 @@\n export interface RecordFileHost {\n \taddDraft(\n \t\tagent: AgentState,\n-\t\tview: View,\n+\t\tview: ReadView,\n \t\tinput: { edits: readonly EditInput[]; attrs?: readonly AttrSet[] },\n \t\ttime: number,\n \t\tmeta: Meta,\n@@ -34,7 +34,7 @@\n export function recordFile(\n \thost: RecordFileHost,\n \tagent: AgentState,\n-\tview: View,\n+\tview: ReadView,\n \tpath: string,\n \ttext: string | null | undefined,\n \ttime: number,"},{"path":"worker/project/record.ts","added":5,"removed":5,"diff":"--- a/worker/project/record.ts\n+++ b/worker/project/record.ts\n@@ -1,7 +1,7 @@\n // Whole files as the agent's folder has them. Writes go through RecordHost;\n // today the host is Project.\n \n-import { canonicalText, type Hunk, type View } from \"../../src/engine/index.ts\";\n+import { canonicalText, type Hunk, type ReadView } from \"../../src/engine/index.ts\";\n import { checkPath } from \"./path-rules.ts\";\n import { isComposed, pathKey } from \"./pathkey.ts\";\n import { ProjectError } from \"./project-error.ts\";\n@@ -24,12 +24,12 @@\n \treadonly agents: ReadonlyMap<string, AgentState>;\n \treadonly whole: ProjectOptions[\"whole\"];\n \tinitialized(): boolean;\n-\tagentView(agent: AgentState): View;\n-\tsharedView(): View;\n+\tagentView(agent: AgentState): ReadView;\n+\tsharedView(): ReadView;\n \twholeOut(\n \t\tfiles: Readonly<Record<string, string | null>>,\n \t\tblobs: Readonly<Record<string, string>>,\n-\t\tview: View | undefined,\n+\t\tview: ReadView | undefined,\n \t\tconfig?: string,\n \t): { files: Record<string, string | null>; blobs: Record<string, string> };\n \tcheckBlobs(blobs: unknown, files: object): Record<string, string>;\n@@ -37,7 +37,7 @@\n \tdraftFiles(agent: AgentState): Set<string>;\n \trecordFile(\n \t\tagent: AgentState,\n-\t\tview: View,\n+\t\tview: ReadView,\n \t\tpath: string,\n \t\ttext: string | null | undefined,\n \t\ttime: number,"},{"path":"worker/project/restore.ts","added":5,"removed":5,"diff":"--- a/worker/project/restore.ts\n+++ b/worker/project/restore.ts\n@@ -1,7 +1,7 @@\n // Discard unpublished changes to some files, like git restore. Writes go through RestoreHost;\n // today the host is Project.\n \n-import type { AtomId, Graph, Hunk, View } from \"../../src/engine/index.ts\";\n+import type { AtomId, Graph, Hunk, ReadView } from \"../../src/engine/index.ts\";\n import { checkReadPath } from \"./path-rules.ts\";\n import { ProjectError } from \"./project-error.ts\";\n import type { AgentState, Blobs, Entry, Files, Meta, Mode, Modes, RestoreAnswer } from \"./project-types.ts\";\n@@ -11,14 +11,14 @@\n \treadonly graph: Graph;\n \tagent(name: string, entries: Entry[]): AgentState;\n \tdraft(agent: AgentState): AtomId[];\n-\ttouchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;\n+\ttouchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>;\n \tapply(entry: Entry): void;\n-\tview(set: ReadonlySet<AtomId>): View;\n+\tview(set: ReadonlySet<AtomId>): ReadView;\n \tagentSet(agent: AgentState): Set<AtomId>;\n-\tagentView(agent: AgentState): View;\n+\tagentView(agent: AgentState): ReadView;\n \trecordFile(\n \t\tagent: AgentState,\n-\t\tview: View,\n+\t\tview: ReadView,\n \t\tpath: string,\n \t\ttext: string | null | undefined,\n \t\ttime: number,"},{"path":"worker/project/spelling.ts","added":3,"removed":3,"diff":"--- a/worker/project/spelling.ts\n+++ b/worker/project/spelling.ts\n@@ -2,7 +2,7 @@\n // would make two spellings of one name live at once, and which spelling a\n // path has in a view. Plain functions of views; the project calls them.\n \n-import type { View } from \"../../src/engine/index.ts\";\n+import type { ReadView } from \"../../src/engine/index.ts\";\n import { pathKey } from \"./pathkey.ts\";\n \n /**\n@@ -14,7 +14,7 @@\n  * clash shared already holds isn't charged to this work. The answer is the\n  * refusal's reason, or undefined.\n  */\n-export function clashIn(view: View, touched: Iterable<string>, now: View): string | undefined {\n+export function clashIn(view: ReadView, touched: Iterable<string>, now: ReadView): string | undefined {\n \tconst byKey = new Map<string, string[]>();\n \tfor (const p of view.knownPaths()) {\n \t\tconst k = pathKey(p);\n@@ -67,7 +67,7 @@\n }\n \n /** The spelling a path has in this view: itself, or the one existing file it matches by pathKey (case and Unicode form ignored). */\n-export function spellingOf(view: View, path: string): string {\n+export function spellingOf(view: ReadView, path: string): string {\n \tif (view.hasFile(path)) return path;\n \tconst key = pathKey(path);\n \t// Known paths first, by key, then only those laid out (#46)."},{"path":"worker/project/switch-to.ts","added":4,"removed":3,"diff":"--- a/worker/project/switch-to.ts\n+++ b/worker/project/switch-to.ts\n@@ -1,7 +1,8 @@\n+import { View } from \"../../src/engine/index.ts\";\n // Move an agent to a named draft, or back to shared. Writes go through\n // SwitchHost; today the host is Project.\n \n-import { type AtomId, type Graph, View } from \"../../src/engine/index.ts\";\n+import type { AtomId, Graph, ReadView } from \"../../src/engine/index.ts\";\n import { ProjectError } from \"./project-error.ts\";\n import { checkDraftName } from \"./project-helpers.ts\";\n import type { AgentState, Entry, SwitchAnswer, SyncAnswer } from \"./project-types.ts\";\n@@ -12,13 +13,13 @@\n \tagent(name: string, entries: Entry[]): AgentState;\n \tflush(entries: Entry[]): void;\n \treadonly spaces: ReadonlyMap<string, Space>;\n-\tagentView(agent: AgentState): View;\n+\tagentView(agent: AgentState): ReadView;\n \treadonly graph: Graph;\n \tversion(): number;\n \tapply(entry: Entry): void;\n \tdraft(agent: AgentState): readonly AtomId[];\n \tsetOf(space: Space): ReadonlySet<AtomId>;\n-\tchangesSince(agent: AgentState, before: View): SyncAnswer;\n+\tchangesSince(agent: AgentState, before: ReadView): SyncAnswer;\n }\n \n /**"},{"path":"worker/project/sync.ts","added":5,"removed":4,"diff":"--- a/worker/project/sync.ts\n+++ b/worker/project/sync.ts\n@@ -1,7 +1,8 @@\n+import { View } from \"../../src/engine/index.ts\";\n // Move the agent's base to its space's newest version. Writes go through\n // SyncHost; today the host is Project.\n \n-import { type AtomId, type Graph, View } from \"../../src/engine/index.ts\";\n+import type { AtomId, Graph, ReadView } from \"../../src/engine/index.ts\";\n import { ProjectError } from \"./project-error.ts\";\n import type { AgentState, Entry, MergedLine, SyncAnswer } from \"./project-types.ts\";\n import { last, SHARED, type Space } from \"./spaces.ts\";\n@@ -12,7 +13,7 @@\n \treadonly labels: ReadonlyMap<string, readonly number[]>;\n \tagent(name: string, entries: Entry[]): AgentState;\n \tspaceOf(agent: AgentState): Space;\n-\tagentView(agent: AgentState): View;\n+\tagentView(agent: AgentState): ReadView;\n \tat(space: Space, version: number): ReadonlySet<AtomId>;\n \tdraft(agent: AgentState): AtomId[];\n \tstrandedFiles(draft: readonly AtomId[], set: ReadonlySet<AtomId>): string[];\n@@ -20,13 +21,13 @@\n \tflush(entries: Entry[]): void;\n \tmergeIdentical(\n \t\tagent: AgentState,\n-\t\tbefore: View,\n+\t\tbefore: ReadView,\n \t\toldBase: ReadonlySet<AtomId>,\n \t\toldVersion: number,\n \t\ttime: number,\n \t\tentries: Entry[],\n \t): MergedLine[];\n-\tchangesSince(agent: AgentState, before: View): SyncAnswer;\n+\tchangesSince(agent: AgentState, before: ReadView): SyncAnswer;\n }\n \n /**"},{"path":"worker/project/test/projection-integration.test.ts","added":791,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/test/projection-integration.test.ts\n@@ -0,0 +1,791 @@\n+import assert from \"node:assert/strict\";\n+import { createHash } from \"node:crypto\";\n+import { mkdtempSync } from \"node:fs\";\n+import { tmpdir } from \"node:os\";\n+import { join } from \"node:path\";\n+import { performance } from \"node:perf_hooks\";\n+import { test } from \"node:test\";\n+import { ExperimentalMarkerProjection } from \"../../../src/engine/experimental/projection-marker.ts\";\n+import { ProjectionOverlayStorage } from \"../../../src/engine/experimental/projection-overlay-storage.ts\";\n+import { ProjectionReadScope } from \"../../../src/engine/experimental/projection-read-scope.ts\";\n+import { ProjectionReader } from \"../../../src/engine/experimental/projection-reader.ts\";\n+import type { ProjectionHandle, ProjectionIdentity } from \"../../../src/engine/experimental/projection-root.ts\";\n+import { ProjectionSnapshots } from \"../../../src/engine/experimental/projection-snapshots.ts\";\n+import type { Graph } from \"../../../src/engine/graph.ts\";\n+import { CachedStateStorage, storedArray } from \"../../../src/engine/state-source.ts\";\n+import { SqlState } from \"../../../src/engine/test/storage-helper.ts\";\n+import { MemoryStore, Project } from \"../project.ts\";\n+import type { Entry, ProjectOptions, ProjectStore } from \"../project-types.ts\";\n+import { projectedReader } from \"../projection-provider.ts\";\n+import { Membership } from \"../spaces.ts\";\n+import { ViewCache } from \"../views.ts\";\n+import { WriterAgents } from \"../writer-agents.ts\";\n+\n+// Private test host only. Canonical frames and projection receipts share one SQLite transaction.\n+class ProjectionHost {\n+\treadonly storage: SqlState;\n+\treadonly entries: Entry[];\n+\tverifyReadParity = true;\n+\treadViewProvider?: ProjectOptions[\"readViewProvider\"];\n+\tenableReaderProvider(): void {\n+\t\tthis.readViewProvider = (graph) => {\n+\t\t\tconst scope = this.newReadScope(graph);\n+\t\t\treturn { keyed: (key) => this.readerForKey(key, graph, scope.guard(graph)) };\n+\t\t};\n+\t}\n+\t#scopeFrames: { token: object; scopes: ProjectionReadScope[]; overlays: ProjectionOverlayStorage[] }[] = [];\n+\t#nextOverlay = 0;\n+\tnewReadScope(graph: Graph): ProjectionReadScope {\n+\t\tconst frame = this.#scopeFrames.at(-1);\n+\t\tassert.ok(frame, \"reader provider requires an active transaction\");\n+\t\tconst scope = new ProjectionReadScope(graph, () => this.#scopeFrames.at(-1)?.token);\n+\t\tframe.scopes.push(scope);\n+\t\treturn scope;\n+\t}\n+\t#transaction<T>(operation: () => T): T {\n+\t\tconst parent = this.#scopeFrames.at(-1);\n+\t\tif (parent) {\n+\t\t\tfor (const scope of parent.scopes) scope.close();\n+\t\t\tparent.scopes.length = 0;\n+\t\t}\n+\t\tconst frame = { token: {}, scopes: [] as ProjectionReadScope[], overlays: [] as ProjectionOverlayStorage[] };\n+\t\tthis.#scopeFrames.push(frame);\n+\t\ttry {\n+\t\t\treturn this.storage.transaction(() => {\n+\t\t\t\ttry {\n+\t\t\t\t\treturn operation();\n+\t\t\t\t} finally {\n+\t\t\t\t\tfor (const overlay of frame.overlays) overlay.close();\n+\t\t\t\t}\n+\t\t\t});\n+\t\t} finally {\n+\t\t\tfor (const scope of frame.scopes) scope.close();\n+\t\t\tassert.equal(this.#scopeFrames.pop(), frame);\n+\t\t}\n+\t}\n+\n+\tconstructor(filename = \":memory:\") {\n+\t\tthis.storage = new SqlState(filename);\n+\t\tthis.entries = storedArray<Entry>(this.storage, \"integration:canonical\");\n+\t}\n+\treadonly store: ProjectStore = {\n+\t\tappend: (batch) => {\n+\t\t\tfor (const entry of batch) {\n+\t\t\t\tconst digest = this.storage.read(\"integration:source\", \"digest\") ?? \"\";\n+\t\t\t\tthis.entries.push(entry);\n+\t\t\t\tthis.storage.write(\n+\t\t\t\t\t\"integration:source\",\n+\t\t\t\t\t\"digest\",\n+\t\t\t\t\tcreateHash(\"sha256\")\n+\t\t\t\t\t\t.update(JSON.stringify([digest, entry]))\n+\t\t\t\t\t\t.digest(\"hex\"),\n+\t\t\t\t);\n+\t\t\t\tthis.storage.write(\n+\t\t\t\t\t\"integration:prefixes\",\n+\t\t\t\t\tString(this.entries.length),\n+\t\t\t\t\tthis.storage.read(\"integration:source\", \"digest\"),\n+\t\t\t\t);\n+\t\t\t}\n+\t\t},\n+\t};\n+\trun<T>(\n+\t\tid: string,\n+\t\texpectedLength: number,\n+\t\toperation: (project: Project) => T,\n+\t\tfail = false,\n+\t\trequest: { body: string; target: string; authority: string } = {\n+\t\t\tbody: id,\n+\t\t\ttarget: \"shared\",\n+\t\t\tauthority: \"test-writer\",\n+\t\t},\n+\t): T {\n+\t\t// The real host must supply a normalized request body, never a callback's source text.\n+\t\tconst requestDigest = createHash(\"sha256\")\n+\t\t\t.update(JSON.stringify([request.body, request.target, request.authority]))\n+\t\t\t.digest(\"hex\");\n+\t\treturn this.#transaction(() => {\n+\t\t\tconst receipt = this.storage.read(\"integration:receipts\", id) as { result: T; requestDigest: string } | undefined;\n+\t\t\tif (receipt) {\n+\t\t\t\tif (receipt.requestDigest !== requestDigest) throw Error(\"operation ID request conflict\");\n+\t\t\t\treturn receipt.result;\n+\t\t\t}\n+\t\t\tassert.equal(this.entries.length, expectedLength, \"stale canonical head\");\n+\t\t\tconst project = this.entries.length\n+\t\t\t\t? Project.openWriter(this.store, this.storage, this.entries.length, { readViewProvider: this.readViewProvider })\n+\t\t\t\t: new Project(this.store, { writerStorage: this.storage });\n+\t\t\tconst adapter = new ExperimentalMarkerProjection(\n+\t\t\t\tthis.storage,\n+\t\t\t\tproject.graph,\n+\t\t\t\t\"a.txt\",\n+\t\t\t\tJSON.stringify([\"database-a\", \"projection-a\"]),\n+\t\t\t);\n+\t\t\tconst context = {\n+\t\t\t\tdatabase: \"database-a\",\n+\t\t\t\tnamespace: JSON.stringify([\"database-a\", \"projection-a\"]),\n+\t\t\t\tregistry: \"registry-a\",\n+\t\t\t\tdefaultFile: \"a.txt\",\n+\t\t\t};\n+\t\t\tconst snapshots = new ProjectionSnapshots(this.storage, adapter, context);\n+\t\t\tconst previous = this.storage.read(\"integration:head\", \"projection\") as ProjectionHandle | undefined;\n+\t\t\tif (this.entries.length && !previous) throw Error(\"missing committed projection head\");\n+\t\t\tconst expected: ProjectionIdentity = {\n+\t\t\t\t...context,\n+\t\t\t\tsourceGeneration: 1,\n+\t\t\t\tsourceLength: this.entries.length,\n+\t\t\t\tsourceDigest: this.storage.read(\"integration:prefixes\", String(this.entries.length)) as string,\n+\t\t\t\tmembership: this.entries.length ? String(project.version) : \"-1\",\n+\t\t\t};\n+\t\t\tlet state = previous ? snapshots.load(previous, expected) : adapter.empty();\n+\t\t\tconst before = previous ? project.version : -1;\n+\t\t\tconst result = operation(project);\n+\t\t\tconst save = (version: number): ProjectionHandle => {\n+\t\t\t\tconst next = (this.storage.read(\"integration:head\", \"next-root\") as number | undefined) ?? 0;\n+\t\t\t\tconst handle = snapshots.save(\n+\t\t\t\t\tnext,\n+\t\t\t\t\t{\n+\t\t\t\t\t\t...context,\n+\t\t\t\t\t\tsourceGeneration: 1,\n+\t\t\t\t\t\tsourceLength: this.entries.length,\n+\t\t\t\t\t\tsourceDigest: this.storage.read(\"integration:source\", \"digest\") as string,\n+\t\t\t\t\t\tmembership: String(version),\n+\t\t\t\t\t},\n+\t\t\t\t\tstate,\n+\t\t\t\t);\n+\t\t\t\tthis.storage.write(\"integration:head\", \"next-root\", next + 1);\n+\t\t\t\treturn handle;\n+\t\t\t};\n+\t\t\tlet versionHandle: ProjectionHandle | undefined;\n+\t\t\tconst membership = new Membership(this.storage);\n+\t\t\tfor (let version = before + 1; version <= project.version; version++) {\n+\t\t\t\tconst delta = membership.shared.versions[version]!;\n+\t\t\t\tfor (const atom of [...(delta.dropped ?? [])].map((id) => project.graph.atom(id)).sort((a, b) => b.seq - a.seq))\n+\t\t\t\t\tstate = adapter.removeAtom(state, atom);\n+\t\t\t\tfor (const atom of delta.atoms.map((id) => project.graph.atom(id)).sort((a, b) => a.seq - b.seq))\n+\t\t\t\t\tstate = adapter.apply(state, atom);\n+\t\t\t\tversionHandle = save(version);\n+\t\t\t\tthis.storage.write(\"integration:versions\", String(version), versionHandle);\n+\t\t\t}\n+\t\t\tconst handle =\n+\t\t\t\tprevious && this.entries.length === expectedLength ? previous : (versionHandle ?? save(project.version));\n+\t\t\tthis.storage.write(\"integration:head\", \"projection\", handle);\n+\t\t\tthis.storage.write(\"integration:head\", \"version\", project.version);\n+\t\t\tif (!this.storage.read(\"integration:versions\", String(project.version)))\n+\t\t\t\tthis.storage.write(\"integration:versions\", String(project.version), handle);\n+\t\t\tthis.storage.write(\"integration:receipts\", id, { result, requestDigest });\n+\t\t\tfor (const path of this.verifyReadParity ? [\"a.txt\", \"b.txt\"] : []) {\n+\t\t\t\tconst reader = new ProjectionReader(adapter, state, this.newReadScope(project.graph).guard(project.graph));\n+\t\t\t\tassert.deepEqual(reader.lines(path), project.sharedView().lines(path));\n+\t\t\t\tassert.deepEqual(reader.knownPaths(), project.sharedView().knownPaths());\n+\t\t\t\tassert.deepEqual(reader.sequence(path), project.sharedView().sequence(path));\n+\t\t\t\tassert.equal(reader.text(path), project.sharedView().text(path));\n+\t\t\t\tassert.equal(reader.hasFile(path), project.sharedView().hasFile(path));\n+\t\t\t\tassert.deepEqual(\n+\t\t\t\t\tadapter.lines(state, path),\n+\t\t\t\t\tproject\n+\t\t\t\t\t\t.sharedView()\n+\t\t\t\t\t\t.lines(path)\n+\t\t\t\t\t\t.map((line) => line.id),\n+\t\t\t\t);\n+\t\t\t\tassert.deepEqual(adapter.attrs(state, path), project.sharedView().attrs(path));\n+\t\t\t}\n+\t\t\tif (fail) throw Error(\"injected outer rollback\");\n+\t\t\treturn result;\n+\t\t});\n+\t}\n+\tdraftLines(name: string, path: string): string[] {\n+\t\treturn this.withDraftReader(name, (reader) => reader.lines(path).map((line) => line.id));\n+\t}\n+\treaderForKey(key: string, graph: Graph, assertLive?: () => void): ProjectionReader {\n+\t\tconst frame = this.#scopeFrames.at(-1);\n+\t\tassert.ok(frame, \"projection reads require a transaction\");\n+\t\tconst guard = assertLive ?? this.newReadScope(graph).guard(graph);\n+\t\tconst versions = new Membership(this.storage).shared.versions;\n+\t\treturn projectedReader(\n+\t\t\t{\n+\t\t\t\tgraph,\n+\t\t\t\tcontext: {\n+\t\t\t\t\tdatabase: \"database-a\",\n+\t\t\t\t\tnamespace: JSON.stringify([\"database-a\", \"projection-a\"]),\n+\t\t\t\t\tregistry: \"registry-a\",\n+\t\t\t\t\tdefaultFile: \"a.txt\",\n+\t\t\t\t},\n+\t\t\t\tsourceGeneration: 1,\n+\t\t\t\tsourceLength: () => this.entries.length,\n+\t\t\t\tprefixDigest: (length) => this.storage.read(\"integration:prefixes\", String(length)) as string | undefined,\n+\t\t\t\tversion: () => versions.length - 1,\n+\t\t\t\tcommitted: () => ({\n+\t\t\t\t\tversion: this.storage.read(\"integration:head\", \"version\") as number,\n+\t\t\t\t\thandle: this.storage.read(\"integration:head\", \"projection\") as ProjectionHandle,\n+\t\t\t\t}),\n+\t\t\t\tat: (version) => this.storage.read(\"integration:versions\", String(version)) as ProjectionHandle | undefined,\n+\t\t\t\tdelta: (version) => versions[version],\n+\t\t\t\tguard: () => guard,\n+\t\t\t\tallocate: () => {\n+\t\t\t\t\tconst overlay = new ProjectionOverlayStorage(this.storage, `reader-${this.#nextOverlay++}`);\n+\t\t\t\t\tframe.overlays.push(overlay);\n+\t\t\t\t\treturn new CachedStateStorage(overlay, frame.overlays.length <= 32 ? 8192 : 0, 32);\n+\t\t\t\t},\n+\t\t\t},\n+\t\t\tkey,\n+\t\t);\n+\t}\n+\n+\twithDraftReader<T>(name: string, read: (reader: ProjectionReader) => T): T {\n+\t\tconst rollback = Symbol(\"completed draft read\");\n+\t\tlet result!: T;\n+\t\ttry {\n+\t\t\tthis.#transaction(() => {\n+\t\t\t\tconst project = Project.openWriter(this.store, this.storage, this.entries.length, {\n+\t\t\t\t\treadViewProvider: this.readViewProvider,\n+\t\t\t\t});\n+\t\t\t\tconst actor = new WriterAgents(this.storage).get(name);\n+\t\t\t\tassert.ok(actor);\n+\t\t\t\tassert.equal(actor.space, \"\", \"named draft projection is not implemented in this test host\");\n+\t\t\t\tconst handle = this.storage.read(\"integration:versions\", String(actor.base)) as ProjectionHandle;\n+\t\t\t\tassert.ok(handle, \"missing exact base projection\");\n+\t\t\t\tconst context = {\n+\t\t\t\t\tdatabase: \"database-a\",\n+\t\t\t\t\tnamespace: JSON.stringify([\"database-a\", \"projection-a\"]),\n+\t\t\t\t\tregistry: \"registry-a\",\n+\t\t\t\t\tdefaultFile: \"a.txt\",\n+\t\t\t\t};\n+\t\t\t\tconst adapter = new ExperimentalMarkerProjection(this.storage, project.graph, \"a.txt\", context.namespace);\n+\t\t\t\tconst snapshots = new ProjectionSnapshots(this.storage, adapter, context);\n+\t\t\t\tconst expected: ProjectionIdentity = {\n+\t\t\t\t\t...context,\n+\t\t\t\t\tsourceGeneration: 1,\n+\t\t\t\t\tsourceLength: handle.identity.sourceLength,\n+\t\t\t\t\tsourceDigest: this.storage.read(\"integration:prefixes\", String(handle.identity.sourceLength)) as string,\n+\t\t\t\t\tmembership: String(actor.base),\n+\t\t\t\t};\n+\t\t\t\tlet state = snapshots.load(handle, expected);\n+\t\t\t\tfor (const id of actor.mine) state = adapter.apply(state, project.graph.atom(id));\n+\t\t\t\tresult = read(new ProjectionReader(adapter, state, this.newReadScope(project.graph).guard(project.graph)));\n+\t\t\t\tthrow rollback;\n+\t\t\t});\n+\t\t} catch (error) {\n+\t\t\tif (error !== rollback) throw error;\n+\t\t}\n+\t\treturn result;\n+\t}\n+}\n+\n+test(\"measure private routed fixed-working-set cost\", { skip: process.env.ABSO_PROJECTION_COST !== \"1\" }, () => {\n+\tfor (const revisions of [8, 32, 128]) {\n+\t\tconst host = new ProjectionHost();\n+\t\ttry {\n+\t\t\thost.run(\"init\", 0, (p) => p.init({ \"a.txt\": \"head\\nrevision 0\\ntail\\n\" }, 0));\n+\t\t\tfor (let i = 1; i <= revisions; i++)\n+\t\t\t\thost.run(`seed-${i}`, host.entries.length, (p) => {\n+\t\t\t\t\tp.record(\"writer\", { \"a.txt\": `head\\nrevision ${i}\\ntail\\n` }, i * 2);\n+\t\t\t\t\tp.publish(\"writer\", \"Seed\", i * 2 + 1);\n+\t\t\t\t});\n+\t\t\thost.enableReaderProvider();\n+\t\t\thost.verifyReadParity = false;\n+\t\t\tconst byCollection = new Map<string, number>();\n+\t\t\tconst callers = new Map<string, number>();\n+\t\t\tconst read = host.storage.read.bind(host.storage);\n+\t\t\thost.storage.read = (collection, key) => {\n+\t\t\t\tif (process.env.ABSO_PROJECTION_TRACE === \"1\" && collection === \"line-base\") {\n+\t\t\t\t\tconst stack = new Error().stack!.split(\"\\n\").slice(2, 11).join(\"\\n\");\n+\t\t\t\t\tcallers.set(stack, (callers.get(stack) ?? 0) + 1);\n+\t\t\t\t}\n+\t\t\t\tconst group = collection.startsWith(\"projection:temporary:\") ? \"projection:temporary\" : collection;\n+\t\t\t\tbyCollection.set(group, (byCollection.get(group) ?? 0) + 1);\n+\t\t\t\treturn read(collection, key);\n+\t\t\t};\n+\t\t\tconst reads = host.storage.reads,\n+\t\t\t\twrites = host.storage.writes,\n+\t\t\t\tscans = host.storage.scans;\n+\t\t\tconst start = performance.now();\n+\t\t\thost.run(\"measured\", host.entries.length, (p) => {\n+\t\t\t\tp.record(\"writer\", { \"a.txt\": \"head\\nmeasured\\ntail\\n\" }, 1000);\n+\t\t\t\tassert.equal(p.publish(\"writer\", \"Measured\", 1001).ok, true);\n+\t\t\t});\n+\t\t\tconsole.log(\n+\t\t\t\tJSON.stringify({\n+\t\t\t\t\trevisions,\n+\t\t\t\t\tliveLines: 3,\n+\t\t\t\t\tmilliseconds: performance.now() - start,\n+\t\t\t\t\treads: host.storage.reads - reads,\n+\t\t\t\t\twrites: host.storage.writes - writes,\n+\t\t\t\t\tscans: host.storage.scans - scans,\n+\t\t\t\t\tcollections: [...byCollection].sort((a, b) => b[1] - a[1]).slice(0, 12),\n+\t\t\t\t\tcallers: [...callers].sort((a, b) => b[1] - a[1]).slice(0, 3),\n+\t\t\t\t}),\n+\t\t\t);\n+\t\t\tassert.equal(\n+\t\t\t\thost.storage.db.prepare(\"SELECT COUNT(*) AS n FROM state WHERE collection LIKE 'projection:temporary:%'\").get()!\n+\t\t\t\t\t.n,\n+\t\t\t\t0,\n+\t\t\t);\n+\t\t} finally {\n+\t\t\thost.storage.db.close();\n+\t\t}\n+\t}\n+});\n+\n+for (const fail of [false, true]) {\n+\ttest(`nested host transaction permanently expires parent readers after ${fail ? \"rollback\" : \"commit\"}`, () => {\n+\t\tconst host = new ProjectionHost();\n+\t\ttry {\n+\t\t\thost.run(\"init\", 0, (p) => p.init({ \"a.txt\": \"one\\ntwo\\n\" }, 0));\n+\t\t\thost.run(\"outer\", host.entries.length, (p) => {\n+\t\t\t\tconst reader = host.readerForKey(\"v @0\", p.graph, host.newReadScope(p.graph).guard(p.graph));\n+\t\t\t\tconst iterator = reader.visibleLines(\"a.txt\");\n+\t\t\t\titerator.next();\n+\t\t\t\tconst inner = () =>\n+\t\t\t\t\thost.run(\n+\t\t\t\t\t\t\"inner\",\n+\t\t\t\t\t\thost.entries.length,\n+\t\t\t\t\t\t() => {\n+\t\t\t\t\t\t\tassert.throws(() => reader.text(\"a.txt\"), /expired/);\n+\t\t\t\t\t\t},\n+\t\t\t\t\t\tfail,\n+\t\t\t\t\t);\n+\t\t\t\tif (fail) assert.throws(inner, /outer rollback/);\n+\t\t\t\telse inner();\n+\t\t\t\tassert.throws(() => reader.text(\"a.txt\"), /expired/);\n+\t\t\t\tassert.throws(() => iterator.next(), /expired/);\n+\t\t\t\tassert.equal(\n+\t\t\t\t\thost.readerForKey(\"v @0\", p.graph, host.newReadScope(p.graph).guard(p.graph)).text(\"a.txt\"),\n+\t\t\t\t\t\"one\\ntwo\\n\",\n+\t\t\t\t);\n+\t\t\t});\n+\t\t} finally {\n+\t\t\thost.storage.db.close();\n+\t\t}\n+\t});\n+}\n+\n+test(\"private projection host joins actual Project commits and rolls back with canonical state\", () => {\n+\tconst host = new ProjectionHost();\n+\tconst oracle = new Project(new MemoryStore());\n+\tlet id = 0;\n+\tconst run = <T>(operation: (project: Project) => T) =>\n+\t\tassert.deepEqual(host.run(String(id++), host.entries.length, operation), operation(oracle));\n+\ttry {\n+\t\trun((p) => p.init({ \"a.txt\": \"one\\n\", \"b.txt\": \"two\\n\" }, 0));\n+\t\trun((p) => p.record(\"left\", { \"a.txt\": \"ONE\\n\" }, 1));\n+\t\trun((p) => p.record(\"right\", { \"b.txt\": \"TWO\\n\" }, 2));\n+\t\trun((p) => p.publish(\"left\", \"Left\", 3));\n+\t\trun((p) => p.publish(\"right\", \"Right\", 4));\n+\t\tconst rows = () => JSON.stringify(host.storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all());\n+\t\tconst before = rows(),\n+\t\t\tlength = host.entries.length;\n+\t\tassert.throws(\n+\t\t\t() => host.run(\"failure\", length, (p) => p.record(\"left\", { \"a.txt\": \"again\\n\" }, 5), true),\n+\t\t\t/outer rollback/,\n+\t\t);\n+\t\tassert.equal(rows(), before);\n+\t\tassert.throws(() => host.run(\"stale\", length - 1, () => null), /stale canonical head/);\n+\t\tassert.equal(rows(), before);\n+\t\thost.run(\"retry\", length, (p) => p.record(\"left\", { \"a.txt\": \"again\\n\" }, 5));\n+\t\tconst committed = rows();\n+\t\thost.run(\"retry\", length, () => {\n+\t\t\tthrow Error(\"retry executed twice\");\n+\t\t});\n+\t\tassert.equal(rows(), committed);\n+\t} finally {\n+\t\thost.storage.db.close();\n+\t}\n+});\n+\n+test(\"runtime provider refuses a valid root stored under the wrong version\", () => {\n+\tconst host = new ProjectionHost();\n+\ttry {\n+\t\thost.run(\"init\", 0, (p) => p.init({ \"a.txt\": \"one\\n\" }, 0));\n+\t\thost.run(\"edit\", host.entries.length, (p) => {\n+\t\t\tp.record(\"writer\", { \"a.txt\": \"two\\n\" }, 1);\n+\t\t\tp.publish(\"writer\", \"Edit\", 2);\n+\t\t});\n+\t\tconst original = host.storage.read(\"integration:versions\", \"1\");\n+\t\thost.storage.write(\"integration:versions\", \"1\", host.storage.read(\"integration:versions\", \"0\"));\n+\t\tconst writes = host.storage.writes;\n+\t\tassert.throws(\n+\t\t\t() => host.run(\"wrong-version\", host.entries.length, (p) => host.readerForKey(\"v @1\", p.graph)),\n+\t\t\t/mismatch/,\n+\t\t);\n+\t\tassert.equal(host.storage.writes, writes);\n+\t\thost.storage.write(\"integration:versions\", \"1\", original);\n+\t\tfor (const key of [\"v @2\", \"v named@1\", \"v @01\", \"v @1+a0\"])\n+\t\t\tassert.throws(\n+\t\t\t\t() => host.run(key, host.entries.length, (p) => host.readerForKey(key, p.graph)),\n+\t\t\t\t/authority|unsupported/,\n+\t\t\t);\n+\t} finally {\n+\t\thost.storage.db.close();\n+\t}\n+});\n+\n+test(\"private projection host refuses a forged source or membership handle before executing\", () => {\n+\tconst host = new ProjectionHost();\n+\ttry {\n+\t\thost.run(\"init\", 0, (p) => p.init({ \"a.txt\": \"one\\n\" }, 0));\n+\t\tconst original = host.storage.read(\"integration:head\", \"projection\") as ProjectionHandle;\n+\t\tfor (const change of [\n+\t\t\t{ sourceDigest: \"f\".repeat(64) },\n+\t\t\t{ sourceLength: original.identity.sourceLength + 1 },\n+\t\t\t{ membership: \"900\" },\n+\t\t\t{ database: \"other-database\" },\n+\t\t\t{ sourceGeneration: 2 },\n+\t\t]) {\n+\t\t\thost.storage.write(\"integration:head\", \"projection\", {\n+\t\t\t\t...original,\n+\t\t\t\tidentity: { ...original.identity, ...change },\n+\t\t\t});\n+\t\t\tlet invoked = false;\n+\t\t\tconst writes = host.storage.writes;\n+\t\t\tassert.throws(\n+\t\t\t\t() =>\n+\t\t\t\t\thost.run(\"forged\", host.entries.length, () => {\n+\t\t\t\t\t\tinvoked = true;\n+\t\t\t\t\t}),\n+\t\t\t\t/mismatch/,\n+\t\t\t);\n+\t\t\tassert.equal(invoked, false);\n+\t\t\tassert.equal(host.storage.writes, writes);\n+\t\t}\n+\t\thost.storage.write(\"integration:head\", \"projection\", original);\n+\t\thost.run(\"valid\", host.entries.length, (p) => p.record(\"writer\", { \"a.txt\": \"two\\n\" }, 1));\n+\t\tassert.equal(\n+\t\t\thost.storage.read(\"integration:prefixes\", String(original.identity.sourceLength)),\n+\t\t\toriginal.identity.sourceDigest,\n+\t\t\t\"later graph extension preserves the old canonical prefix identity\",\n+\t\t);\n+\t} finally {\n+\t\thost.storage.db.close();\n+\t}\n+});\n+\n+test(\"private projection host routes cross-file moves, later edits and dropping versions\", (t) => {\n+\tconst host = new ProjectionHost();\n+\tconst oracle = new Project(new MemoryStore());\n+\tlet id = 0;\n+\tconst run = <T>(operation: (project: Project) => T) => {\n+\t\tconst read = host.storage.read.bind(host.storage);\n+\t\tconst guard =\n+\t\t\thost.readViewProvider &&\n+\t\t\tt.mock.method(host.storage, \"read\", (collection: string, key: string) => {\n+\t\t\t\tif (collection === 'membership:\"\":events') throw Error(\"historical membership enumeration forbidden\");\n+\t\t\t\treturn read(collection, key);\n+\t\t\t});\n+\t\tlet actual: T;\n+\t\ttry {\n+\t\t\tactual = host.run(`move-${id++}`, host.entries.length, operation);\n+\t\t} finally {\n+\t\t\tif (guard) guard.mock.restore();\n+\t\t}\n+\t\tassert.deepEqual(actual, operation(oracle));\n+\t};\n+\ttry {\n+\t\tconst block = \"function example() {\\n  return 42;\\n}\\n\";\n+\t\trun((p) => p.init({ \"a.txt\": `header\\n${block}`, \"b.txt\": \"destination\\n\" }, 0));\n+\t\thost.enableReaderProvider();\n+\t\trun((p) => p.record(\"mover\", { \"a.txt\": \"header\\n\", \"b.txt\": `destination\\n${block}` }, 1));\n+\t\trun((p) => p.publish(\"mover\", \"Move function\", 2));\n+\t\trun((p) => p.record(\"editor\", { \"b.txt\": `destination\\n${block.replace(\"42\", \"43\")}` }, 3));\n+\t\trun((p) => p.publish(\"editor\", \"Edit moved function\", 4));\n+\t\trun((p) => p.drop(\"cleanup\", [2], \"Undo edit\", 5));\n+\t\trun((p) => p.drop(\"cleanup\", [1], \"Undo move\", 6));\n+\t\tassert.deepEqual(Project.openWriter(host.store, host.storage, host.entries.length).files(), oracle.files());\n+\t} finally {\n+\t\thost.storage.db.close();\n+\t}\n+});\n+\n+test(\"private projection host reopens the database and retries the committed receipt\", () => {\n+\tconst filename = join(mkdtempSync(join(tmpdir(), \"abso-project-projection-\")), \"state.sqlite\");\n+\tlet host = new ProjectionHost(filename);\n+\ttry {\n+\t\thost.run(\"init\", 0, (p) => p.init({ \"a.txt\": \"one\\n\" }, 0));\n+\t\tconst length = host.entries.length;\n+\t\tconst result = host.run(\"record\", length, (p) => p.record(\"writer\", { \"a.txt\": \"two\\n\" }, 1));\n+\t\thost.storage.db.close();\n+\t\thost = new ProjectionHost(filename);\n+\t\tconst before = host.entries.length;\n+\t\tassert.deepEqual(\n+\t\t\thost.run(\"record\", length, () => {\n+\t\t\t\tthrow Error(\"replayed receipt executed\");\n+\t\t\t}),\n+\t\t\tresult,\n+\t\t);\n+\t\tassert.equal(host.entries.length, before);\n+\t\thost.run(\"publish\", before, (p) => p.publish(\"writer\", \"After restart\", 2));\n+\t\thost.storage.db.close();\n+\t\thost = new ProjectionHost(filename);\n+\t\tassert.deepEqual(Project.openWriter(host.store, host.storage, host.entries.length).files(), { \"a.txt\": \"two\\n\" });\n+\t\thost.run(\"later\", host.entries.length, (p) => p.record(\"writer\", { \"a.txt\": \"three\\n\" }, 3));\n+\t} finally {\n+\t\thost.storage.db.close();\n+\t}\n+});\n+\n+test(\"private projection host reuses its snapshot when an operation appends nothing\", () => {\n+\tconst host = new ProjectionHost();\n+\ttry {\n+\t\thost.run(\"init\", 0, (p) => p.init({ \"a.txt\": \"one\\n\" }, 0));\n+\t\tconst head = host.storage.read(\"integration:head\", \"projection\");\n+\t\tconst length = host.entries.length;\n+\t\tassert.deepEqual(\n+\t\t\thost.run(\"read\", length, (p) => p.files()),\n+\t\t\t{ \"a.txt\": \"one\\n\" },\n+\t\t);\n+\t\tassert.deepEqual(host.storage.read(\"integration:head\", \"projection\"), head);\n+\t\tassert.equal(host.entries.length, length);\n+\t} finally {\n+\t\thost.storage.db.close();\n+\t}\n+});\n+\n+test(\"private projection receipts reject changed request, target or authority\", () => {\n+\tconst host = new ProjectionHost();\n+\tconst request = {\n+\t\tbody: JSON.stringify({ kind: \"init\", files: { \"a.txt\": \"one\\n\" } }),\n+\t\ttarget: \"shared\",\n+\t\tauthority: \"writer-a\",\n+\t};\n+\ttry {\n+\t\tconst result = host.run(\"request\", 0, (p) => p.init({ \"a.txt\": \"one\\n\" }, 0), false, request);\n+\t\tfor (const changed of [\n+\t\t\t{ ...request, body: \"different\" },\n+\t\t\t{ ...request, target: \"draft\" },\n+\t\t\t{ ...request, authority: \"writer-b\" },\n+\t\t]) {\n+\t\t\tconst writes = host.storage.writes;\n+\t\t\tassert.throws(\n+\t\t\t\t() =>\n+\t\t\t\t\thost.run(\n+\t\t\t\t\t\t\"request\",\n+\t\t\t\t\t\t0,\n+\t\t\t\t\t\t() => {\n+\t\t\t\t\t\t\tthrow Error(\"must not execute\");\n+\t\t\t\t\t\t},\n+\t\t\t\t\t\tfalse,\n+\t\t\t\t\t\tchanged,\n+\t\t\t\t\t),\n+\t\t\t\t/request conflict/,\n+\t\t\t);\n+\t\t\tassert.equal(host.storage.writes, writes);\n+\t\t}\n+\t\tassert.deepEqual(\n+\t\t\thost.run(\n+\t\t\t\t\"request\",\n+\t\t\t\t0,\n+\t\t\t\t() => {\n+\t\t\t\t\tthrow Error(\"must not execute\");\n+\t\t\t\t},\n+\t\t\t\tfalse,\n+\t\t\t\trequest,\n+\t\t\t),\n+\t\t\tresult,\n+\t\t);\n+\t} finally {\n+\t\thost.storage.db.close();\n+\t}\n+});\n+\n+test(\"private projection derives each concurrent draft from its exact older base\", () => {\n+\tconst host = new ProjectionHost();\n+\ttry {\n+\t\thost.run(\"init\", 0, (p) => p.init({ \"a.txt\": \"one\\n\", \"b.txt\": \"two\\n\" }, 0));\n+\t\thost.run(\"left\", host.entries.length, (p) => p.record(\"left\", { \"a.txt\": \"LEFT\\n\" }, 1));\n+\t\thost.run(\"right\", host.entries.length, (p) => p.record(\"right\", { \"b.txt\": \"RIGHT\\n\" }, 2));\n+\t\thost.run(\"publish\", host.entries.length, (p) => p.publish(\"right\", \"Advance shared\", 3));\n+\t\tconst project = Project.openWriter(host.store, host.storage, host.entries.length);\n+\t\tfor (const actor of [\"left\", \"right\"])\n+\t\t\tfor (const path of [\"a.txt\", \"b.txt\"])\n+\t\t\t\tassert.deepEqual(\n+\t\t\t\t\thost.draftLines(actor, path),\n+\t\t\t\t\tproject\n+\t\t\t\t\t\t.draftOf(actor)!\n+\t\t\t\t\t\t.view.lines(path)\n+\t\t\t\t\t\t.map((line) => line.id),\n+\t\t\t\t);\n+\t\tassert.notDeepEqual(host.draftLines(\"left\", \"b.txt\"), host.draftLines(\"right\", \"b.txt\"));\n+\t} finally {\n+\t\thost.storage.db.close();\n+\t}\n+});\n+\n+test(\"private draft projection does not enumerate historical membership or canonical frames\", (t) => {\n+\tconst host = new ProjectionHost();\n+\ttry {\n+\t\thost.run(\"init\", 0, (p) => p.init({ \"a.txt\": \"one\\n\" }, 0));\n+\t\tfor (let i = 0; i < 12; i++) {\n+\t\t\thost.run(`record-${i}`, host.entries.length, (p) => p.record(\"writer\", { \"a.txt\": `${i}\\n` }, i * 2 + 1));\n+\t\t\thost.run(`publish-${i}`, host.entries.length, (p) => p.publish(\"writer\", `Revision ${i}`, i * 2 + 2));\n+\t\t}\n+\t\thost.run(\"draft\", host.entries.length, (p) => p.record(\"draft\", { \"a.txt\": \"pending\\n\" }, 30));\n+\t\tconst project = Project.openWriter(host.store, host.storage, host.entries.length);\n+\t\tconst expected = project\n+\t\t\t.draftOf(\"draft\")!\n+\t\t\t.view.lines(\"a.txt\")\n+\t\t\t.map((line) => line.id);\n+\t\tconst read = host.storage.read.bind(host.storage);\n+\t\tt.mock.method(host.storage, \"read\", (collection: string, key: string) => {\n+\t\t\tif (\n+\t\t\t\tcollection === \"integration:canonical\" ||\n+\t\t\t\t(collection.startsWith(\"membership:\") && (collection.includes(\":events\") || collection.endsWith(\":own\")))\n+\t\t\t)\n+\t\t\t\tthrow Error(`historical enumeration forbidden: ${collection}`);\n+\t\t\treturn read(collection, key);\n+\t\t});\n+\t\tt.mock.method(host.storage, \"entries\", () => {\n+\t\t\tthrow Error(\"collection enumeration forbidden\");\n+\t\t});\n+\t\tassert.deepEqual(host.draftLines(\"draft\", \"a.txt\"), expected);\n+\t} finally {\n+\t\thost.storage.db.close();\n+\t}\n+});\n+\n+test(\"temporary draft projection leaves no pages after repeated reads or a failed write\", () => {\n+\tconst host = new ProjectionHost();\n+\ttry {\n+\t\thost.run(\"init\", 0, (p) => p.init({ \"a.txt\": \"one\\n\" }, 0));\n+\t\thost.run(\"draft\", host.entries.length, (p) => p.record(\"writer\", { \"a.txt\": \"draft\\n\" }, 1));\n+\t\tconst rows = () => JSON.stringify(host.storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all());\n+\t\tconst before = rows();\n+\t\tconst expected = Project.openWriter(host.store, host.storage, host.entries.length)\n+\t\t\t.draftOf(\"writer\")!\n+\t\t\t.view.lines(\"a.txt\")\n+\t\t\t.map((line) => line.id);\n+\t\tfor (let i = 0; i < 3; i++) {\n+\t\t\tassert.deepEqual(host.draftLines(\"writer\", \"a.txt\"), expected);\n+\t\t\tassert.equal(rows(), before);\n+\t\t}\n+\t\thost.storage.failWrite = host.storage.writes + 3;\n+\t\tassert.throws(() => host.draftLines(\"writer\", \"a.txt\"), /injected/);\n+\t\tassert.equal(rows(), before);\n+\t\thost.storage.failWrite = Infinity;\n+\t\tassert.deepEqual(host.draftLines(\"writer\", \"a.txt\"), expected);\n+\t\tassert.equal(rows(), before);\n+\t} finally {\n+\t\thost.storage.db.close();\n+\t}\n+});\n+\n+test(\"private host retains intermediate version roots inside one outer commit\", () => {\n+\tconst host = new ProjectionHost();\n+\ttry {\n+\t\thost.run(\"init\", 0, (p) => p.init({ \"a.txt\": \"one\\n\" }, 0));\n+\t\thost.run(\"batch\", host.entries.length, (p) => {\n+\t\t\tp.record(\"first\", { \"a.txt\": \"two\\n\" }, 1);\n+\t\t\tp.publish(\"first\", \"Two\", 2);\n+\t\t\tp.record(\"old-base\", { \"a.txt\": \"older draft\\n\" }, 3);\n+\t\t\tp.record(\"second\", { \"a.txt\": \"three\\n\" }, 4);\n+\t\t\tp.publish(\"second\", \"Three\", 5);\n+\t\t});\n+\t\tassert.ok(host.storage.read(\"integration:versions\", \"1\"));\n+\t\tassert.ok(host.storage.read(\"integration:versions\", \"2\"));\n+\t\tconst project = Project.openWriter(host.store, host.storage, host.entries.length);\n+\t\tassert.deepEqual(\n+\t\t\thost.draftLines(\"old-base\", \"a.txt\"),\n+\t\t\tproject\n+\t\t\t\t.draftOf(\"old-base\")!\n+\t\t\t\t.view.lines(\"a.txt\")\n+\t\t\t\t.map((line) => line.id),\n+\t\t);\n+\t} finally {\n+\t\thost.storage.db.close();\n+\t}\n+});\n+\n+for (const competingPath of [\"a.txt\", \"b.txt\"] as const) {\n+\tfor (const mode of [\"rollback\", \"commit\"] as const) {\n+\t\ttest(`actual Project record and publish route privately with ${mode}, competing ${competingPath}, and no old closure`, (t) => {\n+\t\t\tconst filename = join(mkdtempSync(join(tmpdir(), \"projection-route-\")), \"state.sqlite\");\n+\t\t\tlet host = new ProjectionHost(filename);\n+\t\t\ttry {\n+\t\t\t\thost.run(\"init\", 0, (p) => p.init({ \"a.txt\": \"one\\n\", \"b.txt\": \"two\\n\" }, 0));\n+\t\t\t\thost.run(\"left\", host.entries.length, (p) => p.record(\"left\", { \"a.txt\": \"LEFT\\n\" }, 1));\n+\t\t\t\thost.run(\"right\", host.entries.length, (p) => p.record(\"right\", { [competingPath]: \"RIGHT\\n\" }, 2));\n+\t\t\t\thost.run(\"publish\", host.entries.length, (p) => p.publish(\"right\", \"Advance shared\", 3));\n+\t\t\t\tconst expected = \"LEFT\\n\";\n+\t\t\t\tconst oracle = Project.load([...host.entries], new MemoryStore());\n+\t\t\t\tconst recorded = oracle.record(\"left\", { \"a.txt\": \"UPDATED\\n\" }, 4);\n+\t\t\t\tconst published = oracle.publish(\"left\", \"Publish routed edit\", 5);\n+\t\t\t\tassert.equal(published.ok, competingPath !== \"a.txt\");\n+\t\t\t\tconst rows = () => JSON.stringify(host.storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all());\n+\t\t\t\tconst before = rows();\n+\t\t\t\tlet calls = 0;\n+\t\t\t\tlet lastReader: ProjectionReader | undefined;\n+\t\t\t\thost.readViewProvider = (graph) => {\n+\t\t\t\t\tconst scope = host.newReadScope(graph);\n+\t\t\t\t\treturn {\n+\t\t\t\t\t\tkeyed: (key) => {\n+\t\t\t\t\t\t\tcalls++;\n+\t\t\t\t\t\t\treturn (lastReader = host.readerForKey(key, graph, scope.guard(graph)));\n+\t\t\t\t\t\t},\n+\t\t\t\t\t};\n+\t\t\t\t};\n+\t\t\t\tconst route = (project: Project) => {\n+\t\t\t\t\tcalls = 0;\n+\t\t\t\t\tconst unkeyed = t.mock.method(ViewCache.prototype, \"view\", () => {\n+\t\t\t\t\t\tthrow Error(\"unkeyed historical View construction is forbidden\");\n+\t\t\t\t\t});\n+\t\t\t\t\tconst replay = t.mock.method(Project, \"load\", () => {\n+\t\t\t\t\t\tthrow Error(\"canonical Project replay is forbidden\");\n+\t\t\t\t\t});\n+\t\t\t\t\tconst read = host.storage.read.bind(host.storage);\n+\t\t\t\t\tconst guard = t.mock.method(host.storage, \"read\", (collection: string, key: string) => {\n+\t\t\t\t\t\tif (collection === 'membership:\"\":events') throw Error(\"old closure membership enumeration forbidden\");\n+\t\t\t\t\t\treturn read(collection, key);\n+\t\t\t\t\t});\n+\t\t\t\t\ttry {\n+\t\t\t\t\t\tassert.equal(project.draftOf(\"left\")!.view.text(\"a.txt\"), expected);\n+\t\t\t\t\t\tassert.equal(calls, 1);\n+\t\t\t\t\t\tassert.deepEqual(project.record(\"left\", { \"a.txt\": \"UPDATED\\n\" }, 4), recorded);\n+\t\t\t\t\t\tassert.deepEqual(project.publish(\"left\", \"Publish routed edit\", 5), published);\n+\t\t\t\t\t} finally {\n+\t\t\t\t\t\treplay.mock.restore();\n+\t\t\t\t\t\tunkeyed.mock.restore();\n+\t\t\t\t\t\tguard.mock.restore();\n+\t\t\t\t\t}\n+\t\t\t\t};\n+\t\t\t\tif (mode === \"rollback\") {\n+\t\t\t\t\thost.withDraftReader(\"left\", () =>\n+\t\t\t\t\t\troute(\n+\t\t\t\t\t\t\tProject.openWriter(host.store, host.storage, host.entries.length, {\n+\t\t\t\t\t\t\t\treadViewProvider: host.readViewProvider,\n+\t\t\t\t\t\t\t}),\n+\t\t\t\t\t\t),\n+\t\t\t\t\t);\n+\t\t\t\t\tassert.equal(rows(), before);\n+\t\t\t\t} else {\n+\t\t\t\t\tconst length = host.entries.length;\n+\t\t\t\t\tassert.throws(() => host.run(\"routed\", length, route, true), /injected outer rollback/);\n+\t\t\t\t\tassert.equal(rows(), before);\n+\t\t\t\t\tassert.throws(() => lastReader!.text(\"a.txt\"), /expired|stale/);\n+\t\t\t\t\thost.run(\"routed\", length, route);\n+\t\t\t\t\tassert.equal(\n+\t\t\t\t\t\thost.storage.db\n+\t\t\t\t\t\t\t.prepare(\"SELECT COUNT(*) AS n FROM state WHERE collection LIKE 'projection:temporary:%'\")\n+\t\t\t\t\t\t\t.get()!.n,\n+\t\t\t\t\t\t0,\n+\t\t\t\t\t);\n+\t\t\t\t\tconst committed = rows();\n+\t\t\t\t\thost.storage.db.close();\n+\t\t\t\t\thost = new ProjectionHost(filename);\n+\t\t\t\t\tassert.equal(rows(), committed);\n+\t\t\t\t\thost.run(\"routed\", length, () => {\n+\t\t\t\t\t\tthrow Error(\"committed retry executed twice\");\n+\t\t\t\t\t});\n+\t\t\t\t\tassert.equal(rows(), committed);\n+\t\t\t\t\thost.withDraftReader(\"left\", (reader) => {\n+\t\t\t\t\t\tassert.equal(reader.text(\"a.txt\"), oracle.draftOf(\"left\")!.view.text(\"a.txt\"));\n+\t\t\t\t\t\tassert.equal(reader.text(\"b.txt\"), oracle.draftOf(\"left\")!.view.text(\"b.txt\"));\n+\t\t\t\t\t\tconst shared = host.readerForKey(`v @${oracle.version}`, reader.graph);\n+\t\t\t\t\t\tfor (const path of [\"a.txt\", \"b.txt\"]) assert.equal(shared.text(path), oracle.sharedView().text(path));\n+\t\t\t\t\t});\n+\t\t\t\t\tassert.equal(rows(), committed);\n+\t\t\t\t}\n+\t\t\t\tassert.ok(lastReader);\n+\t\t\t\tassert.throws(() => lastReader!.text(\"a.txt\"), /expired|stale/);\n+\t\t\t} finally {\n+\t\t\t\thost.storage.db.close();\n+\t\t\t}\n+\t\t});\n+\t}\n+}"},{"path":"worker/project/test/view-cache.test.ts","added":5,"removed":4,"diff":"--- a/worker/project/test/view-cache.test.ts\n+++ b/worker/project/test/view-cache.test.ts\n@@ -1,5 +1,6 @@\n import assert from \"node:assert/strict\";\n import { test } from \"node:test\";\n+import type { ReadView } from \"../../../src/engine/index.ts\";\n import { buildBase, Graph, View } from \"../../../src/engine/index.ts\";\n import { StableOverlaySet } from \"../../../src/engine/state-source.ts\";\n import type { AtomId } from \"../../../src/engine/types.ts\";\n@@ -31,16 +32,16 @@\n \n type WeightControls = {\n \tsetIncomingWeights(values: number[]): void;\n-\tsetWeight(view: View, weight: number): void;\n+\tsetWeight(view: ReadView, weight: number): void;\n };\n \n function withControlledWeights(run: (controls: WeightControls) => void): void {\n \tconst original = Object.getOwnPropertyDescriptor(View.prototype, \"weight\")!;\n-\tconst weights = new WeakMap<View, number>();\n+\tconst weights = new WeakMap<ReadView, number>();\n \tlet newWeights: number[] = [];\n \tObject.defineProperty(View.prototype, \"weight\", {\n \t\tconfigurable: true,\n-\t\tvalue(this: View) {\n+\t\tvalue(this: ReadView) {\n \t\t\tif (!weights.has(this)) weights.set(this, newWeights.shift() ?? 0);\n \t\t\treturn weights.get(this)!;\n \t\t},\n@@ -60,7 +61,7 @@\n \t}\n }\n \n-function get(cache: ViewCache, key: string): View {\n+function get(cache: ViewCache, key: string): ReadView {\n \treturn cache.keyed(key, () => new Set());\n }\n "},{"path":"worker/project/version-log.ts","added":14,"removed":9,"diff":"--- a/worker/project/version-log.ts\n+++ b/worker/project/version-log.ts\n@@ -1,8 +1,9 @@\n+import { View } from \"../../src/engine/index.ts\";\n // The version list reads: log (versions newest first, or one file's history), ribbon (who published each version),\n // show (one version's changes), fileAt, compare and viewAt. They read through LogHost; today the host is the project\n // in memory.\n \n-import { type AtomId, type Graph, View } from \"../../src/engine/index.ts\";\n+import type { AtomId, Graph, ReadView } from \"../../src/engine/index.ts\";\n import { checkReadPath } from \"./path-rules.ts\";\n import type { PathIndex } from \"./pathindex.ts\";\n import { ProjectError } from \"./project-error.ts\";\n@@ -19,12 +20,12 @@\n \tneedInit(): void;\n \tspaceFor(options: { draft?: string | null; agent?: string }): Space;\n \tcheckVersion(space: Space, version: number): void;\n-\tviewAt(space: Space, version: number): View;\n-\tview(set: ReadonlySet<AtomId>): View;\n+\tviewAt(space: Space, version: number): ReadView;\n+\tview(set: ReadonlySet<AtomId>): ReadView;\n \tat(space: Space, version: number): ReadonlySet<AtomId>;\n-\tspellingIn(view: View, path: string): string;\n+\tspellingIn(view: ReadView, path: string): string;\n \tversionChange(space: Space, version: number): number | undefined;\n-\ttouchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;\n+\ttouchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>;\n }\n \n /**\n@@ -59,7 +60,7 @@\n \t// A file's history (#43): only versions whose changes name the file, or a file moves can carry lines from, can have changed it.\n \tconst sources = path === undefined ? undefined : new Set(names.flatMap((n) => [...moveSources(host.graph, n.path)]));\n \tconst g = host.graph;\n-\tconst views = new Map<number, View>();\n+\tconst views = new Map<number, ReadView>();\n \tfor (; v >= 0 && versions.length < limit; v--) {\n \t\tif (sources && !host.paths.knowsFiles(space, v)) {\n \t\t\tconst p = space.versions[v]!;\n@@ -179,7 +180,7 @@\n \t};\n }\n \n-function logEntry(host: LogHost, space: Space, version: number, views?: Map<number, View>): LogEntry {\n+function logEntry(host: LogHost, space: Space, version: number, views?: Map<number, ReadView>): LogEntry {\n \tconst p = space.versions[version]!;\n \tlet changes = 0;\n \tfor (const id of p.atoms) {\n@@ -264,8 +265,12 @@\n \treturn { from, to, files: changesBetween(host.view(a), host.view(b), files) };\n }\n \n-/** A version of shared (or of a named draft) as a View, for reading lines (blame at a version). */\n-export function viewAt(host: LogHost, version: number, options: { draft?: string | null; agent?: string } = {}): View {\n+/** A version of shared (or of a named draft) as a ReadView, for reading lines (blame at a version). */\n+export function viewAt(\n+\thost: LogHost,\n+\tversion: number,\n+\toptions: { draft?: string | null; agent?: string } = {},\n+): ReadView {\n \thost.needInit();\n \tconst space = host.spaceFor(options);\n \thost.checkVersion(space, version);"},{"path":"worker/project/view-changes.ts","added":5,"removed":5,"diff":"--- a/worker/project/view-changes.ts\n+++ b/worker/project/view-changes.ts\n@@ -1,9 +1,9 @@\n-import type { View } from \"../../src/engine/index.ts\";\n+import type { ReadView } from \"../../src/engine/index.ts\";\n import { ProjectError } from \"./project-error.ts\";\n import type { FileChange, Mode, Modes } from \"./project-types.ts\";\n \n /** The listed files whose text differs between two views, before and after. */\n-export function changesBetween(before: View, after: View, files: Iterable<string>): FileChange[] {\n+export function changesBetween(before: ReadView, after: ReadView, files: Iterable<string>): FileChange[] {\n \tconst out: FileChange[] = [];\n \tfor (const path of [...new Set(files)].toSorted()) {\n \t\tconst b = before.hasFile(path) ? before.text(path) : null;\n@@ -19,7 +19,7 @@\n }\n \n /** Whether a file differs between two views: its text, its mode, or its blob (what changesBetween lists). */\n-export function differs(before: View, after: View, path: string): boolean {\n+export function differs(before: ReadView, after: ReadView, path: string): boolean {\n \tconst had = before.hasFile(path);\n \tif (had !== after.hasFile(path)) return true;\n \tif (had && !before.sameText(path, after)) return true;\n@@ -29,7 +29,7 @@\n }\n \n /** A file's executable bit and link target, before and after, when either changed. */\n-export function modeChange(before: View, after: View, path: string): { before: Mode; after: Mode } | undefined {\n+export function modeChange(before: ReadView, after: ReadView, path: string): { before: Mode; after: Mode } | undefined {\n \tconst b = before.attrs(path);\n \tconst a = after.attrs(path);\n \tif (b.exec === a.exec && b.link === a.link) return undefined;\n@@ -37,7 +37,7 @@\n }\n \n /** Every executable file and link in a view. */\n-export function modesOf(view: View): Modes {\n+export function modesOf(view: ReadView): Modes {\n \tconst out: Modes = {};\n \tfor (const path of view.paths()) {\n \t\tconst a = view.attrs(path);"},{"path":"worker/project/views.ts","added":16,"removed":4,"diff":"--- a/worker/project/views.ts\n+++ b/worker/project/views.ts\n@@ -2,7 +2,7 @@\n // versions never change, so their views are kept by name. Immutable indexed sets use their identity;\n // ordinary in-memory sets use their exact contents.\n \n-import { type AtomId, type Graph, View } from \"../../src/engine/index.ts\";\n+import { type AtomId, type Graph, type ReadView, View } from \"../../src/engine/index.ts\";\n import { StableSet } from \"../../src/engine/state-source.ts\";\n \n /**\n@@ -12,14 +12,24 @@\n  */\n const VIEW_BUDGET = 24_000_000;\n \n+/** Internal opt-in. The owner validates identity and lifetime on every returned reader. */\n+export interface ReadViewProvider {\n+\tkeyed(key: string): ReadView;\n+}\n+\n /** Views by key, most recently used last, held under VIEW_BUDGET bytes and 32 views. */\n export class ViewCache {\n \treadonly #graph: Graph;\n+\treadonly #provider?: ReadViewProvider;\n \treadonly #cache = new Map<string | StableSet<AtomId>, View>();\n \n-\tconstructor(graph: Graph) {\n+\tconstructor(graph: Graph, provider?: (graph: Graph) => ReadViewProvider) {\n \t\tthis.#graph = graph;\n+\t\tthis.#provider = provider?.(graph);\n \t}\n+\tassertUnkeyedAllowed(): void {\n+\t\tif (this.#provider) throw Error(\"unsupported unkeyed projection membership\");\n+\t}\n \n \t/**\n \t * Keep the cached views under VIEW_BUDGET bytes (the website project, #43,\n@@ -37,7 +47,8 @@\n \t}\n \n \t/** Indexed snapshots use identity; ordinary sets use their exact contents. */\n-\tview(set: ReadonlySet<AtomId>): View {\n+\tview(set: ReadonlySet<AtomId>): ReadView {\n+\t\tthis.assertUnkeyedAllowed();\n \t\t// Immutable indexed membership is already a stable identity. Building\n \t\t// a sorted history-sized key defeats its external-storage contract.\n \t\tif (set instanceof StableSet) return this.#get(set, () => set);\n@@ -49,7 +60,8 @@\n \t}\n \n \t/** A view cached under `key`, made from `set()` when it isn't there. */\n-\tkeyed(key: string, set: () => ReadonlySet<AtomId>): View {\n+\tkeyed(key: string, set: () => ReadonlySet<AtomId>): ReadView {\n+\t\tif (this.#provider) return this.#provider.keyed(key);\n \t\treturn this.#get(key, set);\n \t}\n "},{"path":"worker/project/whole-files.ts","added":4,"removed":4,"diff":"--- a/worker/project/whole-files.ts\n+++ b/worker/project/whole-files.ts\n@@ -1,7 +1,7 @@\n // Files kept whole (#46): avcs.json's `\"whole\"` globs, text over WHOLE_LIMIT, or a file that is\n // already a blob. The project holds the blob store; these helpers decide which texts go there.\n \n-import { canonicalText, type View } from \"../../src/engine/index.ts\";\n+import { canonicalText, type ReadView } from \"../../src/engine/index.ts\";\n import { matchesPattern } from \"./globs.ts\";\n import { projectFileIn } from \"./project-helpers.ts\";\n import type { ProjectOptions } from \"./project-types.ts\";\n@@ -15,7 +15,7 @@\n /** What the whole-file helpers need from a project. */\n export interface WholeHost {\n \tinitialized(): boolean;\n-\tsharedView(): View;\n+\tsharedView(): ReadView;\n \twhole: ProjectOptions[\"whole\"];\n }\n \n@@ -45,7 +45,7 @@\n \thost: WholeHost,\n \tpath: string,\n \tlength: number,\n-\tview: View | undefined,\n+\tview: ReadView | undefined,\n \trules: readonly string[],\n ): boolean {\n \tif (!host.whole) return false;\n@@ -61,7 +61,7 @@\n \thost: WholeHost,\n \tfiles: Readonly<Record<string, string | null>>,\n \tblobs: Readonly<Record<string, string>>,\n-\tview: View | undefined,\n+\tview: ReadView | undefined,\n \tconfig?: string,\n ): { files: Record<string, string | null>; blobs: Record<string, string> } {\n \tconst outFiles: Record<string, string | null> = { ...files };"}],"ci":null}