Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

sync: bento/spaces converges — on documents the format calls illegal (#252)

nyblnet634cf8ed2eeb
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 53aaef5d..f683e159 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -365,3 +365,13 @@ jobs:
# no default, because a default is how a spaces call site silently ends
# up holding slides' shape.
run: node scripts/test-sync-shape.ts
+
+ - name: bento/spaces under the shared engine
+ # Convergence for the pages/blocks binding, AND a report on whether
+ # what the replicas converge on is a legal bento/spaces document.
+ # Those are different questions: page.blocks is flat and in pre-order,
+ # while the engine merges `parent` as an ordinary register and order as
+ # a position key — two independent domains describing one tree. The
+ # format half is REPORTED, not asserted, because the fix is a decision
+ # nobody has taken yet; STRICT=1 turns it into a gate the day it is.
+ run: SEEDS=250 STEPS=80 ACTORS=4 node scripts/test-sync-spaces.ts
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 59081ac7..d7046a70 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -14,6 +14,104 @@ Decision. Why. Pointers.
---
+## 2026-08-06 — One CRDT engine, two document shapes, and the shape is never on the wire
+
+**Decision.** `kernel/src/sync/crdt.ts` takes a `DocShape` at construction: two
+property names — the doc key holding the parent array, the parent key holding
+the child array — plus a derived set of doc keys it must never sync.
+`slides/src/sync/crdt.ts` is a facade binding `SLIDES_SHAPE` and exporting
+`SyncState`; bento/spaces binds `('pages','blocks')` the same way. The engine
+knows nothing else about any app's content.
+
+**Bound at construction, never serialized, never on the wire.** A room is
+single-app by construction — the room id is minted per file — so no frame has
+to say which shape it came from, and a shape tag in `SyncStateJSON` would
+change the bytes of every bento/slides file already on a disk.
+
+**NO DEFAULT on the shape argument.** A default is how a spaces call site
+silently ends up holding slides' shape, and a room minted that way cannot be
+repaired: the files are on other people's disks.
+
+**`skipDoc` is DERIVED, not authored.** It must contain the container key: the
+container is synced structurally, per node with its own position key, so
+listing it as an ordinary doc property would collapse the whole document into
+ONE last-writer-wins register. Measured — a shape omitting its own container
+fails six checks in `scripts/test-sync-shape.ts`.
+
+**THE WIRE VOCABULARY IS FROZEN FOR EVERY APP.** Ops keep saying
+`kind:'slide'|'element'` and carrying `sl`/`el` regardless of shape. Renaming
+per app buys prettier debug output and costs a second binding on the
+highest-consequence bytes in the system. Settle it before spaces collab reaches
+a user; after that, spaces files carry the choice permanently.
+
+**Parameterize, THEN move.** The engine was parameterized in place and moved to
+the kernel second. Moving first would have parked `doc.slides` and
+`sl.elements` inside `kernel/src/` for a PR, against kernel/README.md's own
+rule that the kernel never sees an app's content shape.
+
+**What guards it.** `scripts/test-sync-equiv.ts` proves the NEGATIVE (the
+engine still mints the bytes the field was written with) against a FROZEN copy
+of the engine as shipped; `scripts/test-sync-shape.ts` proves the POSITIVE (a
+second shape produces an engine that works and restores as itself). Neither
+suffices alone: a parameterization that quietly did nothing passes the first, a
+broken one passes the second.
+
+## 2026-08-06 — bento/spaces converges under the shared engine, and converges on documents the format calls illegal
+
+**Measured, not argued.** `scripts/test-sync-spaces.ts`, 400 seeds × 100 steps
+× 4 actors, 17,227 ops, the kernel engine bound to `('pages','blocks')`:
+
+- **Convergence is perfect.** Every replica agrees, every seed. The engine
+ serves spaces as a CRDT with no change to its algebra.
+- **52.4% of merged documents violate the spaces format** (209 of 399 seeds
+ whose solo document was provably legal). Worst case in one document: 5 page
+ cycles, 5 dangling page parents, 3 dangling block parents, 3 pages out of
+ pre-order, 1 block out of pre-order, 1 duplicated block id.
+
+The CONTROL matters as much as the result: each seed also runs a lone replica
+through the same edits, receiving nothing, and a seed whose solo document is
+already illegal is EXCLUDED rather than counted. Without it every number above
+could have been the generator's fault. It caught three generator bugs while
+this was being written — a cross-page move that orphaned children, a page
+re-parent that inserted before its new parent, a subtree walk that missed
+grandchildren — and the first draft of this entry overstated the finding by 36
+points.
+
+**Why it happens, and why it is nobody's bug.** `page.blocks` is flat and in
+pre-order — "a child always follows its parent, so one forward pass rebuilds
+the tree" — while the engine stores order as fractional position keys and
+`parent` as an ordinary LWW register. Two independent merge domains describe
+one visual tree. You indent a block, I move one; both edits are legal, both
+apply, every replica agrees, and no forward pass can rebuild the result.
+`render.ts renderBlocks` does not crash on it — it silently renders the block
+at root, un-nested.
+
+**Three things that must be settled before a spaces file carries collab
+state**, because none can be corrected once files exist on other disks:
+
+1. **Pre-order vs `parent`.** Derive the tree at render time and tolerate any
+ array order, or repair after apply. A repair that COMMITS mints `ord` ops
+ and can ping-pong between replicas forever — so if it repairs, it must
+ derive, not commit. The effective-parent rule (2026-08-03) is the right
+ rule and is implemented in exactly one consumer (`render.ts`), while
+ `blocks.ts mdLayout`, `agent.ts descendants` and `editor.indent` use graph
+ semantics. One exported function, invariant asserted.
+2. **Page cycles.** `Store.tree()` recurses from the root with no visited set,
+ so a merged cycle makes pages vanish from the sidebar AND the markdown
+ export while still being in the file. `editor.reparentPage` refuses cycles
+ locally, which two concurrent drags defeat by construction.
+3. **Duplicate block ids.** The engine duplicates a node on concurrent moves to
+ two parents BY DESIGN (docs/collab-design.md) — in slides that is the morph
+ idiom and it is correct. In spaces, block ids are unique document-wide,
+ `buildIndex` keys blocks by bare id, and `#p/<page>/<block>` anchors assume
+ it. Same behaviour, opposite verdict.
+
+**Status of the rig.** It asserts convergence and the control, and REPORTS the
+format violations: failing the build on them would assert an answer nobody has
+chosen. `STRICT=1` turns every one into an assertion — flip it in CI the day
+the three decisions land, and the rig becomes their enforcement rather than
+their evidence.
+
## 2026-08-03 — Sync parameterization is gated on BYTE equivalence, not convergence
Making `slides/src/sync/` serve spaces (`doc.pages[] → page.blocks[]`) by
diff --git a/scripts/lib/sync-fixtures-spaces.ts b/scripts/lib/sync-fixtures-spaces.ts
new file mode 100644
index 00000000..e975ef65
--- /dev/null
+++ b/scripts/lib/sync-fixtures-spaces.ts
@@ -0,0 +1,234 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Random bento/spaces documents and edits, for the sync rigs.
+//
+// SEPARATE FROM sync-fixtures.ts ON PURPOSE. That file picks its mutation with
+// `Math.floor(rnd() * 13)` and is shared by two slides rigs — adding a case
+// there would re-roll the kind mapping for every seed in both, silently
+// changing what years of slides coverage mean while the diff looked purely
+// additive. Per-shape fixture modules behind one interface keep each app's
+// generator frozen with respect to the other's.
+//
+// WHAT A SPACES DOCUMENT HAS THAT A DECK DOES NOT, and therefore what this
+// generator must produce:
+//
+// · BLOCKS NEST INSIDE A PAGE, via `Block.parent`, in a FLAT PRE-ORDER array.
+// Tab indents a block — one property write, no key change. The engine sees
+// `parent` as an ordinary register, and the array order as position keys.
+// Those are two independent merge domains for one visual tree, which is the
+// single most dangerous thing about this shape.
+// · PAGES NEST TOO, via `Page.parent`, with the same split.
+// · `html` is optional on a block, where a slides text element always has one.
+// · Property REMOVAL is ordinary (a to-do's `done`, a code block's `lang`) —
+// the mutation class that hid two crashes in this engine already.
+
+export type Doc = Record<string, unknown> & {
+ pages: Array<Record<string, unknown> & {
+ id: string
+ parent?: string
+ blocks: Array<Record<string, unknown> & { id: string; parent?: string }>
+ }>
+}
+
+/** deterministic PRNG — same one the slides fixtures use */
+export function mulberry32(a: number) {
+ return function () {
+ a |= 0; a = (a + 0x6d2b79f5) | 0
+ let t = Math.imul(a ^ (a >>> 15), 1 | a)
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+export const stable = (v: unknown): string => JSON.stringify(v)
+
+const block = (id: string, extra: Record<string, unknown> = {}) =>
+ ({ id, type: 'p', html: `text ${id}`, ...extra })
+
+/** A space with two pages, one nested; a toggle with two children; a to-do. */
+export function baseDoc(): Doc {
+ return {
+ format: 'bento/spaces',
+ version: 1,
+ docId: 'fixture',
+ title: 'Fixture space',
+ modified: '2026-01-01T00:00:00.000Z',
+ home: 'p1',
+ theme: { background: '#fff', color: '#1E2A3A', accent: '#F7A600', fontFamily: 'x' },
+ assets: {},
+ pages: [
+ {
+ id: 'p1',
+ title: 'One',
+ blocks: [
+ block('b1'),
+ { id: 'b2', type: 'toggle', html: 'a toggle', open: true },
+ block('b3', { parent: 'b2' }),
+ block('b4', { parent: 'b2' }),
+ { id: 'b5', type: 'todo', html: 'a task', done: false },
+ ],
+ },
+ {
+ id: 'p2',
+ title: 'Two',
+ parent: 'p1',
+ blocks: [
+ { id: 'b6', type: 'code', html: 'const x = 1', lang: 'js' },
+ block('b7'),
+ ],
+ },
+ ],
+ }
+}
+
+let seq = 0
+const fresh = (p: string) => `${p}${(seq++).toString(36)}`
+
+/**
+ * One random edit, as a mutation applied to the document in place.
+ *
+ * Every case is something the editor actually does. The ones that matter most
+ * are the re-parents (Tab / ⇧Tab, and dragging a page in the sidebar), because
+ * they are the operations with no slides equivalent at all.
+ */
+export function randomMutation(doc: Doc, rnd: () => number): (d: Doc) => void {
+ const kind = Math.floor(rnd() * 12)
+ const pg = doc.pages[Math.floor(rnd() * doc.pages.length)]
+ const blocks = pg?.blocks ?? []
+ const bl = blocks[Math.floor(rnd() * blocks.length)]
+
+ switch (kind) {
+ case 0: // type into a block
+ return (d) => {
+ const p = d.pages.find((x) => x.id === pg?.id)
+ const b = p?.blocks.find((x) => x.id === bl?.id)
+ if (b) b.html = `${String(b.html ?? '')}${Math.floor(rnd() * 10)}`
+ }
+ case 1: // add a block
+ return (d) => {
+ const p = d.pages.find((x) => x.id === pg?.id)
+ if (p) p.blocks.push(block(fresh('nb')))
+ }
+ case 2: // INDENT: re-parent a block under an earlier sibling
+ return (d) => {
+ const p = d.pages.find((x) => x.id === pg?.id)
+ if (!p || p.blocks.length < 2) return
+ const i = 1 + Math.floor(rnd() * (p.blocks.length - 1))
+ p.blocks[i].parent = p.blocks[i - 1].id
+ }
+ case 3: // OUTDENT: drop the parent link
+ return (d) => {
+ const p = d.pages.find((x) => x.id === pg?.id)
+ const b = p?.blocks.find((x) => x.id === bl?.id)
+ if (b) delete b.parent
+ }
+ case 4: // reorder TOP-LEVEL blocks, subtree in tow — the drag gesture
+ return (d) => {
+ const p = d.pages.find((x) => x.id === pg?.id)
+ if (!p || p.blocks.length < 2) return
+ const roots = p.blocks.map((b, i) => ({ b, i })).filter((x) => x.b.parent === undefined)
+ if (roots.length < 2) return
+ const pick = roots[Math.floor(rnd() * roots.length)]
+ // the run is the block plus everything nested under it, which in a
+ // pre-order array is a contiguous slice
+ // the descendant set, by fixed point — a contiguous walk misses a
+ // grandchild whose own parent was added to the set after it was passed
+ const kin = new Set([pick.b.id])
+ for (let pass = 0; pass < p.blocks.length; pass++) {
+ for (const b of p.blocks) if (b.parent && kin.has(String(b.parent))) kin.add(b.id)
+ }
+ let end = pick.i + 1
+ while (end < p.blocks.length && kin.has(p.blocks[end].id)) end++
+ const run0 = p.blocks.splice(pick.i, end - pick.i)
+ const dest = roots.filter((r) => r.b.id !== pick.b.id)
+ const target = dest.length ? p.blocks.findIndex((x) => x.id === dest[Math.floor(rnd() * dest.length)].b.id) : 0
+ p.blocks.splice(Math.max(0, target), 0, ...run0)
+ }
+ case 5: // delete a block AND its subtree — a local edit must stay legal
+ return (d) => {
+ const p = d.pages.find((x) => x.id === pg?.id)
+ if (!p || !bl) return
+ const doomed = new Set([bl.id])
+ for (let pass = 0; pass < p.blocks.length; pass++) {
+ for (const b of p.blocks) if (b.parent && doomed.has(String(b.parent))) doomed.add(b.id)
+ }
+ p.blocks = p.blocks.filter((b) => !doomed.has(b.id))
+ }
+ case 6: // move a block and its SUBTREE to another page
+ // The subtree has to travel: leaving children behind pointing at a
+ // parent that is now on another page is a dangling reference, and this
+ // rig's control asserts a lone replica never produces one.
+ return (d) => {
+ if (d.pages.length < 2 || !bl) return
+ const from = d.pages.find((x) => x.id === pg?.id)
+ const to = d.pages[Math.floor(rnd() * d.pages.length)]
+ if (!from || !to || from.id === to.id) return
+ const kin = new Set([bl.id])
+ for (let pass = 0; pass < from.blocks.length; pass++) {
+ for (const b of from.blocks) if (b.parent && kin.has(String(b.parent))) kin.add(b.id)
+ }
+ const moving = from.blocks.filter((b) => kin.has(b.id))
+ if (!moving.length) return
+ from.blocks = from.blocks.filter((b) => !kin.has(b.id))
+ delete moving[0].parent // the root of the run detaches
+ to.blocks.push(...moving)
+ }
+ case 7: // add a page (sometimes nested)
+ return (d) => {
+ const id = fresh('np')
+ const parent = rnd() < 0.5 && d.pages.length ? d.pages[0].id : undefined
+ d.pages.push({ id, title: `Page ${id}`, ...(parent ? { parent } : {}), blocks: [block(fresh('nb'))] })
+ }
+ case 8: // re-parent a PAGE, refusing a cycle the way editor.ts does
+ return (d) => {
+ if (d.pages.length < 2) return
+ const a = d.pages[Math.floor(rnd() * d.pages.length)]
+ const b = d.pages[Math.floor(rnd() * d.pages.length)]
+ if (a.id === b.id) return
+ // would b end up inside a? walk b's ancestors
+ const seen = new Set<string>()
+ for (let up: string | undefined = b.id; up && !seen.has(up);
+ up = d.pages.find((q) => q.id === up)?.parent as string | undefined) {
+ seen.add(up)
+ if (up === a.id) return
+ }
+ a.parent = b.id
+ // keep the array in pre-order: a page must follow its parent, and its
+ // OWN descendants must follow it — so the whole subtree relocates to
+ // just after b
+ const kin = new Set([a.id])
+ for (let pass = 0; pass < d.pages.length; pass++) {
+ for (const q of d.pages) if (q.parent && kin.has(String(q.parent))) kin.add(q.id)
+ }
+ const moving = d.pages.filter((q) => kin.has(q.id))
+ d.pages = d.pages.filter((q) => !kin.has(q.id))
+ const bi = d.pages.findIndex((x) => x.id === b.id)
+ d.pages.splice(bi + 1, 0, ...moving)
+ }
+ case 9: // delete a page AND its descendants — the editor cascades
+ return (d) => {
+ if (d.pages.length < 2) return
+ const victim = d.pages[Math.floor(rnd() * d.pages.length)]
+ const doomed = new Set([victim.id])
+ for (let pass = 0; pass < d.pages.length; pass++) {
+ for (const q of d.pages) if (q.parent && doomed.has(String(q.parent))) doomed.add(q.id)
+ }
+ if (doomed.size >= d.pages.length) return // never empty the space
+ d.pages = d.pages.filter((q) => !doomed.has(q.id))
+ }
+ case 10: // REMOVE a property — the class that hid two crashes
+ return (d) => {
+ const p = d.pages.find((x) => x.id === pg?.id)
+ const b = p?.blocks.find((x) => x.id === bl?.id)
+ if (!b) return
+ for (const k of ['done', 'lang', 'open', 'parent']) {
+ if (k in b) { delete b[k]; return }
+ }
+ }
+ default: // set a page property
+ return (d) => {
+ const p = d.pages.find((x) => x.id === pg?.id)
+ if (p) p.title = `T${Math.floor(rnd() * 100)}`
+ }
+ }
+}
diff --git a/scripts/test-sync-spaces.ts b/scripts/test-sync-spaces.ts
new file mode 100644
index 00000000..f9b1ca5a
--- /dev/null
+++ b/scripts/test-sync-spaces.ts
@@ -0,0 +1,267 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// bento/spaces under the shared CRDT engine — convergence, and the format's
+// own invariants after convergence.
+//
+// node scripts/test-sync-spaces.ts
+// SEEDS=300 STEPS=80 ACTORS=4 node scripts/test-sync-spaces.ts
+//
+// TWO DIFFERENT QUESTIONS, and only the first is what a CRDT rig usually asks.
+//
+// 1. DO REPLICAS CONVERGE? Standard, and the engine's own property.
+//
+// 2. IS WHAT THEY CONVERGE ON A LEGAL bento/spaces DOCUMENT? This is the one
+// that matters here, and it has no slides equivalent. `page.blocks` is
+// FLAT AND IN PRE-ORDER — the format's guarantee is "a child always
+// follows its parent, so one forward pass rebuilds the tree" — while the
+// engine stores order as fractional position keys and `parent` as an
+// ordinary last-writer-wins register. Those are two independent merge
+// domains describing one visual tree. Two perfectly legal concurrent edits
+// (you indent a block, I move one) can therefore converge on a state every
+// replica agrees about and no renderer can draw correctly.
+//
+// If that is real, it is a FORMAT-LEVEL decision and it has to be made
+// before any spaces file carries collaboration state — which is why this
+// rig reports it as data rather than asserting a verdict it cannot know.
+//
+// The engine is the kernel's, bound to ('pages','blocks'). Nothing here is
+// spaces app code: this is the shape binding and its evidence.
+
+import { SyncEngine, shape } from '../kernel/src/sync/crdt.ts'
+import { mulberry32, baseDoc, randomMutation, type Doc } from './lib/sync-fixtures-spaces.ts'
+
+export const SPACES_SHAPE = shape('pages', 'blocks')
+class SpacesSync extends SyncEngine {
+ constructor(actor: string) { super(actor, SPACES_SHAPE) }
+}
+
+const SEEDS = parseInt(process.env.SEEDS ?? '120', 10)
+const STEPS = parseInt(process.env.STEPS ?? '60', 10)
+const ACTORS = parseInt(process.env.ACTORS ?? '3', 10)
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+}
+const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v))
+
+class Replica {
+ doc: Doc
+ state: SpacesSync
+ shadow: string
+ constructor(actor: string, doc: Doc) {
+ this.doc = doc
+ this.state = new SpacesSync(actor)
+ this.state.adopt(this.doc as never)
+ this.shadow = JSON.stringify(this.doc)
+ }
+ mutate(fn: (d: Doc) => void) {
+ fn(this.doc)
+ return this.flush()
+ }
+ flush() {
+ const ops = this.state.diff(JSON.parse(this.shadow), this.doc as never, { text: true })
+ this.shadow = JSON.stringify(this.doc)
+ return ops
+ }
+ receive(ops: unknown[]) {
+ this.state.apply(this.doc as never, ops as never)
+ this.shadow = JSON.stringify(this.doc)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// the format's invariants, checked on a MERGED document
+// ---------------------------------------------------------------------------
+
+interface Violations {
+ preorderBlocks: number // a block whose parent appears later, or not at all
+ danglingBlock: number // parent names a block not in this page
+ preorderPages: number
+ danglingPage: number
+ pageCycle: number
+ dupBlockId: number // the same block id on two pages
+}
+
+function inspect(doc: Doc): Violations {
+ const v: Violations = { preorderBlocks: 0, danglingBlock: 0, preorderPages: 0, danglingPage: 0, pageCycle: 0, dupBlockId: 0 }
+ const seenBlock = new Map<string, string>()
+ for (const p of doc.pages) {
+ const at = new Map<string, number>()
+ p.blocks.forEach((b, i) => at.set(b.id, i))
+ p.blocks.forEach((b, i) => {
+ if (seenBlock.has(b.id) && seenBlock.get(b.id) !== p.id) v.dupBlockId++
+ seenBlock.set(b.id, p.id)
+ if (b.parent === undefined) return
+ const j = at.get(String(b.parent))
+ if (j === undefined) v.danglingBlock++
+ else if (j >= i) v.preorderBlocks++ // parent at or after the child
+ })
+ }
+ const pageAt = new Map<string, number>()
+ doc.pages.forEach((p, i) => pageAt.set(p.id, i))
+ doc.pages.forEach((p, i) => {
+ if (p.parent === undefined) return
+ const j = pageAt.get(String(p.parent))
+ if (j === undefined) v.danglingPage++
+ else if (j >= i) v.preorderPages++
+ })
+ // page cycles: walk up from every page with a hop cap
+ for (const p of doc.pages) {
+ const seen = new Set<string>()
+ let up: string | undefined = p.id
+ while (up && !seen.has(up)) {
+ seen.add(up)
+ up = doc.pages.find((q) => q.id === up)?.parent as string | undefined
+ if (up && seen.has(up)) { v.pageCycle++; break }
+ }
+ }
+ return v
+}
+
+const total = (v: Violations) => Object.values(v).reduce((a, b) => a + b, 0)
+
+// ---------------------------------------------------------------------------
+// the run
+// ---------------------------------------------------------------------------
+
+console.log('bento/spaces under the shared CRDT engine\n')
+
+const worst: Violations = { preorderBlocks: 0, danglingBlock: 0, preorderPages: 0, danglingPage: 0, pageCycle: 0, dupBlockId: 0 }
+let seedsWithViolations = 0
+let diverged = 0
+let opsTotal = 0
+let soloBroken = 0
+let measured = 0
+
+for (let seed = 1; seed <= SEEDS; seed++) {
+ const rnd = mulberry32(seed * 7919)
+ const base = baseDoc()
+ const reps = Array.from({ length: ACTORS }, (_, i) => new Replica(`a${i}`, clone(base)))
+ // a lone replica running actor 0's edits and receiving nothing
+ const solo = new Replica('solo', clone(base))
+ const queues = new Map<string, unknown[][]>()
+ for (let f = 0; f < ACTORS; f++) for (let t = 0; t < ACTORS; t++) if (f !== t) queues.set(`${f}>${t}`, [])
+
+ for (let s = 0; s < STEPS; s++) {
+ if (rnd() < 0.6) {
+ const a = Math.floor(rnd() * ACTORS)
+ const mseed = (seed * 1_000_003 + s * 7919) >>> 0
+ if (a === 0) solo.mutate(randomMutation(solo.doc, mulberry32(mseed)))
+ const ops = reps[a].mutate(randomMutation(reps[a].doc, mulberry32(mseed)))
+ opsTotal += ops.length
+ if (ops.length) for (let t = 0; t < ACTORS; t++) if (t !== a) queues.get(`${a}>${t}`)!.push(ops)
+ } else {
+ const keys = [...queues.keys()].filter((k) => queues.get(k)!.length)
+ if (!keys.length) continue
+ const k = keys[Math.floor(rnd() * keys.length)]
+ const to = parseInt(k.split('>')[1], 10)
+ reps[to].receive(queues.get(k)!.shift()!)
+ }
+ }
+ // drain everything
+ let guard = 0
+ for (;;) {
+ const k = [...queues.keys()].find((x) => queues.get(x)!.length)
+ if (!k || guard++ > 10000) break
+ reps[parseInt(k.split('>')[1], 10)].receive(queues.get(k)!.shift()!)
+ }
+
+ const first = JSON.stringify(reps[0].doc)
+ for (let i = 1; i < ACTORS; i++) {
+ if (JSON.stringify(reps[i].doc) !== first) {
+ diverged++
+ if (diverged === 1) console.log(` FAIL seed ${seed}: replicas a0 and a${i} disagree`)
+ break
+ }
+ }
+
+ // THE CONTROL, and the rig is worthless without it. If the generator itself
+ // produced illegal documents, every violation below would be its fault
+ // rather than the merge's. So each replica is inspected BEFORE it receives
+ // anything (soloDoc, driven by the same edits), and that must be spotless.
+ // A seed whose SOLO document is already illegal proves nothing about
+ // merging, so it is excluded from the statistic rather than counted. The
+ // measurement is then over seeds where the generator is provably clean —
+ // which is a stronger basis than "every generator bug we happened to find
+ // has been fixed".
+ if (total(inspect(solo.doc)) > 0) { soloBroken++; continue }
+ measured++
+
+ const v = inspect(reps[0].doc)
+ if (total(v) > 0) {
+ seedsWithViolations++
+ for (const k of Object.keys(worst) as Array<keyof Violations>) worst[k] = Math.max(worst[k], v[k])
+ }
+}
+
+ok(diverged === 0, `all replicas converge (${diverged} seed(s) diverged)`)
+// The control is REPORTED, not asserted: a seed the generator got wrong is
+// excluded from the measurement, so it cannot contaminate the finding. What
+// would invalidate the rig is excluding most of them, so that IS asserted.
+console.log(` ok control: ${measured}/${SEEDS} seeds had a provably legal solo document ` +
+ `(${soloBroken} excluded — the generator, not the merge)`)
+ok(measured > SEEDS * 0.9,
+ `the control excluded too much to measure anything (${measured}/${SEEDS} usable)`)
+console.log(` ok convergence: ${SEEDS} seeds × ${STEPS} steps × ${ACTORS} actors, ${opsTotal} ops`)
+
+// ---- the format report ------------------------------------------------------
+console.log('')
+console.log(' bento/spaces format invariants on the MERGED document:')
+console.log(` seeds producing at least one violation: ${seedsWithViolations}/${measured} ` +
+ `(${(seedsWithViolations / Math.max(1, measured) * 100).toFixed(1)}%)`)
+for (const [k, n] of Object.entries(worst)) {
+ console.log(` ${k.padEnd(16)} worst-case in one document: ${n}`)
+}
+console.log('')
+
+// ---------------------------------------------------------------------------
+// WHAT IS ASSERTED, AND WHY IT IS ONLY CONVERGENCE
+//
+// Convergence is the ENGINE's property, and it holds. Everything in the table
+// above is a property of the FORMAT meeting the engine, and every one of them
+// is an open design question this rig exists to have discovered rather than to
+// have pre-judged:
+//
+// · pre-order vs `parent` — two independent merge domains for one visual
+// tree. The fix is a rule (derive the tree at render time and tolerate any
+// array order, or repair after apply), and a repair that COMMITS would mint
+// ord ops and can ping-pong between replicas forever.
+// · page cycles — `Store.tree()` recurses from the root with no visited set,
+// so a cycle makes pages vanish from the sidebar AND from the markdown
+// export, while still being in the file.
+// · duplicate block ids — the engine duplicates a node on concurrent moves to
+// two different parents, BY DESIGN (docs/collab-design.md). In slides that
+// is the morph idiom and it is correct. In spaces, block ids are unique
+// document-wide (parseDoc's `seen` set spans pages and blocks),
+// `buildIndex` keys blocks by bare id, and `#p/<page>/<block>` anchors
+// assume it — so the same behaviour is a defect.
+//
+// Failing the build on any of those would be asserting an answer nobody has
+// chosen. STRICT=1 turns them into assertions — flip it in CI the moment the
+// decisions land, and this rig becomes their enforcement.
+// ---------------------------------------------------------------------------
+const STRICT = process.env.STRICT === '1'
+if (STRICT) {
+ ok(worst.dupBlockId === 0, `no merge produced the same block id on two pages (worst ${worst.dupBlockId})`)
+ ok(worst.preorderBlocks === 0, `no merge broke block pre-order (worst ${worst.preorderBlocks})`)
+ ok(worst.danglingBlock === 0, `no merge left a dangling block parent (worst ${worst.danglingBlock})`)
+ ok(worst.preorderPages === 0, `no merge broke page pre-order (worst ${worst.preorderPages})`)
+ ok(worst.danglingPage === 0, `no merge left a dangling page parent (worst ${worst.danglingPage})`)
+ ok(worst.pageCycle === 0, `no merge produced a page cycle (worst ${worst.pageCycle})`)
+} else if (seedsWithViolations) {
+ console.log(' OPEN — merged documents violate the flat pre-order invariant, and')
+ console.log(' that is the expected consequence of `parent` being an ordinary')
+ console.log(' register while order is a position key. Two legal concurrent edits')
+ console.log(' meet, every replica agrees, and no forward pass can rebuild the tree.')
+ console.log(' These are FORMAT decisions and they must be settled before a spaces')
+ console.log(' file carries collaboration state. Re-run with STRICT=1 to hold the')
+ console.log(' line once they are. See docs/DECISIONS.md.')
+ console.log('')
+}
+
+console.log(`${checks - failures}/${checks} assertions passed`)
+if (failures) process.exit(1)