Linora

Document core (packages/doc)

Owner: WP-A, then DC2 (wave 3). Contract: shared/src/doc-api.ts (DocCore, DocFactory, DocQueries, TextMeasurer, ScanBatch, BatchScan, StructIndex, DOC_RULES_VERSION = 3). ADRs 0003, 0004, 0008, 0014, 0019, 0024, 0101, 0102, 0103, 0104, 0105, 0106.

Current

Implemented (wave 1, A1 + A2; wave 3 DC2): doc model, rules, apply/inverse/change feed, block/snapshot/structure codecs, ScanBatch, StructIndex, JSON and inverse helpers, keys, queries + SVG (bounded, ADR 0105), text metrics, generators, bench; bulk TRANSFORM / SET_GEOMETRY ops (ADR 0103); run-length id map (memory E2, ADR 0104); doc.cols paint views follow intern-table growth (ADR 0106: fixes empty shapes after a reload on pages with more than 15 distinct fills or stroke styles).

Target

One headless implementation of page semantics. Pure TypeScript, ES2022, no DOM, no Node APIs.

packages/doc/src/
  doc.ts          DocCore: SoA columns, handles + free list, tree links, props, apply/inverse, change feed, encoders
  idmap.ts        ids: handle->client runs, chunked affine counters, per-client affine segments + explicit table (ADR 0104)
  table.ts        typed-array hash maps (handle / id keyed) and refcounted intern tables
  stores.ts       containers, text records + UTF-8 arena, points arena, names, long keys, unknown props
  keys.ts         fractional keys: keyBetween, nKeysBetween, sequential keys, validation, 8 B packing
  rules.ts        the rule tables (types, kind masks, bounds, limits, tombstone retention) + check order
  validate.ts     stateless checks over Op objects (DocCore)
  scan.ts         ScanBatch: the same stateless checks over wire bytes, zero allocations
  structIndex.ts  StructIndex: 14 B/node, delta hash, lazy merge, tombstones
  codec/block.ts  node block format, shared block validator, builders
  codec/snapshot.ts, codec/structure.ts   framing; structure section CFST format 2
  json.ts         JSON op form <-> ops, rejection names and hints (API, MCP)
  inverse.ts      inverse and block helpers for peers without a DocCore (MCP)
  empty.ts        empty page snapshot/structure (API)
  query/          find, outline, summary, toSvg
  text/           metrics.ts (generated by tools/gen-font-metrics.mjs), measure.ts (TextMeasurer, forEachLine)
  gen/            generateShapes (POC stress), generateSite (POC website) -> CREATE_BULK blocks
assets/fonts/     Inter 4.1 (OFL): woff2 for the engine atlas, ttf for resvg, OFL.txt

