oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

Delegated document editing

Status: approved November 1, 2026 by independent GPT-6 Astra review, with the minimal edit acknowledgement amendment below. This adds to 2026-10-25-agent-access.md, including its October 30 roster amendment, on branch baseline 87de917 and fetched origin/main 7d218bd. Existing reads and creation remain compatible.

Contract

Add docs_update, requiring docs:write, to the same exported registry used by HTTP, CLI, Paseo, ChatGPT and Claude through the shared gateway/MCP server. It edits an existing document; it does not change its title, owner, grants or links. Input is:

{
  "team": "configured-team",
  "id": "document-sqid",
  "client_id": "canonical-nonzero-uuid",
  "expected_revision": "12",
  "edits": [
    {"index": 1, "delete_count": 1,
     "blocks": [{"type": "paragraph", "text": "Replacement text."}]}
  ]
}

id is the existing ten-character public Sqid. client_id has the same canonical nonzero UUID validation as creation. expected_revision is the exact canonical nonnegative decimal string returned as body_revision by docs_get, within the stored signed 64-bit sequence range: no signs, leading zeroes except 0, whitespace, exponent or coercion. It versions the CRDT body, not title or other metadata. A title-only browser change does not invalidate this body precondition.

Each edit splices top-level blocks at a zero-based index into the body read at that revision. delete_count:0 inserts; empty blocks deletes. Positions refer to the original body, not the result of a preceding edit. Require 1–32 edits in strictly descending index order, no duplicate index and no overlapping deletion ranges. Insertion at the end is valid. All indices and counts are exact bounded unsigned 32-bit integers, checked without overflowing sums. An edit with both zero deletion and zero inserted blocks is invalid.

Across the request allow at most 200 inserted blocks, 200 deleted blocks and 128 KiB of inserted UTF-8 text. Inserted blocks use the existing creation literal paragraph/heading contract: paragraph level absent/zero; heading level 1–6; no HTML, Markdown, marks, arbitrary attributes or opaque Yjs bytes. Unknown fields, duplicate JSON keys and malformed Unicode are refused before lossy decoding. The existing HTTP request limit remains in force. Do not trim or normalize literal text. The resulting body must contain at least one top-level block; an explicit empty paragraph represents an empty document.

The successful acknowledgement is {id,url,revision}. revision is the canonical decimal sequence originally committed by this operation, including on an exact retry. The acknowledgement contains no body or mutable title/ timestamp metadata. Read again with docs_get to obtain current content and its body_revision; existing read/create contracts retain their semantics.

Stale new edits and reuse of a UUID with different canonical arguments return conflict/409. Invalid coordinates or unsupported editable content return invalid/422 without mutation; oversized requests/updates return too_large/

  1. Existing missing/unauthorized-document behavior remains unchanged. Storage, decryption, authority and guest-runtime failures are sanitized, never converted into an empty body or a successful edit.

Read coordinates and preserved content

docs_get.content.content already reports the ordered top-level structure at the returned body_revision. Its zero-based array positions are edit indices. Lists, tables, code blocks and other elements remain visible at their positions; clients must not count only paragraphs. No read result is flattened into text to make it editable, and the existing 1 MiB read cap remains in force.

The new core primitive verifies that every root child is an XML element, so each top-level JSON entry corresponds to exactly one CRDT child. A malformed root containing top-level XML text or nested fragments is refused for edits because rendering can split or flatten those children and make coordinates ambiguous. Reads keep their existing behavior; a refused edit explains that the current structure is unsupported without echoing document content.

Deletion/replacement ranges may contain only paragraph or heading elements whose direct children are XML text. Whole-block replacement intentionally replaces all text, inline marks and attributes on the selected block. It is not a formatting-preserving substring replacement. Unsupported elements may remain untouched or have blocks inserted beside them, but cannot be silently flattened or deleted through this operation. Every untouched element retains its existing CRDT identity, children, attributes and marks.

Canonical CRDT mutation

