Repository Public
1<!--2SP Notes Core3File: docs/DOCUMENT_API.md4Author: Simon-Pierre Boucher5Contact: contact@spboucher.ai6-->7# SPNotesDocument — public API89Foundation only, Swift 6, value types, all `Sendable` and `Hashable`. The backend stores a note as ProseMirror / Tiptap JSON;10this module turns it into a flat list of lines an editor can drive, and back, without losing anything.1112```swift13import SPNotesDocument1415var doc = try NoteDocument(json: data) // ProseMirror JSON → lines16doc.toggleMark(.bold, in: 0..<5, at: 2) // edit17doc.ensureBlockIds() // before saving18let body = try doc.jsonData() // lines → canonical JSON (sorted keys)19```2021## Conventions2223- **Line index**: index in `doc.lines`. Commands taking a `Range<Int>` of lines clamp it to the document.24- **Inline offset / range**: UTF-16 code units (`NSString` / `NSRange` compatible). An inline atom (hard break, mention,25 inline math, footnote reference, unknown inline node) counts as exactly **1** unit: display it as one `U+FFFC`26 attachment character. `Line.displayString` gives such a string (hard break as `U+2028`), `Line.inlineLength` its length.27- Commands are `public mutating func` on `NoteDocument`. They return `Bool` (whether the document changed) unless stated28 otherwise, never trap on out-of-range input, and leave a document that is valid for the web schema when they were29 given one.30- New nodes are created with every schema attribute (defaults included) and a fresh block id, exactly as the web editor31 serializes them.32- `==` on `NoteDocument` compares container keys too; use `isStructurallyEqual(to:)` to compare content only.3334## Model3536```swift37public enum JSONValue { case null, bool(Bool), int(Int64), double(Double), string(String), array([JSONValue]), object([String: JSONValue]) }38public struct PMMark { var type: String; var attrs: [String: JSONValue]? }39public struct PMNode { var type: String; var attrs: [String: JSONValue]?; var content: [PMNode]?; var text: String?; var marks: [PMMark]?; var extra: [String: JSONValue] }4041public struct NoteDocument { var lines: [Line] }42public struct Line { var path: [Container]; var type: String; var attrs: [String: JSONValue]; var content: LineContent }43public struct Container { var key: Int; var type: String; var attrs: [String: JSONValue] }44public enum LineContent { case inline([InlineRun]); case blockAtom(PMNode) }45public enum InlineRun { case text(String, marks: [PMMark]); case atom(PMNode) }46public struct InlinePosition { var line: Int; var offset: Int }47```4849- A **text block** (paragraph, heading, codeBlock, footnote, detailsSummary, unknown node with inline children) is one50 line with `.inline` runs. A code block is ONE line whose text contains the `\n`.51- A **block atom** (table with its whole subtree, image, fileBlock, blockMath, horizontalRule, youtube, unknown leaf,52 container with no child) is one line with `.blockAtom(node)`. The line's `type` and `attrs` are authoritative (the id53 lives in `line.attrs["id"]`); the node supplies the rest. `line.atomNode` gives the effective node.54- A **container** (bulletList, orderedList, taskList, listItem, taskItem, blockquote, callout, aiBlock, details,55 detailsContent, unknown node with block children) is not a line: it is a frame in `line.path`, outermost first,56 `doc` excluded. Every line of the same container node carries an equal frame (same `key`). Consecutive lines sharing57 a key at a depth form one node.5859```text60- [ ] buy milk path [taskList#1, taskItem#2] paragraph61 - [x] oat path [taskList#1, taskItem#2, taskList#3, taskItem#4] paragraph62> quote path [blockquote#5] paragraph63```6465Because a frame is repeated on each line of its group, change a container through66`doc.updateContainer(key:) { $0.attrs["open"] = true }` (updates every copy), and create frames with67`doc.makeContainer(NodeType.blockquote)` (fresh key, default attrs, fresh id) or `doc.newContainerKey()`.6869### Reading and writing7071```swift72init() // one empty paragraph73init(lines: [Line])74init(node: PMNode) // flatten a `doc` node75init(json: Data) throws76init(markdown: String) // server import rules, schema-valid, ids assigned77init(markdown: String, resolvePage: (String) -> String?) // [[Wiki links]] → mentions when a page id is returned78func pmNode() -> PMNode79func jsonData() throws -> Data // canonical: sorted keys80func isStructurallyEqual(to: NoteDocument) -> Bool81mutating func ensureBlockIds() // same rule as the server's ensureBlockIds — call before saving82mutating func newContainerKey() -> Int83mutating func makeContainer(_ type: String, attrs: [String: JSONValue] = [:]) -> Container84mutating func updateContainer(key: Int, _ body: (inout Container) -> Void)85mutating func normalizeContainerKeys() // re-keys a container whose lines are no longer contiguous86mutating func insert(lines: [Line], at index: Int) // paste: foreign container keys are remapped87func schemaViolations(strict: Bool = false) -> [String] // empty when valid for the web schema; strict also reports88 // what ProseMirror would normalize (missing attrs, mark order…)89```9091**Lossless guarantee.** For an unmodified document, `NoteDocument(json:)` then `jsonData()` is semantically identical to92the input (key order aside): unknown node types, unknown attributes, unknown keys, mark order, empty paragraphs,93`attrs: {}` vs no `attrs`, `content: []` vs no `content`. On serialization adjacent text runs with identical marks are94merged and empty text runs are dropped. (A document that already held two adjacent text nodes with the same marks, an95empty text node or `marks: []` — none of which ProseMirror produces — still comes back unchanged: such nodes are kept as96raw `.atom` runs of type `text`.)9798Useful accessors: `line.runs`, `line.isText`, `line.inlineLength`, `line.displayString`, `line.node` (the line's own99ProseMirror node), `line.atomNode`, `run.length`, `run.marks`, `node.plainText`, `JSONValue.stringValue / intValue / …`,100`JSONValue.canonicalData()`, `JSONValue.semanticallyEquals(_:)`, `BlockID.generate()`, `NodeType.<name>` constants.101102### Building lines and nodes103104```swift105Line.paragraph(_ runs: [InlineRun] = [], path: [Container] = [])106Line.paragraph(text: String, path: [Container] = [])107Line.heading(level: Int, _ runs: [InlineRun] = [], path: [Container] = [])108Line.codeBlock(language: String? = nil, text: String = "", path: [Container] = [])109Line(blockAtom: PMNode, path: [Container] = [])110PMNode.image(src:alt:title:) PMNode.fileBlock(src:name:size:mime:attachmentId:) PMNode.horizontalRule()111PMNode.blockMath(latex:) PMNode.table(rows:cols:withHeaderRow:)112PMNode.mention(id:label:) PMNode.hardBreak() PMNode.inlineMath(latex:) PMNode.text(_:marks:)113PMMark.mark(_ kind: MarkKind) PMMark.link(href:title:)114```115116## Commands117118### Block structure119120```swift121mutating func setLineType(_ kind: LineKind, at lines: Range<Int>) -> Bool122 // LineKind: .paragraph | .heading(level: 1...3) | .codeBlock(language: String?)123mutating func toggleList(_ kind: ListKind, at lines: Range<Int>) -> Bool // .bullet | .ordered | .task124mutating func indentListItems(at lines: Range<Int>) -> Bool // Tab125mutating func outdentListItems(at lines: Range<Int>) -> Bool // Shift-Tab126mutating func toggleBlockquote(at lines: Range<Int>) -> Bool127mutating func toggleCallout(kind: String, icon: String, at lines: Range<Int>) -> Bool128mutating func setTaskChecked(_ checked: Bool, at line: Int) -> Bool129mutating func splitLine(at line: Int, offset: Int) -> InlinePosition // Enter; returns the caret130mutating func mergeWithPrevious(at line: Int) -> InlinePosition? // Backspace at offset 0; nil = nothing done131mutating func insertBlockAtom(_ node: PMNode, after line: Int?) -> Int // returns the index of the new line132mutating func replaceBlockAtom(at line: Int, with node: PMNode) -> Bool // e.g. after a table edit; keeps the id133mutating func deleteLine(at line: Int) -> Bool134```135136- `setLineType` acts on paragraph / heading / codeBlock lines. The first paragraph of a list item stays a paragraph137 (schema: `listItem: "paragraph block*"`), such lines are skipped. To a code block: marks are dropped, atoms become138 their text. From a code block: each `\n` becomes a hard break.139- `toggleList`: paragraphs and headings outside a list are wrapped (one item per line, joined with an adjacent list of140 the same kind); lines of a list of another kind convert that whole list; when every line is already in a list of141 that kind the items are lifted out of it.142- `indentListItems` nests the item inside the previous item of its list (false when there is none).143 `outdentListItems` moves it one level out; the items that followed it in the inner list follow it as its children;144 at the first level the item leaves the list.145- `toggleBlockquote` / `toggleCallout` wrap the blocks covering the lines, at the deepest level the schema allows (the146 first paragraph of a list item cannot be wrapped alone: its whole list is; a later block of an item is wrapped inside147 the item). When every line is already inside one, the blocks are lifted out. A callout of another kind is re-typed.148- `toggleList` on an item of a nested list that is already of that kind turns it into a plain block of its parent item149 (use `outdentListItems` to move it one level out instead).150- `splitLine`: in a list item → a new item (unchecked for tasks), the rest of the item follows the new one; on an151 empty item → leaves the list (one level); empty paragraph in a quote / callout → leaves it; heading split at its152 end → paragraph; in a code block → inserts `\n`; on a block atom → empty paragraph after it.153- `mergeWithPrevious`: the first line of a list item is outdented / lifted out of the list; the first block of a quote154 or callout is lifted out of it; otherwise the line's content is appended to the previous text line and the caret155 position returned. An empty paragraph after a block atom is removed. Returns nil when nothing can be done (first156 line, non-empty line after a block atom, structural boundary such as a details summary).157158### Inline159160```swift161mutating func replaceText(in range: Range<Int>, at line: Int, with text: String, marks: [PMMark]? = nil) -> Bool162 // typing, deleting, pasting plain text in one line; marks nil = inherit from the text before the range163mutating func insertInlineAtom(_ node: PMNode, at offset: Int, line: Int) -> Bool164mutating func toggleMark(_ kind: MarkKind, in range: Range<Int>, at line: Int) -> Bool165 // MarkKind: bold, italic, underline, strike, code, highlight, subscript, superscript; `code` excludes the others166mutating func setLink(href: String, in range: Range<Int>, at line: Int) -> Bool167mutating func removeLink(in range: Range<Int>, at line: Int) -> Bool168func marks(at offset: Int, line: Int) -> [PMMark] // marks typed text would take at this caret169func hasMark(_ kind: MarkKind, in range: Range<Int>, at line: Int) -> Bool170func linkRange(at offset: Int, line: Int) -> Range<Int>? // extent of the link around a caret171```172173### Queries for the editor chrome174175```swift176func listKind(at line: Int) -> ListKind? // innermost list of the line177func listDepth(at line: Int) -> Int // number of nested lists178func isListItemHead(at line: Int) -> Bool // first paragraph of an item (draws the bullet / number / checkbox)179func isTaskChecked(at line: Int) -> Bool? // nil outside a task item180func listItemNumber(at line: Int) -> Int? // ordinal in an ordered list (honours `start`)181```182183## Tables (on the raw table node)184185```swift186extension PMNode {187 var tableGrid: [[TableCell]] // TableCell { text: String; isHeader: Bool; colspan: Int; rowspan: Int }188 mutating func setTableCellText(_ text: String, row: Int, column: Int) -> Bool // no-op when the text is unchanged189 mutating func insertTableRow(at row: Int) -> Bool190 mutating func deleteTableRow(at row: Int) -> Bool // false if it is the last one191 mutating func insertTableColumn(at column: Int) -> Bool192 mutating func deleteTableColumn(at column: Int) -> Bool // false if it is the last one193 mutating func toggleTableHeaderRow() -> Bool194}195```196197```swift198guard var table = doc.lines[i].atomNode else { return }199table.setTableCellText("Total", row: 2, column: 0)200doc.replaceBlockAtom(at: i, with: table)201```202203Setting a cell's text replaces its content by one paragraph of plain text (line feeds as hard breaks) only when the204text differs from the cell's current plain text, so formatted cells that were not edited are preserved.205206## Text, Markdown, HTML207208```swift209func plainText() -> String // == server docText210var wordCount: Int // == server wordCount(docText)211func preview(maxLength: Int) -> String // first non-empty line, whitespace collapsed, "…" when cut212func pageReferences() -> [String] // == server extractPageRefs213func attachmentReferences() -> [String] // /api/files/<uuid> of images and files + fileBlock attachmentId214func taskItems() -> TaskCounts // { total, checked }215func markdown() -> String // == server toMarkdown216func html(title: String) -> String // standalone HTML5 file, embedded stylesheet, images by their src217func htmlBody() -> String // the body markup alone218static func wordCount(of: String) -> Int219```220221- `plainText`, `wordCount` and `markdown` reproduce the server byte for byte (checked on the fixtures and on 400 random222 trees against outputs recorded from the web application's own helpers).223- `pageReferences()` returns string ids only (the server would also keep a non-string truthy mention id).224- Markdown import follows the server (`marked` + the import fixes): images with an absolute, `data:` or `/api/files/`225 source become image blocks, other images become `[image: alt]` text, `[[Wiki links]]` become mentions when resolved.226 Where the server would leave a document the schema rejects, the import repairs it: an empty paragraph is added in227 front of a list item that starts with another block and inside an empty quote, text marked `code` keeps only that228 mark, `javascript:` links are dropped. Reference-style links, footnotes and HTML blocks are imported as text.229- HTML: same markup as the server's print view, without KaTeX — math is exported as its LaTeX source in230 `<code class="math">`. Link and image URLs go through the same allow-list as the server (`#` otherwise).231232## 3.0 nodes (SPNotesCore 2.0)233234SPEC §2 adds ten block-level leaf atoms and one inline atom. They keep all their data in `attrs`; binary data is an attachment235referenced by id. Constants: `NodeType.mermaid`, `.drawing`, `.chart`, `.queryView`, `.bibliography`, `.pdf`, `.blockRef`,236`.runCode`, `.audio`, `.canvasLink`, `.citation` (inline); `NodeType.nextBlocks` lists the ten blocks.237238In the flat model a new block is a `.blockAtom` line (`line.atomNode`), a `citation` is an `.atom` run of a text line (one UTF-16239unit for the editors). Insert, replace and delete with the existing commands (`insertBlockAtom`, `replaceBlockAtom`,240`insertInlineAtom`, `deleteLine`).241242### Typed views243244Editors never read raw JSON: each node has a struct conforming to `TypedNode` with `init?(node: PMNode)` (nil for another type),245`node() -> PMNode`, a builder with the schema defaults and a fresh block id, and typed properties.246247```swift248if case .audio(var audio)? = document.typedBlock(at: line) { // or TypedBlock(node:), or AudioBlock(node:)249 audio.title = "Réunion budget"250 document.replaceBlockAtom(at: line, with: audio.node())251}252document.insertBlockAtom(MermaidBlock(code: "graph TD\n A-->B").node(), after: line)253document.insertInlineAtom(CitationInline(refId: id, label: "Fama 1970", locator: "p. 3").node(), at: offset, line: line)254```255256| View | Properties | Helpers |257|---|---|---|258| `MermaidBlock` | `code`, `preview`, `previewHash` | `isPreviewCurrent` (render made from the current source: SHA-256 of `code`), `setPreview(attachmentId:)`, `MermaidBlock.hash(of:)` |259| `DrawingBlock` | `ink`, `preview`, `pk`, `width`, `height`, `background` | `setInk(attachmentId:preview:width:height:pk:)` — without `pk` it is cleared (an editor without PencilKit changed the ink) |260| `ChartBlock` | `kind: ChartKind`, `title`, `columns`, `rows: [[ChartCell]]`, `x`, `y`, `source: ChartSource?` | `resolvedX`, `resolvedY`, `series() -> [ChartSeries]` (ready for Swift Charts) |261| `QueryViewBlock` | `source: QuerySource`, `databaseId`, `viewId`, `filter: QueryFilter`, `layout: QueryLayout`, `limit` (1…500), `title` | — |262| `CitationInline` | `refId`, `locator`, `label` | `displayText` |263| `BibliographyBlock` | `style`, `title` | — |264| `PDFBlock` | `attachmentId`, `name`, `page`, `annotations: [PDFAnnotation]` | `add`, `update`, `remove(annotationId:)`, `annotations(onPage:)` |265| `PDFAnnotation` | `id`, `page`, `kind: PDFAnnotationKind`, `color`, `rects: [PDFRect]`, `text`, `note`, `ink: [PDFPoint]?`, `createdAt` | `summaryLine`; coordinates 0…1, origin top-left |266| `BlockRefBlock` | `pageId`, `blockId`, `mode: BlockRefMode` | `BlockRefBlock.missingTargetText` (« Référence introuvable ») |267| `RunCodeBlock` | `language`, `code`, `output: RunCodeOutput?` (read-only) | `clearOutput()`; natives never execute |268| `AudioBlock` | `attachmentId`, `duration`, `title`, `recordedAt`, `transcript: [TranscriptSegment]`, `transcriptStatus`, `transcriptEngine`, `summary: AudioSummary?` (read-only) | `transcriptText`, `segmentIndex(at:)`, `TranscriptSegment.timecode` |269| `CanvasLinkBlock` | `pageId` | — |270271`ChartKind`, `QuerySource`, `QueryLayout`, `PDFAnnotationKind`, `BlockRefMode`, `TranscriptStatus`, `CalloutKind` are `OpenChoice`272values: string-backed, with static constants for the known values and `isKnown == false` for a value written by a newer editor273(which is kept).274275**Lossless rule.** A typed view wraps the node it was read from. Attributes it does not know, unknown keys of the node and values276of an unexpected shape are returned untouched by `node()`; a setter changes its own attribute only. `PDFAnnotation.fields`,277`QueryFilter.fields` and `ChartBlock.source` keep unknown keys the same way; `PDFBlock.add / update / remove` never rewrite the278other entries of `annotations`. `view[attr: "name"]` reads or writes any attribute. An id property (`preview`, `attachmentId`,279`pageId`, `refId`…) reads as nil unless the stored value is a UUID, exactly as the server treats it. Unknown node types still280round-trip verbatim (`node.isKnownType == false` → show the neutral read-only card).281282### Existing nodes extended283284| Node | New optional attributes | API |285|---|---|---|286| `taskItem` | `due` (ISO date), `priority` (`low`, `medium`, `high`), `taskId` | `taskAttributes(at:)`, `setTaskDue(_:at:)`, `setTaskPriority(_:at:)`, `setTaskId(_:at:)`, `taskItemDetails() -> [TaskItemDetail]` (the server's `docTaskItems`) |287| `aiBlock` | `sources` (`[{pageId, blockId, title}]`), `action` | `aiBlockInfo(at:) -> AIBlockInfo?`, `AIBlockInfo(attrs:)`, `applied(to:)` |288| `callout` | kinds `decision`, `question`, `hypothesis` | `CalloutKind`, `calloutKind(at:)`, `toggleCallout(_:at:)`; `defaultIcon` is a native suggestion (the web had not fixed icons for the new kinds) |289| `listItem`, `taskItem` | block `id` | assigned by `ensureBlockIds()` and by every command creating an item |290291**Block ids.** `Schema.idTypes` equals the 3.0 server's `ID_TYPES`: the 2.x list plus `listItem`, `taskItem` and the ten new292blocks. Consequence for the apps: `ensureBlockIds()` now gives an id to the list items of a document written by a 2.x editor293(the 3.0 server does the same at every save), so "load then serialize" is no longer the identity on such a document. Splitting294an item creates an item with a fresh id; in a task list the new item is unchecked and has no due date, priority or linked task.295Converting an item between list kinds keeps its id and adds or removes the task-only attributes.296297**Schema check.** In strict mode the attributes added in 3.0 to existing nodes may be absent (a 2.x document); nodes built by Core298always carry the full 3.0 set.299300### Text, Markdown, HTML of the new nodes301302A line-by-line port of the server (`docs/reference/next/`), verified byte for byte on the four fixtures the backend publishes303(`Tests/SPNotesDocumentTests/Fixtures/next-nodes/`: `.json` with its expected `.md`, `.txt`, `.html`) and on 521 documents304recorded from the server's own functions (`Fixtures/next-server.json`).305306| Node | Markdown | Plain text |307|---|---|---|308| `mermaid` | fenced `mermaid` block | the source |309| `runCode` | fenced block with its language; when `output.text` is a string, a blank line then a fenced `output` block | code, then output |310| `chart` | title line, blank line, Markdown table of `columns` / `rows` (cells: null → empty, numbers as ECMAScript prints them, `|` escaped, one line); without columns: the title or `[Graphique]` | title, columns, rows (cells separated by a space) |311| `drawing` | `` or `[Dessin]` | `Dessin` |312| `pdf` | `[PDF: name](/api/files/<id>)` (or `[PDF]`…), blank line, one `> p.<page> — <text> — <note>` per annotation (empty parts dropped) | the same lines without syntax |313| `audio` | `[Audio: title](/api/files/<id>)`, blank line, `[mm:ss] text` per segment (minutes not capped at 59, empty segments dropped) | label then the segments' text (no time codes) |314| `queryView` | `[Vue: title]` or `[Vue]` | `Vue: title` |315| `blockRef` | `[[<pageId>#<blockId>]]` | empty |316| `citation` | `[@<label or refId or ?>]` | the label |317| `bibliography` | `## <title or Références>` | the title |318| `canvasLink` | `[Canvas](/p/<pageId>)` or `[Canvas]` | `Canvas` |319320Transcript and annotation text are therefore in `plainText()`, the word count and the full-text index; attachment ids, time codes321and the AI summary are not. `attachmentReferences()` now also returns the files of `mermaid` (render), `drawing` (ink, render,322PencilKit data), `pdf` and `audio`; `pageReferences()` the targets of `blockRef` and `canvasLink`; `citedReferences()` the ids323cited. `htmlBody()` prints one element of class `nx nx-<type>` per node (static: a chart is its table, code is never executed).324Numbers in exported text now follow ECMAScript's `Number::toString` (`1e-7`, `1e+21`).325326### Ink (`spn-ink-1`)327328**Width law (the one law of every platform — lead decision 2026-11-19, the web adopts it).** A `pen` stroke is drawn329`width × (0.35 + 0.65 × pressure)` wide: the nominal `width` at pressure 1, 35 % of it at pressure 0. `marker` and `highlighter`330strokes have a constant `width`. A point without pressure has pressure 1 (a mouse or a finger writes 1). An opaque highlighter331colour is drawn at 40 % opacity. `InkRenderer.penWidth(_:_:)` is the law; `InkRenderer.pressure(forWidth:nominal:)` is its332inverse, for editors that measure a width (PencilKit) and must store a pressure.333334`InkDocument { width, height, strokes }`, `InkStroke { tool: InkTool, color: InkColor, width, points: [InkPoint] }` — the neutral335format of a `drawing`'s `ink` attachment (`init(data:)`, `jsonData()`, unknown fields kept). `simplified(tolerance:)`336(Ramer–Douglas–Peucker, pressure-aware), `boundingBox`, hit testing (`strokeIndices(near:radius:)`, `strokeIndices(intersecting:)`).337`InkRenderer.image(_:scale:background:)`, `pngData(…)` and `draw(_:in:)` render with CoreGraphics only, identically on macOS and338iOS (the `preview` attachment). PencilKit is not importable here: the iOS app converts `PKDrawing` ⇄ `InkDocument` (the mapping339`PKInkType` → `InkTool` is in the doc comment of `InkTool`). Only lossy case: numbers beyond the third in a point.340341### Canvas (`spn-canvas-1`)342343`CanvasDocument { nodes: [CanvasNode], edges: [CanvasEdge], viewport: CanvasViewport }` with unknown fields kept at every level344(`init(data:)`, `jsonData()`), editing helpers (`addNode`, `updateNode`, `removeNode` — which removes the node's edges —,345`addEdge`, `updateEdge`, `removeEdge`, `bringToFront`, `sendToBack`, `normalizeZ`, `bounds`, `nodes(in:)`).346347`CanvasDocument.merge(base:local:remote:) -> CanvasMergeResult` merges by node / edge id: an element changed, added or deleted on348one side only is taken; the same change on both sides is taken; the same id edited differently on both sides is a349`CanvasConflict` (the merged canvas keeps the local version, the conflict carries base, local and remote); edited on one side and350deleted on the other keeps the edited version and reports `.editedAndDeleted`; an edge left dangling by a deletion is dropped when351nobody touched it, otherwise its node is restored and `.deletedButReferenced` is reported. Order: base order, then additions352sorted by id (a clean merge is byte-identical whichever side is "local"). The viewport is per-device view state: local wins353unless only the remote changed. `resolving(_:takingRemote:)` applies a decision. Granularity is the element: two different fields354of the same node edited on the two sides conflict.355356`CanvasLayout.grid(…)` and `CanvasLayout.forceDirected(…, seed:)` (`step`, `energy`, `overlapArea`) lay nodes out357deterministically from a seed.358359## Three-way merge360361```swift362static func merge(base: NoteDocument, mine: NoteDocument, theirs: NoteDocument) -> MergeResult // .merged(doc) | .conflict363```364365Top-level blocks are matched by their block id (blocks without an id, such as a horizontal rule, by their content).366A block changed, inserted, deleted or moved on one side only is taken from that side. `.conflict` when the same block367was changed differently on both sides, changed on one side and deleted on the other, when both sides inserted or368reordered at the same place differently, when the result would be empty, or when top-level ids are duplicated. The merge369never drops a change silently. A top-level block is the whole node (an entire list, quote or table): two edits inside370the same list conflict. The result is a new document (fresh container keys).371372## Validating against the real web schema373374`swift test` writes every document the module emits in its scenarios (fixture, each command, Markdown imports, merges,375random command sequences) to `/tmp/spn-docs.json`; validate them as described in `docs/reference/README.md`:376377```sh378scp /tmp/spn-docs.json M4M64c:/tmp/spn-docs.json379ssh M4M64c 'bash -lc "cd ~/dev/note-v2 && node_modules/.bin/tsx .spn-schema.mts validate /tmp/spn-docs.json"'380```381382Every line must read `ok … identical`. `doc.schemaViolations(strict: true)` is the native equivalent used by the tests.383384## Known limits385386- Swift compares strings by canonical equivalence: two documents differing only by Unicode normalization are `==`.387- A lone UTF-16 surrogate escape in JSON (`\ud800`) is read as U+FFFD.388- Marks are toggled on text only; inline atoms keep their own marks.389- Table helpers address cells by their position in each row; they do not resolve `colspan` / `rowspan` geometry.390