oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

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