Add a bounded semantic splice primitive to the existing Rust/yrs core and its Go wrapper; no Node process or separate wire encoder participates at runtime. Parse the complete private binary input, enforce all limits, verify all ranges and selected block shapes, and check the resulting root length before the first mutation. Apply descending splices directly to the existing prosemirror XML fragment. Heading levels are typed numeric attributes as in initial creation.

Replay existing history with a fresh, nonzero, uint32-compatible client ID for this edit. Do not reuse a historical stored client ID or rewrite it in the DB. The core refuses a candidate already present in the document state vector; the host may choose a new candidate for at most eight collision attempts. Refuse editing while yrs reports pending missing updates or delete sets, since their unseen client clock ranges cannot safely participate in this collision check. Existing browser application/replay/snapshot behavior remains unchanged; once missing dependencies arrive a fresh read/edit can proceed.

Encode the new yrs transaction's update, including its deletions, rather than replacing the document with a reconstructed JSON tree or a fresh initialization. The emitted update must be nonempty and at most 1 MiB. Discard the private mutation handle on every outcome. Read generated bytes directly from that handle: recovery that merely replays its pre-edit history must never masquerade as a successful edit after a guest trap. No uncertain mutation is retried on the same handle. Existing read-only handle recovery stays intact.

Increment core ABI consistently and rebuild the canonical Wasm artifact through the existing deterministic build script. Existing snapshot ABI fallback and retained full history must continue to replay correctly. The guest time budget is unchanged. Real Yjs plus the production ProseMirror schema verifies that the update is a normal editor update and that later browser edits still converge.

Atomic authority, precondition and receipt

Use a new additive migration for operation-specific update receipts and sealed per-update attribution. Do not reinterpret or reset creation receipts. The immutable authority marker continues to bind Home DEK, exact Home issuer, delegation issuer and configured team. Bootstrap refuses adoption if either creation/update receipts or attribution already exist without a marker.

The update receipt coordinate is a keyed, versioned domain-separated digest of both issuers, subject, delegated client, configured team, operation name and client UUID. Its payload digest binds the target Sqid, exact expected revision and ordered, validated semantic edits with explicit block type/text/level. Normalizing an omitted paragraph level to zero is the only optional-field normalization; unknown fields never enter the canonical form. Separate domains prevent a creation UUID from colliding with an update UUID.

Receipts persist keyed coordinate/content digests, document ID and applied body sequence. They store no document text, clear external identity or credential. Per-update attribution stores the local operator plus delegated client sealed with Home DEK and a purpose binding document GUID, applied sequence and receipt coordinate. Both records are atomic with the existing sealed CRDT update row and document timestamp. Existing sealed snapshot/AAD and log semantics apply.

The writer sequence is:

  1. Reserve SQLite's writer with the existing immutable marker write and verify it. Reverify the original credential through the underlying verifier, then use Home bridge ResolveOn on that transaction's connection to check the complete current linked identity and unchanged actor. Check current document write permission through the existing store predicate and latched Access.
  2. Look up this update receipt. A different payload is a conflict. A matching receipt must still identify the live requested document and a valid applied sequence; it skips mutation entirely, including the expected-revision test. It never replays a prior edit over later manual changes or recreates deletion.
  3. For a new receipt, compare expected_revision against the current body sequence while holding the writer, replay the canonical document at that same sequence, validate and construct the semantic update, and append it through the existing sealed Store.ApplyUpdate path on the same transaction. The precondition, update, timestamp, receipt and attribution commit together.
  4. Immediately before commit, repeat original-credential continuity, complete transaction-local linked identity and current write permission. This final check also runs for completed receipt retries. Any refusal rolls back all effects, including newly inserted marker/receipt/attribution rows.

Separate write-scope selection from creation admission: updating requires the existing document's write permission, not permission to create a new document. In team mode an applicable independent writer grant continues to work under NotMember/Unknown as ordinary editor writes do; ownership requires current Member standing. A reader grant never authorizes updates. Non-team admission retains the existing linked local-account and allowlist/grant checks. HomeOnly identities remain refused without allocating local accounts. Creation admission and existing write-only discovery behavior do not change accidentally.

Only after a successful new commit, publish its document ID and sequence to the existing editor hub so connected editors fetch the ordinary update. No notification occurs for a refusal or completed retry. A lost response after commit is recovered through the receipt, without another update row.

