63 files, 3686 lines added, 206 removed.
--- a/src/engine/build.ts
+++ b/src/engine/build.ts
@@ -23,6 +23,11 @@
2424import { View } from "./view.ts"; 26+/** Exact read surface used to build atoms; membership requires point lookup only. */ 27+export type AtomBuildView = Pick<View, "graph" | "lines" | "sequence" | "sequenceIndex" | "parentOf"> & { 28+ readonly set: Pick<ReadonlySet<AtomId>, "has">; 2631/** Replace the one exact occurrence of `old` in `file` with `new`. */ 2732export interface TextEdit { 2833 readonly file: string; @@ -108,7 +113,7 @@
108113 * the graph's next id; accept it with `graph.add(atom)` and put it in a set. 109114 * Its dependencies are derived from what it touched in the view (see deriveDeps). 111−export function buildAtom(view: View, input: AtomInput): Atom {
116+export function buildAtom(view: AtomBuildView, input: AtomInput): Atom { 112117 return build(view, input, false); @@ -126,7 +131,7 @@
126131 return build(view, { ...meta, edits, attrs }, true); 129−function build(view: View, input: AtomInput, allowEmpty: boolean): Atom {
134+function build(view: AtomBuildView, input: AtomInput, allowEmpty: boolean): Atom { 130135 const graph = view.graph; 131136 const id = graph.nextId(); 132137 if (typeof input.author !== "string" || typeof input.message !== "string") { @@ -275,7 +280,7 @@
275280 * lines into each other collide in all but the rarest cases (the view breaks 276281 * any loop that is left). 278−function planMove(view: View, move: MoveInput, writes: Set<Key>, reads: Set<Key>): Relocation[] {
283+function planMove(view: AtomBuildView, move: MoveInput, writes: Set<Key>, reads: Set<Key>): Relocation[] { 279284 for (const path of [move.file, move.to]) { 280285 if (typeof path !== "string" || path === "" || /[\n\r]/.test(path)) 281286 throw new EngineError("bad-edit", `bad file path ${JSON.stringify(path)}`); @@ -341,7 +346,7 @@
341346 * the semantic contract. A missing tip still implies its required ancestors. 343348function deriveDeps( 344− view: View,
349+ view: AtomBuildView, 346351 writes: readonly Key[]; 347352 reads: readonly Key[]; @@ -390,7 +395,7 @@
393−function rangeLines(view: View, range: LineRange): LineId[] {
398+function rangeLines(view: AtomBuildView, range: LineRange): LineId[] { 394399 const visible = view.lines(range.file); 396401 !Number.isInteger(range.start) || @@ -407,7 +412,7 @@
407412 return visible.slice(range.start, range.end).map((l) => l.id); 410−function uniqueAtoms(view: View, ids: readonly AtomId[], what: string): AtomId[] {
415+function uniqueAtoms(view: AtomBuildView, ids: readonly AtomId[], what: string): AtomId[] { 411416 const out: AtomId[] = []; 412417 for (const id of ids) { 413418 if (!view.graph.has(id)) throw new EngineError("unknown-atom", `${what} names unknown atom ${id}`); @@ -419,7 +424,7 @@
420425// Matching edits --------------------------------------------------------------- 422−function resolveRegions(view: View, edits: readonly EditInput[]): Region[] {
427+function resolveRegions(view: AtomBuildView, edits: readonly EditInput[]): Region[] { 423428 const regions = edits.map((edit, order) => { 424429 const mode = edit.mode ?? "both"; 425430 if (!MODES.includes(mode)) throw new EngineError("bad-edit", `mode must be one of ${MODES.join(", ")}`); @@ -455,7 +460,7 @@
455460 * whole lines. If the replacement would leave a line without its newline, the 456461 * next line joins the region (that is what the plain-text edit does). 458−function matchText(view: View, edit: TextEdit, mode: Mode, order: number): Region {
463+function matchText(view: AtomBuildView, edit: TextEdit, mode: Mode, order: number): Region { 459464 if (typeof edit.old !== "string" || typeof edit.new !== "string") { 460465 throw new EngineError("bad-edit", "a text edit needs old and new strings"); @@ -514,7 +519,7 @@
514519 return { file, start: startLine, end: endLine + 1, lines: splitLines(replacement), mode, order }; 517−function matchSplice(view: View, edit: SpliceEdit, mode: Mode, order: number): Region {
522+function matchSplice(view: AtomBuildView, edit: SpliceEdit, mode: Mode, order: number): Region { 518523 const count = view.lines(edit.file).length; 520525 !Number.isInteger(edit.start) || --- /dev/null
+++ b/src/engine/experimental/projection-locator.ts
@@ -0,0 +1,111 @@
1+import type { GraphStateStorage } from "../state-source.ts"; 3+type Page = number | null; 14+ children: Record<string, number>; 16+type Node = Leaf | Branch; 17+const safe = (n: unknown): n is number => Number.isSafeInteger(n) && Number(n) >= 0; 18+const object = (value: unknown): value is Record<string, unknown> => 19+ value !== null && typeof value === "object" && !Array.isArray(value); 20+function page(id: unknown): asserts id is Page { 21+ if (id !== null && !safe(id)) throw Error("invalid locator page reference"); 23+function keyOf(id: number): string { 24+ if (!safe(id) || id >= 2 ** 32) throw Error("experimental locator identity limit"); 25+ return id.toString(16).padStart(8, "0"); 27+/** Internal immutable experiment. Hosts bind roots through ProjectionIdentity. */ 28+export class ProjectionLocator<T> { 29+ readonly #storage: GraphStateStorage; 30+ readonly #collection: string; 31+ readonly #decode: (value: unknown) => T; 32+ constructor(storage: GraphStateStorage, namespace: string, decode: (value: unknown) => T) { 33+ if (!namespace || namespace.length > 4096) throw Error("invalid locator namespace"); 34+ this.#storage = storage; 35+ this.#collection = `experimental-locator:${JSON.stringify(namespace)}`; 36+ this.#decode = decode; 38+ #read(id: number, parent?: string, digit?: string): Node { 40+ const row = this.#storage.read(this.#collection, String(id)); 41+ if (!object(row) || row.format !== 1 || typeof row.prefix !== "string" || !/^[0-9a-f]{0,8}$/.test(row.prefix)) 42+ throw Error("invalid locator node"); 43+ if (parent !== undefined && (row.prefix.length <= parent.length || !row.prefix.startsWith(parent + digit))) 44+ throw Error("invalid locator edge"); 45+ if (row.kind === "leaf") { 46+ if (row.prefix.length !== 8 || Object.keys(row).length !== 4 || !("value" in row)) 47+ throw Error("invalid locator leaf"); 48+ return row as unknown as Leaf; 50+ if (row.kind !== "branch" || row.prefix.length >= 8 || Object.keys(row).length !== 4 || !object(row.children)) 51+ throw Error("invalid locator branch"); 52+ const children = Object.entries(row.children); 53+ if (children.length < 2 || children.length > 16) throw Error("invalid locator fanout"); 54+ for (const [digit, child] of children) 55+ if (!/^[0-9a-f]$/.test(digit) || !safe(child) || child === id) throw Error("invalid locator child"); 56+ return row as unknown as Branch; 58+ #write(node: Node): number { 59+ const next = this.#storage.read(this.#collection, "next") ?? 0; 60+ if (!safe(next) || !Number.isSafeInteger(next + 1)) throw Error("invalid locator allocation"); 61+ if (this.#storage.read(this.#collection, String(next)) !== undefined) throw Error("locator allocation collision"); 62+ this.#storage.write(this.#collection, String(next), node); 63+ this.#storage.write(this.#collection, "next", next + 1); 66+ get(root: Page, id: number): T | undefined { 68+ const key = keyOf(id); 70+ parent: string | undefined, 71+ digit: string | undefined; 72+ for (let depth = 0; current !== null; depth++) { 73+ if (depth > 8) throw Error("invalid locator depth"); 74+ const node = this.#read(current, parent, digit); 75+ if (!key.startsWith(node.prefix)) return undefined; 76+ if (node.kind === "leaf") return this.#decode(structuredClone(node.value)); 77+ parent = node.prefix; 78+ digit = key[parent.length]!; 79+ current = node.children[digit] ?? null; 83+ set(root: Page, id: number, value: T): number { 85+ const key = keyOf(id), 86+ checked = structuredClone(this.#decode(structuredClone(value))); 87+ return this.#storage.transaction(() => { 88+ const visit = (current: Page, parent?: string, digit?: string, depth = 0): number => { 89+ if (depth > 8) throw Error("invalid locator depth"); 90+ if (current === null) return this.#write({ format: 1, kind: "leaf", prefix: key, value: checked }); 91+ const node = this.#read(current, parent, digit); 93+ while (common < node.prefix.length && node.prefix[common] === key[common]) common++; 94+ if (common < node.prefix.length) { 95+ const leaf = this.#write({ format: 1, kind: "leaf", prefix: key, value: checked }); 99+ prefix: key.slice(0, common), 100+ children: { [node.prefix[common]!]: current, [key[common]!]: leaf }, 103+ if (node.kind === "leaf") return this.#write({ format: 1, kind: "leaf", prefix: key, value: checked }); 104+ const nextDigit = key[common]!; 105+ const child = visit(node.children[nextDigit] ?? null, node.prefix, nextDigit, depth + 1); 106+ return this.#write({ ...node, children: { ...node.children, [nextDigit]: child } }); --- /dev/null
+++ b/src/engine/experimental/projection-marker.ts
@@ -0,0 +1,428 @@
1+import type { Graph } from "../graph.ts"; 2+import { orderedChildKey } from "../ordered-index.ts"; 3+import { resolveScratchMoves } from "../relocation-scratch.ts"; 4+import type { GraphStateStorage } from "../state-source.ts"; 5+import type { Atom, AtomId } from "../types.ts"; 6+import { ProjectionLocator } from "./projection-locator.ts"; 7+import { ProjectionPriority } from "./projection-priority.ts"; 9+ type ProjectionAttributeName, 10+ type ProjectionAttributes, 11+ type ProjectionAttributeValue, 12+ type ProjectionChildRoot, 13+ type ProjectionMarker, 14+ type ProjectionMembership, 15+ projectionAttributes, 16+ projectionAttributeValue, 19+ projectionMembership, 20+} from "./projection-records.ts"; 21+import { ProjectionSequence, type SequenceState } from "./projection-sequence.ts"; 23+type Page = number | null; 24+export interface MarkerState { 25+ readonly context: string; 26+ sequence: SequenceState; 30+ attributeFiles: Page; 37+function relocationPlan(value: unknown): Plan { 38+ if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("invalid relocation plan"); 39+ const row = value as Record<string, unknown>; 41+ Object.keys(row).length !== 3 || 42+ !Number.isSafeInteger(row.n) || 44+ Number(row.n) >= 0x7fffffff || 45+ !Number.isSafeInteger(row.parentKey) || 46+ Number(row.parentKey) < 0 || 47+ Number(row.parentKey) >= 2 ** 32 || 48+ typeof row.key !== "string" || 49+ !/^[0-9a-f]{57}$/.test(row.key) 51+ throw Error("invalid relocation plan"); 52+ return { n: row.n as number, parentKey: row.parentKey as number, key: row.key }; 54+const numeric = (value: unknown): number => { 55+ if (!Number.isSafeInteger(value) || Number(value) < 0) throw Error("invalid projection number"); 56+ return value as number; 58+function required<T>(value: T | undefined): T { 59+ if (value === undefined) throw Error("missing projection record"); 62+/** Internal typed experiment; root binding wrapper is still required before integration. */ 63+export class ExperimentalMarkerProjection { 64+ readonly context: string; 65+ readonly storage: GraphStateStorage; 66+ readonly graph: Graph; 67+ readonly path: string; 68+ readonly sequence: ProjectionSequence; 69+ readonly markers: ProjectionLocator<ProjectionMarker>; 70+ readonly members: ProjectionLocator<ProjectionMembership>; 71+ readonly childRoots: ProjectionLocator<ProjectionChildRoot>; 72+ readonly attributeRoots: ProjectionLocator<ProjectionAttributes>; 73+ readonly priorities: ProjectionPriority<number>; 74+ readonly attributePriorities: ProjectionPriority<ProjectionAttributeValue>; 75+ constructor(storage: GraphStateStorage, graph: Graph, path: string, namespace: string) { 76+ if (!namespace || namespace.length > 4096) throw Error("invalid projection namespace"); 77+ this.context = JSON.stringify([namespace, path]); 78+ const prefix = `experimental-marker:${JSON.stringify(namespace)}:`; 80+ read: (collection, key) => storage.read(prefix + collection, key), 81+ write: (collection, key, value) => storage.write(prefix + collection, key, value), 82+ remove: (collection, key) => storage.remove(prefix + collection, key), 83+ entries: (collection) => storage.entries(prefix + collection), 84+ transaction: (body) => storage.transaction(body), 88+ this.sequence = new ProjectionSequence(storage, namespace + ":sequence"); 89+ this.markers = new ProjectionLocator(storage, namespace + ":markers", projectionMarker); 90+ this.members = new ProjectionLocator(storage, namespace + ":membership", projectionMembership); 91+ this.childRoots = new ProjectionLocator(storage, namespace + ":children", projectionChildRoot); 92+ this.attributeRoots = new ProjectionLocator(storage, namespace + ":attributes", projectionAttributes); 93+ this.priorities = new ProjectionPriority(storage, namespace + ":priorities", numeric); 94+ this.attributePriorities = new ProjectionPriority( 96+ namespace + ":attribute-priorities", 97+ projectionAttributeValue, 100+ assertContext(state: MarkerState): void { 101+ if (!state || state.context !== this.context) throw Error("projection constructor context mismatch"); 103+ empty(): MarkerState { 105+ context: this.context, 106+ sequence: this.sequence.empty(), 110+ attributeFiles: null, 113+ apply(previous: MarkerState, atom: Atom): MarkerState { 114+ this.assertContext(previous); 115+ if (JSON.stringify(this.graph.atom(atom.id)) !== JSON.stringify(atom)) throw Error("canonical atom mismatch"); 116+ if (this.members.get(previous.membership, atom.seq)?.present) return previous; 117+ for (const id of atom.deps) 118+ if (!this.members.get(previous.membership, this.graph.atom(id).seq)?.present) throw Error("missing dependency"); 119+ return this.storage.transaction(() => { 120+ const state = { ...previous }; 121+ const sequence = this.sequence; 122+ const insert = (rank: number, text: string, hidden = false): number => { 123+ const id = state.sequence.next; 124+ state.sequence = sequence.update(state.sequence, { kind: "insert", rank, text }); 125+ if (hidden) state.sequence = sequence.update(state.sequence, { kind: "visibility", id, delta: 1 }); 128+ this.ensureFile(state, this.path); 129+ for (const run of atom.inserts) this.ensureFile(state, run.file); 131+ for (const run of atom.inserts) 132+ for (const text of run.lines) { 133+ const line = `${atom.id}.${k++}`, 134+ n = this.graph.lineN(line), 135+ parent = this.graph.parentCodeOf(n); 136+ if (n + 1 >= 0x80000000) throw Error("prototype line identity limit"); 137+ const existing = this.markers.get(state.locator, n + 1); 139+ state.sequence = sequence.update(state.sequence, { kind: "visibility", id: existing.enter, delta: -1 }); 142+ const parentMarker = this.markers.get(state.locator, this.parentKey(parent)); 143+ if (!parentMarker) throw Error("missing parent marker"); 144+ const parentKey = this.parentKey(parent); 145+ const index = this.priorities; 146+ const root = this.childRoots.get(state.children, parentKey)?.root ?? null; 147+ const seq = this.graph.writerSeqOf(n); 148+ const key = orderedChildKey({ 150+ replaces: this.graph.replacesN(n) ? 1 : 0, 151+ lamport: this.graph.lamportOfSeq(seq), 153+ k: this.graph.kOf(n), 155+ const preceding = index.before(root, key); 157+ preceding === undefined 158+ ? parentMarker.enter 159+ : required(this.markers.get(state.locator, preceding + 1)).exit; 160+ state.children = this.childRoots.set(state.children, parentKey, { root: index.insert(root, key, n) }); 161+ const at = sequence.rank(state.sequence, anchor) + 1; 162+ const enter = insert(at, line), 163+ exit = insert(at + 1, `${line}:end`, true); 164+ state.locator = this.markers.set(state.locator, n + 1, { kind: "line", enter, exit, parentKey, key }); 166+ for (const line of atom.deletes) { 167+ const marker = this.markers.get(state.locator, this.graph.lineN(line) + 1); 168+ if (!marker) throw Error("missing deleted marker"); 169+ state.sequence = sequence.update(state.sequence, { kind: "visibility", id: marker.enter, delta: 1 }); 171+ for (const id of atom.deps) { 172+ const seq = this.graph.atom(id).seq, 173+ member = required(this.members.get(state.membership, seq)); 174+ state.membership = this.members.set(state.membership, seq, { ...member, dependents: member.dependents + 1 }); 176+ this.updateAttributes(state, atom, true); 177+ this.updateFiles(state, atom, 1); 178+ state.membership = this.members.set(state.membership, atom.seq, { present: true, dependents: 0 }); 179+ return atom.moves?.length ? this.reconcileMoves(state) : state; 182+ removeDeleter(previous: MarkerState, atom: Atom): MarkerState { 183+ return this.removeAtom(previous, atom); 185+ removeAtom(previous: MarkerState, atom: Atom): MarkerState { 186+ this.assertContext(previous); 187+ if (JSON.stringify(this.graph.atom(atom.id)) !== JSON.stringify(atom)) throw Error("canonical atom mismatch"); 188+ if (!this.members.get(previous.membership, atom.seq)?.present) return previous; 189+ if (required(this.members.get(previous.membership, atom.seq)).dependents) 190+ throw Error("included dependent prevents removal"); 191+ return this.storage.transaction(() => { 192+ const state = { ...previous }; 194+ for (const run of atom.inserts) 195+ for (const text of run.lines) { 196+ const marker = this.markers.get(state.locator, this.graph.lineN(`${atom.id}.${k++}`) + 1); 197+ if (!marker) throw Error("missing inserted marker"); 198+ state.sequence = this.sequence.update(state.sequence, { kind: "visibility", id: marker.enter, delta: 1 }); 200+ for (const line of atom.deletes) { 201+ const marker = this.markers.get(state.locator, this.graph.lineN(line) + 1); 202+ if (!marker) throw Error("missing deleted marker"); 203+ state.sequence = this.sequence.update(state.sequence, { kind: "visibility", id: marker.enter, delta: -1 }); 205+ for (const id of atom.deps) { 206+ const seq = this.graph.atom(id).seq, 207+ member = required(this.members.get(state.membership, seq)); 208+ if (!member?.present || member.dependents < 1) throw Error("invalid dependency count"); 209+ state.membership = this.members.set(state.membership, seq, { ...member, dependents: member.dependents - 1 }); 211+ this.updateAttributes(state, atom, false); 212+ this.updateFiles(state, atom, -1); 213+ state.membership = this.members.set(state.membership, atom.seq, { present: false, dependents: 0 }); 214+ return atom.moves?.length ? this.reconcileMoves(state) : state; 217+ reconcileMoves(previous: MarkerState): MarkerState { 218+ this.assertContext(previous); 219+ return this.storage.transaction(() => { 220+ const scope = numeric(this.storage.read("sequence-meta", "work-scope") ?? 0); 221+ this.storage.write("sequence-meta", "work-scope", scope + 1); 222+ const prefix = `sequence-resolver:${scope}:`, 223+ collections = new Set<string>(); 224+ const scratch: GraphStateStorage = { 225+ read: (c, k) => this.storage.read(prefix + c, k), 226+ write: (c, k, v) => { 228+ this.storage.write(prefix + c, k, v); 230+ remove: (c, k) => this.storage.remove(prefix + c, k), 231+ entries: (c) => this.storage.entries(prefix + c), 232+ transaction: (body) => this.storage.transaction(body), 234+ const has = (id: AtomId) => this.members.get(previous.membership, this.graph.atom(id).seq)?.present ?? false; 235+ previous = { ...previous }; 236+ for (const id of this.graph.movers()) 237+ for (const move of this.graph.atom(id).moves ?? []) 238+ if (move.parent.startsWith("^")) this.ensureFile(previous, move.parent.slice(1)); 239+ const resolved = resolveScratchMoves(this.graph, has, scratch), 241+ function* plans(): IterableIterator<Plan> { 242+ for (const id of self.graph.movers()) 243+ for (const move of self.graph.atom(id).moves ?? []) { 244+ if (scratch.read("planned", move.line)) continue; 245+ scratch.write("planned", move.line, true); 246+ const n = self.graph.lineN(move.line); 247+ if (!has(self.graph.idOfSeq(self.graph.writerSeqOf(n)))) continue; 248+ const marker = self.markers.get(previous.locator, n + 1); 249+ if (!marker || marker.kind !== "line") throw Error("missing selected relocation marker"); 250+ const selected = resolved.selected(move.line), 251+ parent = resolved.parent(move.line); 252+ const parentKey = parent.startsWith("^") 253+ ? required(self.fileKey(parent.slice(1))) 254+ : self.graph.lineN(parent) + 1; 255+ const seq = selected ? self.graph.atom(selected.atom).seq : self.graph.writerSeqOf(n); 256+ const key = orderedChildKey({ 258+ replaces: selected ? 0 : Number(self.graph.replacesN(n)), 259+ lamport: self.graph.lamportOfSeq(seq), 261+ k: selected ? selected.k : self.graph.kOf(n), 263+ if (parentKey !== marker.parentKey || key !== marker.key) yield { n, parentKey, key }; 266+ const state = this.relocateBatch(previous, plans()); 267+ for (const collection of collections) 268+ for (const [key] of this.storage.entries(prefix + collection)) this.storage.remove(prefix + collection, key); 272+ relocateBatch(previous: MarkerState, plans: Iterable<Plan>): MarkerState { 273+ this.assertContext(previous); 274+ return this.storage.transaction(() => { 275+ const scope = numeric(this.storage.read("sequence-meta", "work-scope") ?? 0); 276+ this.storage.write("sequence-meta", "work-scope", scope + 1); 277+ const name = `sequence-relocation-work:${scope}`; 280+ for (const candidate of plans) { 281+ const plan = relocationPlan(candidate); 282+ if (this.storage.read(name, `seen:${plan.n}`)) throw Error("duplicate relocation plan"); 283+ this.storage.write(name, `seen:${plan.n}`, true); 284+ this.storage.write(name, String(count++), plan); 286+ // A file root is the temporary parking parent. All phases are invisible 287+ // outside this transaction; no history-sized plan array is retained. 288+ for (let i = 0; i < count; i++) { 289+ const plan = relocationPlan(this.storage.read(name, String(i))); 290+ const marker = this.markers.get(state.locator, plan.n + 1); 291+ if (!marker || marker.kind !== "line") throw Error("missing relocation marker"); 292+ state = this.relocate(state, plan.n, 0, marker.key); 294+ for (let i = 0; i < count; i++) { 295+ const plan = relocationPlan(this.storage.read(name, String(i))); 296+ state = this.relocate(state, plan.n, plan.parentKey, plan.key); 298+ for (let i = 0; i < count; i++) { 299+ const plan = relocationPlan(this.storage.read(name, String(i))); 300+ this.storage.remove(name, `seen:${plan.n}`); 301+ this.storage.remove(name, String(i)); 306+ relocate(previous: MarkerState, n: number, parentKey: number, key: string): MarkerState { 307+ this.assertContext(previous); 308+ return this.storage.transaction(() => { 309+ const state = { ...previous }, 310+ seq = this.sequence, 311+ index = this.priorities; 312+ const marker = this.markers.get(state.locator, n + 1), 313+ target = this.markers.get(state.locator, parentKey); 314+ if (!marker || marker.kind !== "line" || !target) throw Error("missing relocation marker"); 315+ const oldRoot = this.childRoots.get(state.children, marker.parentKey)?.root ?? null; 316+ state.children = this.childRoots.set(state.children, marker.parentKey, { 317+ root: index.remove(oldRoot, marker.key), 319+ const newRoot = this.childRoots.get(state.children, parentKey)?.root ?? null; 320+ const sibling = index.before(newRoot, key); 321+ const anchor = sibling === undefined ? target.enter : required(this.markers.get(state.locator, sibling + 1)).exit; 322+ const from = seq.rank(state.sequence, marker.enter), 323+ end = seq.rank(state.sequence, marker.exit); 324+ const anchorRank = seq.rank(state.sequence, anchor), 325+ length = end - from + 1; 326+ if (anchorRank >= from && anchorRank <= end) throw Error("relocation would cycle"); 327+ const to = anchorRank + 1 - (anchorRank > end ? length : 0); 328+ state.sequence = seq.update(state.sequence, { kind: "move", from, length, to }); 329+ state.children = this.childRoots.set(state.children, parentKey, { root: index.insert(newRoot, key, n) }); 330+ state.locator = this.markers.set(state.locator, n + 1, { ...marker, parentKey, key }); 334+ fileKey(path: string): number | undefined { 335+ if (path === this.path) return 0; 336+ const id = this.storage.read("sequence-file-identities", path); 337+ return id === undefined ? undefined : numeric(id); 339+ parentKey(code: number): number { 340+ return code < 0 ? this.fileKey(this.graph.nodeOf(code).slice(1))! : code + 1; 342+ ensureFile(state: MarkerState, path: string): void { 343+ this.assertContext(state); 344+ let key = this.fileKey(path); 345+ if (key === undefined) { 346+ key = numeric(this.storage.read("sequence-meta", "next-file") ?? 0x80000000); 347+ if (key >= 2 ** 32) throw Error("file identity limit"); 348+ this.storage.write("sequence-file-identities", path, key); 349+ this.storage.write("sequence-meta", "next-file", key + 1); 351+ if (this.markers.get(state.locator, key)) return; 352+ const seq = this.sequence; 353+ const insert = (text: string): number => { 354+ const id = state.sequence.next, 355+ rank = state.sequence.root === null ? 0 : seq.get(state.sequence.map, state.sequence.root).count; 356+ state.sequence = seq.update(state.sequence, { kind: "insert", rank, text }); 357+ state.sequence = seq.update(state.sequence, { kind: "visibility", id, delta: 1 }); 360+ const enter = insert(`root:${path}`), 361+ exit = insert(`end:${path}`); 362+ state.locator = this.markers.set(state.locator, key, { kind: "file", enter, exit, contributions: 0 }); 364+ updateFiles(state: MarkerState, atom: Atom, delta: 1 | -1): void { 365+ for (const path of this.graph.filesOf(atom.id)) { 366+ this.ensureFile(state, path); 367+ const key = required(this.fileKey(path)); 368+ const marker = this.markers.get(state.locator, key); 369+ if (marker?.kind !== "file" || marker.contributions + delta < 0) throw Error("invalid file contribution count"); 370+ state.locator = this.markers.set(state.locator, key, { ...marker, contributions: marker.contributions + delta }); 373+ knownPaths(state: MarkerState): string[] { 374+ this.assertContext(state); 375+ const paths: string[] = []; 376+ for (const path of this.graph.knownFiles()) { 377+ const key = this.fileKey(path), 378+ marker = key === undefined ? undefined : this.markers.get(state.locator, key); 379+ if (marker?.kind === "file" && marker.contributions > 0) paths.push(path); 381+ return paths.sort(); 383+ updateAttributes(state: MarkerState, atom: Atom, adding: boolean): void { 384+ this.assertContext(state); 385+ const index = this.attributePriorities, 386+ hex = (n: number) => n.toString(16).padStart(14, "0"); 387+ const key = `0${hex(this.graph.lamportOfSeq(atom.seq))}${hex(atom.seq)}${hex(0)}${hex(0)}`; 388+ const names = new Set<string>(); 389+ for (const attr of atom.attrs ?? []) { 390+ if (!["exists", "exec", "link", "blob"].includes(attr.name)) throw Error("unsupported attribute"); 391+ const identity = JSON.stringify([attr.file, attr.name]); 392+ if (names.has(identity)) continue; 393+ names.add(identity); 394+ this.ensureFile(state, attr.file); 395+ const file = required(this.fileKey(attr.file)), 396+ roots = this.attributeRoots.get(state.attributeFiles, file) ?? {}; 397+ const root = roots[attr.name] ?? null; 398+ state.attributeFiles = this.attributeRoots.set(state.attributeFiles, file, { 400+ [attr.name]: adding ? index.insert(root, key, { value: attr.value }) : index.remove(root, key), 404+ attrs(state: MarkerState, path = this.path) { 405+ this.assertContext(state); 406+ const index = this.attributePriorities, 407+ file = this.fileKey(path); 408+ const roots = file === undefined ? {} : (this.attributeRoots.get(state.attributeFiles, file) ?? {}); 409+ const value = (name: ProjectionAttributeName) => index.before(roots[name] ?? null, "f".repeat(57))?.value ?? null; 410+ return { exists: value("exists") === "1", exec: value("exec") === "1", link: value("link"), blob: value("blob") }; 412+ lines(state: MarkerState, path = this.path): string[] { 413+ return [...this.lineIds(state, path)]; 415+ *lineIds(state: MarkerState, path = this.path): IterableIterator<string> { 416+ this.assertContext(state); 417+ const key = this.fileKey(path); 418+ if (key === undefined) return; 419+ const marker = this.markers.get(state.locator, key); 420+ if (!marker) return; 421+ for (const line of this.sequence.range( 423+ this.sequence.rank(state.sequence, marker.enter) + 1, 424+ this.sequence.rank(state.sequence, marker.exit), --- /dev/null
+++ b/src/engine/experimental/projection-overlay-storage.ts
@@ -0,0 +1,71 @@
1+import type { GraphStateStorage } from "../state-source.ts"; 3+type OverlayRow = { collection: string; key: string; present: boolean; value?: unknown }; 5+/** Disk-backed temporary pages over immutable committed projection pages. */ 6+export class ProjectionOverlayStorage implements GraphStateStorage { 7+ readonly #base: GraphStateStorage; 8+ readonly #collection: string; 10+ constructor(base: GraphStateStorage, namespace: string) { 11+ if (!namespace) throw Error("missing projection overlay namespace"); 13+ this.#collection = `projection:temporary:${namespace}`; 14+ for (const _ of base.entries(this.#collection)) throw Error("projection overlay namespace is occupied"); 17+ if (!this.#open) throw Error("closed projection overlay"); 19+ #key(collection: string, key: string): string { 20+ return JSON.stringify([collection, key]); 22+ read(collection: string, key: string): unknown { 24+ const row = this.#base.read(this.#collection, this.#key(collection, key)) as OverlayRow | undefined; 25+ return row ? (row.present ? row.value : undefined) : this.#base.read(collection, key); 27+ write(collection: string, key: string, value: unknown): void { 29+ this.#base.write(this.#collection, this.#key(collection, key), { collection, key, present: true, value }); 31+ remove(collection: string, key: string): void { 33+ this.#base.write(this.#collection, this.#key(collection, key), { collection, key, present: false }); 35+ *entries(collection: string): Iterable<readonly [string, unknown]> { 37+ for (const [key, value] of this.#rows(collection)) { 39+ if (!this.#base.read(this.#collection, this.#key(collection, key))) yield [key, value]; 41+ for (const [, value] of this.#rows(this.#collection)) { 43+ const row = value as OverlayRow; 44+ if (row.collection === collection && row.present) yield [row.key, row.value]; 48+ *#rows(collection: string): Iterable<readonly [string, unknown]> { 50+ const iterator = this.#base.entries(collection)[Symbol.iterator](); 53+ const next = iterator.next(); 55+ if (next.done) return; 59+ transaction<T>(body: () => T): T { 61+ return this.#base.transaction(body); 63+ /** Invoke before the owning outer transaction commits; failed cleanup must abort it. */ 65+ if (!this.#open) return; 66+ this.#base.transaction(() => { 67+ for (const [key] of this.#base.entries(this.#collection)) this.#base.remove(this.#collection, key); --- /dev/null
+++ b/src/engine/experimental/projection-priority.ts
@@ -0,0 +1,115 @@
1+import type { GraphStateStorage } from "../state-source.ts"; 3+type Page = number | null; 14+ children: Record<string, number>; 16+type Node = Leaf | Branch; 17+const safe = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0; 18+const object = (value: unknown): value is Record<string, unknown> => 19+ value !== null && typeof value === "object" && !Array.isArray(value); 20+function check(root: Page, key: string): void { 21+ if ((root !== null && !safe(root)) || !/^[0-9a-f]{57}$/.test(key)) throw Error("invalid priority lookup"); 23+/** Internal immutable priority experiment. At most 57 levels and 16 children. */ 24+export class ProjectionPriority<T> { 25+ readonly #storage: GraphStateStorage; 26+ readonly #collection: string; 27+ readonly #decode: (value: unknown) => T; 28+ constructor(storage: GraphStateStorage, namespace: string, decode: (value: unknown) => T) { 29+ if (!namespace || namespace.length > 4096) throw Error("invalid priority namespace"); 30+ this.#storage = storage; 31+ this.#collection = `experimental-priority:${JSON.stringify(namespace)}`; 32+ this.#decode = decode; 34+ #read(id: number, depth: number): Node { 35+ if (!safe(id) || !safe(depth) || depth > 57) throw Error("invalid priority reference"); 36+ const row = this.#storage.read(this.#collection, String(id)); 37+ if (!object(row) || row.format !== 1 || row.depth !== depth || Object.keys(row).length !== 4) 38+ throw Error("invalid priority node"); 40+ if (row.kind !== "leaf" || !("value" in row)) throw Error("invalid priority leaf"); 41+ return row as unknown as Leaf; 43+ if (row.kind !== "branch" || !object(row.children)) throw Error("invalid priority branch"); 44+ const entries = Object.entries(row.children); 45+ if (!entries.length || entries.length > 16) throw Error("invalid priority fanout"); 46+ for (const [digit, child] of entries) 47+ if (!/^[0-9a-f]$/.test(digit) || !safe(child) || child === id) throw Error("invalid priority child"); 48+ return row as unknown as Branch; 50+ #write(node: Node): number { 51+ const next = this.#storage.read(this.#collection, "next") ?? 0; 52+ if (!safe(next) || !Number.isSafeInteger(next + 1)) throw Error("invalid priority allocation"); 53+ if (this.#storage.read(this.#collection, String(next)) !== undefined) throw Error("priority allocation collision"); 54+ this.#storage.write(this.#collection, String(next), node); 55+ this.#storage.write(this.#collection, "next", next + 1); 58+ insert(root: Page, key: string, value: T): number { 60+ const checked = structuredClone(this.#decode(structuredClone(value))); 61+ return this.#storage.transaction(() => { 62+ const visit = (id: Page, depth: number): number => { 63+ const node = id === null ? undefined : this.#read(id, depth); 64+ if (depth === 57) return this.#write({ format: 1, kind: "leaf", depth: 57, value: checked }); 65+ if (node?.kind === "leaf") throw Error("invalid priority depth"); 66+ const children = node?.children ?? {}, 68+ const child = visit(children[digit] ?? null, depth + 1); 69+ return this.#write({ format: 1, kind: "branch", depth, children: { ...children, [digit]: child } }); 71+ return visit(root, 0); 74+ remove(root: Page, key: string): Page { 76+ return this.#storage.transaction(() => { 77+ const visit = (id: Page, depth: number): Page => { 78+ if (id === null) throw Error("missing priority key"); 79+ const node = this.#read(id, depth); 80+ if (node.kind === "leaf") return null; 81+ const digit = key[depth]!, 82+ child = visit(node.children[digit] ?? null, depth + 1), 83+ children = { ...node.children }; 84+ if (child === null) delete children[digit]; 85+ else children[digit] = child; 86+ return Object.keys(children).length ? this.#write({ ...node, children }) : null; 88+ return visit(root, 0); 91+ before(root: Page, key: string): T | undefined { 94+ let candidate: { id: number; depth: number } | undefined; 95+ for (let depth = 0; current !== null && depth < 57; depth++) { 96+ const node = this.#read(current, depth); 97+ if (node.kind !== "branch") throw Error("invalid priority depth"); 98+ const digit = key[depth]!, 99+ lower = Object.keys(node.children) 100+ .filter((item) => item < digit) 103+ if (lower !== undefined) candidate = { id: node.children[lower]!, depth: depth + 1 }; 104+ current = node.children[digit] ?? null; 106+ if (!candidate) return undefined; 107+ let { id, depth } = candidate; 108+ for (; depth <= 57; depth++) { 109+ const node = this.#read(id, depth); 110+ if (node.kind === "leaf") return this.#decode(structuredClone(node.value)); 111+ id = node.children[Object.keys(node.children).sort().at(-1)!]!; 113+ throw Error("invalid priority depth"); --- /dev/null
+++ b/src/engine/experimental/projection-read-scope.ts
@@ -0,0 +1,59 @@
1+import type { Graph } from "../graph.ts"; 3+/** Private host-owned lifetime. The host closes it in commit/rollback finally blocks. */ 4+export class ProjectionReadScope { 5+ readonly #graph: Graph; 6+ readonly #source: () => unknown; 7+ readonly #identity: unknown; 8+ readonly #parent: () => void; 9+ readonly #onClose: () => void; 13+ constructor(graph: Graph, source: () => unknown, parent = () => {}, onClose = () => {}) { 15+ this.#source = source; 16+ this.#identity = source(); 17+ this.#parent = parent; 18+ this.#onClose = onClose; 22+ if (!this.#active || this.#source() !== this.#identity) throw Error("expired projection read scope"); 24+ /** Capture this exact graph revision and scope generation, not a mutable validity flag. */ 25+ guard(graph: Graph): () => void { 27+ if (graph !== this.#graph || this.#child) throw Error("projection read scope mismatch"); 28+ const epoch = this.#epoch, 32+ if (this.#child || this.#epoch !== epoch || graph.size !== size) throw Error("stale projection reader"); 35+ nested(): ProjectionReadScope { 37+ if (this.#child) throw Error("projection child scope already active"); 39+ const epoch = ++this.#epoch; 40+ return new ProjectionReadScope( 45+ if (this.#epoch !== epoch) throw Error("expired projection parent scope"); 54+ if (!this.#active) return; 55+ this.#active = false; --- /dev/null
+++ b/src/engine/experimental/projection-reader.ts
@@ -0,0 +1,183 @@
1+import { startNode } from "../keys.ts"; 2+import { StableSet } from "../state-source.ts"; 3+import { joinLines } from "../text.ts"; 4+import type { FileAttrs, ReadView, SeqLine, VisibleLine } from "../view.ts"; 5+import type { ExperimentalMarkerProjection, MarkerState } from "./projection-marker.ts"; 7+/** Private reader for a host-verified immutable projection. Not a production View replacement. */ 8+export class ProjectionReader implements ReadView { 9+ readonly #adapter: ExperimentalMarkerProjection; 10+ readonly #state: MarkerState; 11+ readonly #assertLive: () => void; 12+ constructor(adapter: ExperimentalMarkerProjection, state: MarkerState, assertLive: () => void) { 14+ this.#assertLive = assertLive; 15+ adapter.assertContext(state); 16+ this.#adapter = adapter; 17+ this.#state = structuredClone(state); 21+ return this.#adapter.graph; 23+ get set(): ReadonlySet<string> { 25+ const has = (id: string) => 26+ this.graph.has(id) && 27+ (this.#adapter.members.get(this.#state.membership, this.graph.atom(id).seq)?.present ?? false); 28+ const assertLive = this.#assertLive; 29+ return new (class extends StableSet<string> { 30+ readonly retainedBytes = 64; 31+ has(id: string): boolean { 35+ values(): SetIterator<string> { 37+ throw Error("unsupported projected membership enumeration"); 43+ return this.knownPaths().filter((path) => this.hasFile(path)); 45+ files(): Record<string, string> { 47+ return Object.fromEntries( 49+ .filter((path) => this.attrs(path).blob === null) 50+ .map((path) => [path, this.text(path)]), 53+ blobs(): Record<string, string> { 55+ const result: Record<string, string> = {}; 56+ for (const path of this.paths()) { 57+ const blob = this.attrs(path).blob; 58+ if (blob !== null) result[path] = blob; 62+ lineNumber(path: string, line: string): number { 64+ return this.lines(path).findIndex((item) => item.id === line); 66+ sameText(path: string, other: ReadView): boolean { 68+ const a = this.lines(path), 69+ b = other.lines(path); 70+ return a.length === b.length && a.every((line, index) => line.text === b[index]!.text); 72+ visibleNeighbours(_path: string, _line: string): string[] { 74+ throw Error("unsupported projected visibleNeighbours"); 78+ throw Error("transaction projections cannot enter historical View cache"); 81+ attrs(path: string): FileAttrs { 83+ return this.#adapter.attrs(this.#state, path); 85+ knownPaths(): string[] { 87+ return this.#adapter.knownPaths(this.#state); 89+ hasMoves(): boolean { 91+ for (const id of this.graph.movers()) if (this.set.has(id)) return true; 94+ *visibleLines(path: string): IterableIterator<VisibleLine> { 96+ const graph = this.#adapter.graph; 97+ const iterator = this.#adapter.lineIds(this.#state, path); 100+ const next = iterator.next(); 102+ if (next.done) return; 103+ const id = next.value; 104+ const n = graph.lineN(id); 105+ yield { id, text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) }; 108+ lines(path: string): readonly VisibleLine[] { 110+ return [...this.visibleLines(path)]; 112+ sequence(path: string): readonly SeqLine[] { 114+ const adapter = this.#adapter, 115+ state = this.#state, 116+ graph = adapter.graph; 117+ const key = adapter.fileKey(path); 118+ const file = key === undefined ? undefined : adapter.markers.get(state.locator, key); 119+ if (!file) return []; 120+ const result: SeqLine[] = []; 121+ for (const node of adapter.sequence.range( 123+ adapter.sequence.rank(state.sequence, file.enter) + 1, 124+ adapter.sequence.rank(state.sequence, file.exit), 127+ if (node.text.endsWith(":end")) continue; 128+ const n = graph.lineN(node.text), 129+ writer = graph.writerSeqOf(n); 130+ if (!adapter.members.get(state.membership, writer)?.present) continue; 131+ const deletedBy = [...graph.eachDeleterSeqOf(n)] 132+ .filter((seq) => adapter.members.get(state.membership, seq)?.present) 133+ .sort((a, b) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b) 134+ .map((seq) => graph.idOfSeq(seq)); 137+ text: graph.textOf(n), 138+ atom: graph.idOfSeq(writer), 140+ visible: deletedBy.length === 0, 145+ sequenceIndex(path: string, line: string): number { 147+ return this.sequence(path).findIndex((item) => item.id === line); 149+ parentOf(line: string): string { 151+ const adapter = this.#adapter, 152+ state = this.#state; 153+ const marker = adapter.markers.get(state.locator, adapter.graph.lineN(line) + 1); 154+ if (marker?.kind !== "line") throw Error("missing projected line"); 155+ if (marker.parentKey > 0 && marker.parentKey < 0x80000000) return adapter.graph.lineIdOf(marker.parentKey - 1); 156+ const parent = adapter.markers.get(state.locator, marker.parentKey); 157+ if (parent?.kind !== "file") throw Error("missing projected file parent"); 158+ const text = adapter.sequence.get(state.sequence.map, parent.enter).text; 159+ if (!text.startsWith("root:")) throw Error("invalid projected file parent"); 160+ return startNode(text.slice(5)); 162+ fileOf(line: string): string { 164+ if (line.startsWith("^")) return line.slice(1); 165+ const marker = this.#adapter.markers.get(this.#state.locator, this.graph.lineN(line) + 1); 166+ if (marker?.kind !== "line") throw Error("missing projected line"); 167+ return this.#adapter.sequence.fileAt(this.#state.sequence, marker.enter); 169+ text(path: string): string { 171+ return joinLines([...this.visibleLines(path)].map((line) => line.text)); 173+ hasFile(path: string): boolean { 175+ const attrs = this.attrs(path); 178+ attrs.link !== null || 179+ attrs.blob !== null || 180+ !this.#adapter.lineIds(this.#state, path).next().done --- /dev/null
+++ b/src/engine/experimental/projection-records.ts
@@ -0,0 +1,79 @@
1+/** Persisted records for the internal projection experiment; not a production format. */ 2+export type ProjectionPage = number | null; 3+export interface FileMarker { 4+ readonly contributions: number; 5+ readonly kind: "file"; 6+ readonly enter: number; 7+ readonly exit: number; 9+export interface LineMarker { 10+ readonly kind: "line"; 11+ readonly enter: number; 12+ readonly exit: number; 13+ readonly parentKey: number; 14+ readonly key: string; 16+export type ProjectionMarker = FileMarker | LineMarker; 17+export interface ProjectionMembership { 18+ readonly present: boolean; 19+ readonly dependents: number; 21+export interface ProjectionChildRoot { 22+ readonly root: ProjectionPage; 24+export type ProjectionAttributeName = "exists" | "exec" | "link" | "blob"; 25+export type ProjectionAttributes = Partial<Record<ProjectionAttributeName, ProjectionPage>>; 26+export interface ProjectionAttributeValue { 27+ readonly value: string | null; 29+const safe = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0; 30+const record = (value: unknown): value is Record<string, unknown> => 31+ value !== null && typeof value === "object" && !Array.isArray(value); 32+const markerId = (value: unknown): value is number => safe(value) && value < 2 ** 32; 33+const page = (value: unknown): value is ProjectionPage => value === null || safe(value); 34+export function projectionMarker(value: unknown): ProjectionMarker { 35+ if (!record(value) || !markerId(value.enter) || !markerId(value.exit) || value.enter === value.exit) 36+ throw Error("invalid projection marker endpoints"); 37+ if (value.kind === "file" && Object.keys(value).length === 4 && safe(value.contributions)) 38+ return { kind: "file", enter: value.enter, exit: value.exit, contributions: value.contributions }; 40+ value.kind !== "line" || 41+ Object.keys(value).length !== 5 || 42+ !markerId(value.parentKey) || 43+ typeof value.key !== "string" || 44+ !/^[0-9a-f]{57}$/.test(value.key) 46+ throw Error("invalid projection line marker"); 47+ return { kind: "line", enter: value.enter, exit: value.exit, parentKey: value.parentKey, key: value.key }; 49+export function projectionMembership(value: unknown): ProjectionMembership { 52+ Object.keys(value).length !== 2 || 53+ typeof value.present !== "boolean" || 54+ !safe(value.dependents) || 55+ (!value.present && value.dependents !== 0) 57+ throw Error("invalid projection membership"); 58+ return { present: value.present, dependents: value.dependents }; 60+export function projectionChildRoot(value: unknown): ProjectionChildRoot { 61+ if (!record(value) || Object.keys(value).length !== 1 || !page(value.root)) 62+ throw Error("invalid projection child root"); 63+ return { root: value.root }; 65+export function projectionAttributes(value: unknown): ProjectionAttributes { 66+ if (!record(value) || Object.keys(value).length > 4) throw Error("invalid projection attributes"); 67+ const out: ProjectionAttributes = {}; 68+ for (const [name, root] of Object.entries(value)) { 69+ if (!["exists", "exec", "link", "blob"].includes(name) || !page(root)) 70+ throw Error("invalid projection attribute root"); 71+ out[name as ProjectionAttributeName] = root; 75+export function projectionAttributeValue(value: unknown): ProjectionAttributeValue { 76+ if (!record(value) || Object.keys(value).length !== 1 || (value.value !== null && typeof value.value !== "string")) 77+ throw Error("invalid projection attribute value"); 78+ return { value: value.value }; --- /dev/null
+++ b/src/engine/experimental/projection-root.ts
@@ -0,0 +1,121 @@
1+import type { GraphStateStorage } from "../state-source.ts"; 3+/** Internal experiment only. No production writer selects this format. */ 4+export interface ProjectionIdentity { 5+ readonly database: string; 6+ readonly namespace: string; 7+ readonly sourceGeneration: number; 8+ readonly sourceLength: number; 9+ readonly sourceDigest: string; 10+ readonly membership: string; 11+ readonly registry: string; 12+ readonly defaultFile: string; 14+export interface ProjectionRoots { 15+ readonly sequence: number | null; 16+ readonly sequenceRoot: number | null; 17+ readonly sequenceNext: number; 18+ readonly locator: number | null; 19+ readonly children: number | null; 20+ readonly membership: number | null; 21+ readonly attributes: number | null; 23+export interface ProjectionHandle { 26+ readonly identity: ProjectionIdentity; 28+interface RootRecord extends ProjectionHandle { 29+ readonly roots: ProjectionRoots; 50+const integer = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0; 51+const object = (value: unknown): value is Record<string, unknown> => 52+ value !== null && typeof value === "object" && !Array.isArray(value); 53+function identity(value: unknown): asserts value is ProjectionIdentity { 54+ if (!object(value) || Object.keys(value).length !== fields.length) throw Error("invalid projection identity"); 55+ for (const field of fields) { 56+ const item = value[field]; 57+ if (field === "sourceGeneration" || field === "sourceLength") { 58+ if (!integer(item)) throw Error("invalid projection source position"); 59+ } else if (typeof item !== "string" || item.length === 0 || item.length > 4096) 60+ throw Error("invalid projection identity field"); 62+ if (!/^[a-f0-9]{64}$/.test(value.sourceDigest as string)) throw Error("invalid projection source digest"); 64+function roots(value: unknown): asserts value is ProjectionRoots { 65+ if (!object(value) || Object.keys(value).length !== rootFields.length) throw Error("invalid projection roots"); 66+ for (const field of rootFields) 67+ if (value[field] !== null && !integer(value[field])) throw Error("invalid projection page reference"); 69+ !integer(value.sequenceNext) || 70+ value.sequenceNext > 2 ** 32 || 71+ (value.sequenceRoot !== null && (!integer(value.sequenceRoot) || value.sequenceRoot >= value.sequenceNext)) || 72+ (value.sequenceRoot === null) !== (value.sequenceNext === 0) || 73+ (value.sequence === null) !== (value.sequenceRoot === null) 75+ throw Error("invalid projection sequence state"); 77+export function assertProjectionIdentity(actual: ProjectionIdentity, expected: ProjectionIdentity): void { 80+ for (const field of fields) 81+ if (actual[field] !== expected[field]) throw Error(`projection identity mismatch: ${field}`); 83+function collection(expected: ProjectionIdentity): string { 84+ return `experimental-projection:${JSON.stringify([expected.database, expected.namespace])}:roots`; 86+/** Identity checks precede storage access. The host supplies trusted expected identity. */ 87+export function readProjectionRoot( 88+ storage: GraphStateStorage, 89+ handle: ProjectionHandle, 90+ expected: ProjectionIdentity, 92+ if (!object(handle) || handle.format !== 1 || !integer(handle.id)) throw Error("invalid projection handle"); 93+ assertProjectionIdentity(handle.identity, expected); 94+ const record = storage.read(collection(expected), String(handle.id)); 95+ if (!object(record) || record.format !== 1 || record.id !== handle.id || Object.keys(record).length !== 4) 96+ throw Error("invalid projection root record"); 97+ identity(record.identity); 98+ assertProjectionIdentity(record.identity, expected); 100+ return structuredClone(record.roots); 102+/** The caller's enclosing transaction must include canonical state and its receipt. */ 103+export function createProjectionRoot( 104+ storage: GraphStateStorage, 105+ expected: ProjectionIdentity, 107+ pages: ProjectionRoots, 108+): ProjectionHandle { 111+ if (!integer(id)) throw Error("invalid projection root id"); 112+ const frozenIdentity = structuredClone(expected), 113+ frozenPages = structuredClone(pages); 114+ return storage.transaction(() => { 115+ const name = collection(frozenIdentity); 116+ if (storage.read(name, String(id)) !== undefined) throw Error("projection root already exists"); 117+ const record: RootRecord = { format: 1, id, identity: frozenIdentity, roots: frozenPages }; 118+ storage.write(name, String(id), record); 119+ return { format: 1, id, identity: structuredClone(frozenIdentity) }; --- /dev/null
+++ b/src/engine/experimental/projection-sequence.ts
@@ -0,0 +1,343 @@
1+import type { GraphStateStorage } from "../state-source.ts"; 2+import { ProjectionLocator } from "./projection-locator.ts"; 4+type Page = number | null; 5+interface SequenceNode { 17+export interface SequenceState { 20+ readonly next: number; 22+export type SequenceOperation = 23+ | { kind: "insert"; rank: number; text: string } 24+ | { kind: "visibility"; id: number; delta: number } 25+ | { kind: "move"; from: number; length: number; to: number }; 26+const safe = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0; 27+function decode(value: unknown): SequenceNode { 28+ if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("invalid sequence node"); 29+ const row = value as Record<string, unknown>; 30+ if (Object.keys(row).length !== 10 || !safe(row.id) || row.id >= 2 ** 32 || typeof row.text !== "string") 31+ throw Error("invalid sequence node fields"); 32+ for (const name of ["parent", "left", "right"]) 33+ if (row[name] !== null && (!safe(row[name]) || Number(row[name]) >= 2 ** 32 || row[name] === row.id)) 34+ throw Error("invalid sequence edge"); 35+ for (const name of ["deletions", "height", "count", "visible", "fileStarts"]) 36+ if (!safe(row[name])) throw Error("invalid sequence aggregate"); 38+ Number(row.height) < 1 || 39+ Number(row.height) > 64 || 40+ Number(row.count) < 1 || 41+ Number(row.visible) > Number(row.count) || 42+ Number(row.fileStarts) > Number(row.count) 44+ throw Error("invalid sequence aggregate bounds"); 45+ return row as unknown as SequenceNode; 47+export class ProjectionSequence { 48+ readonly storage: GraphStateStorage; 49+ readonly #locator: ProjectionLocator<SequenceNode>; 50+ constructor(storage: GraphStateStorage, namespace: string) { 51+ this.storage = storage; 52+ this.#locator = new ProjectionLocator(storage, namespace, decode); 54+ empty(): SequenceState { 55+ return { map: null, root: null, next: 0 }; 57+ get(map: Page, id: number): SequenceNode { 58+ const node = this.#locator.get(map, id); 59+ if (!node || node.id !== id) throw Error("missing sequence node"); 60+ const child = (key: Page): SequenceNode | undefined => { 61+ if (key === null) return undefined; 62+ const value = this.#locator.get(map, key); 63+ if (!value || value.id !== key || value.parent !== id) throw Error("invalid sequence child identity"); 66+ const left = child(node.left), 67+ right = child(node.right); 69+ node.height !== 1 + Math.max(left?.height ?? 0, right?.height ?? 0) || 70+ Math.abs((left?.height ?? 0) - (right?.height ?? 0)) > 1 || 71+ node.count !== 1 + (left?.count ?? 0) + (right?.count ?? 0) || 72+ node.visible !== (node.deletions === 0 ? 1 : 0) + (left?.visible ?? 0) + (right?.visible ?? 0) || 73+ node.fileStarts !== (node.text.startsWith("root:") ? 1 : 0) + (left?.fileStarts ?? 0) + (right?.fileStarts ?? 0) 75+ throw Error("inconsistent sequence aggregate"); 78+ #state(state: SequenceState): void { 82+ state.next > 2 ** 32 || 83+ (state.map !== null && !safe(state.map)) || 84+ (state.root !== null && (!safe(state.root) || state.root >= state.next)) || 85+ (state.root === null) !== (state.next === 0) || 86+ (state.map === null) !== (state.root === null) 88+ throw Error("invalid sequence state"); 89+ if (state.root !== null && this.get(state.map, state.root).parent !== null) 90+ throw Error("invalid sequence root parent"); 92+ set(map: Page, id: number, node: SequenceNode): number { 93+ if (node.id !== id) throw Error("sequence node identity mismatch"); 94+ return this.#locator.set(map, id, node); 96+ rank(state: SequenceState, id: number): number { 98+ let node = this.get(state.map, id); 99+ if (!node) throw Error("unknown marker"); 100+ const count = (id: Page): number => (id === null ? 0 : this.get(state.map, id).count); 101+ let rank = count(node.left), 103+ while (node.parent !== null) { 104+ if (++steps > 64) throw Error("invalid parent chain"); 105+ const parent = this.get(state.map, node.parent); 106+ if (parent.right === node.id) rank += count(parent.left) + 1; 107+ else if (parent.left !== node.id) throw Error("broken parent edge"); 110+ if (node.id !== state.root) throw Error("wrong root"); 113+ /** Nearest file start before a marker, using subtree counts instead of line ancestry. */ 114+ fileAt(state: SequenceState, id: number): string { 115+ const target = this.rank(state, id); 116+ const seek = (id: Page, offset: number, depth: number): string | undefined => { 117+ if (id === null || offset > target) return undefined; 118+ if (depth > 64) throw Error("invalid file lookup depth"); 119+ const node = this.get(state.map, id); 120+ if (!node.fileStarts) return undefined; 121+ const leftCount = node.left === null ? 0 : this.get(state.map, node.left).count; 122+ const at = offset + leftCount; 124+ const right = seek(node.right, at + 1, depth + 1); 125+ if (right !== undefined) return right; 126+ if (node.text.startsWith("root:")) return node.text.slice(5); 128+ return seek(node.left, offset, depth + 1); 130+ const file = seek(state.root, 0, 0); 131+ if (file === undefined) throw Error("missing projected file start"); 134+ update(state: SequenceState, operation: SequenceOperation): SequenceState { 136+ return this.storage.transaction(() => { 137+ let map = state.map; 138+ // One operation changes an AVL path plus rotation neighbors, not history. 139+ // Keep only those decoded records and persist each final record once. 140+ const changed = new Map<number, SequenceNode>(); 141+ const get = (id: number): SequenceNode => changed.get(id) ?? this.get(map, id); 142+ const put = (node: SequenceNode): number => { 143+ changed.set(node.id, node); 146+ const height = (id: Page): number => (id === null ? 0 : get(id).height); 147+ const count = (id: Page): number => (id === null ? 0 : get(id).count); 148+ const visible = (id: Page): number => (id === null ? 0 : get(id).visible); 149+ const fileStarts = (id: Page): number => (id === null ? 0 : get(id).fileStarts); 150+ const parent = (id: Page, p: Page): void => { 152+ const node = get(id); 153+ if (node.parent !== p) put({ ...node, parent: p }); 156+ const save = (node: SequenceNode): number => { 157+ parent(node.left, node.id); 158+ parent(node.right, node.id); 161+ height: 1 + Math.max(height(node.left), height(node.right)), 162+ count: 1 + count(node.left) + count(node.right), 163+ visible: (node.deletions === 0 ? 1 : 0) + visible(node.left) + visible(node.right), 164+ fileStarts: (node.text.startsWith("root:") ? 1 : 0) + fileStarts(node.left) + fileStarts(node.right), 167+ const rotateLeft = (id: number): number => { 170+ save({ ...a, right: b.left, parent: b.id }); 171+ return save({ ...b, left: a.id, parent: a.parent }); 173+ const rotateRight = (id: number): number => { 176+ save({ ...a, left: b.right, parent: b.id }); 177+ return save({ ...b, right: a.id, parent: a.parent }); 179+ const balance = (id: number): number => { 180+ const node = get(id); 181+ if (height(node.left) - height(node.right) > 1) { 182+ const left = get(node.left!); 183+ if (height(left.left) < height(left.right)) save({ ...node, left: rotateLeft(left.id) }); 184+ return rotateRight(id); 186+ if (height(node.right) - height(node.left) > 1) { 187+ const right = get(node.right!); 188+ if (height(right.right) < height(right.left)) save({ ...node, right: rotateRight(right.id) }); 189+ return rotateLeft(id); 193+ let root = state.root, 195+ if (operation.kind === "insert") { 196+ const { rank, text } = operation; 197+ if (!Number.isInteger(rank) || rank < 0 || rank > count(root) || next >= 2 ** 32) throw Error("invalid insert"); 198+ const added = next++; 199+ const insert = (id: Page, at: number, p: Page): number => { 211+ fileStarts: text.startsWith("root:") ? 1 : 0, 213+ const node = get(id), 214+ leftCount = count(node.left); 215+ if (at <= leftCount) save({ ...node, left: insert(node.left, at, id) }); 216+ else save({ ...node, right: insert(node.right, at - leftCount - 1, id) }); 219+ root = insert(root, rank, null); 221+ } else if (operation.kind === "move") { 222+ const { from, length, to } = operation; 223+ const total = count(root); 225+ ![from, length, to].every(Number.isSafeInteger) || 228+ from + length > total || 232+ throw Error("invalid move range"); 233+ // Join two AVL trees around one existing stable marker. 234+ const join = (left: Page, pivot: number, right: Page): number => { 235+ if (height(left) > height(right) + 1) { 236+ const node = get(left!); 237+ save({ ...node, right: join(node.right, pivot, right) }); 238+ const result = balance(left!); 239+ parent(result, null); 242+ if (height(right) > height(left) + 1) { 243+ const node = get(right!); 244+ save({ ...node, left: join(left, pivot, node.left) }); 245+ const result = balance(right!); 246+ parent(result, null); 249+ return save({ ...get(pivot), left, right, parent: null }); 251+ const split = (id: Page, at: number): [Page, Page] => { 252+ if (id === null) return [null, null]; 253+ const node = get(id), 254+ size = count(node.left); 256+ const [left, middle] = split(node.left, at); 257+ const right = join(middle, id, node.right); 259+ parent(right, null); 260+ return [left, right]; 262+ const [middle, right] = split(node.right, at - size - 1); 263+ const left = join(node.left, id, middle); 265+ parent(right, null); 266+ return [left, right]; 268+ const merge = (left: Page, right: Page): Page => { 269+ if (left === null) { 270+ parent(right, null); 273+ if (right === null) { 277+ const [pivot, rest] = split(right, 1); 278+ return join(left, pivot!, rest); 280+ if (length && from !== to) { 281+ const [left, tail] = split(root, from); 282+ const [moved, right] = split(tail, length); 283+ const remaining = merge(left, right); 284+ const [before, after] = split(remaining, to); 285+ root = merge(merge(before, moved), after); 288+ } else if (operation.kind === "visibility") { 289+ let node = get(operation.id); 292+ !Number.isInteger(operation.delta) || 293+ Math.abs(operation.delta) !== 1 || 294+ node.deletions + operation.delta < 0 296+ throw Error("invalid visibility"); 297+ save({ ...node, deletions: node.deletions + operation.delta }); 298+ while (node.parent !== null) { 299+ node = get(node.parent); 302+ } else throw Error("unknown operation"); 303+ for (const [id, node] of changed) map = this.set(map, id, node); 304+ return { map, root, next }; 308+ state: SequenceState, 312+ ): IterableIterator<{ id: number; text: string }> { 314+ if (!safe(from) || !safe(to) || from > to) throw Error("invalid sequence range"); 315+ const visit = function* ( 316+ seq: ProjectionSequence, 319+ ): IterableIterator<{ id: number; text: string }> { 320+ if (id === null) return; 321+ const node = seq.get(state.map, id); 322+ if ((visibleOnly && !node.visible) || offset >= to || offset + node.count <= from) return; 323+ const leftCount = node.left === null ? 0 : seq.get(state.map, node.left).count; 324+ yield* visit(seq, node.left, offset); 325+ const at = offset + leftCount; 326+ if (at >= from && at < to && (!visibleOnly || node.deletions === 0)) yield { id: node.id, text: node.text }; 327+ yield* visit(seq, node.right, at + 1); 329+ yield* visit(this, state.root, 0); 331+ *values(state: SequenceState, visibleOnly = true): IterableIterator<{ id: number; text: string }> { 333+ const visit = function* (seq: ProjectionSequence, id: Page): IterableIterator<{ id: number; text: string }> { 334+ if (id === null) return; 335+ const node = seq.get(state.map, id); 336+ if (visibleOnly && node.visible === 0) return; 337+ yield* visit(seq, node.left); 338+ if (!visibleOnly || node.deletions === 0) yield { id: node.id, text: node.text }; 339+ yield* visit(seq, node.right); 341+ yield* visit(this, state.root); --- /dev/null
+++ b/src/engine/experimental/projection-snapshots.ts
@@ -0,0 +1,82 @@
1+import type { GraphStateStorage } from "../state-source.ts"; 2+import type { ExperimentalMarkerProjection, MarkerState } from "./projection-marker.ts"; 4+ assertProjectionIdentity, 6+ type ProjectionHandle, 7+ type ProjectionIdentity, 9+} from "./projection-root.ts"; 11+type Context = Pick<ProjectionIdentity, "database" | "namespace" | "registry" | "defaultFile">; 12+/** Internal snapshot boundary. The host supplies verified canonical and membership identities. */ 13+export class ProjectionSnapshots { 14+ readonly #storage: GraphStateStorage; 15+ readonly #adapter: ExperimentalMarkerProjection; 16+ readonly #context: Context; 17+ readonly #collection: string; 18+ constructor(storage: GraphStateStorage, adapter: ExperimentalMarkerProjection, context: Context) { 19+ this.#storage = storage; 20+ this.#adapter = adapter; 22+ database: context.database, 23+ namespace: context.namespace, 24+ registry: context.registry, 25+ defaultFile: context.defaultFile, 27+ this.#collection = `experimental-projection:${JSON.stringify([context.database, context.namespace])}:context`; 28+ if (adapter.context !== JSON.stringify([context.namespace, context.defaultFile])) 29+ throw Error("projection snapshot constructor mismatch"); 31+ #expected(expected: ProjectionIdentity): void { 32+ assertProjectionIdentity(expected, expected); 33+ for (const field of ["database", "namespace", "registry", "defaultFile"] as const) 34+ if (expected[field] !== this.#context[field]) throw Error(`projection snapshot context mismatch: ${field}`); 36+ #registry(create: boolean): void { 37+ const stored = this.#storage.read(this.#collection, "binding"); 38+ if (stored === undefined) { 39+ if (!create) throw Error("missing projection registry binding"); 40+ this.#storage.write(this.#collection, "binding", this.#context); 43+ if (!stored || typeof stored !== "object" || Array.isArray(stored) || Object.keys(stored).length !== 4) 44+ throw Error("invalid projection registry binding"); 45+ for (const field of ["database", "namespace", "registry", "defaultFile"] as const) 46+ if ((stored as Record<string, unknown>)[field] !== this.#context[field]) 47+ throw Error("projection registry binding mismatch"); 49+ save(id: number, expected: ProjectionIdentity, state: MarkerState): ProjectionHandle { 50+ this.#expected(expected); 51+ this.#adapter.assertContext(state); 52+ return this.#storage.transaction(() => { 53+ this.#registry(true); 54+ if (state.sequence.root !== null) this.#adapter.sequence.rank(state.sequence, state.sequence.root); 55+ return createProjectionRoot(this.#storage, expected, id, { 56+ sequence: state.sequence.map, 57+ sequenceRoot: state.sequence.root, 58+ sequenceNext: state.sequence.next, 59+ locator: state.locator, 60+ children: state.children, 61+ membership: state.membership, 62+ attributes: state.attributeFiles, 66+ load(handle: ProjectionHandle, expected: ProjectionIdentity): MarkerState { 67+ this.#expected(expected); 68+ assertProjectionIdentity(handle.identity, expected); 69+ this.#registry(false); 70+ const roots = readProjectionRoot(this.#storage, handle, expected); 71+ const state: MarkerState = { 72+ context: this.#adapter.context, 73+ sequence: { map: roots.sequence, root: roots.sequenceRoot, next: roots.sequenceNext }, 74+ locator: roots.locator, 75+ children: roots.children, 76+ membership: roots.membership, 77+ attributeFiles: roots.attributes, 79+ if (state.sequence.root !== null) this.#adapter.sequence.rank(state.sequence, state.sequence.root); --- /dev/null
+++ b/src/engine/test/projection-locator.test.ts
@@ -0,0 +1,49 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { ProjectionLocator } from "../experimental/projection-locator.ts"; 4+import { SqlState } from "./storage-helper.ts"; 6+const decode = (value: unknown): number => { 7+ if (!Number.isSafeInteger(value)) throw Error("invalid payload"); 8+ return value as number; 10+test("experimental locator preserves sparse old roots and rejects corrupt storage", () => { 11+ const storage = new SqlState(); 13+ const index = new ProjectionLocator(storage, "test", decode), 14+ keys = [0, 0xffffffff, 16, 1, 0x80000000, 255, 256]; 15+ let root: number | null = null; 16+ const versions: number[] = []; 17+ for (const id of keys) { 18+ root = index.set(root, id, id); 21+ for (let i = 0; i < versions.length; i++) 22+ for (let j = 0; j < keys.length; j++) 23+ assert.equal(index.get(versions[i]!, keys[j]!), j <= i ? keys[j] : undefined); 24+ const before = JSON.stringify(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all()); 25+ storage.failWrite = storage.writes + 3; 26+ assert.throws(() => index.set(root, 42, 42), /injected/); 27+ assert.equal(JSON.stringify(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all()), before); 28+ storage.failWrite = Infinity; 29+ for (const id of [-1, 2 ** 32, 0.5, NaN]) assert.throws(() => index.get(root, id), /identity limit/); 30+ const collection = 'experimental-locator:"test"', 31+ saved = storage.read(collection, String(root)); 32+ for (const corrupt of [ 33+ { format: 2, kind: "leaf", prefix: "00000000", value: 0 }, 34+ { format: 1, kind: "leaf", prefix: "0", value: 0 }, 35+ { format: 1, kind: "branch", prefix: "", children: { "0": root, f: 0 } }, 36+ { format: 1, kind: "branch", prefix: "", children: { "00": 0, f: 1 } }, 38+ storage.write(collection, String(root), corrupt); 39+ assert.throws(() => index.get(root, 0), /invalid locator/); 41+ storage.write(collection, String(root), saved); 42+ assert.equal(index.get(root, 16), 16); 43+ const leaf = index.set(null, 7, 7); 44+ storage.write(collection, String(leaf), { format: 1, kind: "leaf", prefix: "00000007", value: "bad" }); 45+ assert.throws(() => index.get(leaf, 7), /invalid payload/); --- /dev/null
+++ b/src/engine/test/projection-marker-cycle.test.ts
@@ -0,0 +1,83 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { ExperimentalMarkerProjection as MarkerProjection } from "../experimental/projection-marker.ts"; 4+import { Graph } from "../graph.ts"; 5+import { CachedStateStorage } from "../state-source.ts"; 6+import { Repo, Rng } from "./helpers.ts"; 7+import { SqlState } from "./storage-helper.ts"; 9+test("typed marker projection matches competing cyclic moves and removals", () => { 10+ const db = new SqlState(); 12+ const repo = Repo.init({ "f.txt": Array.from({ length: 12 }, (_, n) => `${n}\n`).join("") }), 13+ graph = new Graph({ storage: new CachedStateStorage(db) }), 14+ rng = new Rng(45131); 15+ graph.add(repo.graph.atom("a0")); 16+ const p = new MarkerProjection(db, graph, "f.txt", "typed-" + "cycle"); 17+ let state = p.apply(p.empty(), repo.graph.atom("a0")), 20+ const check = () => { 21+ const view = repo.view(); 24+ view.lines("f.txt").map((x) => x.id), 26+ for (let n = 0; n < 12; n++) { 27+ const parent = view.parentOf(`a0.${n}`); 29+ (p.markers.get(state.locator, n + 1) as { parentKey: number }).parentKey, 30+ parent.startsWith("^") ? 0 : graph.lineN(parent) + 1, 35+ for (let j = 0; j < 24; j++) { 36+ const offset = rng.int(12), 37+ moves = Array.from({ length: 3 }, (_, i) => { 38+ const line = `a0.${(offset + i) % 12}`, 39+ candidate = `a0.${rng.int(12)}`; 40+ return { line, parent: candidate === line ? "^f.txt" : candidate }; 43+ id: repo.graph.nextId(), 44+ seq: repo.graph.size, 50+ writes: moves.flatMap((m) => [`P:${m.line}`, `G:${m.parent}`]), 59+ repo.graph.add(atom); 60+ repo.shared.add(atom.id); 63+ state = p.apply(state, atom); 66+ for (const atom of atoms.filter((_, i) => i % 2 === 0)) { 67+ repo.shared.delete(atom.id); 68+ state = p.removeAtom(state, atom); 74+ "SELECT count(*) AS n FROM state WHERE collection LIKE '%sequence-resolver:%' OR collection LIKE '%sequence-relocation-work:%'", 79+ assert.equal(checks, 36); --- /dev/null
+++ b/src/engine/test/projection-marker-move-failures.test.ts
@@ -0,0 +1,86 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { ExperimentalMarkerProjection as MarkerProjection } from "../experimental/projection-marker.ts"; 4+import { Graph } from "../graph.ts"; 5+import { CachedStateStorage } from "../state-source.ts"; 6+import { Repo, Rng } from "./helpers.ts"; 7+import { SqlState } from "./storage-helper.ts"; 9+test("typed marker move transaction rolls back each selected phase", () => { 10+ const db = new SqlState(); 12+ const repo = Repo.init({ "f.txt": "a\nb\nc\n" }), 13+ graph = new Graph({ storage: new CachedStateStorage(db) }); 14+ graph.add(repo.graph.atom("a0")); 15+ const p = new MarkerProjection(db, graph, "f.txt", "typed-" + "move-failures"), 16+ before = p.apply(p.empty(), repo.graph.atom("a0")); 17+ const atom = repo.edit({ move: { file: "f.txt", start: 0, end: 1, to: "f.txt", at: 3 } }); 19+ const originalWrite = db.write.bind(db), 20+ originalRemove = db.remove.bind(db), 21+ events: { kind: string; collection: string; key: string }[] = []; 22+ db.write = (collection, key, value) => { 23+ events.push({ kind: "write", collection, key }); 24+ return originalWrite(collection, key, value); 26+ db.remove = (collection, key) => { 27+ events.push({ kind: "remove", collection, key }); 28+ return originalRemove(collection, key); 30+ const sentinel = Error("rollback measured success"); 33+ db.transaction(() => { 34+ p.apply(before, atom); 37+ (e) => e === sentinel, 39+ db.write = originalWrite; 40+ db.remove = originalRemove; 41+ const offsets = new Set([0, events.length - 1]); 42+ for (const prefix of ["sequence-resolver:", "sequence-relocation-work:"]) { 43+ offsets.add(events.findIndex((e) => e.collection.includes(prefix))); 44+ offsets.add(events.findIndex((e) => e.kind === "remove" && e.collection.includes(prefix))); 46+ const plan = events.findIndex((e) => e.collection.includes("sequence-relocation-work:")); 47+ offsets.add(events.findIndex((e, i) => i > plan && e.collection.includes(":sequence"))); 48+ const rows = () => JSON.stringify(db.db.prepare("SELECT * FROM state ORDER BY collection,key").all()); 49+ const baseline = rows(), 51+ for (const offset of [...offsets].filter((n) => n >= 0).sort((a, b) => a - b)) { 54+ if (cursor++ === offset) throw Error("injected phase failure"); 56+ db.write = (c, k, v) => { 58+ return originalWrite(c, k, v); 60+ db.remove = (c, k) => { 62+ return originalRemove(c, k); 64+ assert.throws(() => p.apply(before, atom), /injected phase failure/); 65+ db.write = originalWrite; 66+ db.remove = originalRemove; 67+ assert.equal(rows(), baseline); 68+ assert.deepEqual(p.lines(before), ["a0.0", "a0.1", "a0.2"]); 69+ results.push({ offset, ...events[offset] }); 71+ const state = p.apply(before, atom); 79+ const writes = db.writes; 80+ assert.equal(p.apply(state, atom), state); 81+ assert.equal(db.writes, writes); 82+ assert.equal(results.length, 7); --- /dev/null
+++ b/src/engine/test/projection-marker.test.ts
@@ -0,0 +1,120 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { ExperimentalMarkerProjection as MarkerProjection } from "../experimental/projection-marker.ts"; 4+import { Graph } from "../graph.ts"; 5+import { CachedStateStorage } from "../state-source.ts"; 6+import { Repo } from "./helpers.ts"; 7+import { SqlState } from "./storage-helper.ts"; 9+test("typed marker projection matches mixed multi-file edits and reverse removals", () => { 10+ const db = new SqlState(); 12+ const repo = Repo.init({ "f.txt": "a\nb\nc\n", "g.txt": "x\ny\n" }), 13+ graph = new Graph({ storage: new CachedStateStorage(db) }); 14+ graph.add(repo.graph.atom("a0")); 15+ const p = new MarkerProjection(db, graph, "f.txt", "typed-mixed"); 16+ let state = p.apply(p.empty(), repo.graph.atom("a0")), 20+ const check = () => { 21+ const view = repo.view(); 22+ for (const path of ["f.txt", "g.txt"]) { 24+ p.lines(state, path), 25+ view.lines(path).map((x) => x.id), 27+ assert.deepEqual(p.attrs(state, path), view.attrs(path)); 31+ for (let i = 0; i < 36; i++) { 32+ const file = i % 2 ? "f.txt" : "g.txt", 33+ other = i % 2 ? "g.txt" : "f.txt", 35+ let input: Parameters<Repo["edit"]>[0]; 36+ if (i % 3 === 0 && view.lines(file).length) input = { move: { file, start: 0, end: 1, to: other, at: 0 } }; 37+ else if (i % 3 === 1) 39+ edits: [{ file, old: view.text(file), new: `new ${i}\n${view.text(file)}` }], 40+ attrs: [{ file, name: "exec", value: i % 2 ? "1" : null }], 42+ else input = { edits: [{ file, old: view.text(file), new: `rewrite ${i}\n` }] }; 43+ const atom = repo.edit(input); 46+ state = p.apply(state, atom); 48+ if (i % 9 === 0) roots.push({ state, f: p.lines(state, "f.txt"), g: p.lines(state, "g.txt") }); 50+ for (const atom of atoms.toReversed()) { 51+ repo.shared.delete(atom.id); 52+ state = p.removeAtom(state, atom); 55+ for (const root of roots) { 56+ assert.deepEqual(p.lines(root.state, "f.txt"), root.f); 57+ assert.deepEqual(p.lines(root.state, "g.txt"), root.g); 59+ assert.equal(checks, 72); 65+test("typed marker namespaces isolate file identities and temporary metadata", () => { 66+ const storage = new SqlState(); 68+ const repo = Repo.init({ "f.txt": "f\n", "g.txt": "g\n" }); 69+ const graph = new Graph({ storage: new CachedStateStorage(storage) }); 70+ graph.add(repo.graph.atom("a0")); 71+ const alpha = new MarkerProjection(storage, graph, "f.txt", "alpha"); 72+ const beta = new MarkerProjection(storage, graph, "g.txt", "beta"); 73+ const a = alpha.apply(alpha.empty(), repo.graph.atom("a0")); 74+ const b = beta.apply(beta.empty(), repo.graph.atom("a0")); 75+ const wrongFile = new MarkerProjection(storage, graph, "g.txt", "alpha"); 76+ for (const other of [beta, wrongFile]) { 77+ const reads = storage.reads, 78+ writes = storage.writes; 79+ assert.throws(() => other.lines(a, "f.txt"), /constructor context mismatch/); 80+ assert.throws(() => other.apply(a, repo.graph.atom("a0")), /constructor context mismatch/); 81+ assert.equal(storage.reads, reads); 82+ assert.equal(storage.writes, writes); 85+ for (const path of ["f.txt", "g.txt"]) { 87+ alpha.lines(a, path), 101+ alpha.storage.write("sequence-meta", "work-scope", 91); 102+ assert.equal(beta.storage.read("sequence-meta", "work-scope"), undefined); 103+ const rows = () => JSON.stringify(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all()); 104+ const before = rows(); 106+ () => alpha.relocateBatch(a, [{ n: -1, parentKey: 0, key: "0".repeat(57) }]), 107+ /invalid relocation plan/, 109+ assert.equal(rows(), before); 111+ beta.lines(b, "f.txt"), --- /dev/null
+++ b/src/engine/test/projection-overlay-storage.test.ts
@@ -0,0 +1,51 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { ProjectionOverlayStorage } from "../experimental/projection-overlay-storage.ts"; 4+import { SqlState } from "./storage-helper.ts"; 6+test("temporary projection pages shadow committed pages and cleanup preserves durable writes", () => { 7+ const storage = new SqlState(); 9+ storage.write("pages", "one", { n: 1 }); 10+ storage.write("pages", "two", { n: 2 }); 11+ const overlay = new ProjectionOverlayStorage(storage, "read-a"); 12+ storage.transaction(() => { 13+ overlay.write("pages", "one", { n: 10 }); 14+ overlay.remove("pages", "two"); 15+ overlay.write("pages", "three", { n: 3 }); 16+ assert.deepEqual(overlay.read("pages", "one"), { n: 10 }); 17+ assert.equal(overlay.read("pages", "two"), undefined); 18+ assert.deepEqual([...overlay.entries("pages")].sort(), [ 22+ assert.throws(() => new ProjectionOverlayStorage(storage, "read-a"), /occupied/); 25+ overlay.transaction(() => { 26+ overlay.write("pages", "one", 99); 31+ assert.deepEqual(overlay.read("pages", "one"), { n: 10 }); 32+ storage.write("roots", "committed", { root: 7 }); 33+ const iterator = overlay.entries("pages")[Symbol.iterator](); 36+ assert.throws(() => iterator.next(), /closed/); 39+ [...storage.entries("pages")], 45+ assert.deepEqual(storage.read("roots", "committed"), { root: 7 }); 46+ assert.deepEqual([...storage.entries("projection:temporary:read-a")], []); 47+ assert.throws(() => overlay.read("pages", "one"), /closed/); --- /dev/null
+++ b/src/engine/test/projection-priority.test.ts
@@ -0,0 +1,53 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { ProjectionPriority } from "../experimental/projection-priority.ts"; 4+import { orderedChildKey } from "../ordered-index.ts"; 5+import { SqlState } from "./storage-helper.ts"; 7+const decode = (value: unknown): number => { 8+ if (!Number.isSafeInteger(value)) throw Error("invalid payload"); 9+ return value as number; 11+test("experimental priority retains old roots, removes winners and rejects corrupt pages", () => { 12+ const storage = new SqlState(); 14+ const index = new ProjectionPriority(storage, "test", decode), 15+ oracle: { key: string; value: number }[] = []; 16+ let root: number | null = null; 17+ for (let n = 0; n < 96; n++) { 18+ const key = orderedChildKey({ n, replaces: n % 2, lamport: (n * 71) % 97, seq: n, k: 0 }); 19+ const expected = oracle.filter((entry) => entry.key < key).at(-1)?.value; 20+ assert.equal(index.before(root, key), expected); 21+ const old: number | null = root; 22+ root = index.insert(root, key, n); 23+ assert.equal(index.before(old, key), expected); 24+ oracle.push({ key, value: n }); 25+ oracle.sort((a, b) => a.key.localeCompare(b.key)); 28+ const greatest = oracle.pop()!; 29+ root = index.remove(root, greatest.key); 30+ assert.equal(index.before(root, "f".repeat(57)), oracle.at(-1)!.value); 31+ assert.equal(index.before(full, "f".repeat(57)), greatest.value); 32+ const rows = () => JSON.stringify(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all()); 33+ const before = rows(); 34+ storage.failWrite = storage.writes + 3; 35+ assert.throws(() => index.insert(root, "e".repeat(57), 100), /injected/); 36+ assert.equal(rows(), before); 37+ storage.failWrite = Infinity; 38+ const collection = 'experimental-priority:"test"', 39+ saved = storage.read(collection, String(root)); 40+ for (const corrupt of [ 41+ { format: 1, kind: "branch", depth: 1, children: { "0": 0 } }, 42+ { format: 1, kind: "branch", depth: 0, children: { f: root } }, 43+ { format: 1, kind: "branch", depth: 0, children: {} }, 45+ storage.write(collection, String(root), corrupt); 46+ assert.throws(() => index.before(root, "f".repeat(57)), /invalid priority/); 48+ storage.write(collection, String(root), saved); 49+ assert.equal(index.before(root, "f".repeat(57)), oracle.at(-1)!.value); --- /dev/null
+++ b/src/engine/test/projection-read-scope.test.ts
@@ -0,0 +1,56 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { ExperimentalMarkerProjection } from "../experimental/projection-marker.ts"; 4+import { ProjectionReadScope } from "../experimental/projection-read-scope.ts"; 5+import { ProjectionReader } from "../experimental/projection-reader.ts"; 6+import { Graph } from "../graph.ts"; 7+import { Repo } from "./helpers.ts"; 8+import { SqlState } from "./storage-helper.ts"; 10+for (const end of ["commit", "rollback", "source", "nested", "graph"] as const) { 11+ test(`projected reads reject stale methods, membership and iterator resume after ${end}`, (t) => { 12+ const storage = new SqlState(); 14+ const repo = Repo.init({ "f.txt": "one\ntwo\n" }); 15+ const graph = new Graph(); 16+ graph.add(repo.graph.atom("a0")); 17+ const adapter = new ExperimentalMarkerProjection(storage, graph, "f.txt", "scope-test"); 18+ const state = adapter.apply(adapter.empty(), graph.atom("a0")); 20+ const scope = new ProjectionReadScope(graph, () => source); 21+ assert.throws(() => scope.guard(new Graph()), /mismatch/); 22+ const reader = new ProjectionReader(adapter, state, scope.guard(graph)); 23+ const membership = reader.set; 24+ const iterator = reader.visibleLines("f.txt"); 25+ assert.equal(iterator.next().value?.text, "one"); 26+ if (end === "source") source = {}; 27+ else if (end === "nested") { 28+ const child = scope.nested(); 29+ assert.throws(() => reader.text("f.txt"), /stale/); 30+ const childGuard = child.guard(graph); 33+ assert.throws(childGuard, /expired/); 34+ scope.guard(graph)(); 35+ } else if (end === "graph") { 36+ repo.edit({ edits: [{ file: "f.txt", old: "one\ntwo\n", new: "changed\n" }] }); 37+ graph.add(repo.graph.atom("a1")); 38+ } else scope.close(); 40+ const refuseAccess = () => { 42+ throw Error("expired reader touched data"); 44+ t.mock.method(storage, "read", refuseAccess); 45+ t.mock.method(storage, "entries", refuseAccess); 46+ t.mock.method(graph, "lineN", refuseAccess); 47+ t.mock.method(graph, "textOf", refuseAccess); 48+ assert.throws(() => reader.text("f.txt"), /expired|stale/); 49+ assert.throws(() => membership.has("a0"), /expired|stale/); 50+ assert.throws(() => iterator.next(), /expired|stale/); 51+ assert.equal(touched, false); --- /dev/null
+++ b/src/engine/test/projection-reader.test.ts
@@ -0,0 +1,113 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { buildAtom } from "../build.ts"; 4+import { ExperimentalMarkerProjection } from "../experimental/projection-marker.ts"; 5+import { ProjectionReadScope } from "../experimental/projection-read-scope.ts"; 6+import { ProjectionReader } from "../experimental/projection-reader.ts"; 7+import { Graph } from "../graph.ts"; 8+import { CachedStateStorage } from "../state-source.ts"; 10+import { Repo } from "./helpers.ts"; 11+import { SqlState } from "./storage-helper.ts"; 13+test("unchanged atom builder consumes the private reader for replacement and insertion edits", () => { 14+ const storage = new SqlState(); 16+ const repo = Repo.init({ "f.txt": "one\ntwo\nthree\n" }); 17+ const graph = new Graph({ storage: new CachedStateStorage(storage) }); 18+ graph.add(repo.graph.atom("a0")); 19+ const adapter = new ExperimentalMarkerProjection(storage, graph, "f.txt", "builder-reader"); 20+ let state = adapter.apply(adapter.empty(), graph.atom("a0")); 21+ for (let i = 0; i < 16; i++) { 24+ message: `Edit ${i}`, 29+ old: repo.view().text("f.txt"), 30+ new: `one\nrevision ${i}\nthree\n${i % 2 ? "extra\n" : ""}`, 34+ const expected = buildAtom(repo.view(), input); 35+ const reader = new ProjectionReader(adapter, state, new ProjectionReadScope(graph, () => graph).guard(graph)); 36+ const actual = buildAtom(reader, input); 37+ assert.deepEqual(actual, expected); 39+ repo.graph.add(expected); 40+ repo.shared.add(expected.id); 41+ state = adapter.apply(state, actual); 43+ new ProjectionReader(adapter, state, new ProjectionReadScope(graph, () => graph).guard(graph)).text("f.txt"), 44+ repo.view().text("f.txt"), 52+test("private reader builds cross-file moves and resurrects a deleted file", (t) => { 53+ const storage = new SqlState(); 55+ const repo = Repo.init({ "f.txt": "one\ntwo\nthree\n", "g.txt": "other\n" }); 56+ const graph = new Graph({ storage: new CachedStateStorage(storage) }); 57+ graph.add(repo.graph.atom("a0")); 58+ const adapter = new ExperimentalMarkerProjection(storage, graph, "f.txt", "reader-moves"); 59+ let state = adapter.apply(adapter.empty(), graph.atom("a0")); 60+ const inputs: Parameters<typeof buildAtom>[1][] = [ 61+ { author: "writer", message: "Move", move: { file: "f.txt", start: 1, end: 2, to: "g.txt", at: 1 } }, 62+ { author: "writer", message: "Delete file", edits: [{ file: "f.txt", old: "one\nthree\n", new: "" }] }, 63+ { author: "writer", message: "Recreate file", edits: [{ file: "f.txt", old: "", new: "reborn\n" }] }, 64+ { author: "writer", message: "Move back", move: { file: "g.txt", start: 1, end: 2, to: "f.txt", at: 0 } }, 66+ for (const input of inputs) { 67+ const expected = buildAtom(repo.view(), input), 68+ reader = new ProjectionReader(adapter, state, new ProjectionReadScope(graph, () => graph).guard(graph)); 69+ const actual = buildAtom(reader, input); 70+ assert.deepEqual(actual, expected); 72+ repo.graph.add(expected); 73+ repo.shared.add(expected.id); 74+ state = adapter.apply(state, actual); 75+ const projected = new ProjectionReader(adapter, state, new ProjectionReadScope(graph, () => graph).guard(graph)); 76+ t.mock.method(projected, "parentOf", () => { 77+ throw Error("line ancestry traversal forbidden"); 79+ for (const path of ["f.txt", "g.txt"]) { 80+ assert.deepEqual(projected.sequence(path), repo.view().sequence(path)); 81+ for (const line of projected.sequence(path)) 82+ assert.equal(projected.fileOf(line.id), repo.view().fileOf(line.id)); 90+test("reader orders deletion contributors by Lamport before sequence and treats unknown membership as absent", () => { 91+ const storage = new SqlState(); 93+ const repo = Repo.init({ "f.txt": "target\n", "g.txt": "other\n" }); 94+ const chain = repo.edit({ edits: [{ file: "g.txt", old: "other", new: "changed" }] }); 95+ const high = repo.edit({ edits: [{ file: "f.txt", old: "target\n", new: "" }], needs: [chain.id] }); 96+ const low = repo.edit({ edits: [{ file: "f.txt", old: "target\n", new: "" }] }, ["a0"]); 97+ assert.ok(repo.graph.lamportOfSeq(high.seq) > repo.graph.lamportOfSeq(low.seq)); 98+ assert.ok(high.seq < low.seq); 99+ const graph = new Graph({ storage: new CachedStateStorage(storage) }); 100+ const adapter = new ExperimentalMarkerProjection(storage, graph, "f.txt", "reader-priority"); 101+ let state = adapter.empty(); 102+ for (const id of ["a0", chain.id, high.id, low.id]) { 103+ const atom = repo.graph.atom(id); 105+ state = adapter.apply(state, atom); 107+ const reader = new ProjectionReader(adapter, state, new ProjectionReadScope(graph, () => graph).guard(graph)); 108+ assert.deepEqual(reader.sequence("f.txt"), repo.view().sequence("f.txt")); 109+ assert.equal(reader.set.has("unknown-atom"), false); --- /dev/null
+++ b/src/engine/test/projection-records.test.ts
@@ -0,0 +1,41 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 5+ projectionAttributeValue, 9+} from "../experimental/projection-records.ts"; 11+test("experimental projection record decoders reject contradictory persisted state", () => { 12+ const file = { kind: "file", enter: 1, exit: 2, contributions: 0 }; 13+ assert.deepEqual(projectionMarker(file), file); 14+ const line = { kind: "line", enter: 3, exit: 4, parentKey: 0, key: "0".repeat(57) }; 15+ assert.deepEqual(projectionMarker(line), line); 16+ for (const value of [ 17+ { ...file, exit: 1 }, 18+ { ...file, parentKey: 0 }, 19+ { ...line, key: "f" }, 20+ { ...line, parentKey: 2 ** 32 }, 21+ { ...line, enter: -1 }, 23+ assert.throws(() => projectionMarker(value), /invalid projection/); 24+ assert.deepEqual(projectionMembership({ present: true, dependents: 2 }), { present: true, dependents: 2 }); 25+ for (const value of [ 26+ { present: false, dependents: 1 }, 27+ { present: true, dependents: -1 }, 28+ { present: true, dependents: 0.5 }, 29+ { present: 1, dependents: 0 }, 31+ assert.throws(() => projectionMembership(value), /invalid projection/); 32+ assert.deepEqual(projectionChildRoot({ root: null }), { root: null }); 33+ assert.throws(() => projectionChildRoot({ root: NaN }), /invalid projection/); 34+ const roots = { exec: 4, link: null }; 35+ assert.deepEqual(projectionAttributes(roots), roots); 36+ assert.notEqual(projectionAttributes(roots), roots); 37+ assert.throws(() => projectionAttributes({ unknown: 0 }), /invalid projection/); 38+ assert.throws(() => projectionAttributes({ exec: -1 }), /invalid projection/); 39+ assert.deepEqual(projectionAttributeValue({ value: null }), { value: null }); 40+ assert.throws(() => projectionAttributeValue({ value: 4 }), /invalid projection/); --- /dev/null
+++ b/src/engine/test/projection-root.test.ts
@@ -0,0 +1,74 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 5+ type ProjectionIdentity, 8+} from "../experimental/projection-root.ts"; 9+import { SqlState } from "./storage-helper.ts"; 11+test("experimental roots bind identity before storage access and remain immutable", () => { 12+ const storage = new SqlState(); 14+ const expected: ProjectionIdentity = { 19+ sourceDigest: "a".repeat(64), 20+ membership: "closed:2", 22+ defaultFile: "f.txt", 24+ const pages: ProjectionRoots = { 33+ const handle = createProjectionRoot(storage, expected, 0, pages); 34+ assert.deepEqual(readProjectionRoot(storage, handle, expected), pages); 35+ for (const field of Object.keys(expected) as (keyof ProjectionIdentity)[]) { 39+ typeof expected[field] === "number" 40+ ? Number(expected[field]) + 1 41+ : field === "sourceDigest" 43+ : `${expected[field]}:other`, 45+ const reads = storage.reads, 46+ writes = storage.writes; 47+ assert.throws(() => readProjectionRoot(storage, handle, changed), /identity mismatch/); 48+ assert.equal(storage.reads, reads); 49+ assert.equal(storage.writes, writes); 51+ assert.throws(() => createProjectionRoot(storage, expected, 0, pages), /already exists/); 52+ const copy = readProjectionRoot(storage, handle, expected) as { sequence: number | null }; 54+ assert.deepEqual(readProjectionRoot(storage, handle, expected), pages); 57+ storage.transaction(() => { 58+ createProjectionRoot(storage, expected, 1, pages); 59+ throw Error("fail after root"); 63+ assert.throws(() => readProjectionRoot(storage, { ...handle, id: 1 }, expected), /invalid projection root record/); 64+ storage.write('experimental-projection:["db","index"]:roots', "0", { 68+ roots: { ...pages, locator: -1 }, 70+ assert.throws(() => readProjectionRoot(storage, handle, expected), /invalid projection page reference/); --- /dev/null
+++ b/src/engine/test/projection-sequence.test.ts
@@ -0,0 +1,49 @@
1+import assert from "node:assert/strict"; 2+import { test } from "node:test"; 3+import { ProjectionSequence } from "../experimental/projection-sequence.ts"; 4+import { SqlState } from "./storage-helper.ts"; 6+test("typed sequence preserves ordering, moves, old roots and rollback", () => { 7+ const storage = new SqlState(); 9+ const sequence = new ProjectionSequence(storage, "test"); 10+ let state = sequence.empty(); 11+ const oracle: { id: number; text: string }[] = []; 12+ for (let i = 0; i < 64; i++) { 13+ const rank = i % 2 ? 0 : oracle.length; 14+ state = sequence.update(state, { kind: "insert", rank, text: String(i) }); 15+ oracle.splice(rank, 0, { id: i, text: String(i) }); 17+ const original = state, 18+ old = structuredClone(oracle); 19+ for (let i = 0; i < 32; i++) { 21+ length = 1 + (i % 12), 22+ to = (i * 7) % (65 - length); 23+ state = sequence.update(state, { kind: "move", from, length, to }); 24+ const block = oracle.splice(from, length); 25+ oracle.splice(to, 0, ...block); 26+ assert.deepEqual([...sequence.values(state)], oracle); 27+ for (let k = 0; k < oracle.length; k++) assert.equal(sequence.rank(state, oracle[k]!.id), k); 29+ state = sequence.update(state, { kind: "visibility", id: 0, delta: 1 }); 31+ [...sequence.values(state)], 32+ oracle.filter((x) => x.id !== 0), 34+ assert.deepEqual([...sequence.values(original)], old); 35+ const rows = () => JSON.stringify(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all()); 36+ const before = rows(); 37+ storage.failWrite = storage.writes + 3; 38+ assert.throws(() => sequence.update(state, { kind: "insert", rank: 0, text: "failure" }), /injected/); 39+ assert.equal(rows(), before); 40+ storage.failWrite = Infinity; 41+ assert.throws(() => sequence.rank({ ...state, next: -1 }, 0), /invalid sequence state/); 42+ const root = sequence.get(state.map, state.root!); 43+ const corrupt = sequence.set(state.map, root.id, { ...root, count: root.count + 1 }); 44+ assert.throws(() => [...sequence.values({ ...state, map: corrupt })], /inconsistent sequence aggregate/); 45+ assert.deepEqual([...sequence.values(original)], old); --- /dev/null
+++ b/src/engine/test/projection-snapshots.test.ts
@@ -0,0 +1,174 @@
1+import assert from "node:assert/strict"; 2+import { mkdtempSync, rmSync } from "node:fs"; 3+import { tmpdir } from "node:os"; 4+import { join } from "node:path"; 5+import { test } from "node:test"; 6+import { ExperimentalMarkerProjection } from "../experimental/projection-marker.ts"; 7+import type { ProjectionIdentity } from "../experimental/projection-root.ts"; 8+import { ProjectionSnapshots } from "../experimental/projection-snapshots.ts"; 9+import { Graph } from "../graph.ts"; 10+import { CachedStateStorage } from "../state-source.ts"; 11+import { Repo } from "./helpers.ts"; 12+import { SqlState } from "./storage-helper.ts"; 14+test("experimental snapshots reopen and refuse wrong identities before projection reads", () => { 15+ const filename = join(mkdtempSync(join(tmpdir(), "abso-projection-snapshot-")), "state.sqlite"); 16+ let storage = new SqlState(filename); 17+ const repo = Repo.init({ "f.txt": "hello\n", "g.txt": "other\n" }); 18+ const identity: ProjectionIdentity = { 19+ database: "database-a", 20+ namespace: "index-a", 21+ registry: "registry-a", 22+ defaultFile: "f.txt", 25+ sourceDigest: "a".repeat(64), 29+ let graph = new Graph({ storage: new CachedStateStorage(storage) }); 30+ graph.add(repo.graph.atom("a0")); 31+ let adapter = new ExperimentalMarkerProjection(storage, graph, "f.txt", "index-a"); 32+ let snapshots = new ProjectionSnapshots(storage, adapter, identity); 33+ const state = adapter.apply(adapter.empty(), repo.graph.atom("a0")); 34+ const handle = snapshots.save(0, identity, state); 36+ storage = new SqlState(filename); 37+ graph = new Graph({ storage: new CachedStateStorage(storage) }); 38+ adapter = new ExperimentalMarkerProjection(storage, graph, "f.txt", "index-a"); 39+ snapshots = new ProjectionSnapshots(storage, adapter, identity); 40+ const reopened = snapshots.load(handle, identity); 41+ assert.deepEqual(adapter.lines(reopened), ["a0.0"]); 42+ for (const field of Object.keys(identity) as (keyof ProjectionIdentity)[]) { 46+ typeof identity[field] === "number" 47+ ? Number(identity[field]) + 1 48+ : field === "sourceDigest" 50+ : `${identity[field]}:other`, 52+ const reads = storage.reads, 53+ writes = storage.writes; 54+ assert.throws(() => snapshots.load(handle, changed), /mismatch/); 55+ assert.equal(storage.reads, reads); 56+ assert.equal(storage.writes, writes); 60+ new ProjectionSnapshots( 62+ new ExperimentalMarkerProjection(storage, graph, "g.txt", "index-a"), 65+ /constructor mismatch/, 67+ const rows = () => JSON.stringify(storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all()); 68+ const before = rows(); 71+ storage.transaction(() => { 72+ snapshots.save(1, identity, reopened); 73+ throw Error("fail after snapshot"); 75+ /fail after snapshot/, 77+ assert.equal(rows(), before); 78+ storage.write('experimental-projection:["database-a","index-a"]:context', "binding", { 80+ registry: "replaced", 82+ assert.throws(() => snapshots.load(handle, identity), /registry binding/); 88+test("experimental snapshots preserve mixed files across two reopens and subsequent writes", () => { 89+ const directory = mkdtempSync(join(tmpdir(), "abso-projection-mixed-")); 90+ const filename = join(directory, "state.sqlite"); 91+ let storage = new SqlState(filename); 92+ const repo = Repo.init({ "f.txt": "a\nb\n", "g.txt": "x\n" }); 93+ const identity: ProjectionIdentity = { 94+ database: "mixed-database", 95+ namespace: "mixed-index", 96+ registry: "mixed-registry", 97+ defaultFile: "f.txt", 100+ sourceDigest: "a".repeat(64), 103+ let graph = new Graph({ storage: new CachedStateStorage(storage) }); 104+ let adapter = new ExperimentalMarkerProjection(storage, graph, "f.txt", identity.namespace); 105+ let snapshots = new ProjectionSnapshots(storage, adapter, identity); 106+ graph.add(repo.graph.atom("a0")); 107+ let state = adapter.apply(adapter.empty(), repo.graph.atom("a0")); 108+ const original = snapshots.save(0, identity, state); 109+ const reopen = () => { 111+ storage = new SqlState(filename); 112+ graph = new Graph({ storage: new CachedStateStorage(storage) }); 113+ adapter = new ExperimentalMarkerProjection(storage, graph, "f.txt", identity.namespace); 114+ snapshots = new ProjectionSnapshots(storage, adapter, identity); 116+ const check = () => { 117+ const view = repo.view(); 118+ for (const path of ["f.txt", "g.txt", "empty.txt"]) { 120+ adapter.lines(state, path), 121+ view.lines(path).map((line) => line.id), 123+ assert.deepEqual(adapter.attrs(state, path), view.attrs(path)); 127+ const move = repo.edit({ move: { file: "f.txt", start: 0, end: 1, to: "g.txt", at: 0 } }); 129+ state = adapter.apply(state, move); 130+ const attr = repo.edit({ 132+ { file: "empty.txt", name: "exists", value: "1" }, 133+ { file: "g.txt", name: "exec", value: "1" }, 137+ state = adapter.apply(state, attr); 138+ const mixedIdentity = { ...identity, sourceLength: 3, sourceDigest: "b".repeat(64), membership: "mixed" }; 139+ const mixed = snapshots.save(1, mixedIdentity, state); 141+ state = snapshots.load(mixed, mixedIdentity); 143+ const writes = storage.writes; 144+ assert.equal(adapter.apply(state, attr), state); 145+ assert.equal(storage.writes, writes); 146+ for (const atom of [attr, move]) { 147+ repo.shared.delete(atom.id); 148+ state = adapter.removeAtom(state, atom); 151+ assert.deepEqual(adapter.lines(snapshots.load(original, identity), "f.txt"), ["a0.0", "a0.1"]); 152+ const edit = repo.edit({ edits: [{ file: "g.txt", old: "x\n", new: "after restart\n" }] }); 154+ state = adapter.apply(state, edit); 156+ const finalIdentity = { ...identity, sourceLength: 4, sourceDigest: "c".repeat(64), membership: "edited" }; 157+ const final = snapshots.save(2, finalIdentity, state); 159+ state = snapshots.load(final, finalIdentity); 161+ assert.deepEqual(adapter.lines(snapshots.load(mixed, mixedIdentity), "g.txt"), ["a0.0", "a0.2"]); 165+ "SELECT count(*) AS n FROM state WHERE collection LIKE '%sequence-resolver:%' OR collection LIKE '%sequence-relocation-work:%'", 172+ rmSync(directory, { recursive: true, force: true }); --- a/src/engine/view.ts
+++ b/src/engine/view.ts
@@ -45,6 +45,11 @@
4545 readonly blob: string | null; 48+/** Structural read boundary shared by historical and transaction-bound projections. */ 49+export type ReadView = Omit<Pick<View, keyof View>, "sameText"> & { 50+ sameText(path: string, other: ReadView): boolean; 4853const NO_ATTRS: FileAttrs = { exists: false, exec: false, link: null, blob: null }; 4954const NONE: readonly never[] = Object.freeze([]); @@ -523,7 +528,12 @@
525530 /** Whether a file reads the same here and in `other` (of the same graph), compared line by line without joining either (#46). */ 526− sameText(path: string, other: View): boolean {
531+ sameText(path: string, other: ReadView): boolean { 532+ if (!(other instanceof View)) { 533+ const a = this.lines(path), 534+ b = other.lines(path); 535+ return a.length === b.length && a.every((line, i) => line.text === b[i]!.text); 527537 const a = this.#file(path).vis; 528538 const b = other.#file(path).vis; 529539 if (a.length !== b.length) return false; @@ -698,7 +708,7 @@
700710/** Where a node sits in a file's sequence: the index just after it (0 for a start node). */ 701−export function indexAfter(view: View, path: string, node: NodeId): number {
711+export function indexAfter(view: Pick<ReadView, "sequenceIndex">, path: string, node: NodeId): number { 702712 if (isStartNode(node)) return 0; 703713 const i = view.sequenceIndex(path, node); 704714 if (i < 0) throw new EngineError("not-in-view", `line ${node} is not in ${path} in this view`); --- a/worker/project/add-draft.ts
+++ b/worker/project/add-draft.ts
@@ -11,7 +11,7 @@
14− type View,
1515} from "../../src/engine/index.ts"; 1616import type { Pair } from "./collisions.ts"; 1717import type { AgentState, Entry, Meta } from "./project-types.ts"; @@ -20,7 +20,7 @@
2020export interface AddDraftHost { 2121 readonly graph: Graph; 2222 openPairs(agent: AgentState): Pair[]; 23− markersSettled(agent: AgentState, view: View, atom: Atom): AtomId[];
23+ markersSettled(agent: AgentState, view: ReadView, atom: Atom): AtomId[]; 2424 apply(entry: Entry): void; @@ -32,7 +32,7 @@
3232export function addDraft( 35− view: View,
3636 input: { edits: readonly EditInput[]; attrs?: readonly AttrSet[]; move?: MoveInput }, --- a/worker/project/changes-since.ts
+++ b/worker/project/changes-since.ts
@@ -1,7 +1,7 @@
11// The files whose text in the agent's view differs from before, and its open 22// collisions. Reads go through ChangesSinceHost; today the host is Project. 4−import type { AtomId, View } from "../../src/engine/index.ts";
4+import type { AtomId, ReadView } from "../../src/engine/index.ts"; 55import type { Pair } from "./collisions.ts"; 66import { sortKeys } from "./project-helpers.ts"; 77import type { AgentState, Blobs, Collision, Files, Modes, SyncAnswer } from "./project-types.ts"; @@ -9,8 +9,8 @@
1010/** What a changes-since read needs from a project. */ 1111export interface ChangesSinceHost { 12− agentView(agent: AgentState): View;
13− touchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;
12+ agentView(agent: AgentState): ReadView; 13+ touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>; 1414 openPairs(agent: AgentState): Pair[]; 1515 collision(agent: AgentState, pair: Pair): Collision; 1616 duplicates(agent: AgentState): Collision[]; @@ -18,7 +18,7 @@
2020/** The files whose text in the agent's view differs from `before`, and its open collisions. */ 21−export function changesSince(host: ChangesSinceHost, agent: AgentState, before: View): SyncAnswer {
21+export function changesSince(host: ChangesSinceHost, agent: AgentState, before: ReadView): SyncAnswer { 2222 const after = host.agentView(agent); 2323 // Only files that an atom in one view but not the other touches can differ. 2424 const touched = new Set<string>(); --- a/worker/project/check-clash.ts
+++ b/worker/project/check-clash.ts
@@ -1,7 +1,7 @@
11// Refuse work whose paths would clash in shared. Reads go through 22// CheckClashHost; today the host is Project. 4−import type { AtomId, View } from "../../src/engine/index.ts";
4+import type { AtomId, ReadView } from "../../src/engine/index.ts"; 55import { unionOverlay } from "../../src/engine/state-source.ts"; 66import { ProjectError } from "./project-error.ts"; 77import { configProblem, PROJECT_FILES } from "./project-helpers.ts"; @@ -12,9 +12,10 @@
1212export interface CheckClashHost { 1414 setOf(space: Space): ReadonlySet<AtomId>; 15− view(set: ReadonlySet<AtomId>): View;
16− sharedView(): View;
17− touchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;
15+ view(set: ReadonlySet<AtomId>): ReadView; 16+ sharedView(): ReadView; 17+ sharedOverlay?(atoms: readonly AtomId[]): ReadView; 18+ touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>; @@ -27,14 +28,15 @@
2728 ahead: ReadonlySet<AtomId> = new Set(), 2930 if (changes.length === 0) return; 30− let view: View;
31− let now: View;
3334 // Publishes queued ahead (#39) land first, so they count as shared. 3435 const base = host.setOf(host.shared()); 3536 const queued = unionOverlay(base, ahead); 36− view = host.view(unionOverlay(queued, changes));
37− now = ahead.size === 0 ? host.sharedView() : host.view(queued);
37+ view = host.sharedOverlay ? host.sharedOverlay([...ahead, ...changes]) : host.view(unionOverlay(queued, changes)); 39+ ahead.size === 0 ? host.sharedView() : host.sharedOverlay ? host.sharedOverlay([...ahead]) : host.view(queued); 3941 if ((e as { code?: string }).code === "not-closed") return; // stranded by a drop: the publish says so itself --- a/worker/project/collisions.ts
+++ b/worker/project/collisions.ts
@@ -10,7 +10,7 @@
13− type View,
1414} from "../../src/engine/index.ts"; 1515import { differenceSet, StableOverlaySet } from "../../src/engine/state-source.ts"; 1616import { definedTwice } from "./definitions.ts"; @@ -147,8 +147,8 @@
148148 origin: (atom: AtomId, spaceName: string) => Origin, 150− yoursView: View,
151− theirsView: View,
150+ yoursView: ReadView, 151+ theirsView: ReadView, 152152 spaceName: string, 154154 const file = fileOfKey(pair.keys[0]!.key, yoursView); @@ -157,7 +157,7 @@
157157 if (attrsOnly.length === fileKeys.length) { 158158 // Both set the same attribute of the file: show each side's value. 159159 const name = attrsOnly[0]!.attr!; 160− const valueIn = (view: View, atom: AtomId): string => {
160+ const valueIn = (view: ReadView, atom: AtomId): string => { 161161 const set = (g.atom(atom).attrs ?? []).find((a) => a.file === file && a.name === name); 162162 return set?.value ?? (name === "exec" ? "" : String(view.attrs(file)[name] ?? "")); @@ -177,7 +177,7 @@
180−export function fileOfKey(key: string, view: View): string {
180+export function fileOfKey(key: string, view: ReadView): string { 181181 const { kind, node } = parseKey(key); 182182 if (kind === "attr") return node; 183183 return node.startsWith("^") ? node.slice(1) : view.fileOf(node); @@ -187,7 +187,7 @@
187187 * The files some atoms change: the graph's files of each, and, in views 188188 * with moves (#28), wherever the lines they touch are in those views. 190−export function touchedFiles(g: Graph, ids: Iterable<AtomId>, views: readonly View[]): Set<string> {
190+export function touchedFiles(g: Graph, ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string> { 191191 const out = new Set<string>(); 192192 const moved = views.filter((v) => v.hasMoves()); 193193 for (const id of ids) { @@ -206,7 +206,7 @@
208208/** The atom's visible lines in a file of a view, or where it acted when none are left. */ 209−export function describeSide(view: View, atom: AtomId, file: string, keys: readonly string[]): CollisionSide {
209+export function describeSide(view: ReadView, atom: AtomId, file: string, keys: readonly string[]): CollisionSide { 210210 const visible = view.lines(file); 212212 let lastLine = -1; @@ -238,7 +238,7 @@
238238 spaceOf(agent: AgentState): Space; 239239 agentSet(agent: AgentState): ReadonlySet<AtomId>; 240240 draft(agent: AgentState): AtomId[]; 241− agentView(agent: AgentState): View;
241+ agentView(agent: AgentState): ReadView; 242242 at(space: Space, version: number): ReadonlySet<AtomId>; --- a/worker/project/definition-rule.ts
+++ b/worker/project/definition-rule.ts
@@ -4,7 +4,7 @@
44// views; the project hands in who published an atom, and keeps the rule's 7−import { type AtomId, type Graph, joinLines, type LineId, type View } from "../../src/engine/index.ts";
7+import { type AtomId, type Graph, joinLines, type LineId, type ReadView } from "../../src/engine/index.ts"; 88import { type Origin, touchedFiles } from "./collisions.ts"; 99import { type Definition, definitionsIn, importsOf, usedNames } from "./definitions.ts"; 1010import { codeOfLines, declaredIn, holdsNoCode } from "./names.ts"; @@ -52,7 +52,7 @@
5252 * replaced the block of lines the atom deleted just before it in `base`. 5353 * A pure insertion replaced nothing. 55− #replacedNames(line: LineId, base: View, runsOf: Map<AtomId, readonly RunEnd[]>): ReadonlySet<string> {
55+ #replacedNames(line: LineId, base: ReadView, runsOf: Map<AtomId, readonly RunEnd[]>): ReadonlySet<string> { 5656 const g = this.#graph; 5757 const info = g.line(line); 5858 if (!info) return EMPTY_NAMES; @@ -97,9 +97,9 @@
9999 draft: ReadonlySet<AtomId>, 100− view: View,
101− baseView: View,
102− nowView: View,
103103 newer: ReadonlySet<AtomId>, 104104 spaceName: string, 105105 ): DefinitionCollision[] { --- a/worker/project/definitions.ts
+++ b/worker/project/definitions.ts
@@ -19,7 +19,7 @@
1919// A use means a definition only through an import of it, or in the file 2020// that defines it (project.ts, #definitionCore). 22−import type { LineId, View } from "../../src/engine/index.ts";
22+import type { LineId, ReadView } from "../../src/engine/index.ts"; 2323import { codeOfLines, holdsNoCode, isCommonName } from "./names.ts"; 2525export interface Definition { @@ -90,13 +90,13 @@
9090const TOP_ASSIGN = new RegExp(`^(${NAME})\\s*(?::[^=]*)?=(?![=>])`); 9191const MAX_HEADER = 30; 93−const cache = new WeakMap<View, Map<string, readonly Definition[]>>();
93+const cache = new WeakMap<ReadView, Map<string, readonly Definition[]>>(); 9696 * Every definition in the view's code files (or only in `files`), by name. 9797 * Each file's definitions are cached per view. 99−export function definitionsIn(view: View, files?: Iterable<string>): Map<string, Definition[]> {
99+export function definitionsIn(view: ReadView, files?: Iterable<string>): Map<string, Definition[]> { 100100 let perFile = cache.get(view); 102102 perFile = new Map(); @@ -118,7 +118,7 @@
121−function definitionsInFile(view: View, file: string, keepCommon = false): Definition[] {
121+function definitionsInFile(view: ReadView, file: string, keepCommon = false): Definition[] { 122122 if (holdsNoCode(file) || !view.hasFile(file)) return []; 123123 const out: Definition[] = []; 124124 const visible = view.lines(file); @@ -149,7 +149,7 @@
149149 * included (two `parse` functions in a file are a mistake whatever the name). 150150 * Each spans its whole block, body and all, for showing to the agent. 152−export function definedTwice(view: View, file: string): Map<string, Definition[]> {
152+export function definedTwice(view: ReadView, file: string): Map<string, Definition[]> { 153153 const out = new Map<string, Definition[]>(); 154154 const all = definitionsInFile(view, file, true); 155155 const count = new Map<string, number>(); @@ -306,7 +306,7 @@
309−const importCache = new WeakMap<View, Map<string, ReadonlyMap<string, string>>>();
309+const importCache = new WeakMap<ReadView, Map<string, ReadonlyMap<string, string>>>(); 312312 * Names a file imports by name, and the project file each comes from, when @@ -316,7 +316,7 @@
316316 * x.y import a, b`. Lets a use of a name be matched to the definition it 317317 * means instead of every definition with that name. 319−export function importsOf(view: View, file: string): ReadonlyMap<string, string> {
319+export function importsOf(view: ReadView, file: string): ReadonlyMap<string, string> { 320320 let perFile = importCache.get(view); 322322 perFile = new Map(); @@ -367,7 +367,7 @@
367367 return parts.join("/"); 370−function resolveModule(view: View, from: string, spec: string): string | undefined {
370+function resolveModule(view: ReadView, from: string, spec: string): string | undefined { 371371 if (!spec.startsWith(".")) return undefined; 372372 const base = joinPath(dirOf(from), spec); 373373 const stem = base.replace(/\.(?:js|mjs|cjs|jsx)$/, ""); @@ -385,7 +385,7 @@
388−function resolvePython(view: View, from: string, spec: string): string | undefined {
388+function resolvePython(view: ReadView, from: string, spec: string): string | undefined { 389389 const dots = /^\.*/.exec(spec)![0].length; 390390 const rest = spec.slice(dots).replace(/\./g, "/"); 391391 let dir = dots > 0 ? dirOf(from) : ""; --- a/worker/project/draft-collisions.ts
+++ b/worker/project/draft-collisions.ts
@@ -1,7 +1,7 @@
11// Whether agents' unpublished changes would collide (#41, F22), read through DraftCollisionHost; today the host 22// is the project in memory. 4−import { type AtomId, type Graph, parseKey, type View } from "../../src/engine/index.ts";
4+import { type AtomId, type Graph, parseKey, type ReadView } from "../../src/engine/index.ts"; 55import { describeSide, fileOfKey, type Pair } from "./collisions.ts"; 66import type { DefinitionRule } from "./definition-rule.ts"; 77import { type Definition, definedTwice } from "./definitions.ts"; @@ -20,13 +20,13 @@
2020 readonly agents: ReadonlyMap<string, Agent>; 23− sharedView(): View;
23+ sharedView(): ReadView; 2424 definitionRule(): DefinitionRule; 2525 draft(agent: Agent): AtomId[]; 26− agentView(agent: Agent): View;
27− view(set: ReadonlySet<AtomId>): View;
26+ agentView(agent: Agent): ReadView; 27+ view(set: ReadonlySet<AtomId>): ReadView; 2828 pairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[]; 29− touchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;
29+ touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>; --- a/worker/project/draft-diff.ts
+++ b/worker/project/draft-diff.ts
@@ -1,7 +1,7 @@
11// An agent's unpublished changes, file by file. They read through DraftDiffHost; today the host is the project 4−import type { AtomId, View } from "../../src/engine/index.ts";
4+import type { AtomId, ReadView } from "../../src/engine/index.ts"; 55import { ProjectError } from "./project-error.ts"; 66import type { DiffAnswer } from "./project-types.ts"; 77import { SHARED } from "./spaces.ts"; @@ -17,9 +17,9 @@
1717 readonly agents: ReadonlyMap<string, Agent>; 1919 draft(agent: Agent): AtomId[]; 20− agentView(agent: Agent): View;
21− view(set: ReadonlySet<AtomId>): View;
22− touchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;
20+ agentView(agent: Agent): ReadView; 21+ view(set: ReadonlySet<AtomId>): ReadView; 22+ touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>; 2525/** An agent's draft diff for a reader (#41, the website): never creates the agent, never writes. */ --- a/worker/project/edit.ts
+++ b/worker/project/edit.ts
@@ -7,7 +7,7 @@
10− type View,
1111} from "../../src/engine/index.ts"; 1212import { checkPath } from "./path-rules.ts"; 1313import { isComposed } from "./pathkey.ts"; @@ -32,9 +32,9 @@
3232 readonly agents: ReadonlyMap<string, AgentState>; 3333 readonly whole: ProjectOptions["whole"]; 3434 initialized(): boolean; 35− agentView(agent: AgentState): View;
36− sharedView(): View;
37− isWhole(path: string, length: number, view: View | undefined, rules: readonly string[]): boolean;
35+ agentView(agent: AgentState): ReadView; 36+ sharedView(): ReadView; 37+ isWhole(path: string, length: number, view: ReadView | undefined, rules: readonly string[]): boolean; 3838 wholeRules(config?: string): string[]; @@ -48,7 +48,7 @@
4848 draftFiles(agent: AgentState): Set<string>; 51− view: View,
5353 text: string | null | undefined, @@ -60,7 +60,7 @@
63− view: View,
6464 input: { edits: readonly EditInput[] }, --- a/worker/project/express-moves.ts
+++ b/worker/project/express-moves.ts
@@ -2,7 +2,7 @@
22// text that arrives somewhere else is the same line. Before a publish, those matches become move 33// atoms so the lines keep their ids. Writes go through ExpressMovesHost; today the host is Project. 5−import type { AtomId, AttrSet, EditInput, Graph, LineId, MoveInput, View } from "../../src/engine/index.ts";
5+import type { AtomId, AttrSet, EditInput, Graph, LineId, MoveInput, ReadView } from "../../src/engine/index.ts"; 66import { differenceSet, StableOverlaySet } from "../../src/engine/state-source.ts"; 77import { PLAIN_LINE } from "./collisions.ts"; 88import type { AgentState, Entry, Meta, Mode } from "./project-types.ts"; @@ -18,12 +18,13 @@
1818export interface ExpressMovesHost { 1919 readonly graph: Graph; 2020 draft(agent: AgentState): AtomId[]; 21− agentView(agent: AgentState): View;
22− view(set: ReadonlySet<AtomId>): View;
21+ agentView(agent: AgentState): ReadView; 22+ beforeDraft?(agent: AgentState, draft: readonly AtomId[]): ReadView; 23+ view(set: ReadonlySet<AtomId>): ReadView; 2324 apply(entry: Entry): void; 26− view: View,
2728 input: { edits: readonly EditInput[]; attrs?: readonly AttrSet[]; move?: MoveInput }, @@ -31,7 +32,7 @@
34− view: View,
3637 text: string | null | undefined, @@ -59,7 +60,9 @@
5960 const g = host.graph; 6061 const mine = new Set(draft); 6162 const after = host.agentView(agent); 62− const before = host.view(differenceSet(after.set, new StableOverlaySet(draft)));
63+ const before = host.beforeDraft 64+ ? host.beforeDraft(agent, draft) 65+ : host.view(differenceSet(after.set, new StableOverlaySet(draft))); 6366 const touched = new Set<string>(); 6467 for (const id of draft) for (const file of g.filesOf(id)) touched.add(file); @@ -171,6 +174,8 @@
177+ // Keep the intended membership, but reacquire its reader after each graph mutation. 178+ const finalAgent = { ...agent, mine: [...agent.mine] }; 174179 const discard: Entry = { type: "discard", agent: agent.name, atoms: draft.filter((id) => drop.has(id)) }; 175180 entries.push(discard); 176181 host.apply(discard); @@ -180,7 +185,7 @@
180185 const start = view.lineNumber(m.from, m.ids[0]!); 181186 if (start < 0 || m.ids.some((id, k) => view.lineNumber(m.from, id) !== start + k)) continue; 182187 // Land after the nearest line above it in the final text that is already there. 183− const finalLines = after.lines(m.to);
188+ const finalLines = host.agentView(finalAgent).lines(m.to); 185190 for (let i = m.at - 1; i >= 0; i--) { 186191 const n = view.lineNumber(m.to, finalLines[i]!.id); @@ -200,12 +205,13 @@
202207 for (const path of [...involved].toSorted()) { 203− const was = after.attrs(path);
208+ const finalView = host.agentView(finalAgent); 209+ const was = finalView.attrs(path); 206212 host.agentView(agent), 208− after.hasFile(path) ? after.text(path) : null,
214+ finalView.hasFile(path) ? finalView.text(path) : null, --- a/worker/project/history.ts
+++ b/worker/project/history.ts
@@ -2,7 +2,7 @@
22// (pathLife), and where lines went (follow). They read through HistoryHost, the one seam the derived tables 33// (abso issues 48 and 79) plug into: today the host is the project in memory. 5−import type { Graph, LineId, View } from "../../src/engine/index.ts";
5+import type { Graph, LineId, ReadView } from "../../src/engine/index.ts"; 66import { pathKey } from "./pathkey.ts"; 77import { checkReadPath, differs, type LastChange, ProjectError, utf8Bytes } from "./project.ts"; 88import { last, SHARED, type Space } from "./spaces.ts"; @@ -15,9 +15,9 @@
1616 spaceNamed(name: string | null): Space; 1717 checkVersion(space: Space, version: number): void; 18− viewAt(space: Space, version: number): View;
19− agentView(agent: { readonly name: string; readonly space: string; readonly base: number }): View;
20− spellingIn(view: View, asked: string): string;
18+ viewAt(space: Space, version: number): ReadView; 19+ agentView(agent: { readonly name: string; readonly space: string; readonly base: number }): ReadView; 20+ spellingIn(view: ReadView, asked: string): string; 2121 pathsOf(space: Space): Map<string, PathLifeRecord>; 2222 lastChange(space: Space, version: number): LastChange; 2323 atOrBefore(list: readonly number[], version: number): number | undefined; --- a/worker/project/ingest.ts
+++ b/worker/project/ingest.ts
@@ -1,6 +1,6 @@
11// Take in commits a person pushed with plain git. Writes go through IngestHost; today the host is Project. 3−import { type AtomId, canonicalText, type Hunk, type View } from "../../src/engine/index.ts";
3+import { type AtomId, canonicalText, type Hunk, type ReadView } from "../../src/engine/index.ts"; 44import { checkPath } from "./path-rules.ts"; 55import { ProjectError } from "./project-error.ts"; 66import { configProblem, PROJECT_FILES } from "./project-helpers.ts"; @@ -20,13 +20,13 @@
2121 files: Readonly<Record<string, string | null>>, 2222 blobs: Readonly<Record<string, string>>, 23− view: View | undefined,
23+ view: ReadView | undefined, 2525 ): { files: Record<string, string | null>; blobs: Record<string, string> }; 26− agentView(agent: AgentState): View;
26+ agentView(agent: AgentState): ReadView; 29− view: View,
3131 text: string | null | undefined, --- a/worker/project/init.ts
+++ b/worker/project/init.ts
@@ -1,7 +1,7 @@
11// Create the project from its first files. Writes go through InitHost; today 22// the host is Project. 4−import { type AttrSet, buildBase, canonicalText, type View } from "../../src/engine/index.ts";
4+import { type AttrSet, buildBase, canonicalText, type ReadView } from "../../src/engine/index.ts"; 55import { checkPath } from "./path-rules.ts"; 66import { ProjectError } from "./project-error.ts"; 77import { configProblem, PROJECT_FILES, projectFileOf } from "./project-helpers.ts"; @@ -16,7 +16,7 @@
1717 files: Readonly<Record<string, string | null>>, 1818 blobs: Readonly<Record<string, string>>, 19− view: View | undefined,
19+ view: ReadView | undefined, 2121 ): { files: Record<string, string | null>; blobs: Record<string, string> }; 2222 checkBlobs(blobs: unknown, files: object): Record<string, string>; --- a/worker/project/land.ts
+++ b/worker/project/land.ts
@@ -1,7 +1,7 @@
11// Land a named draft in shared as one unit. Writes go through LandHost; today 22// the host is Project. Ingest and pluck call landDraft, the inner step. 4−import { type AtomId, buildAtom, type Graph, type View } from "../../src/engine/index.ts";
4+import { type AtomId, buildAtom, type Graph, type ReadView } from "../../src/engine/index.ts"; 55import type { Pair } from "./collisions.ts"; 66import type { DefinitionRule } from "./definition-rule.ts"; 77import { ProjectError } from "./project-error.ts"; @@ -22,10 +22,10 @@
2323 setOf(space: Space): ReadonlySet<AtomId>; 2424 at(space: Space, version: number): ReadonlySet<AtomId>; 25− view(set: ReadonlySet<AtomId>): View;
26− sharedView(): View;
25+ view(set: ReadonlySet<AtomId>): ReadView; 26+ sharedView(): ReadView; 2727 pairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[]; 28− describe(pair: Pair, yoursView: View, theirsView: View, spaceName: string): Collision;
28+ describe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision; 2929 definitionRule(): DefinitionRule; --- a/worker/project/markers.ts
+++ b/worker/project/markers.ts
@@ -14,7 +14,7 @@
1414// Settled means the block is gone. These helpers also say what an agent kept 1515// once it settled one. 17−import { type Atom, type AtomId, diffLines, type Graph, type Hunk, type View } from "../../src/engine/index.ts";
17+import { type Atom, type AtomId, diffLines, type Graph, type Hunk, type ReadView } from "../../src/engine/index.ts"; 1818import type { AgentState, AgentStatus, Collision } from "./project-types.ts"; 2020export const YOURS = "<<<<<<< yours (unpublished)"; @@ -263,7 +263,7 @@
263263/** What the marker reads need from a project. */ 264264export interface MarkerHost { 265265 readonly graph: Graph; 266− agentView(agent: AgentState): View;
266+ agentView(agent: AgentState): ReadView; 267267 draft(agent: AgentState): AtomId[]; 268268 draftFiles(agent: AgentState): Set<string>; @@ -309,7 +309,7 @@
311311/** The collided changes behind each block whose marker lines `atom` deletes (#11). */ 312−export function markersSettled(host: MarkerHost, agent: AgentState, view: View, atom: Atom): AtomId[] {
312+export function markersSettled(host: MarkerHost, agent: AgentState, view: ReadView, atom: Atom): AtomId[] { 313313 if (agent.marked.length === 0) return []; 314314 const out = new Set<AtomId>(); 315315 const blocksBy = new Map<string, Block[]>(); --- a/worker/project/merge-identical.ts
+++ b/worker/project/merge-identical.ts
@@ -8,8 +8,8 @@
12− type View,
1313} from "../../src/engine/index.ts"; 1414import type { Origin, Pair } from "./collisions.ts"; 1515import { type MarkedRegion, markedHunks, markerBlock } from "./markers.ts"; @@ -22,14 +22,14 @@
2222 openPairs(agent: AgentState): Pair[]; 2323 draft(agent: AgentState): AtomId[]; 2424 origin(atom: AtomId, spaceName: string): Origin; 25− view(set: ReadonlySet<AtomId>): View;
26− viewAt(space: Space, version: number): View;
25+ view(set: ReadonlySet<AtomId>): ReadView; 26+ viewAt(space: Space, version: number): ReadView; 2727 spaceOf(agent: AgentState): Space; 2828 apply(entry: Entry): void; 29− agentView(agent: AgentState): View;
29+ agentView(agent: AgentState): ReadView; 32− view: View,
3434 text: string | null | undefined, @@ -53,7 +53,7 @@
5353export function mergeIdentical( 56− before: View,
5757 oldBase: ReadonlySet<AtomId>, @@ -91,7 +91,7 @@
9191 if ([...involved].some((f) => shown.has(f))) return []; 9292 const baseView = host.view(oldBase); 9393 const theirs = host.viewAt(host.spaceOf(agent), agent.base); 94− const textOf = (v: View, path: string): string | null => (v.hasFile(path) ? v.text(path) : null);
94+ const textOf = (v: ReadView, path: string): string | null => (v.hasFile(path) ? v.text(path) : null); 9595 const merged = new Map<string, { text: string | null; mode: Mode; hunks?: Hunk[] }>(); 9696 const notices: MergedLine[] = []; 9797 const regions: MarkedRegion[] = []; --- a/worker/project/move.ts
+++ b/worker/project/move.ts
@@ -1,7 +1,7 @@
11// Move a file in the agent's draft. Writes go through MoveHost; today the 4−import type { EditInput, Hunk, MoveInput, View } from "../../src/engine/index.ts";
4+import type { EditInput, Hunk, MoveInput, ReadView } from "../../src/engine/index.ts"; 55import { checkPath } from "./path-rules.ts"; 66import { pathKey } from "./pathkey.ts"; 77import { ProjectError } from "./project-error.ts"; @@ -11,12 +11,12 @@
1111export interface MoveHost { 1313 readonly agents: ReadonlyMap<string, AgentState>; 14− agentView(agent: AgentState): View;
15− sharedView(): View;
14+ agentView(agent: AgentState): ReadView; 15+ sharedView(): ReadView; 1616 agent(name: string, entries: Entry[]): AgentState; 19− view: View,
2020 input: { edits: readonly EditInput[]; move?: MoveInput }, @@ -24,7 +24,7 @@
27− view: View,
2929 text: string | null | undefined, --- a/worker/project/news.ts
+++ b/worker/project/news.ts
@@ -1,7 +1,7 @@
11// How news reads: one sentence for each thing an agent should hear, with the key that makes it heard 22// once, and who hears it after an edit, publish or land. Writes (the news entry) stay on Project. 4−import { type AtomId, type Graph, isStartNode, parseKey, type View } from "../../src/engine/index.ts";
4+import { type AtomId, type Graph, isStartNode, parseKey, type ReadView } from "../../src/engine/index.ts"; 55import { unionOverlay } from "../../src/engine/state-source.ts"; 66import { type Origin, type Pair, pairsIn, touchedFiles } from "./collisions.ts"; 77import { type DefinitionCollision, signature } from "./definition-rule.ts"; @@ -196,7 +196,7 @@
196196 newerFor(agent: AgentState): ReadonlySet<AtomId>; 197197 spaceOf(agent: AgentState): Space; 198198 setOf(space: Space): ReadonlySet<AtomId>; 199− viewAt(space: Space, version: number): View;
199+ viewAt(space: Space, version: number): ReadView; 200200 origin(atom: AtomId, spaceName: string): Origin; 201201 collision(agent: AgentState, pair: Pair): Collision; 202202 definitionCollisions(agent: AgentState, newer: ReadonlySet<AtomId>): DefinitionCollision[]; --- a/worker/project/notes.ts
+++ b/worker/project/notes.ts
@@ -2,7 +2,7 @@
22// reviews which files by avcs.json, the notes list, every agent's start note, and writing or closing 33// a note. Reads go through NoteHost, writes through NoteWriteHost; today the host is Project. 5−import type { AtomId, Graph, LineId, View } from "../../src/engine/index.ts";
5+import type { AtomId, Graph, LineId, ReadView } from "../../src/engine/index.ts"; 66import { matchesPattern } from "./globs.ts"; 77import { type NewsItem, noteClosedItem, noteSaid } from "./news.ts"; 88import { checkReadPath } from "./path-rules.ts"; @@ -27,11 +27,11 @@
2727 readonly notes: ReadonlyMap<number, NoteRecord>; 2828 initialized(): boolean; 30− sharedView(): View;
31− spellingIn(view: View, path: string): string;
32− viewAt(space: Space, version: number): View;
33− agentView(agent: AgentState): View;
34− view(set: ReadonlySet<AtomId>): View;
30+ sharedView(): ReadView; 31+ spellingIn(view: ReadView, path: string): string; 32+ viewAt(space: Space, version: number): ReadView; 33+ agentView(agent: AgentState): ReadView; 34+ view(set: ReadonlySet<AtomId>): ReadView; 3535 at(space: Space, version: number): ReadonlySet<AtomId>; 3636 liveNote(agent: AgentState): Starting | undefined; @@ -43,9 +43,9 @@
4343 readonly changes: ReadonlyMap<number, ChangeRecord>; 4444 readonly graph: Graph; 46− agentView(agent: AgentState): View;
47− viewAtVersion(version: number): View;
48− sharedView(): View;
46+ agentView(agent: AgentState): ReadView; 47+ viewAtVersion(version: number): ReadView; 48+ sharedView(): ReadView; 4949 changeOfLines(lines: readonly LineId[]): number | undefined; 5050 apply(entry: Entry): void; 5151 flush(entries: Entry[]): void; @@ -99,7 +99,7 @@
101101/** A note as reads show it, from the view its lines live in (undefined when no space holds them any more). */ 102−export function noteAnswerIn(n: NoteRecord, view: View | undefined): NoteAnswer {
102+export function noteAnswerIn(n: NoteRecord, view: ReadView | undefined): NoteAnswer { 103103 // Where the lines are now, found by their ids: a move (#49) can have taken them to another file. 104104 let lines: [number, number] | null = null; 105105 let file = n.file; @@ -138,7 +138,7 @@
138138 * published into; else their author's draft, where it works now or where it 139139 * parked it. Undefined when no space holds them any more (a discarded draft). 141−export function noteView(host: NoteHost, n: NoteRecord): View | undefined {
141+export function noteView(host: NoteHost, n: NoteRecord): ReadView | undefined { 142142 const writers = new Set(n.lines.map((l) => host.graph.lineAtom(l)).filter((a): a is AtomId => a !== undefined)); 143143 const holds = (set: ReadonlySet<AtomId> | readonly AtomId[]) => 144144 [...writers].some((a) => (set instanceof Set ? set.has(a) : (set as readonly AtomId[]).includes(a))); @@ -218,7 +218,7 @@
218218 throw new ProjectError("bad-request", "a note needs {file, from, to}, or {reply}"); 220220 checkReadPath(file); 221− let view: View;
222222 if (typeof body.of === "string") { 223223 const of = host.agents.get(body.of); 224224 if (!of) throw new ProjectError("not-found", `there is no agent ${JSON.stringify(body.of)}`); --- a/worker/project/overlaps.ts
+++ b/worker/project/overlaps.ts
@@ -2,7 +2,7 @@
22// the news when a draft first touches one. Reads and news writes go through 33// OverlapHost; today the host is Project. overlapsOf is the pure match. 5−import { type AtomId, type Graph, isStartNode, type View } from "../../src/engine/index.ts";
5+import { type AtomId, type Graph, isStartNode, type ReadView } from "../../src/engine/index.ts"; 66import { matchesPattern, pathsInText, patternsMeet } from "./globs.ts"; 77import { type NewsItem, overlapItems } from "./news.ts"; 88import type { AgentState, Entry, Overlap, Starting } from "./project-types.ts"; @@ -22,7 +22,7 @@
2222export interface OverlapHost { 2323 readonly graph: Graph; 2424 readonly agents: ReadonlyMap<string, AgentState>; 25− agentView(agent: AgentState): View;
25+ agentView(agent: AgentState): ReadView; 2626 draft(agent: AgentState): readonly AtomId[]; 2727 /** draftFiles below, kept per agent by the host. */ 2828 draftFiles(agent: AgentState): Set<string>; --- a/worker/project/pathindex.ts
+++ b/worker/project/pathindex.ts
@@ -1,8 +1,9 @@
1+import { View } from "../../src/engine/index.ts"; 12// Each version's files and shape, and each path's history in a space (#41; #46, disk-first 1). Built the first 23// time it's asked for and kept up as versions land; a version's files are also kept in the shapes table, so a 34// load needn't lay them out again. 5−import { type AtomId, type Graph, type LineId, View } from "../../src/engine/index.ts";
6+import type { AtomId, Graph, LineId, ReadView } from "../../src/engine/index.ts"; @@ -17,8 +18,8 @@
1718export interface PathIndexDeps { 1819 readonly graph: Graph; 1920 at(space: Space, version: number): ReadonlySet<AtomId>; 20− viewAt(space: Space, version: number): View;
21− touchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;
21+ viewAt(space: Space, version: number): ReadView; 22+ touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>; 2223 readonly shapes: ProjectOptions["shapes"]; @@ -44,7 +45,7 @@
4445 readonly #pathIndex = new WeakMap<Space, { upTo: number; paths: Map<string, PathLife> }>(); 4647 /** The files a version changed. `views` holds views by version, so a run of versions builds each once. */ 47− versionFiles(space: Space, version: number, views = new Map<number, View>()): string[] {
48+ versionFiles(space: Space, version: number, views = new Map<number, ReadView>()): string[] { 4849 let cache = this.#filesCache.get(space); 4950 if (!cache) this.#filesCache.set(space, (cache = new Map())); 5051 const known = cache.get(version); @@ -53,7 +54,7 @@
5354 if (kept) return kept; 5455 const shapes = this.#shapeCache.get(space)!; 5556 const p = space.versions[version]!; 56− const viewAt = (v: number): View => {
57+ const viewAt = (v: number): ReadView => { 5758 let view = views.get(v); 5859 if (!view) views.set(v, (view = v < 0 ? new View(this.#deps.graph, []) : this.#deps.viewAt(space, v))); @@ -107,7 +108,7 @@
109110 /** A version's files made and taken out, and moves (#41). */ 110− versionShape(space: Space, version: number, views?: Map<number, View>): VersionShape {
111+ versionShape(space: Space, version: number, views?: Map<number, ReadView>): VersionShape { 111112 const known = this.#shapeCache.get(space)?.get(version); 112113 if (known) return known; 113114 this.#filesCache.get(space)?.delete(version); @@ -124,7 +125,7 @@
124125 pathsOf(space: Space): Map<string, PathLife> { 125126 let index = this.#pathIndex.get(space); 126127 if (!index) this.#pathIndex.set(space, (index = { upTo: -1, paths: new Map() })); 127− const views = new Map<number, View>();
128+ const views = new Map<number, ReadView>(); 128129 // Shared's sets grow version by version, so walk them forward rather than build each from the 129130 // start; the views stay out of the cache, which they would only push other views from. A version 130131 // whose files are kept (#41) needs no views at all. --- a/worker/project/project-status.ts
+++ b/worker/project/project-status.ts
@@ -1,7 +1,7 @@
11// What the project looks like now: status, the paths in a folder, and the labels. They read through 22// SnapshotHost; today the host is the project in memory. 4−import type { AtomId, View } from "../../src/engine/index.ts";
4+import type { AtomId, ReadView } from "../../src/engine/index.ts"; 55import { ProjectError } from "./project-error.ts"; 66import { countRefusals, type projectFileIn } from "./project-helpers.ts"; @@ -39,8 +39,8 @@
3939 setOf(space: Space): ReadonlySet<AtomId>; 4040 spaceNamed(name: string | null): Space; 4141 checkVersion(space: Space, version: number): void; 42− viewAt(space: Space, version: number): View;
43− agentView(agent: AgentState): View;
42+ viewAt(space: Space, version: number): ReadView; 43+ agentView(agent: AgentState): ReadView; 4545 /** Shared's project file (224), or undefined before init or without one. */ 4646 projectFile(): ReturnType<typeof projectFileIn>; --- a/worker/project/project-types.ts
+++ b/worker/project/project-types.ts
@@ -1,6 +1,7 @@
1−import type { Atom, AtomId, LineId } from "../../src/engine/index.ts";
1+import type { Atom, AtomId, Graph, LineId } from "../../src/engine/index.ts"; 22import type { GraphStateStorage } from "../../src/engine/state-source.ts"; 33import type { Kept, MarkedRegion } from "./markers.ts"; 4+import type { ReadViewProvider } from "./views.ts"; 45/** Whole files: path -> text, or null for a deleted file. */ 56export type Files = Record<string, string | null>; @@ -566,6 +567,8 @@
567568/** What the project needs from the store of binary files' bytes. */ 568569export interface ProjectOptions { 570+ /** Private experimental reader route; never falls back for unsupported membership. */ 571+ readViewProvider?: (graph: Graph) => ReadViewProvider; 570573 * Writer indexes for a fresh project or adoption into an empty namespace. 571574 * The host must wrap each operation and canonical log append in the same --- a/worker/project/project.ts
+++ b/worker/project/project.ts
@@ -12,7 +12,7 @@
1212// agents publish into under the same rules, and that lands in shared as one 1313// unit. Every agent works in one space at a time. 15−import { type Atom, type AtomId, EngineError, Graph, type LineId, type View } from "../../src/engine/index.ts";
15+import { type Atom, type AtomId, EngineError, Graph, type LineId, type ReadView } from "../../src/engine/index.ts"; @@ -406,7 +406,7 @@
407407 ? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) }) 409− this.#views = new ViewCache(this.#graph);
409+ this.#views = new ViewCache(this.#graph, options.readViewProvider); 410410 this.#paths = new PathIndex({ 411411 graph: this.#graph, 412412 at: (space, version) => this.#at(space, version), @@ -606,8 +606,8 @@
606606 return modesOf(this.#sharedView()); 609− /** Shared as a View, for reading lines (blame, why). Don't hold on to it across calls. */
610− sharedView(): View {
609+ /** Shared as a ReadView, for reading lines (blame, why). Don't hold on to it across calls. */ 610+ sharedView(): ReadView { 611611 return this.#sharedView(); @@ -621,7 +621,7 @@
621621 * The view is laid out on first use: where asks every agent, most have no changes, and a big project has more 622622 * agents than the view cache holds, so building every view cost each call about 0.7 s. 624− draftOf(agentName: string): { atoms: AtomId[]; readonly view: View } | undefined {
624+ draftOf(agentName: string): { atoms: AtomId[]; readonly view: ReadView } | undefined { 625625 const agent = this.#agents.get(agentName); 626626 if (!agent) return undefined; 627627 const view = () => this.#agentView(agent); @@ -757,7 +757,7 @@
757757 * last makes it one-way: a file kept whole stays whole while it exists, 758758 * even if it shrinks or the rule changes, so it never flips back and forth. 760− #isWhole(path: string, length: number, view: View | undefined, rules: readonly string[]): boolean {
760+ #isWhole(path: string, length: number, view: ReadView | undefined, rules: readonly string[]): boolean { 761761 return hostedIsWhole(this.#wholeHost, path, length, view, rules); @@ -765,7 +765,7 @@
766766 files: Readonly<Record<string, string | null>>, 767767 blobs: Readonly<Record<string, string>>, 768− view: View | undefined,
768+ view: ReadView | undefined, 770770 ): { files: Record<string, string | null>; blobs: Record<string, string> } { 771771 return hostedWholeOut(this.#wholeHost, files, blobs, view, config); @@ -1085,7 +1085,7 @@
10861086 #mergeIdentical( 10871087 agent: AgentState, 1088− before: View,
10891089 oldBase: ReadonlySet<AtomId>, 10901090 oldVersion: number, @@ -1172,7 +1172,7 @@
11741174 /** The collided changes behind each block whose marker lines `atom` deletes (#11). */ 1175− #markersSettled(agent: AgentState, view: View, atom: Atom): AtomId[] {
1175+ #markersSettled(agent: AgentState, view: ReadView, atom: Atom): AtomId[] { 11761176 return hostedMarkersSettled(this.#markerHost, agent, view, atom); @@ -1418,7 +1418,7 @@
14181418 * the one file ever in the view it matches, for a file since taken out. 14191419 * A path that matches two files is answered exactly. 1421− spellingIn(view: View, path: string): string {
1421+ spellingIn(view: ReadView, path: string): string { 14221422 if (view.hasFile(path)) return path; 14231423 const key = pathKey(path); 14241424 const live = view.knownPaths().filter((p) => pathKey(p) === key && view.hasFile(p)); @@ -1660,7 +1660,7 @@
16601660 return versionCompare(this.#logHost, ...args); 1663− /** A version of shared (or of a named draft) as a View (version-log.ts). */
1663+ /** A version of shared (or of a named draft) as a ReadView (version-log.ts). */ 16641664 viewAt(...args: Tail<Parameters<typeof versionViewAt>>): ReturnType<typeof versionViewAt> { 16651665 return versionViewAt(this.#logHost, ...args); @@ -1725,6 +1725,16 @@
17251725 this.#movesHost ??= { 17261726 graph: this.#graph, 17271727 draft: (agent) => this.#unqueuedDraft(agent), 1728+ beforeDraft: (agent, draft) => { 1729+ const base = this.#at(this.#spaceOf(agent), agent.base); 1730+ if (draft.some((id) => base.has(id))) 1731+ return this.#view(differenceSet(this.#agentView(agent).set, new StableOverlaySet(draft))); 1732+ const removed = new Set(draft), 1733+ kept = agent.mine.filter((id) => !removed.has(id)); 1734+ return kept.length === 0 1735+ ? this.#viewAt(this.#spaceOf(agent), agent.base) 1736+ : this.#viewKeyed(`a ${agent.space}@${agent.base}+${kept.join(",")}`, () => unionOverlay(base, kept)); 17281738 agentView: (agent) => this.#agentView(agent), 17291739 view: (set) => this.#view(set), 17301740 apply: (entry) => this.#apply(entry), @@ -1923,6 +1933,10 @@
19231933 this.#enqueue(agent, message, time, draft, resolves, entries), 19241934 view: (set) => this.#view(set), 19251935 requireClosed: (tie, union) => this.#requireClosed(tie, union), 1936+ spaceOverlay: (space, atoms) => 1937+ this.#viewKeyed(`a ${space.name}@${last(space)}+${atoms.join(",")}`, () => 1938+ unionOverlay(this.#setOf(space), atoms), 19261940 newerFor: (agent) => this.#newerFor(agent), 19271941 currentChange: (agent, time) => this.#currentChange(agent, time), 19281942 apply: (entry) => this.#apply(entry), @@ -2189,6 +2203,10 @@
21892203 setOf: (space) => this.#setOf(space), 21902204 view: (set) => this.#view(set), 21912205 sharedView: () => this.#sharedView(), 2206+ sharedOverlay: (atoms) => 2207+ this.#viewKeyed(`a @${last(this.#shared)}+${atoms.join(",")}`, () => 2208+ unionOverlay(this.#setOf(this.#shared), atoms), 21922210 touchedFiles: (ids, views) => this.#touchedFiles(ids, views), 21942212 return this.#checkClashes; @@ -2475,7 +2493,7 @@
24752493 return new Set([...this.#at(this.#spaceOf(agent), agent.base), ...agent.mine]); 2478− #agentView(agent: AgentState): View {
2496+ #agentView(agent: AgentState): ReadView { 24792497 return this.#viewKeyed(this.#agentViewKey(agent), () => { 24802498 const base = this.#at(this.#spaceOf(agent), agent.base); 24812499 return base instanceof StableSet @@ -2493,21 +2511,22 @@
24952513 /** A space at a version: published versions never change, so the key is just their names (#46). */ 2496− #viewAt(space: Space, version: number): View {
2514+ #viewAt(space: Space, version: number): ReadView { 24972515 return this.#viewKeyed(`v ${space.name}@${version}`, () => this.#at(space, version)); 2500− #sharedView(): View {
2518+ #sharedView(): ReadView { 25012519 return this.#viewAt(this.#shared, last(this.#shared)); 25042522 /** A view of a set, cached by the set's exact contents (views.ts). */ 2505− #view(set: ReadonlySet<AtomId>): View {
2523+ #view(set: ReadonlySet<AtomId>): ReadView { 2524+ this.#views.assertUnkeyedAllowed(); 25062525 return this.#views.view(this.#closed(set)); 25092528 /** A view cached under `key` (views.ts). */ 2510− #viewKeyed(key: string, set: () => ReadonlySet<AtomId>): View {
2529+ #viewKeyed(key: string, set: () => ReadonlySet<AtomId>): ReadView { 25112530 return this.#views.keyed(key, () => this.#closed(set())); @@ -2672,7 +2691,7 @@
2675− #describe(pair: Pair, yoursView: View, theirsView: View, spaceName: string): Collision {
2694+ #describe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision { 26762695 return describePair( 26782697 (atom, space) => this.#origin(atom, space), @@ -2683,7 +2702,7 @@
2686− #touchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string> {
2705+ #touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string> { 26872706 return touchedFiles(this.#graph, ids, views); --- /dev/null
+++ b/worker/project/projection-provider.ts
@@ -0,0 +1,80 @@
1+import { ExperimentalMarkerProjection } from "../../src/engine/experimental/projection-marker.ts"; 2+import { ProjectionReader } from "../../src/engine/experimental/projection-reader.ts"; 3+import type { ProjectionHandle, ProjectionIdentity } from "../../src/engine/experimental/projection-root.ts"; 4+import { ProjectionSnapshots } from "../../src/engine/experimental/projection-snapshots.ts"; 5+import type { Graph } from "../../src/engine/graph.ts"; 6+import type { GraphStateStorage } from "../../src/engine/state-source.ts"; 7+import type { Published } from "./spaces.ts"; 9+/** Internal host contract; canonical proofs and version authority are independent of saved handles. */ 10+export interface ProjectionReadBinding { 11+ readonly graph: Graph; 12+ readonly context: Pick<ProjectionIdentity, "database" | "namespace" | "registry" | "defaultFile">; 13+ readonly sourceGeneration: number; 14+ sourceLength(): number; 15+ prefixDigest(length: number): string | undefined; 17+ committed(): { version: number; handle: ProjectionHandle }; 18+ at(version: number): ProjectionHandle | undefined; 19+ delta(version: number): Published | undefined; 20+ /** Read-through overlay owned and cleaned by the current transaction. */ 21+ allocate(): GraphStateStorage; 22+ /** Checks this exact transaction, graph revision and verified source binding. */ 26+/** Explicit private route. Unsupported memberships never fall back to historical View construction. */ 27+export function projectedReader(binding: ProjectionReadBinding, key: string): ProjectionReader { 28+ const scopeGuard = binding.guard(); 30+ const sourceLength = binding.sourceLength(), 31+ sourceGeneration = binding.sourceGeneration; 32+ const sourceDigest = binding.prefixDigest(sourceLength); 33+ if (sourceDigest === undefined) throw Error("missing verified current canonical prefix"); 34+ const assertLive = () => { 37+ binding.sourceGeneration !== sourceGeneration || 38+ binding.sourceLength() !== sourceLength || 39+ binding.prefixDigest(sourceLength) !== sourceDigest 41+ throw Error("expired projection source binding"); 44+ const match = /^(v|a) @(0|[1-9]\d*)(?:\+(.+))?$/.exec(key); 45+ if (!match || (match[1] === "v" && match[3])) throw Error(`unsupported projection key: ${key}`); 46+ const version = Number(match[2]); 47+ if (!Number.isSafeInteger(version) || version > binding.version()) 48+ throw Error("projection version outside authority"); 49+ const exact = binding.at(version); 50+ const anchor = exact ? { version, handle: exact } : binding.committed(); 51+ if (!Number.isSafeInteger(anchor.version) || anchor.version < 0 || (!exact && version <= anchor.version)) 52+ throw Error("missing historical version projection"); 53+ const length = anchor.handle.identity.sourceLength; 54+ if (!Number.isSafeInteger(length) || length < 0 || length > binding.sourceLength()) 55+ throw Error("projection source outside authority"); 56+ const digest = binding.prefixDigest(length); 57+ if (digest === undefined) throw Error("missing verified canonical prefix"); 58+ const storage = binding.allocate(); 59+ const context = { ...binding.context }; 60+ const adapter = new ExperimentalMarkerProjection(storage, binding.graph, context.defaultFile, context.namespace); 61+ const snapshots = new ProjectionSnapshots(storage, adapter, context); 62+ let state = snapshots.load(anchor.handle, { 64+ sourceGeneration: binding.sourceGeneration, 65+ sourceLength: length, 66+ sourceDigest: digest, 67+ membership: String(anchor.version), 69+ for (let next = anchor.version + 1; next <= version; next++) { 70+ const delta = binding.delta(next); 71+ if (!delta || delta.version !== next) throw Error("missing transaction-local version delta"); 72+ for (const atom of [...(delta.dropped ?? [])].map((id) => binding.graph.atom(id)).sort((a, b) => b.seq - a.seq)) 73+ state = adapter.removeAtom(state, atom); 74+ for (const atom of delta.atoms.map((id) => binding.graph.atom(id)).sort((a, b) => a.seq - b.seq)) 75+ state = adapter.apply(state, atom); 77+ for (const id of match[3]?.split(",") ?? []) state = adapter.apply(state, binding.graph.atom(id)); 79+ return new ProjectionReader(adapter, state, assertLive); --- a/worker/project/publish.ts
+++ b/worker/project/publish.ts
@@ -1,7 +1,7 @@
11// Add the agent's draft to its space. Writes go through PublishHost; today 22// the host is Project. Ingest calls publishDraft, the inner step. 4−import { type AtomId, buildAtom, type Hunk, joinLines, type View } from "../../src/engine/index.ts";
4+import { type AtomId, buildAtom, type Hunk, joinLines, type ReadView } from "../../src/engine/index.ts"; 55import { differenceSet, unionOverlay } from "../../src/engine/state-source.ts"; 66import type { Pair } from "./collisions.ts"; 77import type { DefinitionCollision } from "./definition-rule.ts"; @@ -23,10 +23,10 @@
2323 strandedFiles(draft: readonly AtomId[], set: ReadonlySet<AtomId>): string[]; 2424 setOf(space: Space): ReadonlySet<AtomId>; 2525 markedFiles(agent: AgentState): string[]; 26− agentView(agent: AgentState): View;
26+ agentView(agent: AgentState): ReadView; 29− view: View,
3131 text: string | null | undefined, @@ -58,7 +58,8 @@
5858 resolves: readonly AtomId[], 61− view(set: ReadonlySet<AtomId>): View;
61+ view(set: ReadonlySet<AtomId>): ReadView; 62+ spaceOverlay?(space: Space, atoms: readonly AtomId[]): ReadView; 6263 requireClosed(tie: { deps: readonly AtomId[] }, union: ReadonlySet<AtomId>): void; 6364 newerFor(agent: AgentState): ReadonlySet<AtomId>; 6465 currentChange(agent: AgentState, time: number): number | undefined; @@ -155,7 +156,8 @@
155156 const resolves = [...new Set(seen.flatMap((p) => [p.yours, p.theirs]))]; 156157 if (space.name === SHARED && !direct && host.queueOn()) 157158 return host.enqueue(agent, message, time, draft, resolves, entries); 158− const tie = buildAtom(host.view(union), { author: agent.name, message, time, needs: draft, resolves });
159+ const candidate = host.spaceOverlay ? host.spaceOverlay(space, draft) : host.view(union); 160+ const tie = buildAtom(candidate, { author: agent.name, message, time, needs: draft, resolves }); 159161 host.requireClosed(tie, union); 160162 const version = last(space) + 1; 161163 const othersPublished = space.versions.slice(agent.base + 1).some((p) => p.agent !== agent.name); --- a/worker/project/queue.ts
+++ b/worker/project/queue.ts
@@ -1,7 +1,7 @@
11// The merge queue: publishes to shared waiting for their batch's check. 22// Writes go through QueueHost; today the host is Project. 4−import { type AtomId, buildAtom, type Graph, type View } from "../../src/engine/index.ts";
4+import { type AtomId, buildAtom, type Graph, type ReadView } from "../../src/engine/index.ts"; 55import type { Pair } from "./collisions.ts"; 66import { definedTwice } from "./definitions.ts"; 77import { keptOf, lostLines } from "./markers.ts"; @@ -27,7 +27,7 @@
2727export interface QueueHost { 2828 readonly graph: Graph; 2929 checkerReady(): boolean; 30− sharedView(): View;
30+ sharedView(): ReadView; 3131 queued(): readonly QueuedPublish[]; 3333 checkingHas(id: number): boolean; @@ -36,12 +36,12 @@
3838 setOf(space: Space): ReadonlySet<AtomId>; 39− view(set: ReadonlySet<AtomId>): View;
39+ view(set: ReadonlySet<AtomId>): ReadView; 4040 agentSet(agent: AgentState): Set<AtomId>; 41− agentView(agent: AgentState): View;
41+ agentView(agent: AgentState): ReadView; 4242 pairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[]; 43− describe(pair: Pair, yoursView: View, theirsView: View, spaceName: string): Collision;
44− touchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;
43+ describe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision; 44+ touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>; --- a/worker/project/record-file.ts
+++ b/worker/project/record-file.ts
@@ -7,9 +7,9 @@
12− type View,
1313} from "../../src/engine/index.ts"; 1414import type { AgentState, Entry, Meta, Mode } from "./project-types.ts"; @@ -17,7 +17,7 @@
1717export interface RecordFileHost { 20− view: View,
2121 input: { edits: readonly EditInput[]; attrs?: readonly AttrSet[] }, @@ -34,7 +34,7 @@
3434export function recordFile( 3535 host: RecordFileHost, 37− view: View,
3939 text: string | null | undefined, --- a/worker/project/record.ts
+++ b/worker/project/record.ts
@@ -1,7 +1,7 @@
11// Whole files as the agent's folder has them. Writes go through RecordHost; 22// today the host is Project. 4−import { canonicalText, type Hunk, type View } from "../../src/engine/index.ts";
4+import { canonicalText, type Hunk, type ReadView } from "../../src/engine/index.ts"; 55import { checkPath } from "./path-rules.ts"; 66import { isComposed, pathKey } from "./pathkey.ts"; 77import { ProjectError } from "./project-error.ts"; @@ -24,12 +24,12 @@
2424 readonly agents: ReadonlyMap<string, AgentState>; 2525 readonly whole: ProjectOptions["whole"]; 2626 initialized(): boolean; 27− agentView(agent: AgentState): View;
28− sharedView(): View;
27+ agentView(agent: AgentState): ReadView; 28+ sharedView(): ReadView; 3030 files: Readonly<Record<string, string | null>>, 3131 blobs: Readonly<Record<string, string>>, 32− view: View | undefined,
32+ view: ReadView | undefined, 3434 ): { files: Record<string, string | null>; blobs: Record<string, string> }; 3535 checkBlobs(blobs: unknown, files: object): Record<string, string>; @@ -37,7 +37,7 @@
3737 draftFiles(agent: AgentState): Set<string>; 40− view: View,
4242 text: string | null | undefined, --- a/worker/project/restore.ts
+++ b/worker/project/restore.ts
@@ -1,7 +1,7 @@
11// Discard unpublished changes to some files, like git restore. Writes go through RestoreHost; 22// today the host is Project. 4−import type { AtomId, Graph, Hunk, View } from "../../src/engine/index.ts";
4+import type { AtomId, Graph, Hunk, ReadView } from "../../src/engine/index.ts"; 55import { checkReadPath } from "./path-rules.ts"; 66import { ProjectError } from "./project-error.ts"; 77import type { AgentState, Blobs, Entry, Files, Meta, Mode, Modes, RestoreAnswer } from "./project-types.ts"; @@ -11,14 +11,14 @@
1111 readonly graph: Graph; 1212 agent(name: string, entries: Entry[]): AgentState; 1313 draft(agent: AgentState): AtomId[]; 14− touchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;
14+ touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>; 1515 apply(entry: Entry): void; 16− view(set: ReadonlySet<AtomId>): View;
16+ view(set: ReadonlySet<AtomId>): ReadView; 1717 agentSet(agent: AgentState): Set<AtomId>; 18− agentView(agent: AgentState): View;
18+ agentView(agent: AgentState): ReadView; 21− view: View,
2323 text: string | null | undefined, --- a/worker/project/spelling.ts
+++ b/worker/project/spelling.ts
@@ -2,7 +2,7 @@
22// would make two spellings of one name live at once, and which spelling a 33// path has in a view. Plain functions of views; the project calls them. 5−import type { View } from "../../src/engine/index.ts";
5+import type { ReadView } from "../../src/engine/index.ts"; 66import { pathKey } from "./pathkey.ts"; @@ -14,7 +14,7 @@
1414 * clash shared already holds isn't charged to this work. The answer is the 1515 * refusal's reason, or undefined. 17−export function clashIn(view: View, touched: Iterable<string>, now: View): string | undefined {
17+export function clashIn(view: ReadView, touched: Iterable<string>, now: ReadView): string | undefined { 1818 const byKey = new Map<string, string[]>(); 1919 for (const p of view.knownPaths()) { 2020 const k = pathKey(p); @@ -67,7 +67,7 @@
6969/** The spelling a path has in this view: itself, or the one existing file it matches by pathKey (case and Unicode form ignored). */ 70−export function spellingOf(view: View, path: string): string {
70+export function spellingOf(view: ReadView, path: string): string { 7171 if (view.hasFile(path)) return path; 7272 const key = pathKey(path); 7373 // Known paths first, by key, then only those laid out (#46). --- a/worker/project/switch-to.ts
+++ b/worker/project/switch-to.ts
@@ -1,7 +1,8 @@
1+import { View } from "../../src/engine/index.ts"; 12// Move an agent to a named draft, or back to shared. Writes go through 23// SwitchHost; today the host is Project. 4−import { type AtomId, type Graph, View } from "../../src/engine/index.ts";
5+import type { AtomId, Graph, ReadView } from "../../src/engine/index.ts"; 56import { ProjectError } from "./project-error.ts"; 67import { checkDraftName } from "./project-helpers.ts"; 78import type { AgentState, Entry, SwitchAnswer, SyncAnswer } from "./project-types.ts"; @@ -12,13 +13,13 @@
1213 agent(name: string, entries: Entry[]): AgentState; 1314 flush(entries: Entry[]): void; 1415 readonly spaces: ReadonlyMap<string, Space>; 15− agentView(agent: AgentState): View;
16+ agentView(agent: AgentState): ReadView; 1617 readonly graph: Graph; 1819 apply(entry: Entry): void; 1920 draft(agent: AgentState): readonly AtomId[]; 2021 setOf(space: Space): ReadonlySet<AtomId>; 21− changesSince(agent: AgentState, before: View): SyncAnswer;
22+ changesSince(agent: AgentState, before: ReadView): SyncAnswer; --- a/worker/project/sync.ts
+++ b/worker/project/sync.ts
@@ -1,7 +1,8 @@
1+import { View } from "../../src/engine/index.ts"; 12// Move the agent's base to its space's newest version. Writes go through 23// SyncHost; today the host is Project. 4−import { type AtomId, type Graph, View } from "../../src/engine/index.ts";
5+import type { AtomId, Graph, ReadView } from "../../src/engine/index.ts"; 56import { ProjectError } from "./project-error.ts"; 67import type { AgentState, Entry, MergedLine, SyncAnswer } from "./project-types.ts"; 78import { last, SHARED, type Space } from "./spaces.ts"; @@ -12,7 +13,7 @@
1213 readonly labels: ReadonlyMap<string, readonly number[]>; 1314 agent(name: string, entries: Entry[]): AgentState; 1415 spaceOf(agent: AgentState): Space; 15− agentView(agent: AgentState): View;
16+ agentView(agent: AgentState): ReadView; 1617 at(space: Space, version: number): ReadonlySet<AtomId>; 1718 draft(agent: AgentState): AtomId[]; 1819 strandedFiles(draft: readonly AtomId[], set: ReadonlySet<AtomId>): string[]; @@ -20,13 +21,13 @@
2021 flush(entries: Entry[]): void; 23− before: View,
2425 oldBase: ReadonlySet<AtomId>, 29− changesSince(agent: AgentState, before: View): SyncAnswer;
30+ changesSince(agent: AgentState, before: ReadView): SyncAnswer; --- /dev/null
+++ b/worker/project/test/projection-integration.test.ts
@@ -0,0 +1,791 @@
1+import assert from "node:assert/strict"; 2+import { createHash } from "node:crypto"; 3+import { mkdtempSync } from "node:fs"; 4+import { tmpdir } from "node:os"; 5+import { join } from "node:path"; 6+import { performance } from "node:perf_hooks"; 7+import { test } from "node:test"; 8+import { ExperimentalMarkerProjection } from "../../../src/engine/experimental/projection-marker.ts"; 9+import { ProjectionOverlayStorage } from "../../../src/engine/experimental/projection-overlay-storage.ts"; 10+import { ProjectionReadScope } from "../../../src/engine/experimental/projection-read-scope.ts"; 11+import { ProjectionReader } from "../../../src/engine/experimental/projection-reader.ts"; 12+import type { ProjectionHandle, ProjectionIdentity } from "../../../src/engine/experimental/projection-root.ts"; 13+import { ProjectionSnapshots } from "../../../src/engine/experimental/projection-snapshots.ts"; 14+import type { Graph } from "../../../src/engine/graph.ts"; 15+import { CachedStateStorage, storedArray } from "../../../src/engine/state-source.ts"; 16+import { SqlState } from "../../../src/engine/test/storage-helper.ts"; 17+import { MemoryStore, Project } from "../project.ts"; 18+import type { Entry, ProjectOptions, ProjectStore } from "../project-types.ts"; 19+import { projectedReader } from "../projection-provider.ts"; 20+import { Membership } from "../spaces.ts"; 21+import { ViewCache } from "../views.ts"; 22+import { WriterAgents } from "../writer-agents.ts"; 24+// Private test host only. Canonical frames and projection receipts share one SQLite transaction. 25+class ProjectionHost { 26+ readonly storage: SqlState; 27+ readonly entries: Entry[]; 28+ verifyReadParity = true; 29+ readViewProvider?: ProjectOptions["readViewProvider"]; 30+ enableReaderProvider(): void { 31+ this.readViewProvider = (graph) => { 32+ const scope = this.newReadScope(graph); 33+ return { keyed: (key) => this.readerForKey(key, graph, scope.guard(graph)) }; 36+ #scopeFrames: { token: object; scopes: ProjectionReadScope[]; overlays: ProjectionOverlayStorage[] }[] = []; 38+ newReadScope(graph: Graph): ProjectionReadScope { 39+ const frame = this.#scopeFrames.at(-1); 40+ assert.ok(frame, "reader provider requires an active transaction"); 41+ const scope = new ProjectionReadScope(graph, () => this.#scopeFrames.at(-1)?.token); 42+ frame.scopes.push(scope); 45+ #transaction<T>(operation: () => T): T { 46+ const parent = this.#scopeFrames.at(-1); 48+ for (const scope of parent.scopes) scope.close(); 49+ parent.scopes.length = 0; 51+ const frame = { token: {}, scopes: [] as ProjectionReadScope[], overlays: [] as ProjectionOverlayStorage[] }; 52+ this.#scopeFrames.push(frame); 54+ return this.storage.transaction(() => { 58+ for (const overlay of frame.overlays) overlay.close(); 62+ for (const scope of frame.scopes) scope.close(); 63+ assert.equal(this.#scopeFrames.pop(), frame); 67+ constructor(filename = ":memory:") { 68+ this.storage = new SqlState(filename); 69+ this.entries = storedArray<Entry>(this.storage, "integration:canonical"); 71+ readonly store: ProjectStore = { 73+ for (const entry of batch) { 74+ const digest = this.storage.read("integration:source", "digest") ?? ""; 75+ this.entries.push(entry); 77+ "integration:source", 80+ .update(JSON.stringify([digest, entry])) 84+ "integration:prefixes", 85+ String(this.entries.length), 86+ this.storage.read("integration:source", "digest"), 93+ expectedLength: number, 94+ operation: (project: Project) => T, 96+ request: { body: string; target: string; authority: string } = { 99+ authority: "test-writer", 102+ // The real host must supply a normalized request body, never a callback's source text. 103+ const requestDigest = createHash("sha256") 104+ .update(JSON.stringify([request.body, request.target, request.authority])) 106+ return this.#transaction(() => { 107+ const receipt = this.storage.read("integration:receipts", id) as { result: T; requestDigest: string } | undefined; 109+ if (receipt.requestDigest !== requestDigest) throw Error("operation ID request conflict"); 110+ return receipt.result; 112+ assert.equal(this.entries.length, expectedLength, "stale canonical head"); 113+ const project = this.entries.length 114+ ? Project.openWriter(this.store, this.storage, this.entries.length, { readViewProvider: this.readViewProvider }) 115+ : new Project(this.store, { writerStorage: this.storage }); 116+ const adapter = new ExperimentalMarkerProjection( 120+ JSON.stringify(["database-a", "projection-a"]), 123+ database: "database-a", 124+ namespace: JSON.stringify(["database-a", "projection-a"]), 125+ registry: "registry-a", 126+ defaultFile: "a.txt", 128+ const snapshots = new ProjectionSnapshots(this.storage, adapter, context); 129+ const previous = this.storage.read("integration:head", "projection") as ProjectionHandle | undefined; 130+ if (this.entries.length && !previous) throw Error("missing committed projection head"); 131+ const expected: ProjectionIdentity = { 133+ sourceGeneration: 1, 134+ sourceLength: this.entries.length, 135+ sourceDigest: this.storage.read("integration:prefixes", String(this.entries.length)) as string, 136+ membership: this.entries.length ? String(project.version) : "-1", 138+ let state = previous ? snapshots.load(previous, expected) : adapter.empty(); 139+ const before = previous ? project.version : -1; 140+ const result = operation(project); 141+ const save = (version: number): ProjectionHandle => { 142+ const next = (this.storage.read("integration:head", "next-root") as number | undefined) ?? 0; 143+ const handle = snapshots.save( 147+ sourceGeneration: 1, 148+ sourceLength: this.entries.length, 149+ sourceDigest: this.storage.read("integration:source", "digest") as string, 150+ membership: String(version), 154+ this.storage.write("integration:head", "next-root", next + 1); 157+ let versionHandle: ProjectionHandle | undefined; 158+ const membership = new Membership(this.storage); 159+ for (let version = before + 1; version <= project.version; version++) { 160+ const delta = membership.shared.versions[version]!; 161+ for (const atom of [...(delta.dropped ?? [])].map((id) => project.graph.atom(id)).sort((a, b) => b.seq - a.seq)) 162+ state = adapter.removeAtom(state, atom); 163+ for (const atom of delta.atoms.map((id) => project.graph.atom(id)).sort((a, b) => a.seq - b.seq)) 164+ state = adapter.apply(state, atom); 165+ versionHandle = save(version); 166+ this.storage.write("integration:versions", String(version), versionHandle); 169+ previous && this.entries.length === expectedLength ? previous : (versionHandle ?? save(project.version)); 170+ this.storage.write("integration:head", "projection", handle); 171+ this.storage.write("integration:head", "version", project.version); 172+ if (!this.storage.read("integration:versions", String(project.version))) 173+ this.storage.write("integration:versions", String(project.version), handle); 174+ this.storage.write("integration:receipts", id, { result, requestDigest }); 175+ for (const path of this.verifyReadParity ? ["a.txt", "b.txt"] : []) { 176+ const reader = new ProjectionReader(adapter, state, this.newReadScope(project.graph).guard(project.graph)); 177+ assert.deepEqual(reader.lines(path), project.sharedView().lines(path)); 178+ assert.deepEqual(reader.knownPaths(), project.sharedView().knownPaths()); 179+ assert.deepEqual(reader.sequence(path), project.sharedView().sequence(path)); 180+ assert.equal(reader.text(path), project.sharedView().text(path)); 181+ assert.equal(reader.hasFile(path), project.sharedView().hasFile(path)); 183+ adapter.lines(state, path), 187+ .map((line) => line.id), 189+ assert.deepEqual(adapter.attrs(state, path), project.sharedView().attrs(path)); 191+ if (fail) throw Error("injected outer rollback"); 195+ draftLines(name: string, path: string): string[] { 196+ return this.withDraftReader(name, (reader) => reader.lines(path).map((line) => line.id)); 198+ readerForKey(key: string, graph: Graph, assertLive?: () => void): ProjectionReader { 199+ const frame = this.#scopeFrames.at(-1); 200+ assert.ok(frame, "projection reads require a transaction"); 201+ const guard = assertLive ?? this.newReadScope(graph).guard(graph); 202+ const versions = new Membership(this.storage).shared.versions; 203+ return projectedReader( 207+ database: "database-a", 208+ namespace: JSON.stringify(["database-a", "projection-a"]), 209+ registry: "registry-a", 210+ defaultFile: "a.txt", 212+ sourceGeneration: 1, 213+ sourceLength: () => this.entries.length, 214+ prefixDigest: (length) => this.storage.read("integration:prefixes", String(length)) as string | undefined, 215+ version: () => versions.length - 1, 217+ version: this.storage.read("integration:head", "version") as number, 218+ handle: this.storage.read("integration:head", "projection") as ProjectionHandle, 220+ at: (version) => this.storage.read("integration:versions", String(version)) as ProjectionHandle | undefined, 221+ delta: (version) => versions[version], 224+ const overlay = new ProjectionOverlayStorage(this.storage, `reader-${this.#nextOverlay++}`); 225+ frame.overlays.push(overlay); 226+ return new CachedStateStorage(overlay, frame.overlays.length <= 32 ? 8192 : 0, 32); 233+ withDraftReader<T>(name: string, read: (reader: ProjectionReader) => T): T { 234+ const rollback = Symbol("completed draft read"); 237+ this.#transaction(() => { 238+ const project = Project.openWriter(this.store, this.storage, this.entries.length, { 239+ readViewProvider: this.readViewProvider, 241+ const actor = new WriterAgents(this.storage).get(name); 243+ assert.equal(actor.space, "", "named draft projection is not implemented in this test host"); 244+ const handle = this.storage.read("integration:versions", String(actor.base)) as ProjectionHandle; 245+ assert.ok(handle, "missing exact base projection"); 247+ database: "database-a", 248+ namespace: JSON.stringify(["database-a", "projection-a"]), 249+ registry: "registry-a", 250+ defaultFile: "a.txt", 252+ const adapter = new ExperimentalMarkerProjection(this.storage, project.graph, "a.txt", context.namespace); 253+ const snapshots = new ProjectionSnapshots(this.storage, adapter, context); 254+ const expected: ProjectionIdentity = { 256+ sourceGeneration: 1, 257+ sourceLength: handle.identity.sourceLength, 258+ sourceDigest: this.storage.read("integration:prefixes", String(handle.identity.sourceLength)) as string, 259+ membership: String(actor.base), 261+ let state = snapshots.load(handle, expected); 262+ for (const id of actor.mine) state = adapter.apply(state, project.graph.atom(id)); 263+ result = read(new ProjectionReader(adapter, state, this.newReadScope(project.graph).guard(project.graph))); 267+ if (error !== rollback) throw error; 273+test("measure private routed fixed-working-set cost", { skip: process.env.ABSO_PROJECTION_COST !== "1" }, () => { 274+ for (const revisions of [8, 32, 128]) { 275+ const host = new ProjectionHost(); 277+ host.run("init", 0, (p) => p.init({ "a.txt": "head\nrevision 0\ntail\n" }, 0)); 278+ for (let i = 1; i <= revisions; i++) 279+ host.run(`seed-${i}`, host.entries.length, (p) => { 280+ p.record("writer", { "a.txt": `head\nrevision ${i}\ntail\n` }, i * 2); 281+ p.publish("writer", "Seed", i * 2 + 1); 283+ host.enableReaderProvider(); 284+ host.verifyReadParity = false; 285+ const byCollection = new Map<string, number>(); 286+ const callers = new Map<string, number>(); 287+ const read = host.storage.read.bind(host.storage); 288+ host.storage.read = (collection, key) => { 289+ if (process.env.ABSO_PROJECTION_TRACE === "1" && collection === "line-base") { 290+ const stack = new Error().stack!.split("\n").slice(2, 11).join("\n"); 291+ callers.set(stack, (callers.get(stack) ?? 0) + 1); 293+ const group = collection.startsWith("projection:temporary:") ? "projection:temporary" : collection; 294+ byCollection.set(group, (byCollection.get(group) ?? 0) + 1); 295+ return read(collection, key); 297+ const reads = host.storage.reads, 298+ writes = host.storage.writes, 299+ scans = host.storage.scans; 300+ const start = performance.now(); 301+ host.run("measured", host.entries.length, (p) => { 302+ p.record("writer", { "a.txt": "head\nmeasured\ntail\n" }, 1000); 303+ assert.equal(p.publish("writer", "Measured", 1001).ok, true); 309+ milliseconds: performance.now() - start, 310+ reads: host.storage.reads - reads, 311+ writes: host.storage.writes - writes, 312+ scans: host.storage.scans - scans, 313+ collections: [...byCollection].sort((a, b) => b[1] - a[1]).slice(0, 12), 314+ callers: [...callers].sort((a, b) => b[1] - a[1]).slice(0, 3), 318+ host.storage.db.prepare("SELECT COUNT(*) AS n FROM state WHERE collection LIKE 'projection:temporary:%'").get()! 323+ host.storage.db.close(); 328+for (const fail of [false, true]) { 329+ test(`nested host transaction permanently expires parent readers after ${fail ? "rollback" : "commit"}`, () => { 330+ const host = new ProjectionHost(); 332+ host.run("init", 0, (p) => p.init({ "a.txt": "one\ntwo\n" }, 0)); 333+ host.run("outer", host.entries.length, (p) => { 334+ const reader = host.readerForKey("v @0", p.graph, host.newReadScope(p.graph).guard(p.graph)); 335+ const iterator = reader.visibleLines("a.txt"); 340+ host.entries.length, 342+ assert.throws(() => reader.text("a.txt"), /expired/); 346+ if (fail) assert.throws(inner, /outer rollback/); 348+ assert.throws(() => reader.text("a.txt"), /expired/); 349+ assert.throws(() => iterator.next(), /expired/); 351+ host.readerForKey("v @0", p.graph, host.newReadScope(p.graph).guard(p.graph)).text("a.txt"), 356+ host.storage.db.close(); 361+test("private projection host joins actual Project commits and rolls back with canonical state", () => { 362+ const host = new ProjectionHost(); 363+ const oracle = new Project(new MemoryStore()); 365+ const run = <T>(operation: (project: Project) => T) => 366+ assert.deepEqual(host.run(String(id++), host.entries.length, operation), operation(oracle)); 368+ run((p) => p.init({ "a.txt": "one\n", "b.txt": "two\n" }, 0)); 369+ run((p) => p.record("left", { "a.txt": "ONE\n" }, 1)); 370+ run((p) => p.record("right", { "b.txt": "TWO\n" }, 2)); 371+ run((p) => p.publish("left", "Left", 3)); 372+ run((p) => p.publish("right", "Right", 4)); 373+ const rows = () => JSON.stringify(host.storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all()); 374+ const before = rows(), 375+ length = host.entries.length; 377+ () => host.run("failure", length, (p) => p.record("left", { "a.txt": "again\n" }, 5), true), 380+ assert.equal(rows(), before); 381+ assert.throws(() => host.run("stale", length - 1, () => null), /stale canonical head/); 382+ assert.equal(rows(), before); 383+ host.run("retry", length, (p) => p.record("left", { "a.txt": "again\n" }, 5)); 384+ const committed = rows(); 385+ host.run("retry", length, () => { 386+ throw Error("retry executed twice"); 388+ assert.equal(rows(), committed); 390+ host.storage.db.close(); 394+test("runtime provider refuses a valid root stored under the wrong version", () => { 395+ const host = new ProjectionHost(); 397+ host.run("init", 0, (p) => p.init({ "a.txt": "one\n" }, 0)); 398+ host.run("edit", host.entries.length, (p) => { 399+ p.record("writer", { "a.txt": "two\n" }, 1); 400+ p.publish("writer", "Edit", 2); 402+ const original = host.storage.read("integration:versions", "1"); 403+ host.storage.write("integration:versions", "1", host.storage.read("integration:versions", "0")); 404+ const writes = host.storage.writes; 406+ () => host.run("wrong-version", host.entries.length, (p) => host.readerForKey("v @1", p.graph)), 409+ assert.equal(host.storage.writes, writes); 410+ host.storage.write("integration:versions", "1", original); 411+ for (const key of ["v @2", "v named@1", "v @01", "v @1+a0"]) 413+ () => host.run(key, host.entries.length, (p) => host.readerForKey(key, p.graph)), 414+ /authority|unsupported/, 417+ host.storage.db.close(); 421+test("private projection host refuses a forged source or membership handle before executing", () => { 422+ const host = new ProjectionHost(); 424+ host.run("init", 0, (p) => p.init({ "a.txt": "one\n" }, 0)); 425+ const original = host.storage.read("integration:head", "projection") as ProjectionHandle; 426+ for (const change of [ 427+ { sourceDigest: "f".repeat(64) }, 428+ { sourceLength: original.identity.sourceLength + 1 }, 429+ { membership: "900" }, 430+ { database: "other-database" }, 431+ { sourceGeneration: 2 }, 433+ host.storage.write("integration:head", "projection", { 435+ identity: { ...original.identity, ...change }, 437+ let invoked = false; 438+ const writes = host.storage.writes; 441+ host.run("forged", host.entries.length, () => { 446+ assert.equal(invoked, false); 447+ assert.equal(host.storage.writes, writes); 449+ host.storage.write("integration:head", "projection", original); 450+ host.run("valid", host.entries.length, (p) => p.record("writer", { "a.txt": "two\n" }, 1)); 452+ host.storage.read("integration:prefixes", String(original.identity.sourceLength)), 453+ original.identity.sourceDigest, 454+ "later graph extension preserves the old canonical prefix identity", 457+ host.storage.db.close(); 461+test("private projection host routes cross-file moves, later edits and dropping versions", (t) => { 462+ const host = new ProjectionHost(); 463+ const oracle = new Project(new MemoryStore()); 465+ const run = <T>(operation: (project: Project) => T) => { 466+ const read = host.storage.read.bind(host.storage); 468+ host.readViewProvider && 469+ t.mock.method(host.storage, "read", (collection: string, key: string) => { 470+ if (collection === 'membership:"":events') throw Error("historical membership enumeration forbidden"); 471+ return read(collection, key); 475+ actual = host.run(`move-${id++}`, host.entries.length, operation); 477+ if (guard) guard.mock.restore(); 479+ assert.deepEqual(actual, operation(oracle)); 482+ const block = "function example() {\n return 42;\n}\n"; 483+ run((p) => p.init({ "a.txt": `header\n${block}`, "b.txt": "destination\n" }, 0)); 484+ host.enableReaderProvider(); 485+ run((p) => p.record("mover", { "a.txt": "header\n", "b.txt": `destination\n${block}` }, 1)); 486+ run((p) => p.publish("mover", "Move function", 2)); 487+ run((p) => p.record("editor", { "b.txt": `destination\n${block.replace("42", "43")}` }, 3)); 488+ run((p) => p.publish("editor", "Edit moved function", 4)); 489+ run((p) => p.drop("cleanup", [2], "Undo edit", 5)); 490+ run((p) => p.drop("cleanup", [1], "Undo move", 6)); 491+ assert.deepEqual(Project.openWriter(host.store, host.storage, host.entries.length).files(), oracle.files()); 493+ host.storage.db.close(); 497+test("private projection host reopens the database and retries the committed receipt", () => { 498+ const filename = join(mkdtempSync(join(tmpdir(), "abso-project-projection-")), "state.sqlite"); 499+ let host = new ProjectionHost(filename); 501+ host.run("init", 0, (p) => p.init({ "a.txt": "one\n" }, 0)); 502+ const length = host.entries.length; 503+ const result = host.run("record", length, (p) => p.record("writer", { "a.txt": "two\n" }, 1)); 504+ host.storage.db.close(); 505+ host = new ProjectionHost(filename); 506+ const before = host.entries.length; 508+ host.run("record", length, () => { 509+ throw Error("replayed receipt executed"); 513+ assert.equal(host.entries.length, before); 514+ host.run("publish", before, (p) => p.publish("writer", "After restart", 2)); 515+ host.storage.db.close(); 516+ host = new ProjectionHost(filename); 517+ assert.deepEqual(Project.openWriter(host.store, host.storage, host.entries.length).files(), { "a.txt": "two\n" }); 518+ host.run("later", host.entries.length, (p) => p.record("writer", { "a.txt": "three\n" }, 3)); 520+ host.storage.db.close(); 524+test("private projection host reuses its snapshot when an operation appends nothing", () => { 525+ const host = new ProjectionHost(); 527+ host.run("init", 0, (p) => p.init({ "a.txt": "one\n" }, 0)); 528+ const head = host.storage.read("integration:head", "projection"); 529+ const length = host.entries.length; 531+ host.run("read", length, (p) => p.files()), 532+ { "a.txt": "one\n" }, 534+ assert.deepEqual(host.storage.read("integration:head", "projection"), head); 535+ assert.equal(host.entries.length, length); 537+ host.storage.db.close(); 541+test("private projection receipts reject changed request, target or authority", () => { 542+ const host = new ProjectionHost(); 544+ body: JSON.stringify({ kind: "init", files: { "a.txt": "one\n" } }), 546+ authority: "writer-a", 549+ const result = host.run("request", 0, (p) => p.init({ "a.txt": "one\n" }, 0), false, request); 550+ for (const changed of [ 551+ { ...request, body: "different" }, 552+ { ...request, target: "draft" }, 553+ { ...request, authority: "writer-b" }, 555+ const writes = host.storage.writes; 562+ throw Error("must not execute"); 569+ assert.equal(host.storage.writes, writes); 576+ throw Error("must not execute"); 584+ host.storage.db.close(); 588+test("private projection derives each concurrent draft from its exact older base", () => { 589+ const host = new ProjectionHost(); 591+ host.run("init", 0, (p) => p.init({ "a.txt": "one\n", "b.txt": "two\n" }, 0)); 592+ host.run("left", host.entries.length, (p) => p.record("left", { "a.txt": "LEFT\n" }, 1)); 593+ host.run("right", host.entries.length, (p) => p.record("right", { "b.txt": "RIGHT\n" }, 2)); 594+ host.run("publish", host.entries.length, (p) => p.publish("right", "Advance shared", 3)); 595+ const project = Project.openWriter(host.store, host.storage, host.entries.length); 596+ for (const actor of ["left", "right"]) 597+ for (const path of ["a.txt", "b.txt"]) 599+ host.draftLines(actor, path), 603+ .map((line) => line.id), 605+ assert.notDeepEqual(host.draftLines("left", "b.txt"), host.draftLines("right", "b.txt")); 607+ host.storage.db.close(); 611+test("private draft projection does not enumerate historical membership or canonical frames", (t) => { 612+ const host = new ProjectionHost(); 614+ host.run("init", 0, (p) => p.init({ "a.txt": "one\n" }, 0)); 615+ for (let i = 0; i < 12; i++) { 616+ host.run(`record-${i}`, host.entries.length, (p) => p.record("writer", { "a.txt": `${i}\n` }, i * 2 + 1)); 617+ host.run(`publish-${i}`, host.entries.length, (p) => p.publish("writer", `Revision ${i}`, i * 2 + 2)); 619+ host.run("draft", host.entries.length, (p) => p.record("draft", { "a.txt": "pending\n" }, 30)); 620+ const project = Project.openWriter(host.store, host.storage, host.entries.length); 621+ const expected = project 623+ .view.lines("a.txt") 624+ .map((line) => line.id); 625+ const read = host.storage.read.bind(host.storage); 626+ t.mock.method(host.storage, "read", (collection: string, key: string) => { 628+ collection === "integration:canonical" || 629+ (collection.startsWith("membership:") && (collection.includes(":events") || collection.endsWith(":own"))) 631+ throw Error(`historical enumeration forbidden: ${collection}`); 632+ return read(collection, key); 634+ t.mock.method(host.storage, "entries", () => { 635+ throw Error("collection enumeration forbidden"); 637+ assert.deepEqual(host.draftLines("draft", "a.txt"), expected); 639+ host.storage.db.close(); 643+test("temporary draft projection leaves no pages after repeated reads or a failed write", () => { 644+ const host = new ProjectionHost(); 646+ host.run("init", 0, (p) => p.init({ "a.txt": "one\n" }, 0)); 647+ host.run("draft", host.entries.length, (p) => p.record("writer", { "a.txt": "draft\n" }, 1)); 648+ const rows = () => JSON.stringify(host.storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all()); 649+ const before = rows(); 650+ const expected = Project.openWriter(host.store, host.storage, host.entries.length) 652+ .view.lines("a.txt") 653+ .map((line) => line.id); 654+ for (let i = 0; i < 3; i++) { 655+ assert.deepEqual(host.draftLines("writer", "a.txt"), expected); 656+ assert.equal(rows(), before); 658+ host.storage.failWrite = host.storage.writes + 3; 659+ assert.throws(() => host.draftLines("writer", "a.txt"), /injected/); 660+ assert.equal(rows(), before); 661+ host.storage.failWrite = Infinity; 662+ assert.deepEqual(host.draftLines("writer", "a.txt"), expected); 663+ assert.equal(rows(), before); 665+ host.storage.db.close(); 669+test("private host retains intermediate version roots inside one outer commit", () => { 670+ const host = new ProjectionHost(); 672+ host.run("init", 0, (p) => p.init({ "a.txt": "one\n" }, 0)); 673+ host.run("batch", host.entries.length, (p) => { 674+ p.record("first", { "a.txt": "two\n" }, 1); 675+ p.publish("first", "Two", 2); 676+ p.record("old-base", { "a.txt": "older draft\n" }, 3); 677+ p.record("second", { "a.txt": "three\n" }, 4); 678+ p.publish("second", "Three", 5); 680+ assert.ok(host.storage.read("integration:versions", "1")); 681+ assert.ok(host.storage.read("integration:versions", "2")); 682+ const project = Project.openWriter(host.store, host.storage, host.entries.length); 684+ host.draftLines("old-base", "a.txt"), 686+ .draftOf("old-base")! 687+ .view.lines("a.txt") 688+ .map((line) => line.id), 691+ host.storage.db.close(); 695+for (const competingPath of ["a.txt", "b.txt"] as const) { 696+ for (const mode of ["rollback", "commit"] as const) { 697+ test(`actual Project record and publish route privately with ${mode}, competing ${competingPath}, and no old closure`, (t) => { 698+ const filename = join(mkdtempSync(join(tmpdir(), "projection-route-")), "state.sqlite"); 699+ let host = new ProjectionHost(filename); 701+ host.run("init", 0, (p) => p.init({ "a.txt": "one\n", "b.txt": "two\n" }, 0)); 702+ host.run("left", host.entries.length, (p) => p.record("left", { "a.txt": "LEFT\n" }, 1)); 703+ host.run("right", host.entries.length, (p) => p.record("right", { [competingPath]: "RIGHT\n" }, 2)); 704+ host.run("publish", host.entries.length, (p) => p.publish("right", "Advance shared", 3)); 705+ const expected = "LEFT\n"; 706+ const oracle = Project.load([...host.entries], new MemoryStore()); 707+ const recorded = oracle.record("left", { "a.txt": "UPDATED\n" }, 4); 708+ const published = oracle.publish("left", "Publish routed edit", 5); 709+ assert.equal(published.ok, competingPath !== "a.txt"); 710+ const rows = () => JSON.stringify(host.storage.db.prepare("SELECT * FROM state ORDER BY collection,key").all()); 711+ const before = rows(); 713+ let lastReader: ProjectionReader | undefined; 714+ host.readViewProvider = (graph) => { 715+ const scope = host.newReadScope(graph); 719+ return (lastReader = host.readerForKey(key, graph, scope.guard(graph))); 723+ const route = (project: Project) => { 725+ const unkeyed = t.mock.method(ViewCache.prototype, "view", () => { 726+ throw Error("unkeyed historical View construction is forbidden"); 728+ const replay = t.mock.method(Project, "load", () => { 729+ throw Error("canonical Project replay is forbidden"); 731+ const read = host.storage.read.bind(host.storage); 732+ const guard = t.mock.method(host.storage, "read", (collection: string, key: string) => { 733+ if (collection === 'membership:"":events') throw Error("old closure membership enumeration forbidden"); 734+ return read(collection, key); 737+ assert.equal(project.draftOf("left")!.view.text("a.txt"), expected); 738+ assert.equal(calls, 1); 739+ assert.deepEqual(project.record("left", { "a.txt": "UPDATED\n" }, 4), recorded); 740+ assert.deepEqual(project.publish("left", "Publish routed edit", 5), published); 742+ replay.mock.restore(); 743+ unkeyed.mock.restore(); 744+ guard.mock.restore(); 747+ if (mode === "rollback") { 748+ host.withDraftReader("left", () => 750+ Project.openWriter(host.store, host.storage, host.entries.length, { 751+ readViewProvider: host.readViewProvider, 755+ assert.equal(rows(), before); 757+ const length = host.entries.length; 758+ assert.throws(() => host.run("routed", length, route, true), /injected outer rollback/); 759+ assert.equal(rows(), before); 760+ assert.throws(() => lastReader!.text("a.txt"), /expired|stale/); 761+ host.run("routed", length, route); 764+ .prepare("SELECT COUNT(*) AS n FROM state WHERE collection LIKE 'projection:temporary:%'") 768+ const committed = rows(); 769+ host.storage.db.close(); 770+ host = new ProjectionHost(filename); 771+ assert.equal(rows(), committed); 772+ host.run("routed", length, () => { 773+ throw Error("committed retry executed twice"); 775+ assert.equal(rows(), committed); 776+ host.withDraftReader("left", (reader) => { 777+ assert.equal(reader.text("a.txt"), oracle.draftOf("left")!.view.text("a.txt")); 778+ assert.equal(reader.text("b.txt"), oracle.draftOf("left")!.view.text("b.txt")); 779+ const shared = host.readerForKey(`v @${oracle.version}`, reader.graph); 780+ for (const path of ["a.txt", "b.txt"]) assert.equal(shared.text(path), oracle.sharedView().text(path)); 782+ assert.equal(rows(), committed); 784+ assert.ok(lastReader); 785+ assert.throws(() => lastReader!.text("a.txt"), /expired|stale/); 787+ host.storage.db.close(); --- a/worker/project/test/view-cache.test.ts
+++ b/worker/project/test/view-cache.test.ts
@@ -1,5 +1,6 @@
11import assert from "node:assert/strict"; 22import { test } from "node:test"; 3+import type { ReadView } from "../../../src/engine/index.ts"; 34import { buildBase, Graph, View } from "../../../src/engine/index.ts"; 45import { StableOverlaySet } from "../../../src/engine/state-source.ts"; 56import type { AtomId } from "../../../src/engine/types.ts"; @@ -31,16 +32,16 @@
3233type WeightControls = { 3334 setIncomingWeights(values: number[]): void; 34− setWeight(view: View, weight: number): void;
35+ setWeight(view: ReadView, weight: number): void; 3738function withControlledWeights(run: (controls: WeightControls) => void): void { 3839 const original = Object.getOwnPropertyDescriptor(View.prototype, "weight")!; 39− const weights = new WeakMap<View, number>();
40+ const weights = new WeakMap<ReadView, number>(); 4041 let newWeights: number[] = []; 4142 Object.defineProperty(View.prototype, "weight", { 43− value(this: View) {
44+ value(this: ReadView) { 4445 if (!weights.has(this)) weights.set(this, newWeights.shift() ?? 0); 4546 return weights.get(this)!; @@ -60,7 +61,7 @@
63−function get(cache: ViewCache, key: string): View {
64+function get(cache: ViewCache, key: string): ReadView { 6465 return cache.keyed(key, () => new Set()); --- a/worker/project/version-log.ts
+++ b/worker/project/version-log.ts
@@ -1,8 +1,9 @@
1+import { View } from "../../src/engine/index.ts"; 12// The version list reads: log (versions newest first, or one file's history), ribbon (who published each version), 23// show (one version's changes), fileAt, compare and viewAt. They read through LogHost; today the host is the project 5−import { type AtomId, type Graph, View } from "../../src/engine/index.ts";
6+import type { AtomId, Graph, ReadView } from "../../src/engine/index.ts"; 67import { checkReadPath } from "./path-rules.ts"; 78import type { PathIndex } from "./pathindex.ts"; 89import { ProjectError } from "./project-error.ts"; @@ -19,12 +20,12 @@
2021 spaceFor(options: { draft?: string | null; agent?: string }): Space; 2122 checkVersion(space: Space, version: number): void; 22− viewAt(space: Space, version: number): View;
23− view(set: ReadonlySet<AtomId>): View;
23+ viewAt(space: Space, version: number): ReadView; 24+ view(set: ReadonlySet<AtomId>): ReadView; 2425 at(space: Space, version: number): ReadonlySet<AtomId>; 25− spellingIn(view: View, path: string): string;
26+ spellingIn(view: ReadView, path: string): string; 2627 versionChange(space: Space, version: number): number | undefined; 27− touchedFiles(ids: Iterable<AtomId>, views: readonly View[]): Set<string>;
28+ touchedFiles(ids: Iterable<AtomId>, views: readonly ReadView[]): Set<string>; @@ -59,7 +60,7 @@
5960 // A file's history (#43): only versions whose changes name the file, or a file moves can carry lines from, can have changed it. 6061 const sources = path === undefined ? undefined : new Set(names.flatMap((n) => [...moveSources(host.graph, n.path)])); 6162 const g = host.graph; 62− const views = new Map<number, View>();
63+ const views = new Map<number, ReadView>(); 6364 for (; v >= 0 && versions.length < limit; v--) { 6465 if (sources && !host.paths.knowsFiles(space, v)) { 6566 const p = space.versions[v]!; @@ -179,7 +180,7 @@
182−function logEntry(host: LogHost, space: Space, version: number, views?: Map<number, View>): LogEntry {
183+function logEntry(host: LogHost, space: Space, version: number, views?: Map<number, ReadView>): LogEntry { 183184 const p = space.versions[version]!; 185186 for (const id of p.atoms) { @@ -264,8 +265,12 @@
264265 return { from, to, files: changesBetween(host.view(a), host.view(b), files) }; 267−/** A version of shared (or of a named draft) as a View, for reading lines (blame at a version). */
268−export function viewAt(host: LogHost, version: number, options: { draft?: string | null; agent?: string } = {}): View {
268+/** A version of shared (or of a named draft) as a ReadView, for reading lines (blame at a version). */ 269+export function viewAt( 272+ options: { draft?: string | null; agent?: string } = {}, 270275 const space = host.spaceFor(options); 271276 host.checkVersion(space, version); --- a/worker/project/view-changes.ts
+++ b/worker/project/view-changes.ts
@@ -1,9 +1,9 @@
1−import type { View } from "../../src/engine/index.ts";
1+import type { ReadView } from "../../src/engine/index.ts"; 22import { ProjectError } from "./project-error.ts"; 33import type { FileChange, Mode, Modes } from "./project-types.ts"; 55/** The listed files whose text differs between two views, before and after. */ 6−export function changesBetween(before: View, after: View, files: Iterable<string>): FileChange[] {
6+export function changesBetween(before: ReadView, after: ReadView, files: Iterable<string>): FileChange[] { 77 const out: FileChange[] = []; 88 for (const path of [...new Set(files)].toSorted()) { 99 const b = before.hasFile(path) ? before.text(path) : null; @@ -19,7 +19,7 @@
2121/** Whether a file differs between two views: its text, its mode, or its blob (what changesBetween lists). */ 22−export function differs(before: View, after: View, path: string): boolean {
22+export function differs(before: ReadView, after: ReadView, path: string): boolean { 2323 const had = before.hasFile(path); 2424 if (had !== after.hasFile(path)) return true; 2525 if (had && !before.sameText(path, after)) return true; @@ -29,7 +29,7 @@
3131/** A file's executable bit and link target, before and after, when either changed. */ 32−export function modeChange(before: View, after: View, path: string): { before: Mode; after: Mode } | undefined {
32+export function modeChange(before: ReadView, after: ReadView, path: string): { before: Mode; after: Mode } | undefined { 3333 const b = before.attrs(path); 3434 const a = after.attrs(path); 3535 if (b.exec === a.exec && b.link === a.link) return undefined; @@ -37,7 +37,7 @@
3939/** Every executable file and link in a view. */ 40−export function modesOf(view: View): Modes {
40+export function modesOf(view: ReadView): Modes { 4141 const out: Modes = {}; 4242 for (const path of view.paths()) { 4343 const a = view.attrs(path); --- a/worker/project/views.ts
+++ b/worker/project/views.ts
@@ -2,7 +2,7 @@
22// versions never change, so their views are kept by name. Immutable indexed sets use their identity; 33// ordinary in-memory sets use their exact contents. 5−import { type AtomId, type Graph, View } from "../../src/engine/index.ts";
5+import { type AtomId, type Graph, type ReadView, View } from "../../src/engine/index.ts"; 66import { StableSet } from "../../src/engine/state-source.ts"; @@ -12,14 +12,24 @@
1313const VIEW_BUDGET = 24_000_000; 15+/** Internal opt-in. The owner validates identity and lifetime on every returned reader. */ 16+export interface ReadViewProvider { 17+ keyed(key: string): ReadView; 1520/** Views by key, most recently used last, held under VIEW_BUDGET bytes and 32 views. */ 1621export class ViewCache { 1722 readonly #graph: Graph; 23+ readonly #provider?: ReadViewProvider; 1824 readonly #cache = new Map<string | StableSet<AtomId>, View>(); 20− constructor(graph: Graph) {
26+ constructor(graph: Graph, provider?: (graph: Graph) => ReadViewProvider) { 2127 this.#graph = graph; 28+ this.#provider = provider?.(graph); 30+ assertUnkeyedAllowed(): void { 31+ if (this.#provider) throw Error("unsupported unkeyed projection membership"); 2535 * Keep the cached views under VIEW_BUDGET bytes (the website project, #43, @@ -37,7 +47,8 @@
3949 /** Indexed snapshots use identity; ordinary sets use their exact contents. */ 40− view(set: ReadonlySet<AtomId>): View {
50+ view(set: ReadonlySet<AtomId>): ReadView { 51+ this.assertUnkeyedAllowed(); 4152 // Immutable indexed membership is already a stable identity. Building 4253 // a sorted history-sized key defeats its external-storage contract. 4354 if (set instanceof StableSet) return this.#get(set, () => set); @@ -49,7 +60,8 @@
5162 /** A view cached under `key`, made from `set()` when it isn't there. */ 52− keyed(key: string, set: () => ReadonlySet<AtomId>): View {
63+ keyed(key: string, set: () => ReadonlySet<AtomId>): ReadView { 64+ if (this.#provider) return this.#provider.keyed(key); 5365 return this.#get(key, set); --- a/worker/project/whole-files.ts
+++ b/worker/project/whole-files.ts
@@ -1,7 +1,7 @@
11// Files kept whole (#46): avcs.json's `"whole"` globs, text over WHOLE_LIMIT, or a file that is 22// already a blob. The project holds the blob store; these helpers decide which texts go there. 4−import { canonicalText, type View } from "../../src/engine/index.ts";
4+import { canonicalText, type ReadView } from "../../src/engine/index.ts"; 55import { matchesPattern } from "./globs.ts"; 66import { projectFileIn } from "./project-helpers.ts"; 77import type { ProjectOptions } from "./project-types.ts"; @@ -15,7 +15,7 @@
1515/** What the whole-file helpers need from a project. */ 1616export interface WholeHost { 1717 initialized(): boolean; 18− sharedView(): View;
18+ sharedView(): ReadView; 1919 whole: ProjectOptions["whole"]; @@ -45,7 +45,7 @@
48− view: View | undefined,
48+ view: ReadView | undefined, 4949 rules: readonly string[], 5151 if (!host.whole) return false; @@ -61,7 +61,7 @@
6262 files: Readonly<Record<string, string | null>>, 6363 blobs: Readonly<Record<string, string>>, 64− view: View | undefined,
64+ view: ReadView | undefined, 6666): { files: Record<string, string | null>; blobs: Record<string, string> } { 6767 const outFiles: Record<string, string | null> = { ...files };