| 1 | # Delegated document editing |
| 2 | |
| 3 | Status: approved November 1, 2026 by independent GPT-6 Astra review, with |
| 4 | the minimal edit acknowledgement amendment below. This adds to `2026-10-25-agent-access.md`, |
| 5 | including its October 30 roster amendment, on branch baseline `87de917` and |
| 6 | fetched `origin/main` `7d218bd`. Existing reads and creation remain compatible. |
| 7 | |
| 8 | ## Contract |
| 9 | |
| 10 | Add `docs_update`, requiring `docs:write`, to the same exported registry used |
| 11 | by HTTP, CLI, Paseo, ChatGPT and Claude through the shared gateway/MCP server. |
| 12 | It edits an existing document; it does not change its title, owner, grants or |
| 13 | links. Input is: |
| 14 | |
| 15 | ```json |
| 16 | { |
| 17 | "team": "configured-team", |
| 18 | "id": "document-sqid", |
| 19 | "client_id": "canonical-nonzero-uuid", |
| 20 | "expected_revision": "12", |
| 21 | "edits": [ |
| 22 | {"index": 1, "delete_count": 1, |
| 23 | "blocks": [{"type": "paragraph", "text": "Replacement text."}]} |
| 24 | ] |
| 25 | } |
| 26 | ``` |
| 27 | |
| 28 | `id` is the existing ten-character public Sqid. `client_id` has the same |
| 29 | canonical nonzero UUID validation as creation. `expected_revision` is the |
| 30 | exact canonical nonnegative decimal string returned as `body_revision` by |
| 31 | `docs_get`, within the stored signed 64-bit sequence range: no signs, leading |
| 32 | zeroes except `0`, whitespace, exponent or coercion. It versions the CRDT body, |
| 33 | not title or other metadata. A title-only browser change does not invalidate |
| 34 | this body precondition. |
| 35 | |
| 36 | Each edit splices top-level blocks at a zero-based `index` into the body read |
| 37 | at that revision. `delete_count:0` inserts; empty `blocks` deletes. Positions |
| 38 | refer to the original body, not the result of a preceding edit. Require 1–32 |
| 39 | edits in strictly descending index order, no duplicate index and no overlapping |
| 40 | deletion ranges. Insertion at the end is valid. All indices and counts are |
| 41 | exact bounded unsigned 32-bit integers, checked without overflowing sums. |
| 42 | An edit with both zero deletion and zero inserted blocks is invalid. |
| 43 | |
| 44 | Across the request allow at most 200 inserted blocks, 200 deleted blocks and |
| 45 | 128 KiB of inserted UTF-8 text. Inserted blocks use the existing creation |
| 46 | literal paragraph/heading contract: paragraph level absent/zero; heading level |
| 47 | 1–6; no HTML, Markdown, marks, arbitrary attributes or opaque Yjs bytes. |
| 48 | Unknown fields, duplicate JSON keys and malformed Unicode are refused before |
| 49 | lossy decoding. The existing HTTP request limit remains in force. Do not trim |
| 50 | or normalize literal text. The resulting body must contain at least one |
| 51 | top-level block; an explicit empty paragraph represents an empty document. |
| 52 | |
| 53 | The successful acknowledgement is `{id,url,revision}`. `revision` is the |
| 54 | canonical decimal sequence originally committed by this operation, including |
| 55 | on an exact retry. The acknowledgement contains no body or mutable title/ |
| 56 | timestamp metadata. Read again with `docs_get` to obtain current content and |
| 57 | its `body_revision`; existing read/create contracts retain their semantics. |
| 58 | |
| 59 | Stale new edits and reuse of a UUID with different canonical arguments return |
| 60 | `conflict`/409. Invalid coordinates or unsupported editable content return |
| 61 | `invalid`/422 without mutation; oversized requests/updates return `too_large`/ |
| 62 | 413. Existing missing/unauthorized-document behavior remains unchanged. Storage, |
| 63 | decryption, authority and guest-runtime failures are sanitized, never converted |
| 64 | into an empty body or a successful edit. |
| 65 | |
| 66 | ## Read coordinates and preserved content |
| 67 | |
| 68 | `docs_get.content.content` already reports the ordered top-level structure at |
| 69 | the returned `body_revision`. Its zero-based array positions are edit indices. |
| 70 | Lists, tables, code blocks and other elements remain visible at their positions; |
| 71 | clients must not count only paragraphs. No read result is flattened into text |
| 72 | to make it editable, and the existing 1 MiB read cap remains in force. |
| 73 | |
| 74 | The new core primitive verifies that every root child is an XML element, so |
| 75 | each top-level JSON entry corresponds to exactly one CRDT child. A malformed |
| 76 | root containing top-level XML text or nested fragments is refused for edits |
| 77 | because rendering can split or flatten those children and make coordinates |
| 78 | ambiguous. Reads keep their existing behavior; a refused edit explains that |
| 79 | the current structure is unsupported without echoing document content. |
| 80 | |
| 81 | Deletion/replacement ranges may contain only paragraph or heading elements |
| 82 | whose direct children are XML text. Whole-block replacement intentionally |
| 83 | replaces all text, inline marks and attributes on the selected block. It is |
| 84 | not a formatting-preserving substring replacement. Unsupported elements may |
| 85 | remain untouched or have blocks inserted beside them, but cannot be silently |
| 86 | flattened or deleted through this operation. Every untouched element retains |
| 87 | its existing CRDT identity, children, attributes and marks. |
| 88 | |
| 89 | ## Canonical CRDT mutation |
| 90 | |
| 91 | Add a bounded semantic splice primitive to the existing Rust/yrs core and its |
| 92 | Go wrapper; no Node process or separate wire encoder participates at runtime. |
| 93 | Parse the complete private binary input, enforce all limits, verify all ranges |
| 94 | and selected block shapes, and check the resulting root length before the first |
| 95 | mutation. Apply descending splices directly to the existing `prosemirror` XML |
| 96 | fragment. Heading levels are typed numeric attributes as in initial creation. |
| 97 | |
| 98 | Replay existing history with a fresh, nonzero, uint32-compatible client ID for |
| 99 | this edit. Do not reuse a historical stored client ID or rewrite it in the DB. |
| 100 | The core refuses a candidate already present in the document state vector; |
| 101 | the host may choose a new candidate for at most eight collision attempts. |
| 102 | Refuse editing while yrs reports pending missing updates or delete sets, since |
| 103 | their unseen client clock ranges cannot safely participate in this collision |
| 104 | check. Existing browser application/replay/snapshot behavior remains unchanged; |
| 105 | once missing dependencies arrive a fresh read/edit can proceed. |
| 106 | |
| 107 | Encode the new yrs transaction's update, including its deletions, rather than |
| 108 | replacing the document with a reconstructed JSON tree or a fresh initialization. |
| 109 | The emitted update must be nonempty and at most 1 MiB. Discard the private |
| 110 | mutation handle on every outcome. Read generated bytes directly from that |
| 111 | handle: recovery that merely replays its pre-edit history must never masquerade |
| 112 | as a successful edit after a guest trap. No uncertain mutation is retried on |
| 113 | the same handle. Existing read-only handle recovery stays intact. |
| 114 | |
| 115 | Increment core ABI consistently and rebuild the canonical Wasm artifact through |
| 116 | the existing deterministic build script. Existing snapshot ABI fallback and |
| 117 | retained full history must continue to replay correctly. The guest time budget |
| 118 | is unchanged. Real Yjs plus the production ProseMirror schema verifies that the |
| 119 | update is a normal editor update and that later browser edits still converge. |
| 120 | |
| 121 | ## Atomic authority, precondition and receipt |
| 122 | |
| 123 | Use a new additive migration for operation-specific update receipts and sealed |
| 124 | per-update attribution. Do not reinterpret or reset creation receipts. The |
| 125 | immutable authority marker continues to bind Home DEK, exact Home issuer, |
| 126 | delegation issuer and configured team. Bootstrap refuses adoption if either |
| 127 | creation/update receipts or attribution already exist without a marker. |
| 128 | |
| 129 | The update receipt coordinate is a keyed, versioned domain-separated digest of |
| 130 | both issuers, subject, delegated client, configured team, operation name and |
| 131 | client UUID. Its payload digest binds the target Sqid, exact expected revision |
| 132 | and ordered, validated semantic edits with explicit block type/text/level. |
| 133 | Normalizing an omitted paragraph level to zero is the only optional-field |
| 134 | normalization; unknown fields never enter the canonical form. Separate domains |
| 135 | prevent a creation UUID from colliding with an update UUID. |
| 136 | |
| 137 | Receipts persist keyed coordinate/content digests, document ID and applied body |
| 138 | sequence. They store no document text, clear external identity or credential. |
| 139 | Per-update attribution stores the local operator plus delegated client sealed |
| 140 | with Home DEK and a purpose binding document GUID, applied sequence and receipt |
| 141 | coordinate. Both records are atomic with the existing sealed CRDT update row |
| 142 | and document timestamp. Existing sealed snapshot/AAD and log semantics apply. |
| 143 | |
| 144 | The writer sequence is: |
| 145 | |
| 146 | 1. Reserve SQLite's writer with the existing immutable marker write and verify |
| 147 | it. Reverify the original credential through the underlying verifier, then |
| 148 | use Home bridge `ResolveOn` on that transaction's connection to check the |
| 149 | complete current linked identity and unchanged actor. Check current document |
| 150 | write permission through the existing store predicate and latched Access. |
| 151 | 2. Look up this update receipt. A different payload is a conflict. A matching |
| 152 | receipt must still identify the live requested document and a valid applied |
| 153 | sequence; it skips mutation entirely, including the expected-revision test. |
| 154 | It never replays a prior edit over later manual changes or recreates deletion. |
| 155 | 3. For a new receipt, compare `expected_revision` against the current body |
| 156 | sequence while holding the writer, replay the canonical document at that |
| 157 | same sequence, validate and construct the semantic update, and append it |
| 158 | through the existing sealed `Store.ApplyUpdate` path on the same transaction. |
| 159 | The precondition, update, timestamp, receipt and attribution commit together. |
| 160 | 4. Immediately before commit, repeat original-credential continuity, complete |
| 161 | transaction-local linked identity and current write permission. This final |
| 162 | check also runs for completed receipt retries. Any refusal rolls back all |
| 163 | effects, including newly inserted marker/receipt/attribution rows. |
| 164 | |
| 165 | Separate write-scope selection from creation admission: updating requires the |
| 166 | existing document's write permission, not permission to create a new document. |
| 167 | In team mode an applicable independent writer grant continues to work under |
| 168 | NotMember/Unknown as ordinary editor writes do; ownership requires current |
| 169 | Member standing. A reader grant never authorizes updates. Non-team admission |
| 170 | retains the existing linked local-account and allowlist/grant checks. HomeOnly |
| 171 | identities remain refused without allocating local accounts. Creation admission |
| 172 | and existing write-only discovery behavior do not change accidentally. |
| 173 | |
| 174 | Only after a successful new commit, publish its document ID and sequence to |
| 175 | the existing editor hub so connected editors fetch the ordinary update. No |
| 176 | notification occurs for a refusal or completed retry. A lost response after |
| 177 | commit is recovered through the receipt, without another update row. |
| 178 | |
| 179 | ## Response and transport authority |
| 180 | |
| 181 | The real HTTP handler recognizes `docs_update` as write-scoped and retains the |
| 182 | original credential for online continuity checks. Register the target document |
| 183 | at write permission in the existing response guard. Before headers and each |
| 184 | 64 KiB chunk, recheck delegation, linked identity and applicable document write |
| 185 | authority with the original latched team standing. Clamp remote verifier work |
| 186 | to the shorter caller deadline and remaining standing lease, as today. |
| 187 | |
| 188 | All result construction/serialization is bounded. A committed mutation whose |
| 189 | response is withheld remains committed; callers retry the identical request. |
| 190 | Neither response withholding nor an ambiguous transport failure proves that |
| 191 | the update failed. HTTP, CLI and official MCP expose the same registry contract |
| 192 | and safe error codes, with no parallel operation implementation. |
| 193 | |
| 194 | ## Required evidence and exclusions |
| 195 | |
| 196 | Core and real Yjs/ProseMirror tests cover insert/replace/delete, several |
| 197 | descending splices, Unicode, literal markup, heading attributes, untouched rich |
| 198 | marks/attributes/unsupported elements, malformed coordinates and binary input, |
| 199 | pending updates, client collision/high IDs, empty resulting body, update size, |
| 200 | trap handling, snapshot fallback and browser edits before/after the agent edit. |
| 201 | An offline browser edit to an untouched block must converge in either update |
| 202 | arrival order; replacing a block has ordinary CRDT deletion semantics. |
| 203 | |
| 204 | App tests cover stale preconditions with zero rows, changed UUID payloads, |
| 205 | concurrent identical requests, two distinct requests at one revision (one |
| 206 | success), restart/retry after later browser edits, deleted retry, title-only |
| 207 | change, complete sealed attribution and rollback on each storage failure. |
| 208 | Authority tests cover reader/writer grants, current/removed/Unknown roster, |
| 209 | HomeOnly, binding/unlink/address changes, a held writer with revocation before |
| 210 | mutation, direct-domain completed-retry final refusal and guarded HTTP emission. |
| 211 | Assert existing hub notification on a new edit and its absence on rollback or |
| 212 | retry. Real shared HTTPS gateway/CLI/MCP calls exercise read/edit/read/retry. |
| 213 | |
| 214 | Selected effective mutants must independently remove the revision comparison, |
| 215 | receipt bypass, reserved-writer authority check, final retry check, response |
| 216 | write-permission check and unsupported-block protection, and fail their intended |
| 217 | behavioral gates. Run relevant Rust, canonical Wasm/wire, Go and race gates and |
| 218 | the complete repository gate; independently review the final branch diff. |
| 219 | |
| 220 | No title-edit, sharing, deletion, comments, history, general rich-text operation |
| 221 | language, automatic conflict rebase, deployment or merge is authorized by this |
| 222 | amendment. A new stale edit requires a fresh read and a new client UUID chosen |
| 223 | by the caller. |
| 224 | |
| 225 | ## Review and verification record (2026-11-01) |
| 226 | |
| 227 | An independent GPT-6 Astra reviewer approved this spec before implementation, |
| 228 | including the minimal `{id,url,revision}` acknowledgement. The same reviewer |
| 229 | read the complete editing diff and approved its ABI 6 bounds and disposable |
| 230 | handle, canonical XML transaction, sealed update/receipt/attribution transaction, |
| 231 | writer and response authority checks, and editor hub notification. Approval was |
| 232 | conditional on effective behavioral mutations and the full canonical gate; |
| 233 | both conditions passed on the restored implementation. |
| 234 | |
| 235 | The complete `.amadan/ci.d/10-gate` passed with Go 1.26.5, including native Rust, |
| 236 | Clippy, reproducible canonical Wasm (465805 bytes), real Yjs/ProseMirror wire |
| 237 | checks, existing editor suites, all Go packages and the application build. |
| 238 | Focused race checks passed with `GOMAXPROCS=2` for the core edit wrapper, |
| 239 | all `TestAgentUpdate` cases, the real HTTPS gateway/CLI/MCP path and adopted |
| 240 | database/reopen coverage (core 5.139s; Docs 169.462s). |
| 241 | |
| 242 | Twelve selected mutations produced behavioral failures, with sources restored |
| 243 | before the final gate: both revision comparisons removed; actual reapplication |
| 244 | of a completed receipt over later browser edits; omitted reserved-writer, |
| 245 | completed-retry-final and new-edit-final authority checks; response permission |
| 246 | downgraded from write to read; omitted receipt; removed outer rollback boundary; |
| 247 | reused stored client ID; omitted client collision rejection; permitted removal |
| 248 | of unsupported blocks; and reconstruction of an untouched rich block. The |
| 249 | revision, retry and new-edit-final mutants were strengthened to demonstrate |
| 250 | the actual prohibited effect without a later guard masking the missing check. |
| 251 | |
| 252 | The final three-app HTTPS acceptance run also passed: real Docs, Calls and |
| 253 | Calendar stores behind the shared gateway, CLI partial result after a lost |
| 254 | committed Calendar response, fresh-gateway MCP resume, content and cross-link |
| 255 | reads, exact repeat, changed-input conflict and revocation. The Docs fixture is |
| 256 | test-only and opt-in. This record covers source and local verification; it |
| 257 | does not claim deployed client acceptance, merge or deployment. |
| 258 | |