Response and transport authority

The real HTTP handler recognizes docs_update as write-scoped and retains the original credential for online continuity checks. Register the target document at write permission in the existing response guard. Before headers and each 64 KiB chunk, recheck delegation, linked identity and applicable document write authority with the original latched team standing. Clamp remote verifier work to the shorter caller deadline and remaining standing lease, as today.

All result construction/serialization is bounded. A committed mutation whose response is withheld remains committed; callers retry the identical request. Neither response withholding nor an ambiguous transport failure proves that the update failed. HTTP, CLI and official MCP expose the same registry contract and safe error codes, with no parallel operation implementation.

Required evidence and exclusions

Core and real Yjs/ProseMirror tests cover insert/replace/delete, several descending splices, Unicode, literal markup, heading attributes, untouched rich marks/attributes/unsupported elements, malformed coordinates and binary input, pending updates, client collision/high IDs, empty resulting body, update size, trap handling, snapshot fallback and browser edits before/after the agent edit. An offline browser edit to an untouched block must converge in either update arrival order; replacing a block has ordinary CRDT deletion semantics.

App tests cover stale preconditions with zero rows, changed UUID payloads, concurrent identical requests, two distinct requests at one revision (one success), restart/retry after later browser edits, deleted retry, title-only change, complete sealed attribution and rollback on each storage failure. Authority tests cover reader/writer grants, current/removed/Unknown roster, HomeOnly, binding/unlink/address changes, a held writer with revocation before mutation, direct-domain completed-retry final refusal and guarded HTTP emission. Assert existing hub notification on a new edit and its absence on rollback or retry. Real shared HTTPS gateway/CLI/MCP calls exercise read/edit/read/retry.

Selected effective mutants must independently remove the revision comparison, receipt bypass, reserved-writer authority check, final retry check, response write-permission check and unsupported-block protection, and fail their intended behavioral gates. Run relevant Rust, canonical Wasm/wire, Go and race gates and the complete repository gate; independently review the final branch diff.

No title-edit, sharing, deletion, comments, history, general rich-text operation language, automatic conflict rebase, deployment or merge is authorized by this amendment. A new stale edit requires a fresh read and a new client UUID chosen by the caller.

Review and verification record (2026-11-01)

An independent GPT-6 Astra reviewer approved this spec before implementation, including the minimal {id,url,revision} acknowledgement. The same reviewer read the complete editing diff and approved its ABI 6 bounds and disposable handle, canonical XML transaction, sealed update/receipt/attribution transaction, writer and response authority checks, and editor hub notification. Approval was conditional on effective behavioral mutations and the full canonical gate; both conditions passed on the restored implementation.

The complete .amadan/ci.d/10-gate passed with Go 1.26.5, including native Rust, Clippy, reproducible canonical Wasm (465805 bytes), real Yjs/ProseMirror wire checks, existing editor suites, all Go packages and the application build. Focused race checks passed with GOMAXPROCS=2 for the core edit wrapper, all TestAgentUpdate cases, the real HTTPS gateway/CLI/MCP path and adopted database/reopen coverage (core 5.139s; Docs 169.462s).

Twelve selected mutations produced behavioral failures, with sources restored before the final gate: both revision comparisons removed; actual reapplication of a completed receipt over later browser edits; omitted reserved-writer, completed-retry-final and new-edit-final authority checks; response permission downgraded from write to read; omitted receipt; removed outer rollback boundary; reused stored client ID; omitted client collision rejection; permitted removal of unsupported blocks; and reconstruction of an untouched rich block. The revision, retry and new-edit-final mutants were strengthened to demonstrate the actual prohibited effect without a later guard masking the missing check.

The final three-app HTTPS acceptance run also passed: real Docs, Calls and Calendar stores behind the shared gateway, CLI partial result after a lost committed Calendar response, fresh-gateway MCP resume, content and cross-link reads, exact repeat, changed-input conflict and revocation. The Docs fixture is test-only and opt-in. This record covers source and local verification; it does not claim deployed client acceptance, merge or deployment.