Entry points: @linorahq/doc (everything), @linorahq/doc/scan, /struct-index, /structure (realtime), /json, /keys, /empty (API), /inverse, /text (MCP), /gen, /fonts/*.

Storage

Compact single-copy layout (ADR 0024, details ADR 0102). The doc is the only CPU copy of node data: the engine renders from these columns.

Part Layout B/node
Tree parent, nextSibling, prevSibling Int32; first/last child + child count in container records 12
Sibling key 8 B inline (up to 10 base-62 chars, 6 bits each, order-preserving); longer keys in a side table 8
Kind + flags kindFlags Uint8: 5-bit kind (31 = free) + VISIBLE/LOCKED/CLIP 1
Geometry x, y, w, h Float32 16
Rotation lazy Float32 (absent until a node is rotated) 0 / 4
Opacity lazy Uint8, canonical 1/255 0 / 1
Fill / stroke style / corner radius interned Uint16 indices (widen to Uint32 past 65,535 values); stroke and radius lazy 2 + 0/2 + 0/2
Ids Run-length id map (ADR 0104): handle -> client runs; counters per 1,024-handle chunk (affine base, or a 4 KB block once a handle leaves the line); id -> handle via per-client affine segments, plus a dense/sparse table for explicit positions ~0 for bulk content (0.01 measured), <= 8 worst case
Record index lazy Int32: container / text / points record (absent without containers, text or paths) 0 / 4
Text 12 B records (offset, length, interned style); UTF-8 arena per text node
Points records + Float32 arena per path
Names, unknown props interned strings / encoded values in typed-array hash tables sparse
Change feed sparse handle -> dirty bits since the last drain + 1 bit/node “created in window” 0.13

Interned paint is read through doc.cols (fillTable, strokeColor, strokeWidth, radiusTable), and those views always point at the tables’ current arrays: InternTable.onGrow re-points them whenever a table grows (ADR 0106), not only when node columns grow. Readers index them on each read and never cache the arrays across edits.

No JS object and no Map entry per node. The only per-value JS objects are distinct names, long keys (> 10 chars) and unknown-prop payloads. Handles are dense; deleted handles are reused only after the ChangeSet that reported them was drained (docs that never drain pass {trackChanges: false}). Arrays are sized exactly on snapshot load (arenas too) and grow by 1.25x. memoryReport() gives allocated bytes per part.

Fractional keys

Strings over base-62 0-9A-Za-z (ASCII order = byte order = numeric order): an integer part with a length prefix plus a fraction, as in the standard fractional-indexing algorithm. Keys are never empty, have no trailing 0 in the fraction, and are at most 256 bytes (MAX_KEY_BYTES). Siblings are ordered by (key, id). nKeysBetween spreads bulk inserts. writeSequentialKey(i) emits the i-th appended key without strings, so 5M siblings get <= 5-char keys.

Rules (apply(ops, {origin, client, inverse}))

Ops apply in order and apply never throws. With origin: 'local' each op fully applies or is rejected with the verdict the server will give. With origin: 'sequenced' (server-accepted batches) id ownership and tombstones are not checked (FOREIGN_ID), and any other still-invalid op is a deterministic no-op. Check order (stateless before structural) is in rules.ts.

Op Checks Inverse
CREATE kind creatable; clientOf(id) === client; key valid; props valid and applicable (no PARENT_INDEX); id unused; parent exists and is a container; node limit DELETE [id]
SET node exists; props applicable to the kind; values within range; PARENT_INDEX: not ROOT, at most one, key valid, parent exists, is a container, no cycle SET of previous values
DELETE ROOT not listed; at least one listed id exists (missing ones skipped) RESTORE blocks of the deleted roots, per parent in sibling order, up to ~10,000 nodes and 1 MiB each (ADR 0107)
CREATE_BULK block validates (framing, per node as CREATE, in-block parents are containers); ids unused and unique; node limit; all-or-nothing DELETE of block roots
RESTORE as CREATE_BULK, but another client’s ids must be restorable tombstones (ADR 0101) DELETE of block roots
TRANSFORM ids strictly ascending, ROOT not listed, |dx|, |dy| <= 2·MAX_COORD; at least one listed id exists (missing ones skipped). x/y += (dx, dy), f32-rounded, clamped to ±MAX_COORD (ADR 0103) SET_GEOMETRY {x, y} of the old values (exact); the UndoStack sends TRANSFORM(-dx, -dy)
SET_GEOMETRY ids as TRANSFORM; at least one column (x, y, w, h, rotation), each value by its prop’s SET rules; at least one listed id exists SET_GEOMETRY of the old values of the same columns

Value rules:

ScanBatch runs exactly the stateless rows and StructIndex.check the structural ones. A property test asserts that ScanBatch + StructIndex verdicts equal DocCore local verdicts on 100K random batches, with sequenced replicas staying byte-identical.

Structural index (realtime tier)

StructIndex (ADR 0019): ids: Float64Array sorted (position = slot), parent: Int32Array, kind, flags = 14 B/node.

Change feed

Each write records the handle and its Dirty bits in a sparse set (deduplicated). Created and deleted handles are separate lists; a node created and deleted between drains is reported in neither. drainChanges() returns the ChangeSet and resets. A snapshot load starts with an empty feed (consumers do a full build).

TRANSFORM ops are reported in transforms (roots + parent-space delta, apply order), not in changed. A consumer applies them first, then re-derives changed (the engine bakes the translation on the GPU; ADR 0103). Roots created in the same window are left out (they are in created).

Node block format (CREATE_BULK, RESTORE and snapshot body)

block   = version:u8(1) n:varuint rootParent:varuint
          ids      n x varuint   (first absolute, then zigzag deltas wrapped to +-2^52)
          kinds    n x u8
          parents  n x varuint   (0 = rootParent, k = k-th node of this block, 1-based, k <= own index)
          keys     n x str
          nCols:varuint col*     (prop ids strictly ascending)
col     = propId:varuint type:u8 presence:u8 (0 = every node, 1 = bitmap follows) [bitmap ceil(n/8) bytes]
          values for present nodes, wire encoding (F32/U32/F64 LE, I32 zigzag varint, BOOL u8, STRING/BYTES str, F32_ARRAY n+floats, NODE_REF varuint, PARENT_INDEX parent+key)

Nodes are in pre-order (= paint order).

Snapshot and structure formats

snapshot  = magic "CFPS" format:u16(1) rulesVersion:u16 seq:varuint nodeCount:varuint block
structure = magic "CFST" format:u16(2) seq:varuint n:varuint ids:f64*n (ascending) parentSlot:i32*n kind:u8*n
            nTomb:varuint tombIds:f64*nTomb (ascending) tombAge:u32*nTomb

Queries (docQueries)

Text

Generators

How it protects the baseline

Typed columns only (no GC-traced per-node objects); one CPU copy of node data shared with the renderer; a change feed instead of per-write callbacks; decode in a worker; doc work happens only when ops arrive, never per frame.

Targets (WP-A acceptance) and measurements

Measured with node packages/doc/bench/run.ts (Node 26, M4 Pro shared with other agents, medians of 5) and npm test -w @linorahq/doc.

Target Measured
Decode 682K-node website snapshot < 300 ms; encode < 300 ms 4,000 pages (662K nodes): decode 212-218 ms, encode 242-244 ms (5M shapes: 1.08-1.11 s / 1.53-1.58 s)
Snapshot gzip <= 20 B/node 9.4 B/node website, 12.2 B/node 5M shapes (structure: 1.1 / 1.4 B/node)
Apply 100K SET props < 50 ms 8.0-8.7 ms (E1 7.2-7.6: id lookups ~3 ns slower, ADR 0104)
Move 200K nodes (ADR 0103): TRANSFORM vs per-node SETs 195 KiB vs 3,711 KiB on the wire; author apply 7.3 vs 51.6 ms; replica decode + apply 8.0 vs 34.8 ms; gateway scan + owner check 1.6 vs 18.7 ms
5M shapes <= 57.8 B/node (memoryReport, after snapshot load) 47.13 B/node with run-length ids (E1: 55.13); 53.6 B/node right after generation (1.25x growth slack)
Website nodes <= 53.6 B/node + text <= 21 MB 43.21 B/node (E1: 51.20) + 19.95 MiB content (text 16.5 + record index 2.5 + points 0.6 + names 0.3)
JS objects independent of node count (< 100K at 5M nodes) whole-process heap snapshot: 72.5K objects (5M shapes), 83.4K (4,000 pages)
Inverse: apply then inverse restores byte-identical snapshots property test (1,200 random batches incl. redo)
ScanBatch <= 300 ns/op, zero allocations after warm-up 47 ns/op; 1.34 B/call against a 1.29 B empty-call baseline over 1M calls (counter granularity)
StructIndex.check <= 200 ns/op on 682K; exactly 14 B/node + delta 84 ns/op; 14.00 B/node; load from structure 3.1 ms
Rule equivalence on 100K random batches 349K ops incl. 22K accepted TRANSFORM / SET_GEOMETRY, every Reject reason, 1,380 accepted foreign restores, index reloads and merges: all equal
Canonical snapshots byte-stable decode/encode round trips; fuzzed corrupt input throws only CodecError