Add revision-checked delegated document editing
25 files changed,
+1,708
−15
core/src/abi.rs+31 −0core/src/bin/emit_edit.rs+22 −0core/src/edit.rs+152 −0core/src/lib.rs+3 −1core/tests/edit.rs+137 −0docs/agent-access.md+21 −3docs/superpowers/plans/2026-11-01-agent-document-editing.md+12 −0docs/superpowers/specs/2026-11-01-agent-document-editing.md+257 −0fixtures/verify-edit.mjs+42 −0internal/core/core.go+1 −1internal/core/edit.go+99 −0internal/core/edit_test.go+63 −0internal/core/testdata/docs_core.wasmbinaryinternal/docs/agent_access.go+21 −4internal/docs/agent_access_test.go+1 −1internal/docs/agent_integration_test.go+25 −0internal/docs/agent_main_compat_test.go+11 −1internal/docs/agent_store.go+8 −3internal/docs/agent_suite_interop_test.go+87 −0internal/docs/agent_update.go+248 −0internal/docs/agent_update_authority_test.go+192 −0internal/docs/agent_update_test.go+260 −0internal/docs/app.go+1 −1internal/docs/migrations/0010_agent_document_edits.sql+13 −0scripts/wire-gate.sh+1 −0
CI passed — run details
diff --git a/core/src/abi.rs b/core/src/abi.rs| index 1661e21..48d5f62 100644 |
| --- a/core/src/abi.rs |
| +++ b/core/src/abi.rs |
| @@ -519,3 +519,34 @@ pub unsafe extern "C" fn docs_core_initialize(handle: u32, ptr: u32, len: u32) - |
| }, |
| } |
| } |
| + |
| +/// Consume an isolated editing handle and copy its transaction update. |
| +/// # Safety |
| +/// Input/output buffers must be valid, nonoverlapping and not concurrently |
| +/// mutated. Bounds are checked before reading input or mutating the document. |
| +#[no_mangle] |
| +pub unsafe extern "C" fn docs_core_edit( |
| + handle: u32, |
| + ptr: u32, |
| + len: u32, |
| + out: u32, |
| + cap: u32, |
| +) -> i32 { |
| + if !in_bounds(ptr, len) || !in_bounds(out, cap) || cap != 1 << 20 { |
| + return ERR_INVALID_LENGTH; |
| + } |
| + let Some(doc) = get_doc(handle) else { |
| + return ERR_NO_DOC; |
| + }; |
| + let input = std::slice::from_raw_parts(ptr as *const u8, len as usize); |
| + match crate::edit::edit(&doc, input) { |
| + Ok(bytes) => { |
| + std::ptr::copy_nonoverlapping(bytes.as_ptr(), out as *mut u8, bytes.len()); |
| + bytes.len() as i32 |
| + } |
| + Err(crate::edit::EditError::Invalid) => -6, |
| + Err(crate::edit::EditError::Collision) => -7, |
| + Err(crate::edit::EditError::TooLarge) => -8, |
| + Err(crate::edit::EditError::Pending) => -9, |
| + } |
| +} |
diff --git a/core/src/bin/emit_edit.rs b/core/src/bin/emit_edit.rs| new file mode 100644 |
| index 0000000..1b48cf0 |
| --- /dev/null |
| +++ b/core/src/bin/emit_edit.rs |
| @@ -0,0 +1,22 @@ |
| +use std::io::{Read, Write}; |
| +use yrs::{Doc, Options}; |
| +fn main() { |
| + let mut base = Vec::new(); |
| + std::io::stdin().read_to_end(&mut base).unwrap(); |
| + let doc = Doc::with_options(Options::with_guid_and_client_id( |
| + "edit-wire".into(), |
| + u32::MAX as u64, |
| + )); |
| + docs_core::apply_update(&doc, &base).unwrap(); |
| + let text = "Edited <script> 😀"; |
| + let mut input = Vec::new(); |
| + for n in [1u32, 1, 1, 1] { |
| + input.extend(n.to_be_bytes()); |
| + } |
| + input.push(2); |
| + input.extend((text.len() as u32).to_be_bytes()); |
| + input.extend(text.as_bytes()); |
| + std::io::stdout() |
| + .write_all(&docs_core::edit::edit(&doc, &input).unwrap()) |
| + .unwrap(); |
| +} |
diff --git a/core/src/edit.rs b/core/src/edit.rs| new file mode 100644 |
| index 0000000..7499f43 |
| --- /dev/null |
| +++ b/core/src/edit.rs |
| @@ -0,0 +1,152 @@ |
| +//! Semantic top-level edits on the existing CRDT, never a JSON reconstruction. |
| +use yrs::branch::{Branch, BranchPtr}; |
| +use yrs::{ |
| + Any, Doc, Map, MapRef, ReadTxn, Transact, XmlElementPrelim, XmlElementRef, XmlFragment, XmlOut, |
| + XmlTextPrelim, |
| +}; |
| + |
| +#[derive(Debug, PartialEq)] |
| +pub enum EditError { |
| + Invalid, |
| + Collision, |
| + Pending, |
| + TooLarge, |
| +} |
| + |
| +struct Edit<'a> { |
| + index: u32, |
| + delete: u32, |
| + blocks: Vec<(u8, &'a str)>, |
| +} |
| + |
| +fn number(input: &mut &[u8]) -> Result<u32, EditError> { |
| + if input.len() < 4 { |
| + return Err(EditError::Invalid); |
| + } |
| + let value = u32::from_be_bytes(input[..4].try_into().unwrap()); |
| + *input = &input[4..]; |
| + Ok(value) |
| +} |
| + |
| +// Count, then repeated index/delete/block-count u32 BE followed by initial |
| +// block encoding (level u8, UTF-8 byte-length u32 BE, bytes). |
| +pub fn edit(doc: &Doc, mut input: &[u8]) -> Result<Vec<u8>, EditError> { |
| + if input.len() > 128 * 1024 + 32 * 12 + 200 * 5 + 4 { |
| + return Err(EditError::TooLarge); |
| + } |
| + if doc.client_id() == 0 || doc.client_id() > u32::MAX as u64 { |
| + return Err(EditError::Invalid); |
| + } |
| + let count = number(&mut input)?; |
| + if count == 0 || count > 32 { |
| + return Err(EditError::Invalid); |
| + } |
| + let mut edits = Vec::new(); |
| + let (mut inserted, mut deleted, mut bytes) = (0u32, 0u32, 0usize); |
| + let mut previous = None; |
| + for _ in 0..count { |
| + let index = number(&mut input)?; |
| + let delete = number(&mut input)?; |
| + let n = number(&mut input)?; |
| + if n > 200 || delete > 200 || n == 0 && delete == 0 { |
| + return Err(EditError::Invalid); |
| + } |
| + inserted += n; |
| + deleted += delete; |
| + if inserted > 200 || deleted > 200 { |
| + return Err(EditError::TooLarge); |
| + } |
| + let end = index.checked_add(delete).ok_or(EditError::Invalid)?; |
| + if previous.is_some_and(|p| index >= p || end > p) { |
| + return Err(EditError::Invalid); |
| + } |
| + previous = Some(index); |
| + let mut blocks = Vec::new(); |
| + for _ in 0..n { |
| + let level = *input.first().ok_or(EditError::Invalid)?; |
| + input = &input[1..]; |
| + let len = number(&mut input)? as usize; |
| + if level > 6 || len > input.len() { |
| + return Err(EditError::Invalid); |
| + } |
| + bytes += len; |
| + if bytes > 128 * 1024 { |
| + return Err(EditError::TooLarge); |
| + } |
| + let text = std::str::from_utf8(&input[..len]).map_err(|_| EditError::Invalid)?; |
| + blocks.push((level, text)); |
| + input = &input[len..]; |
| + } |
| + edits.push(Edit { |
| + index, |
| + delete, |
| + blocks, |
| + }); |
| + } |
| + if !input.is_empty() { |
| + return Err(EditError::Invalid); |
| + } |
| + let root = doc.get_or_insert_xml_fragment(crate::FRAGMENT_ROOT); |
| + let mut txn = doc.transact_mut(); |
| + if txn.has_missing_updates() { |
| + return Err(EditError::Pending); |
| + } |
| + if txn.state_vector().get(&doc.client_id()) != 0 { |
| + return Err(EditError::Collision); |
| + } |
| + let len = root.len(&txn); |
| + if u64::from(len) + u64::from(inserted) <= u64::from(deleted) { |
| + return Err(EditError::Invalid); |
| + } |
| + if root |
| + .children(&txn) |
| + .any(|child| !matches!(child, XmlOut::Element(_))) |
| + { |
| + return Err(EditError::Invalid); |
| + } |
| + for e in &edits { |
| + if e.index > len || e.delete > len - e.index { |
| + return Err(EditError::Invalid); |
| + } |
| + for i in e.index..e.index + e.delete { |
| + match root.get(&txn, i) { |
| + Some(XmlOut::Element(node)) |
| + if (node.tag().as_ref() == "paragraph" || node.tag().as_ref() == "heading") |
| + && node |
| + .children(&txn) |
| + .all(|child| matches!(child, XmlOut::Text(_))) => {} |
| + _ => return Err(EditError::Invalid), |
| + } |
| + } |
| + } |
| + // No validation below can reject a partially applied request. |
| + for e in edits { |
| + if e.delete > 0 { |
| + root.remove_range(&mut txn, e.index, e.delete); |
| + } |
| + for (offset, (level, text)) in e.blocks.into_iter().enumerate() { |
| + let tag = if level == 0 { "paragraph" } else { "heading" }; |
| + let node = root.insert( |
| + &mut txn, |
| + e.index + offset as u32, |
| + XmlElementPrelim::empty(tag), |
| + ); |
| + if level > 0 { |
| + let branch = <XmlElementRef as AsRef<Branch>>::as_ref(&node); |
| + MapRef::from(BranchPtr::from(branch)).insert( |
| + &mut txn, |
| + "level", |
| + Any::Number(level as f64), |
| + ); |
| + } |
| + if !text.is_empty() { |
| + node.push_back(&mut txn, XmlTextPrelim::new(text)); |
| + } |
| + } |
| + } |
| + let update = txn.encode_update_v1(); |
| + if update.len() > 1 << 20 { |
| + return Err(EditError::TooLarge); |
| + } |
| + Ok(update) |
| +} |
diff --git a/core/src/lib.rs b/core/src/lib.rs| index df12264..8efefd3 100644 |
| --- a/core/src/lib.rs |
| +++ b/core/src/lib.rs |
| @@ -54,6 +54,7 @@ |
| //! above) rather than relying on `fastrand` to fail loudly when it can't — |
| //! it won't. |
| pub mod abi; |
| +pub mod edit; |
| mod fragment; |
| pub mod initial; |
| mod snapshot; |
| @@ -88,6 +89,7 @@ extern "Rust" fn __getrandom_v03_custom( |
| /// reason the next paragraph gives. |
| /// |
| /// Version 5 adds bounded initial paragraph/heading construction. |
| +/// Version 6 adds bounded semantic splices on a disposable replay handle. |
| /// |
| /// Adding an export is, strictly, backwards compatible — a host that |
| /// never calls the new function cannot tell 3 from 2 — so the bump is |
| @@ -101,7 +103,7 @@ extern "Rust" fn __getrandom_v03_custom( |
| /// here. |
| #[no_mangle] |
| pub extern "C" fn docs_core_abi_version() -> u32 { |
| - 5 |
| + 6 |
| } |
| use yrs::updates::decoder::Decode; |
diff --git a/core/tests/edit.rs b/core/tests/edit.rs| new file mode 100644 |
| index 0000000..872f669 |
| --- /dev/null |
| +++ b/core/tests/edit.rs |
| @@ -0,0 +1,137 @@ |
| +use docs_core::{ |
| + apply_update, |
| + edit::{edit, EditError}, |
| + fragment_json, |
| + initial::initialize, |
| + snapshot_bytes, |
| +}; |
| +use yrs::{Doc, Options, ReadTxn, Transact, XmlElementPrelim, XmlFragment}; |
| + |
| +fn doc(client: u64) -> Doc { |
| + Doc::with_options(Options::with_guid_and_client_id("edit".into(), client)) |
| +} |
| +type TestEdit<'a> = (u32, u32, Vec<(u8, &'a str)>); |
| +fn input(edits: &[TestEdit<'_>]) -> Vec<u8> { |
| + let mut out = (edits.len() as u32).to_be_bytes().to_vec(); |
| + for (index, delete, blocks) in edits { |
| + out.extend(index.to_be_bytes()); |
| + out.extend(delete.to_be_bytes()); |
| + out.extend((blocks.len() as u32).to_be_bytes()); |
| + for (level, text) in blocks { |
| + out.push(*level); |
| + out.extend((text.len() as u32).to_be_bytes()); |
| + out.extend(text.as_bytes()); |
| + } |
| + } |
| + out |
| +} |
| +fn seeded(client: u64) -> Doc { |
| + let source = doc(1); |
| + let mut raw = Vec::new(); |
| + for text in ["first", "second", "third"] { |
| + raw.push(0); |
| + raw.extend((text.len() as u32).to_be_bytes()); |
| + raw.extend(text.as_bytes()); |
| + } |
| + initialize(&source, &raw).unwrap(); |
| + let d = doc(client); |
| + apply_update(&d, &snapshot_bytes(&source)).unwrap(); |
| + d |
| +} |
| +#[test] |
| +fn splices_are_normal_updates_and_preserve_untouched_items() { |
| + let d = seeded(2); |
| + let before = snapshot_bytes(&d); |
| + let bytes = edit( |
| + &d, |
| + &input(&[(2, 1, vec![]), (1, 1, vec![(3, "<script> 😀"), (0, "")])]), |
| + ) |
| + .unwrap(); |
| + let other = doc(3); |
| + apply_update(&other, &before).unwrap(); |
| + apply_update(&other, &bytes).unwrap(); |
| + assert_eq!(fragment_json(&d), fragment_json(&other)); |
| + let tree: serde_json::Value = serde_json::from_str(&fragment_json(&d)).unwrap(); |
| + assert_eq!(tree["content"][0]["content"][0]["text"], "first"); |
| + assert_eq!(tree["content"][1]["attrs"]["level"], 3); |
| + assert_eq!(tree["content"].as_array().unwrap().len(), 3); |
| + assert_eq!( |
| + edit(&d, &input(&[(0, 1, vec![(0, "again")])])), |
| + Err(EditError::Collision) |
| + ); |
| +} |
| +#[test] |
| +fn invalid_later_edit_never_mutates_valid_prefix() { |
| + let cases = vec![ |
| + input(&[(2, 1, vec![(0, "valid")]), (0, 4, vec![])]), |
| + input(&[(0, 3, vec![])]), |
| + input(&[(0, 0, vec![])]), |
| + input(&[(1, 0, vec![(7, "bad")])]), |
| + input(&[(1, 1, vec![(0, "first")]), (1, 0, vec![(0, "duplicate")])]), |
| + ]; |
| + for mut bad in cases { |
| + let d = seeded(2); |
| + let before = snapshot_bytes(&d); |
| + assert!(edit(&d, &bad).is_err()); |
| + assert_eq!(before, snapshot_bytes(&d)); |
| + bad.push(0); |
| + assert!(edit(&d, &bad).is_err()); |
| + assert_eq!(before, snapshot_bytes(&d)); |
| + } |
| +} |
| +#[test] |
| +fn unsupported_blocks_are_preserved_and_never_deleted() { |
| + let d = seeded(2); |
| + { |
| + let root = d.get_or_insert_xml_fragment("prosemirror"); |
| + root.push_back( |
| + &mut d.transact_mut(), |
| + XmlElementPrelim::empty("future_block"), |
| + ); |
| + } |
| + let e = doc(3); |
| + apply_update(&e, &snapshot_bytes(&d)).unwrap(); |
| + let before = snapshot_bytes(&e); |
| + assert_eq!( |
| + edit(&e, &input(&[(3, 1, vec![(0, "flattened")])])), |
| + Err(EditError::Invalid) |
| + ); |
| + assert_eq!(before, snapshot_bytes(&e)); |
| + edit(&e, &input(&[(3, 0, vec![(0, "beside")])])).unwrap(); |
| + assert!(fragment_json(&e).contains("future_block")); |
| +} |
| +#[test] |
| +fn client_and_input_bounds_are_enforced() { |
| + for client in [0, 1, u32::MAX as u64 + 1] { |
| + assert!(edit(&seeded(client), &input(&[(0, 1, vec![(0, "x")])])).is_err()); |
| + } |
| + for edits in [ |
| + vec![(0, 0, vec![(0, ""); 201])], |
| + vec![(0, 201, vec![])], |
| + vec![(u32::MAX, 1, vec![])], |
| + vec![(0, 0, vec![(0, "x")]); 33], |
| + ] { |
| + assert!(edit(&seeded(2), &input(&edits)).is_err()); |
| + } |
| + let text = "x".repeat(128 * 1024 + 1); |
| + assert!(edit(&seeded(2), &input(&[(0, 1, vec![(0, &text)])])).is_err()); |
| +} |
| +#[test] |
| +fn missing_dependency_refuses_without_losing_pending_update() { |
| + let source = seeded(2); |
| + let root = source.get_or_insert_xml_fragment("prosemirror"); |
| + let bytes = { |
| + let mut tx = source.transact_mut(); |
| + root.push_back(&mut tx, XmlElementPrelim::empty("paragraph")); |
| + tx.encode_update_v1() |
| + }; |
| + let pending = doc(3); |
| + apply_update(&pending, &bytes).unwrap(); |
| + assert!(pending.transact().has_missing_updates()); |
| + let before = snapshot_bytes(&pending); |
| + assert_eq!( |
| + edit(&pending, &input(&[(0, 0, vec![(0, "x")])])), |
| + Err(EditError::Pending) |
| + ); |
| + assert_eq!(before, snapshot_bytes(&pending)); |
| +} |
diff --git a/docs/agent-access.md b/docs/agent-access.md| index 4b01aae..bcb1696 100644 |
| --- a/docs/agent-access.md |
| +++ b/docs/agent-access.md |
| @@ -1,6 +1,6 @@ |
| # Delegated Docs access |
| -This branch adds `docs_list`, `docs_get` and `docs_create` to the shared Oficina |
| +This branch adds `docs_list`, `docs_get`, `docs_create` and `docs_update` to the shared Oficina |
| connection. The same operation contracts serve the Oficina CLI, Paseo, ChatGPT |
| and Claude through the connection service. They require a configured Home |
| identity link to an existing local account and current document permission. |
| @@ -28,8 +28,26 @@ URL and current body revision; read content separately with `docs_get`. |
| Get returns text and ProseMirror JSON from the same replay, with a decimal |
| `body_revision` string. Responses are capped at 1 MiB. List uses 20 items by |
| -default, up to 100, and returns an opaque `next_cursor`. Initial creation does |
| -not provide later edits, sharing, export, comments or deletion. |
| +default, up to 100, and returns an opaque `next_cursor`. |
| + |
| +Update requires `docs:write` and current document write permission. Pass |
| +`{team,id,client_id,expected_revision,edits}`: copy `expected_revision` exactly |
| +from the last get's `body_revision`. Each edit is |
| +`{index,delete_count,blocks}`, using zero-based positions in `content.content`. |
| +Use 1–32 nonoverlapping edits in descending index order, all referring to that |
| +original body. Insert/delete at most 200 blocks and insert at most 128 KiB of |
| +literal paragraph/heading text. Other structures keep their positions and must |
| +remain untouched; this operation refuses to flatten them. Keep at least one |
| +block, using an empty paragraph if needed. |
| + |
| +The edit response is `{id,url,revision}`, where `revision` is the originally |
| +applied body sequence even on retries. Retry the exact request with the same |
| +UUID after an interrupted response; later browser edits are never overwritten |
| +by a retry. A new stale edit returns 409 with no changes: read again and submit |
| +fresh edits with a new UUID. Title-only changes do not change the body revision. |
| +Editing pending/incompletely received CRDT history is refused until its missing |
| +updates arrive. Sharing, export, comments, title edits and deletion remain |
| +outside these delegated operations. |
| The receipt marker binds the Home key, Home issuer, connection issuer and team. |
| Changing any requires an explicit operator migration; never erase receipt state |
diff --git a/docs/superpowers/plans/2026-11-01-agent-document-editing.md b/docs/superpowers/plans/2026-11-01-agent-document-editing.md| new file mode 100644 |
| index 0000000..b8afe8a |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-01-agent-document-editing.md |
| @@ -0,0 +1,12 @@ |
| +# Document editing implementation |
| + |
| +Based on the independently approved November 1 editing spec. |
| + |
| +1. Add validated canonical yrs splices, ABI 6 and a disposable Go mutation |
| + wrapper. Test rejection before mutation and real Yjs/ProseMirror convergence. |
| +2. Add update receipt/attribution migration and the writer transaction, separating |
| + edit permission from creation admission. Wire postcommit editor notification. |
| +3. Export the shared operation and guarded write response; document usage. |
| +4. Prove revision, retry, sealing, authority and transport boundaries with |
| + focused tests and effective mutations. Run the complete gate and race checks. |
| +5. Obtain independent final source/evidence review. No merge or deployment. |
diff --git a/docs/superpowers/specs/2026-11-01-agent-document-editing.md b/docs/superpowers/specs/2026-11-01-agent-document-editing.md| new file mode 100644 |
| index 0000000..5f7cc56 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/2026-11-01-agent-document-editing.md |
| @@ -0,0 +1,257 @@ |
| +# 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: |
| + |
| +```json |
| +{ |
| + "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`/ |
| +413. 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. |
diff --git a/fixtures/verify-edit.mjs b/fixtures/verify-edit.mjs| new file mode 100644 |
| index 0000000..7890264 |
| --- /dev/null |
| +++ b/fixtures/verify-edit.mjs |
| @@ -0,0 +1,42 @@ |
| +import assert from 'node:assert/strict' |
| +import { spawnSync } from 'node:child_process' |
| +import * as Y from 'yjs' |
| +import { yXmlFragmentToProseMirrorRootNode } from 'y-prosemirror' |
| +import { schema } from './schema.mjs' |
| + |
| +const browser = new Y.Doc() |
| +const root = browser.getXmlFragment('prosemirror') |
| +for (const [tag, text] of [['paragraph', 'Rich original'], ['paragraph', 'Replace me'], ['code_block', 'Untouched code']]) { |
| + const block = new Y.XmlElement(tag), body = new Y.XmlText() |
| + body.insert(0, text, tag === 'paragraph' ? {strong: {}} : {}) |
| + block.insert(0, [body]); root.insert(root.length, [block]) |
| +} |
| +root.get(0).setAttribute('align', 'center') |
| +root.get(0).setAttribute('indent', 2) |
| +const untouched = root.get(0), code = root.get(2), base = Y.encodeStateAsUpdate(browser) |
| +const offline = new Y.Doc(); Y.applyUpdate(offline, base) |
| +const sv = Y.encodeStateVector(offline) |
| +offline.getXmlFragment('prosemirror').get(0).get(0).insert(0, 'Offline ') |
| +const concurrent = Y.encodeStateAsUpdate(offline, sv) |
| +const run = spawnSync('cargo', ['run', '--quiet', '--locked', '--manifest-path', 'core/Cargo.toml', '--bin', 'emit_edit'], {input: base, maxBuffer: 8<<20}) |
| +assert.equal(run.status, 0, run.stderr.toString()) |
| +Y.applyUpdate(browser, run.stdout); Y.applyUpdate(browser, concurrent) |
| +Y.applyUpdate(offline, run.stdout) |
| +assert.equal(root.get(0), untouched) |
| +assert.equal(root.get(2), code) |
| +assert.equal(root.get(0).getAttribute('align'), 'center') |
| +assert.equal(root.get(0).getAttribute('indent'), 2) |
| +assert.deepEqual(root.get(0).get(0).toDelta().at(-1).attributes, {strong: {}}) |
| +assert.deepEqual(root.toJSON(), offline.getXmlFragment('prosemirror').toJSON()) |
| +assert.deepEqual(Y.decodeStateVector(Y.encodeStateVector(browser)), Y.decodeStateVector(Y.encodeStateVector(offline))) |
| +const rendered = yXmlFragmentToProseMirrorRootNode(root, schema) |
| +rendered.check() |
| +assert.equal(rendered.child(1).type.name, 'heading') |
| +assert.equal(rendered.child(1).attrs.level, 2) |
| +assert.equal(rendered.child(1).textContent, 'Edited <script> 😀') |
| +assert.equal(rendered.child(0).textContent, 'Offline Rich original') |
| +root.get(1).get(0).insert(0, 'Browser after ') |
| +Y.applyUpdate(offline, Y.encodeStateAsUpdate(browser, Y.encodeStateVector(offline))) |
| +assert.deepEqual(root.toJSON(), offline.getXmlFragment('prosemirror').toJSON()) |
| +yXmlFragmentToProseMirrorRootNode(root, schema).check() |
| +console.log('semantic edits: production schema, rich-content identity and offline convergence passed') |
diff --git a/internal/core/core.go b/internal/core/core.go| index ac6fcb5..d8cb334 100644 |
| --- a/internal/core/core.go |
| +++ b/internal/core/core.go |
| @@ -76,7 +76,7 @@ var moduleWASM []byte |
| // side: the module and this binary ship embedded together with no |
| // version skew to tolerate, so the bump exists to catch a stale .wasm |
| // at load time instead of "unknown export" deep inside a request. |
| -const abiVersion = 5 |
| +const abiVersion = 6 |
| // ABIVersion is abiVersion, exported for callers outside this package |
| // (snapshot storage and its tests) that need to know which ABI contract |
diff --git a/internal/core/edit.go b/internal/core/edit.go| new file mode 100644 |
| index 0000000..69725e9 |
| --- /dev/null |
| +++ b/internal/core/edit.go |
| @@ -0,0 +1,99 @@ |
| +package core |
| + |
| +import ( |
| + "context" |
| + "encoding/binary" |
| + "errors" |
| + "math" |
| + "unicode/utf8" |
| +) |
| + |
| +var ErrEditInvalid = errors.New("core: unsupported edit or coordinates") |
| +var ErrEditCollision = errors.New("core: editing client id already used") |
| +var ErrEditPending = errors.New("core: missing update dependencies") |
| +var ErrEditTooLarge = errors.New("core: edit limit exceeded") |
| + |
| +type BlockEdit struct { |
| + Index uint32 |
| + Delete uint32 |
| + Blocks []InitialBlock |
| +} |
| + |
| +// EditUpdate consumes and closes this private replay handle on every outcome. |
| +// It never recovers a failed guest mutation by replaying the pre-edit history. |
| +func (h *Handle) EditUpdate(ctx context.Context, edits []BlockEdit) ([]byte, error) { |
| + defer h.Close(ctx) |
| + if h.clientID == 0 || h.clientID > math.MaxUint32 || len(edits) == 0 || len(edits) > 32 { |
| + return nil, ErrEditInvalid |
| + } |
| + raw := binary.BigEndian.AppendUint32(nil, uint32(len(edits))) |
| + inserted, deleted, total := 0, uint64(0), 0 |
| + for i, e := range edits { |
| + if len(e.Blocks) > 200 || e.Delete > 200 || len(e.Blocks) == 0 && e.Delete == 0 || uint64(e.Index)+uint64(e.Delete) > math.MaxUint32 { |
| + return nil, ErrEditInvalid |
| + } |
| + if i > 0 && (e.Index >= edits[i-1].Index || uint64(e.Index)+uint64(e.Delete) > uint64(edits[i-1].Index)) { |
| + return nil, ErrEditInvalid |
| + } |
| + inserted += len(e.Blocks) |
| + deleted += uint64(e.Delete) |
| + if inserted > 200 || deleted > 200 { |
| + return nil, ErrEditTooLarge |
| + } |
| + raw = binary.BigEndian.AppendUint32(raw, e.Index) |
| + raw = binary.BigEndian.AppendUint32(raw, e.Delete) |
| + raw = binary.BigEndian.AppendUint32(raw, uint32(len(e.Blocks))) |
| + for _, b := range e.Blocks { |
| + total += len(b.Text) |
| + if b.Level > 6 || !utf8.ValidString(b.Text) { |
| + return nil, ErrEditInvalid |
| + } |
| + if total > 128<<10 { |
| + return nil, ErrEditTooLarge |
| + } |
| + raw = append(raw, b.Level) |
| + raw = binary.BigEndian.AppendUint32(raw, uint32(len(b.Text))) |
| + raw = append(raw, b.Text...) |
| + } |
| + } |
| + ptr, err := allocIn(ctx, h.rt.callTimeout, h.mod, uint64(len(raw))) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer freeIn(ctx, h.rt.callTimeout, h.mod, ptr, uint64(len(raw))) |
| + if !h.mod.Memory().Write(uint32(ptr), raw) { |
| + return nil, errors.New("core: edit input memory") |
| + } |
| + const cap = 1 << 20 |
| + out, err := allocIn(ctx, h.rt.callTimeout, h.mod, cap) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer freeIn(ctx, h.rt.callTimeout, h.mod, out, cap) |
| + result, err := callGuest(ctx, h.rt.callTimeout, h.mod.ExportedFunction("docs_core_edit"), h.handle, ptr, uint64(len(raw)), out, cap) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if len(result) != 1 { |
| + return nil, errors.New("core: edit result") |
| + } |
| + n := int32(result[0]) |
| + switch n { |
| + case -6: |
| + return nil, ErrEditInvalid |
| + case -7: |
| + return nil, ErrEditCollision |
| + case -8: |
| + return nil, ErrEditTooLarge |
| + case -9: |
| + return nil, ErrEditPending |
| + } |
| + if n <= 0 || n > cap { |
| + return nil, errors.New("core: edit refused") |
| + } |
| + bytes, ok := h.mod.Memory().Read(uint32(out), uint32(n)) |
| + if !ok { |
| + return nil, errors.New("core: edit output memory") |
| + } |
| + return append([]byte(nil), bytes...), nil |
| +} |
diff --git a/internal/core/edit_test.go b/internal/core/edit_test.go| new file mode 100644 |
| index 0000000..c159abb |
| --- /dev/null |
| +++ b/internal/core/edit_test.go |
| @@ -0,0 +1,63 @@ |
| +package core_test |
| + |
| +import ( |
| + "errors" |
| + "github.com/carlosframework/docs/internal/core" |
| + "math" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestEditUpdateUsesDisposableCanonicalHandle(t *testing.T) { |
| + ctx := t.Context() |
| + rt, e := core.New(ctx) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer rt.Close(ctx) |
| + base, e := rt.InitialUpdate(ctx, "edited", 1, []core.InitialBlock{{Text: "keep"}, {Text: "replace"}}) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + h, e := rt.NewDoc(ctx, "edited", math.MaxUint32) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = h.Apply(ctx, base); e != nil { |
| + t.Fatal(e) |
| + } |
| + update, e := h.EditUpdate(ctx, []core.BlockEdit{{Index: 1, Delete: 1, Blocks: []core.InitialBlock{{Level: 2, Text: "<script> 😀"}}}}) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = h.Apply(ctx, update); e == nil { |
| + t.Fatal("mutation handle remained reusable") |
| + } |
| + reader, e := rt.NewDoc(ctx, "edited", 3) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer reader.Close(ctx) |
| + for _, u := range [][]byte{base, update} { |
| + if e = reader.Apply(ctx, u); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + html, e := reader.HTML(ctx) |
| + if e != nil || !strings.Contains(html, "<p>keep</p><h2><script> 😀</h2>") { |
| + t.Fatal(html, e) |
| + } |
| + for _, client := range []uint64{0, 1, math.MaxUint32 + 1} { |
| + h, e := rt.NewDoc(ctx, "edited", client) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = h.Apply(ctx, base); e != nil { |
| + t.Fatal(e) |
| + } |
| + _, e = h.EditUpdate(ctx, []core.BlockEdit{{Index: 1, Delete: 1}}) |
| + if client == 1 && !errors.Is(e, core.ErrEditCollision) || client != 1 && !errors.Is(e, core.ErrEditInvalid) { |
| + t.Fatal(client, e) |
| + } |
| + } |
| +} |
diff --git a/internal/core/testdata/docs_core.wasm b/internal/core/testdata/docs_core.wasm| index ad05356..bc3d747 100755 |
| Binary files a/internal/core/testdata/docs_core.wasm and b/internal/core/testdata/docs_core.wasm differ |
diff --git a/internal/docs/agent_access.go b/internal/docs/agent_access.go| index bcfc26b..9a15661 100644 |
| --- a/internal/docs/agent_access.go |
| +++ b/internal/docs/agent_access.go |
| @@ -88,6 +88,23 @@ func (a *documentAgent) registry() (*access.Registry, error) { |
| return a.create(ctx, p, id, in) |
| }}, |
| } |
| + ops = append(ops, access.Operation{ |
| + Name: "docs_update", Description: "Edit top-level paragraph/heading blocks at expected_revision from docs_get.body_revision. Retry with the same UUID and exact arguments; revision acknowledges the original applied edit.", Scope: "docs:write", Idempotent: true, |
| + Input: input(`,"id":{"type":"string","pattern":"^[23456789abcdefghjkmnpqrstuvwxyz]{10}$"},"client_id":{"type":"string","maxLength":36},"expected_revision":{"type":"string","pattern":"^(0|[1-9][0-9]*)$","maxLength":19},"edits":{"type":"array","minItems":1,"maxItems":32,"items":{"type":"object","additionalProperties":false,"required":["index","delete_count","blocks"],"properties":{"index":{"type":"integer","minimum":0,"maximum":4294967295},"delete_count":{"type":"integer","minimum":0,"maximum":200},"blocks":{"type":"array","maxItems":200,"items":{"type":"object","required":["type","text"],"additionalProperties":false,"properties":{"type":{"enum":["paragraph","heading"]},"text":{"type":"string","maxLength":131072},"level":{"type":"integer","minimum":0,"maximum":6}}}}}}}`, `,"id","client_id","expected_revision","edits"`), |
| + Output: json.RawMessage(`{"type":"object","additionalProperties":false,"required":["id","url","revision"],"properties":{"id":{"type":"string"},"url":{"type":"string"},"revision":{"type":"string","pattern":"^[1-9][0-9]*$"}}}`), |
| + Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| + ctx, id, err := a.prepareMode(ctx, p, true, false) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var in agentUpdateInput |
| + if json.Unmarshal(raw, &in) != nil { |
| + return nil, access.Fail("invalid", "Invalid document edits.") |
| + } |
| + return a.update(ctx, p, id, in) |
| + }, |
| + }) |
| + |
| for i := range ops { |
| invoke := ops[i].Invoke |
| ops[i].Invoke = func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| @@ -141,13 +158,13 @@ func (a *documentAgent) httpHandler(verifier access.Verifier) (http.Handler, err |
| return |
| } |
| name := strings.TrimPrefix(r.URL.Path, "/api/v1/operations/") |
| - write := name == "docs_create" |
| + write := name == "docs_create" || name == "docs_update" |
| // Discovery can describe a write-only connection without granting reads. |
| discovery := r.Method == "GET" && r.URL.Path == "/api/v1/operations" |
| if discovery && !p.Allows(a.team, "docs:read") { |
| write = true |
| } |
| - ctx, id, err := a.prepare(r.Context(), p, write) |
| + ctx, id, err := a.prepareMode(r.Context(), p, write, write && name != "docs_update") |
| if err != nil { |
| agentWriteFailure(w, err) |
| return |
| @@ -229,8 +246,8 @@ func (a *documentAgent) httpHandler(verifier access.Verifier) (http.Handler, err |
| }), nil |
| } |
| -func newDocumentAgent(cfg Config, settings *homeSettings, home *homeRoutes, store *Store, list allowlist, verifier access.Verifier) (http.Handler, error) { |
| - a := &documentAgent{store: store, resolver: home.resolver, list: list, origin: cfg.Origin, issuer: cfg.AgentIssuer, identityIssuer: settings.issuer, team: cfg.AgentTeam, key: append([]byte(nil), settings.dek...)} |
| +func newDocumentAgent(cfg Config, settings *homeSettings, home *homeRoutes, store *Store, list allowlist, verifier access.Verifier, notify func(int64, int64)) (http.Handler, error) { |
| + a := &documentAgent{notify: notify, store: store, resolver: home.resolver, list: list, origin: cfg.Origin, issuer: cfg.AgentIssuer, identityIssuer: settings.issuer, team: cfg.AgentTeam, key: append([]byte(nil), settings.dek...)} |
| if err := store.db.Transaction(func(tx *gorm.DB) error { return a.bind(tx) }); err != nil { |
| return nil, err |
| } |
diff --git a/internal/docs/agent_access_test.go b/internal/docs/agent_access_test.go| index db55998..8140d2a 100644 |
| --- a/internal/docs/agent_access_test.go |
| +++ b/internal/docs/agent_access_test.go |
| @@ -97,7 +97,7 @@ func TestAgentDocumentTeamContractsComposeAndWrongInstanceRefuses(t *testing.T) |
| t.Fatal(e) |
| } |
| gateway, e := access.Gateway([]access.Route{{Team: "blue", Resource: bridgeOrigin + "/api/v1", Operations: first.List(f.p)}, {Team: "green", Resource: "https://green.docs.oficina.works/api/v1", Operations: second.List(f.p)}}, docAgentCredentials{}, nil) |
| - if e != nil || len(gateway.List(f.p)) != 3 { |
| + if e != nil || len(gateway.List(f.p)) != 4 { |
| t.Fatal("contracts cannot compose", e) |
| } |
| in := initialAgentInput() |
diff --git a/internal/docs/agent_integration_test.go b/internal/docs/agent_integration_test.go| index fd9502e..0057044 100644 |
| --- a/internal/docs/agent_integration_test.go |
| +++ b/internal/docs/agent_integration_test.go |
| @@ -136,6 +136,31 @@ func TestAgentGatewayToRealDocs(t *testing.T) { |
| if !strings.Contains(string(text), "PRIVATE_INITIAL_BODY_7f39") { |
| t.Fatal("MCP could not read created document") |
| } |
| + edit := editAgentInput(agentBody{agentDocument: document.agentDocument, Revision: document.Revision}) |
| + editJSON, _ := json.Marshal(edit) |
| + edited, err := cli.Call(ctx, "docs_update", editJSON) |
| + if err != nil { |
| + t.Fatal("CLI edit", err) |
| + } |
| + editedJSON, _ := json.Marshal(edited) |
| + var ack agentUpdated |
| + if json.Unmarshal(editedJSON, &ack) != nil || ack.Revision != "2" { |
| + t.Fatal("edit receipt", string(editedJSON)) |
| + } |
| + editRetry, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "docs_update", Arguments: edit}) |
| + if err != nil || editRetry.IsError { |
| + t.Fatal("MCP edit retry", editRetry, err) |
| + } |
| + getJSON, _ := json.Marshal(map[string]any{"team": "blue", "id": document.ID}) |
| + readAfter, err := cli.Call(ctx, "docs_get", getJSON) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + afterJSON, _ := json.Marshal(readAfter) |
| + if !strings.Contains(string(afterJSON), "EDITED_PRIVATE_BODY") { |
| + t.Fatal("edit not readable", string(afterJSON)) |
| + } |
| + |
| var count int |
| if err = f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 { |
| t.Fatal("transport retry duplicated document", count, err) |
diff --git a/internal/docs/agent_main_compat_test.go b/internal/docs/agent_main_compat_test.go| index fe17c4a..b88a08c 100644 |
| --- a/internal/docs/agent_main_compat_test.go |
| +++ b/internal/docs/agent_main_compat_test.go |
| @@ -101,10 +101,20 @@ func TestAgentAdoptedDatabaseSurvivesCreateRetryAndReopen(t *testing.T) { |
| if err := f.a.store.Grant(t.Context(), legacy.paul, created.ID, "carol@example.com", RoleReader); err != nil { |
| t.Fatal(err) |
| } |
| + edit := editAgentInput(created) |
| + if w := f.call(t, "docs_update", edit); w.Code != 200 { |
| + t.Fatal(w.Code, w.Body.String()) |
| + } |
| + |
| if err := f.app.Close(); err != nil { |
| t.Fatal(err) |
| } |
| f = attach() |
| + if w := f.call(t, "docs_update", edit); w.Code != 200 { |
| + t.Fatal("reopened edit receipt", w.Code, w.Body.String()) |
| + } |
| + agentEditCounts(t, f, 1) |
| + |
| retry := decodeAgentBody(t, f.call(t, "docs_create", input)) |
| if retry.ID != created.ID { |
| t.Fatal("reopen duplicated retry", retry.ID, created.ID) |
| @@ -245,7 +255,7 @@ func TestAgentHomeOnlyIdentityRefusedWithoutAllocation(t *testing.T) { |
| } |
| beforePeople, beforeDocs := f.persons() |
| beforeCalls := f.calls |
| - for _, path := range []string{"", "/docs_list", "/docs_get", "/docs_create"} { |
| + for _, path := range []string{"", "/docs_list", "/docs_get", "/docs_create", "/docs_update"} { |
| method := "POST" |
| if path == "" { |
| method = "GET" |
diff --git a/internal/docs/agent_store.go b/internal/docs/agent_store.go| index bde08d5..ddcbbeb 100644 |
| --- a/internal/docs/agent_store.go |
| +++ b/internal/docs/agent_store.go |
| @@ -29,6 +29,7 @@ type documentAgent struct { |
| list allowlist |
| origin, issuer, identityIssuer, team string |
| key []byte |
| + notify func(int64, int64) |
| } |
| type agentBlock struct { |
| Type string `json:"type"` |
| @@ -83,7 +84,7 @@ func (a *documentAgent) digest(domain string, value any) string { |
| func (a *documentAgent) bind(tx *gorm.DB) error { |
| want := a.digest("keycheck", []string{"immutable-authority", a.identityIssuer, a.issuer, a.team}) |
| // This write reserves SQLite's writer before checking state or receipts. |
| - if err := tx.Exec("INSERT INTO docs_agent_state(id,keycheck) SELECT 1,? WHERE NOT EXISTS(SELECT 1 FROM docs_agent_receipts) ON CONFLICT(id) DO NOTHING", want).Error; err != nil { |
| + if err := tx.Exec("INSERT INTO docs_agent_state(id,keycheck) SELECT 1,? WHERE NOT EXISTS(SELECT 1 FROM docs_agent_receipts) AND NOT EXISTS(SELECT 1 FROM docs_agent_attribution) AND NOT EXISTS(SELECT 1 FROM docs_agent_update_receipts) AND NOT EXISTS(SELECT 1 FROM docs_agent_update_attribution) ON CONFLICT(id) DO NOTHING", want).Error; err != nil { |
| return err |
| } |
| var got string |
| @@ -112,6 +113,10 @@ func agentFailure(err error) error { |
| return access.Fail("unavailable", "Document authority or storage is unavailable.") |
| } |
| func (a *documentAgent) prepare(ctx context.Context, p access.Principal, write bool) (context.Context, requestIdentity, error) { |
| + return a.prepareMode(ctx, p, write, write) |
| +} |
| + |
| +func (a *documentAgent) prepareMode(ctx context.Context, p access.Principal, write, create bool) (context.Context, requestIdentity, error) { |
| scope := "docs:read" |
| if write { |
| scope = "docs:write" |
| @@ -128,7 +133,7 @@ func (a *documentAgent) prepare(ctx context.Context, p access.Principal, write b |
| if e != nil { |
| return ctx, id, agentFailure(e) |
| } |
| - if !admitted || write && !a.list.configured(actorAddress(id.Actor)) { |
| + if !admitted || create && !a.list.configured(actorAddress(id.Actor)) { |
| return ctx, id, agentFailure(errIdentityRefused) |
| } |
| } |
| @@ -145,7 +150,7 @@ func (a *documentAgent) prepare(ctx context.Context, p access.Principal, write b |
| } |
| ctx = withAccess(ctx, guard) |
| } |
| - if write { |
| + if create { |
| if e := a.store.requireMember(ctx, id.Actor); e != nil { |
| return ctx, id, agentFailure(e) |
| } |
diff --git a/internal/docs/agent_suite_interop_test.go b/internal/docs/agent_suite_interop_test.go| new file mode 100644 |
| index 0000000..927975d |
| --- /dev/null |
| +++ b/internal/docs/agent_suite_interop_test.go |
| @@ -0,0 +1,87 @@ |
| +package docs |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/home/connect" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// Opt-in subprocess endpoint for the suite's real-store composition test. |
| +// There is no production configuration or runtime switch for this fixture. |
| +func TestSuiteInteropFixture(t *testing.T) { |
| + directory := os.Getenv("OFICINA_INTEROP_DIR") |
| + if directory == "" { |
| + t.Skip("suite interoperability subprocess only") |
| + } |
| + f := newDocAgentFixture(t) |
| + id, e := f.a.resolver.resolveHome(t.Context(), f.p.Subject) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + bridge, ok := f.a.resolver.links.(*connect.Bridge) |
| + if !ok { |
| + t.Fatal("real Home bridge required") |
| + } |
| + tx, e := f.app.db.Writer().BeginTx(t.Context(), nil) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer tx.Rollback() |
| + if _, e = tx.Exec("DELETE FROM home_identity_links"); e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = bridge.Adopt(t.Context(), tx, bridgeIssuer, "opaque-home-alice", id.Actor.PersonID); e != nil { |
| + t.Fatal(e) |
| + } |
| + // No resources/receipts exist yet; establish the fixture's chosen team. |
| + if _, e = tx.Exec("DELETE FROM docs_agent_state"); e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = tx.Commit(); e != nil { |
| + t.Fatal(e) |
| + } |
| + f.a.team = "acme" |
| + f.p = access.Principal{Subject: "opaque-home-alice", Client: "oficina-interop", Grant: "interop-grant", Teams: []string{"acme"}, Scopes: []string{"docs:read", "docs:write"}} |
| + if e = f.a.store.db.Transaction(func(tx *gorm.DB) error { return f.a.bind(tx) }); e != nil { |
| + t.Fatal(e) |
| + } |
| + handler, e := f.a.httpHandler(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return f.p, nil })) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + server := httptest.NewTLSServer(handler) |
| + defer server.Close() |
| + metadata, e := json.Marshal(map[string]string{"url": server.URL, "origin": f.a.origin}) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + temporary := filepath.Join(directory, "docs.json.tmp") |
| + if e = os.WriteFile(temporary, metadata, 0600); e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = os.Rename(temporary, filepath.Join(directory, "docs.json")); e != nil { |
| + t.Fatal(e) |
| + } |
| + tick := time.NewTicker(100 * time.Millisecond) |
| + defer tick.Stop() |
| + deadline := time.NewTimer(2 * time.Minute) |
| + defer deadline.Stop() |
| + for { |
| + select { |
| + case <-tick.C: |
| + if _, e := os.Stat(filepath.Join(directory, "stop")); e == nil { |
| + return |
| + } |
| + case <-deadline.C: |
| + t.Fatal("suite fixture timed out") |
| + } |
| + } |
| +} |
diff --git a/internal/docs/agent_update.go b/internal/docs/agent_update.go| new file mode 100644 |
| index 0000000..9470c7a |
| --- /dev/null |
| +++ b/internal/docs/agent_update.go |
| @@ -0,0 +1,248 @@ |
| +package docs |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "math" |
| + mrand "math/rand/v2" |
| + "strconv" |
| + "unicode/utf8" |
| + |
| + access "amadan.net/oficina/agent-access.git" |
| + "amadan.net/oficina/home/handoff/seal" |
| + "github.com/carlosframework/docs/internal/core" |
| + "github.com/google/uuid" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type agentEdit struct { |
| + Index uint32 `json:"index"` |
| + Delete uint32 `json:"delete_count"` |
| + Blocks []agentBlock `json:"blocks"` |
| +} |
| +type agentUpdateInput struct { |
| + Team string `json:"team"` |
| + ID string `json:"id"` |
| + ClientID string `json:"client_id"` |
| + Expected string `json:"expected_revision"` |
| + Edits []agentEdit `json:"edits"` |
| +} |
| +type agentUpdated struct { |
| + ID string `json:"id"` |
| + URL string `json:"url"` |
| + Revision string `json:"revision"` |
| +} |
| +type agentUpdateReceipt struct { |
| + Coordinate string `gorm:"primaryKey"` |
| + Content string |
| + DocumentID int64 |
| + Revision int64 |
| +} |
| + |
| +func (agentUpdateReceipt) TableName() string { return "docs_agent_update_receipts" } |
| + |
| +type agentUpdateAttribution struct { |
| + DocumentID int64 |
| + Revision int64 |
| + OperatorID int64 |
| + ClientSealed []byte |
| +} |
| + |
| +func (agentUpdateAttribution) TableName() string { return "docs_agent_update_attribution" } |
| + |
| +func validatedAgentEdits(in agentUpdateInput) (int64, []core.BlockEdit, error) { |
| + bad := access.Fail("invalid", "Invalid revision, client UUID or document edits.") |
| + id, e := uuid.Parse(in.ClientID) |
| + if e != nil || id == uuid.Nil || id.String() != in.ClientID { |
| + return 0, nil, bad |
| + } |
| + expected, e := strconv.ParseInt(in.Expected, 10, 64) |
| + if e != nil || expected < 0 || strconv.FormatInt(expected, 10) != in.Expected || len(in.Edits) == 0 || len(in.Edits) > 32 { |
| + return 0, nil, bad |
| + } |
| + result := make([]core.BlockEdit, len(in.Edits)) |
| + inserted, deleted, total := 0, uint64(0), 0 |
| + for i, edit := range in.Edits { |
| + if edit.Delete > 200 || len(edit.Blocks) > 200 || edit.Delete == 0 && len(edit.Blocks) == 0 || uint64(edit.Index)+uint64(edit.Delete) > math.MaxUint32 { |
| + return 0, nil, bad |
| + } |
| + if i > 0 && (edit.Index >= in.Edits[i-1].Index || uint64(edit.Index)+uint64(edit.Delete) > uint64(in.Edits[i-1].Index)) { |
| + return 0, nil, bad |
| + } |
| + inserted += len(edit.Blocks) |
| + deleted += uint64(edit.Delete) |
| + if inserted > 200 || deleted > 200 { |
| + return 0, nil, access.Fail("too_large", "The edit exceeds the block limit.") |
| + } |
| + result[i] = core.BlockEdit{Index: edit.Index, Delete: edit.Delete, Blocks: make([]core.InitialBlock, len(edit.Blocks))} |
| + for j, b := range edit.Blocks { |
| + if !utf8.ValidString(b.Text) || b.Type != "paragraph" && b.Type != "heading" || b.Type == "paragraph" && b.Level != 0 || b.Type == "heading" && (b.Level < 1 || b.Level > 6) { |
| + return 0, nil, bad |
| + } |
| + total += len(b.Text) |
| + if total > 128<<10 { |
| + return 0, nil, access.Fail("too_large", "The edit exceeds the text limit.") |
| + } |
| + result[i].Blocks[j] = core.InitialBlock{Text: b.Text, Level: b.Level} |
| + } |
| + } |
| + return expected, result, nil |
| +} |
| + |
| +func (a *documentAgent) checkEditor(ctx context.Context, tx *gorm.DB, p access.Principal, id requestIdentity, docID int64) error { |
| + guard, ok := ctx.Value(accessContextKey{}).(*requestAccess) |
| + if !ok || guard == nil || guard.delegationCheck == nil { |
| + return errIdentityRefused |
| + } |
| + if e := guard.delegationCheck(ctx); e != nil { |
| + return e |
| + } |
| + current, e := a.resolver.resolveHomeOn(ctx, tx.Statement.ConnPool, p.Subject) |
| + if e != nil { |
| + return e |
| + } |
| + if !sameActor(current.Actor, id.Actor) { |
| + return errIdentityRefused |
| + } |
| + if a.store.team == nil && !a.list.configured(actorAddress(id.Actor)) { |
| + store := *a.store |
| + store.db = tx |
| + allowed, err := store.HasGrant(ctx, actorAddress(id.Actor)) |
| + if err != nil { |
| + return err |
| + } |
| + if !allowed { |
| + return errIdentityRefused |
| + } |
| + } |
| + return a.store.checkPermission(ctx, tx, id.Actor, docID, permissionWrite) |
| +} |
| + |
| +func (a *documentAgent) update(ctx context.Context, p access.Principal, id requestIdentity, in agentUpdateInput) (any, error) { |
| + expected, edits, err := validatedAgentEdits(in) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if a.store.content == nil { |
| + return nil, access.Fail("unavailable", "Activate sealed document storage before agent writes.") |
| + } |
| + coordinate := a.digest("update-coordinate", []string{a.identityIssuer, a.issuer, p.Subject, p.Client, a.team, "docs_update", in.ClientID}) |
| + payload := a.digest("update-content", struct { |
| + ID, Expected string |
| + Edits []agentEdit |
| + }{in.ID, in.Expected, in.Edits}) |
| + var doc Document |
| + var revision int64 |
| + created := false |
| + err = a.store.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| + if e := a.bind(tx); e != nil { |
| + return e |
| + } |
| + // The target lookup grants no authority; checkEditor performs the complete |
| + // transaction-local identity and current permission check before any body work. |
| + if e := tx.Where("sqid=? AND deleted_at IS NULL", in.ID).First(&doc).Error; e != nil { |
| + return e |
| + } |
| + if e := a.checkEditor(ctx, tx, p, id, doc.ID); e != nil { |
| + return e |
| + } |
| + var receipt agentUpdateReceipt |
| + e := tx.Where("coordinate=?", coordinate).First(&receipt).Error |
| + if e == nil { |
| + if receipt.Content != payload { |
| + return access.Fail("conflict", "This client UUID already names different edits.") |
| + } |
| + if receipt.DocumentID != doc.ID || receipt.Revision <= 0 { |
| + return access.Fail("unavailable", "The edit receipt is inconsistent.") |
| + } |
| + var count int64 |
| + if e = tx.Model(&DocUpdate{}).Where("doc_id=? AND seq=?", doc.ID, receipt.Revision).Count(&count).Error; e != nil { |
| + return e |
| + } |
| + if count != 1 { |
| + return access.Fail("unavailable", "The edit receipt is inconsistent.") |
| + } |
| + revision = receipt.Revision |
| + return a.checkEditor(ctx, tx, p, id, doc.ID) |
| + } |
| + if !errors.Is(e, gorm.ErrRecordNotFound) { |
| + return e |
| + } |
| + store := *a.store |
| + store.db = tx |
| + seq, e := store.currentSeq(ctx, doc.ID) |
| + if e != nil { |
| + return e |
| + } |
| + if seq != expected { |
| + return access.Fail("conflict", "The document body changed. Read it again before editing.") |
| + } |
| + if seq == math.MaxInt64 { |
| + return access.Fail("unavailable", "The document revision limit was reached.") |
| + } |
| + var update []byte |
| + for attempt := 0; attempt < 8; attempt++ { |
| + replayDoc := doc |
| + replayDoc.ClientID = uint64(mrand.Uint32N(math.MaxUint32)) + 1 |
| + h, replayed, _, e := store.replay(ctx, &replayDoc) |
| + if e != nil { |
| + return e |
| + } |
| + if replayed != expected { |
| + h.Close(ctx) |
| + return access.Fail("unavailable", "The document replay is inconsistent.") |
| + } |
| + update, e = h.EditUpdate(ctx, edits) // consumes h, including on collision/refusal |
| + if errors.Is(e, core.ErrEditCollision) { |
| + continue |
| + } |
| + if errors.Is(e, core.ErrEditInvalid) || errors.Is(e, core.ErrEditPending) { |
| + return access.Fail("invalid", "The current document structure or edit coordinates are unsupported.") |
| + } |
| + if errors.Is(e, core.ErrEditTooLarge) { |
| + return access.Fail("too_large", "The document edit exceeds its limit.") |
| + } |
| + if e != nil { |
| + return e |
| + } |
| + break |
| + } |
| + if len(update) == 0 { |
| + return access.Fail("unavailable", "Could not allocate a document editing identity.") |
| + } |
| + revision, e = store.ApplyUpdate(ctx, &doc, id.Actor, update) |
| + if e != nil { |
| + return e |
| + } |
| + sealer, e := seal.New(a.key, "oficina/docs") |
| + if e != nil { |
| + return e |
| + } |
| + purpose := "agent-update-client/" + doc.GUID + "/" + strconv.FormatInt(revision, 10) + "/" + coordinate |
| + client, e := sealer.Seal(purpose, []byte(p.Client)) |
| + if e != nil { |
| + return e |
| + } |
| + if e = tx.Create(&agentUpdateAttribution{doc.ID, revision, id.Actor.PersonID, client}).Error; e != nil { |
| + return e |
| + } |
| + if e = tx.Create(&agentUpdateReceipt{coordinate, payload, doc.ID, revision}).Error; e != nil { |
| + return e |
| + } |
| + if e = a.checkEditor(ctx, tx, p, id, doc.ID); e != nil { |
| + return e |
| + } |
| + created = true |
| + return nil |
| + }) |
| + if err != nil { |
| + return nil, agentFailure(err) |
| + } |
| + if created && a.notify != nil { |
| + a.notify(doc.ID, revision) |
| + } |
| + if guard, ok := ctx.Value(accessContextKey{}).(*requestAccess); ok && guard != nil { |
| + guard.responseDocs[doc.ID] = permissionWrite |
| + } |
| + return agentUpdated{doc.Sqid, a.origin + "/d/" + doc.Sqid, strconv.FormatInt(revision, 10)}, nil |
| +} |
diff --git a/internal/docs/agent_update_authority_test.go b/internal/docs/agent_update_authority_test.go| new file mode 100644 |
| index 0000000..ea9d1b9 |
| --- /dev/null |
| +++ b/internal/docs/agent_update_authority_test.go |
| @@ -0,0 +1,192 @@ |
| +package docs |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "net/http/httptest" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "gorm.io/gorm" |
| +) |
| + |
| +func grantAgentEdit(t *testing.T, f *docAgentFixture, sqid string, role Role) { |
| + t.Helper() |
| + other, e := f.a.store.EnsurePerson(t.Context(), "other@example.com") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + var doc Document |
| + if e = f.a.store.db.Where("sqid=?", sqid).First(&doc).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = f.a.store.db.Model(&doc).Update("owner_id", other).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = f.a.store.db.Create(&Grant{DocID: doc.ID, Subject: subjectOf("owner@example.com"), Role: role, CreatedBy: other}).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| +} |
| +func newTeamEditFixture(t *testing.T) (*docAgentFixture, *teamTestClock) { |
| + t.Helper() |
| + f := newDocAgentFixture(t) |
| + _, clock := configureDocAgentTestTeam(t, f) |
| + // Provision the test's final configuration before it owns any receipt. |
| + if e := f.a.store.db.Exec("DELETE FROM docs_agent_state").Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if e := f.a.store.db.Transaction(func(tx *gorm.DB) error { return f.a.bind(tx) }); e != nil { |
| + t.Fatal(e) |
| + } |
| + return f, clock |
| +} |
| +func TestAgentUpdateIndependentGrantAndRosterAuthority(t *testing.T) { |
| + for _, mode := range []string{"member", "unknown-owner", "unknown-writer", "unknown-reader", "expired-final"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f, clock := newTeamEditFixture(t) |
| + create := initialAgentInput() |
| + create.Team = f.a.team |
| + body := decodeAgentBody(t, f.call(t, "docs_create", create)) |
| + in := editAgentInput(body) |
| + in.Team = f.a.team |
| + if strings.Contains(mode, "writer") { |
| + grantAgentEdit(t, f, body.ID, RoleWriter) |
| + } |
| + if strings.Contains(mode, "reader") { |
| + grantAgentEdit(t, f, body.ID, RoleReader) |
| + } |
| + if strings.HasPrefix(mode, "unknown") { |
| + clock.step(time.Minute) |
| + } |
| + if mode == "expired-final" { |
| + ctx, id, e := f.a.prepareMode(t.Context(), f.p, true, false) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + checks := 0 |
| + ctx.Value(accessContextKey{}).(*requestAccess).delegationCheck = func(context.Context) error { |
| + checks++ |
| + if checks == 2 { |
| + clock.step(time.Minute) |
| + } |
| + return nil |
| + } |
| + if result, e := f.a.update(ctx, f.p, id, in); e == nil || result != nil { |
| + t.Fatal("expired writer committed", result, e) |
| + } |
| + agentEditCounts(t, f, 0) |
| + return |
| + } |
| + want := 200 |
| + if mode == "unknown-owner" || mode == "unknown-reader" { |
| + want = 503 |
| + } |
| + if w := f.call(t, "docs_update", in); w.Code != want { |
| + t.Fatal(mode, w.Code, w.Body.String()) |
| + } |
| + expected := int64(0) |
| + if want == 200 { |
| + expected = 1 |
| + } |
| + agentEditCounts(t, f, expected) |
| + }) |
| + } |
| +} |
| + |
| +func TestAgentUpdateResponseRequiresWritePermission(t *testing.T) { |
| + f := newDocAgentFixture(t) |
| + body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput())) |
| + grantAgentEdit(t, f, body.ID, RoleWriter) |
| + in := editAgentInput(body) |
| + f.a.notify = func(docID, seq int64) { |
| + if e := f.a.store.db.Model(&Grant{}).Where("doc_id=?", docID).Update("role", RoleReader).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + w := f.call(t, "docs_update", in) |
| + if w.Code == 200 || strings.Contains(w.Body.String(), body.ID) { |
| + t.Fatal("read-only response disclosed write acknowledgement", w.Code, w.Body.String()) |
| + } |
| + agentEditCounts(t, f, 1) |
| + // The lost acknowledgement did not roll the committed edit back. |
| + if w = f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID}); w.Code != 200 { |
| + t.Fatal(w.Code) |
| + } |
| + f.a.notify = nil |
| + if e := f.a.store.db.Model(&Grant{}).Where("subject=?", subjectOf("owner@example.com")).Update("role", RoleWriter).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if w = f.call(t, "docs_update", in); w.Code != 200 { |
| + t.Fatal(w.Code, w.Body.String()) |
| + } |
| + agentEditCounts(t, f, 1) |
| +} |
| + |
| +func TestAgentUpdateHeldWriterRechecksBeforeBody(t *testing.T) { |
| + f := newDocAgentFixture(t) |
| + body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput())) |
| + in := editAgentInput(body) |
| + var seq int |
| + var name, path string |
| + if e := f.app.db.Writer().QueryRow("PRAGMA database_list").Scan(&seq, &name, &path); e != nil { |
| + t.Fatal(e) |
| + } |
| + held, e := sql.Open("sqlite", path) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer held.Close() |
| + held.SetMaxOpenConns(1) |
| + if _, e = f.app.db.Writer().Exec("PRAGMA busy_timeout=5000"); e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = f.a.store.db.Exec("CREATE TRIGGER edit_body_trap BEFORE INSERT ON doc_updates BEGIN SELECT RAISE(ABORT,'reserved-check omitted'); END").Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + tx, e := held.BeginTx(t.Context(), nil) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer tx.Rollback() |
| + if _, e = tx.Exec("UPDATE docs_agent_state SET keycheck=keycheck WHERE id=1"); e != nil { |
| + t.Fatal(e) |
| + } |
| + reached := make(chan struct{}) |
| + var once sync.Once |
| + const callback = "edit-held-writer" |
| + if e = f.a.store.db.Callback().Raw().Before("gorm:raw").Register(callback, func(db *gorm.DB) { |
| + if strings.HasPrefix(db.Statement.SQL.String(), "INSERT INTO docs_agent_state") { |
| + once.Do(func() { close(reached) }) |
| + } |
| + }); e != nil { |
| + t.Fatal(e) |
| + } |
| + defer f.a.store.db.Callback().Raw().Remove(callback) |
| + result := make(chan *httptest.ResponseRecorder, 1) |
| + go func() { result <- f.call(t, "docs_update", in) }() |
| + select { |
| + case <-reached: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("writer not reached") |
| + } |
| + select { |
| + case w := <-result: |
| + t.Fatal("request did not wait for writer", w.Code) |
| + case <-time.After(50 * time.Millisecond): |
| + } |
| + f.revoked.Store(true) |
| + if e = tx.Commit(); e != nil { |
| + t.Fatal(e) |
| + } |
| + select { |
| + case w := <-result: |
| + if w.Code != 401 { |
| + t.Fatal("revocation did not precede body trap", w.Code, w.Body.String()) |
| + } |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("request remained blocked") |
| + } |
| + agentEditCounts(t, f, 0) |
| +} |
diff --git a/internal/docs/agent_update_test.go b/internal/docs/agent_update_test.go| new file mode 100644 |
| index 0000000..9d46f80 |
| --- /dev/null |
| +++ b/internal/docs/agent_update_test.go |
| @@ -0,0 +1,260 @@ |
| +package docs |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/home/handoff/seal" |
| + "github.com/carlosframework/docs/internal/core" |
| + "github.com/google/uuid" |
| +) |
| + |
| +func editAgentInput(body agentBody) agentUpdateInput { |
| + return agentUpdateInput{Team: "blue", ID: body.ID, ClientID: uuid.NewString(), Expected: body.Revision, Edits: []agentEdit{{Index: 1, Delete: 1, Blocks: []agentBlock{{Type: "paragraph", Text: "EDITED_PRIVATE_BODY 😀 <script>"}}}}} |
| +} |
| +func agentEditCounts(t *testing.T, f *docAgentFixture, want int64) { |
| + t.Helper() |
| + for _, model := range []any{&agentUpdateReceipt{}, &agentUpdateAttribution{}} { |
| + var count int64 |
| + if e := f.a.store.db.Model(model).Count(&count).Error; e != nil || count != want { |
| + t.Fatal("edit rows", count, want, e) |
| + } |
| + } |
| +} |
| +func TestAgentUpdateRevisionRetryAndEditorPublication(t *testing.T) { |
| + f := newDocAgentFixture(t) |
| + body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput())) |
| + in := editAgentInput(body) |
| + var doc Document |
| + if e := f.a.store.db.Where("sqid=?", body.ID).First(&doc).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + live := newHub() |
| + f.a.notify = live.broadcast |
| + changes, unsubscribe := live.subscribe(doc.ID) |
| + defer unsubscribe() |
| + first := f.call(t, "docs_update", in) |
| + if first.Code != 200 { |
| + t.Fatal(first.Code, first.Body.String()) |
| + } |
| + var ack agentUpdated |
| + if e := json.Unmarshal(first.Body.Bytes(), &ack); e != nil || ack.Revision != "2" || ack.ID != body.ID { |
| + t.Fatal(ack, e) |
| + } |
| + select { |
| + case seq := <-changes: |
| + if seq != 2 { |
| + t.Fatal(seq) |
| + } |
| + default: |
| + t.Fatal("editor not notified") |
| + } |
| + after := decodeAgentBody(t, f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID})) |
| + if after.Revision != "2" || !strings.Contains(after.Text, "EDITED_PRIVATE_BODY") { |
| + t.Fatal(after) |
| + } |
| + // An ordinary editor update enters through the existing domain method. |
| + copy := doc |
| + copy.ClientID = 12345 |
| + h, _, _, e := f.a.store.replay(t.Context(), ©) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + browser, e := h.EditUpdate(t.Context(), []core.BlockEdit{{Index: 1, Delete: 1, Blocks: []core.InitialBlock{{Text: "BROWSER LATER"}}}}) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + id, e := f.a.resolver.resolveHome(t.Context(), f.p.Subject) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = f.a.store.ApplyUpdate(t.Context(), &doc, id.Actor, browser); e != nil { |
| + t.Fatal(e) |
| + } |
| + retried := f.call(t, "docs_update", in) |
| + if retried.Code != 200 || !bytes.Equal(first.Body.Bytes(), retried.Body.Bytes()) { |
| + t.Fatal("retry changed receipt", retried.Code, retried.Body.String()) |
| + } |
| + select { |
| + case <-changes: |
| + t.Fatal("retry notified a new effect") |
| + default: |
| + } |
| + after = decodeAgentBody(t, f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID})) |
| + if after.Revision != "3" || !strings.Contains(after.Text, "BROWSER LATER") { |
| + t.Fatal("retry overwrote browser", after) |
| + } |
| + stale := in |
| + stale.ClientID = uuid.NewString() |
| + if w := f.call(t, "docs_update", stale); w.Code != 409 { |
| + t.Fatal("stale accepted", w.Code, w.Body.String()) |
| + } |
| + changed := in |
| + changed.Expected = "3" |
| + if w := f.call(t, "docs_update", changed); w.Code != 409 { |
| + t.Fatal("changed payload accepted", w.Code) |
| + } |
| + agentEditCounts(t, f, 1) |
| + var receipt agentUpdateReceipt |
| + var attribution agentUpdateAttribution |
| + var update DocUpdate |
| + if e = f.a.store.db.First(&receipt).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = f.a.store.db.First(&attribution).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = f.a.store.db.Where("doc_id=? AND seq=2", doc.ID).First(&update).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if bytes.Contains(update.UpdateBin, []byte("EDITED_PRIVATE_BODY")) || bytes.Contains(attribution.ClientSealed, []byte(f.p.Client)) { |
| + t.Fatal("plaintext stored") |
| + } |
| + sealer, e := seal.New(f.a.key, "oficina/docs") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + plain, e := sealer.Open("agent-update-client/"+doc.GUID+"/2/"+receipt.Coordinate, attribution.ClientSealed) |
| + if e != nil || string(plain) != f.p.Client { |
| + t.Fatal("attribution", string(plain), e) |
| + } |
| + if _, e = sealer.Open("agent-update-client/"+doc.GUID+"/3/"+receipt.Coordinate, attribution.ClientSealed); e == nil { |
| + t.Fatal("attribution coordinate not bound") |
| + } |
| + if e = f.a.store.db.Model(&Document{}).Where("id=?", doc.ID).Update("deleted_at", time.Now()).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if w := f.call(t, "docs_update", in); w.Code != 404 { |
| + t.Fatal("deleted retry", w.Code) |
| + } |
| +} |
| + |
| +func TestAgentUpdateConcurrentAndStaleWrites(t *testing.T) { |
| + for _, same := range []bool{true, false} { |
| + t.Run(strconv.FormatBool(same), func(t *testing.T) { |
| + f := newDocAgentFixture(t) |
| + body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput())) |
| + in := editAgentInput(body) |
| + var wg sync.WaitGroup |
| + results := make(chan int, 4) |
| + for i := 0; i < 4; i++ { |
| + request := in |
| + if !same { |
| + request.ClientID = uuid.NewString() |
| + } |
| + wg.Add(1) |
| + go func() { defer wg.Done(); results <- f.call(t, "docs_update", request).Code }() |
| + } |
| + wg.Wait() |
| + close(results) |
| + success := 0 |
| + for code := range results { |
| + if code == 200 { |
| + success++ |
| + } else if same || code != 409 { |
| + t.Fatal(code) |
| + } |
| + } |
| + if same && success != 4 || !same && success != 1 { |
| + t.Fatal("successes", success) |
| + } |
| + agentEditCounts(t, f, 1) |
| + after := decodeAgentBody(t, f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID})) |
| + if after.Revision != "2" { |
| + t.Fatal(after) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAgentUpdateFinalAuthorityAndStorageRollback(t *testing.T) { |
| + for _, mode := range []string{"revoke", "binding", "receipt", "attribution", "update"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f := newDocAgentFixture(t) |
| + body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput())) |
| + in := editAgentInput(body) |
| + want := 503 |
| + switch mode { |
| + case "revoke": |
| + f.checks.Store(0) |
| + f.revokeAt.Store(3) |
| + want = 401 |
| + case "binding": |
| + want = 403 |
| + if e := f.a.store.db.Exec("CREATE TRIGGER edit_unlink AFTER INSERT ON docs_agent_update_receipts BEGIN UPDATE home_identity_links SET person_binding='corrupt'; END").Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + default: |
| + table := map[string]string{"receipt": "docs_agent_update_receipts", "attribution": "docs_agent_update_attribution", "update": "doc_updates"}[mode] |
| + if e := f.a.store.db.Exec("CREATE TRIGGER edit_fail BEFORE INSERT ON " + table + " BEGIN SELECT RAISE(ABORT,'test edit storage failure'); END").Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + if w := f.call(t, "docs_update", in); w.Code != want { |
| + t.Fatal(w.Code, w.Body.String()) |
| + } |
| + agentEditCounts(t, f, 0) |
| + var count int64 |
| + if e := f.a.store.db.Model(&DocUpdate{}).Count(&count).Error; e != nil || count != 1 { |
| + t.Fatal("body did not roll back", count, e) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAgentUpdateCompletedRetryFinalGuardWithoutHTTP(t *testing.T) { |
| + f := newDocAgentFixture(t) |
| + body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput())) |
| + in := editAgentInput(body) |
| + if w := f.call(t, "docs_update", in); w.Code != 200 { |
| + t.Fatal(w.Code, w.Body.String()) |
| + } |
| + ctx, id, e := f.a.prepareMode(t.Context(), f.p, true, false) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + checks := 0 |
| + ctx.Value(accessContextKey{}).(*requestAccess).delegationCheck = func(context.Context) error { |
| + checks++ |
| + if checks == 2 { |
| + return errIdentityRefused |
| + } |
| + return nil |
| + } |
| + if result, e := f.a.update(ctx, f.p, id, in); result != nil || e == nil || checks != 2 { |
| + t.Fatal("retry bypassed final authority", result, e, checks) |
| + } |
| +} |
| + |
| +func TestAgentUpdateInvalidAndTitleOnlyChange(t *testing.T) { |
| + f := newDocAgentFixture(t) |
| + body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput())) |
| + in := editAgentInput(body) |
| + for _, revision := range []string{"", "01", "-1", "1.0", "9223372036854775808"} { |
| + bad := in |
| + bad.Expected = revision |
| + if w := f.call(t, "docs_update", bad); w.Code != 422 { |
| + t.Fatal(revision, w.Code) |
| + } |
| + } |
| + for _, edits := range [][]agentEdit{{{Index: 20, Delete: 1}}, {{Index: 0, Delete: 2}}, {{Index: 0, Delete: 0, Blocks: []agentBlock{}}}, {{Index: 1, Delete: 1, Blocks: []agentBlock{{Type: "html", Text: "unsafe"}}}}} { |
| + bad := in |
| + bad.Edits = edits |
| + if w := f.call(t, "docs_update", bad); w.Code != 422 { |
| + t.Fatal(edits, w.Code, w.Body.String()) |
| + } |
| + } |
| + agentEditCounts(t, f, 0) |
| + if e := f.a.store.db.Model(&Document{}).Where("sqid=?", body.ID).Update("title", "Renamed only").Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if w := f.call(t, "docs_update", in); w.Code != 200 || strings.Contains(w.Body.String(), "Renamed") { |
| + t.Fatal(w.Code, w.Body.String()) |
| + } |
| +} |
diff --git a/internal/docs/app.go b/internal/docs/app.go| index a409670..c803d36 100644 |
| --- a/internal/docs/app.go |
| +++ b/internal/docs/app.go |
| @@ -782,7 +782,7 @@ func New(cfg Config) (*App, error) { |
| mux := http.NewServeMux() |
| mux.Handle("/", r) |
| if agentVerifier != nil { |
| - agentHandler, e := newDocumentAgent(cfg, homeSettings, home, store, list, agentVerifier) |
| + agentHandler, e := newDocumentAgent(cfg, homeSettings, home, store, list, agentVerifier, h.hub.broadcast) |
| if e != nil { |
| rt.Close(context.Background()) |
| d.Close() |
diff --git a/internal/docs/migrations/0010_agent_document_edits.sql b/internal/docs/migrations/0010_agent_document_edits.sql| new file mode 100644 |
| index 0000000..5b4a060 |
| --- /dev/null |
| +++ b/internal/docs/migrations/0010_agent_document_edits.sql |
| @@ -0,0 +1,13 @@ |
| +CREATE TABLE docs_agent_update_receipts ( |
| + coordinate TEXT PRIMARY KEY NOT NULL, |
| + content TEXT NOT NULL, |
| + document_id INTEGER NOT NULL, |
| + revision INTEGER NOT NULL CHECK(revision > 0) |
| +); |
| +CREATE TABLE docs_agent_update_attribution ( |
| + document_id INTEGER NOT NULL, |
| + revision INTEGER NOT NULL CHECK(revision > 0), |
| + operator_id INTEGER NOT NULL, |
| + client_sealed BLOB NOT NULL, |
| + PRIMARY KEY(document_id, revision) |
| +); |
diff --git a/scripts/wire-gate.sh b/scripts/wire-gate.sh| index 9622315..effe860 100755 |
| --- a/scripts/wire-gate.sh |
| +++ b/scripts/wire-gate.sh |
| @@ -21,5 +21,6 @@ echo "--- JS reads what Rust wrote" |
| (cd core && cargo run --quiet --locked --bin emit_update) | node fixtures/verify-rust.mjs |
| (cd core && cargo run --quiet --locked --bin emit_initial) | node fixtures/verify-initial.mjs |
| +node fixtures/verify-edit.mjs |
| echo "wire-gate: ok" |