oficina / docs Public

Merge origin/main (5039cf6, delegated agent access) into feat/suite-producer

Conflicts: app.go (both add handlers after the router: the agent API's
/api/v1/operations and the suite's three routes, kept both) and
internal/shipped FirstParty (agent-access.git and suite, kept both).

Reconciled: main's 0009_agent_access and 0010_agent_document_edits take
those numbers, so the suite migration becomes 0011_suite.sql (it is
unmerged and undeployed; references renamed, the pre-suite restore test
cuts before 0011). TestAgentDocumentPagesUseCurrentPermissionAndExactCursor
made its "Private foreign title" with Store.Create, which is now the team
rung; it is created private, as every isolation test on this branch is.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 48e4cebee7012d3b3153c5ec9b1068d0a70cf86c parent 65acd67parent 5039cf6
50 files changed, +4,273 −46
  • .amadan/ci.d/10-gate +1 −1
  • cmd/docs-contract/main.go +22 −0
  • cmd/docs/main.go +2 −0
  • core/src/abi.rs +51 −0
  • core/src/bin/emit_edit.rs +22 −0
  • core/src/bin/emit_initial.rs +18 −0
  • core/src/edit.rs +152 −0
  • core/src/initial.rs +61 −0
  • core/src/lib.rs +6 −1
  • core/tests/edit.rs +137 −0
  • core/tests/initial.rs +62 −0
  • docs/agent-access.md +67 −0
  • docs/superpowers/plans/2026-11-01-agent-document-editing.md +12 −0
  • docs/superpowers/specs/2026-10-25-agent-access.md +187 −0
  • docs/superpowers/specs/2026-11-01-agent-document-editing.md +257 −0
  • fixtures/verify-edit.mjs +42 −0
  • fixtures/verify-initial.mjs +16 −0
  • go.mod +16 −3
  • go.sum +48 −10
  • internal/core/core.go +1 −1
  • internal/core/edit.go +99 −0
  • internal/core/edit_test.go +63 −0
  • internal/core/initial.go +67 −0
  • internal/core/initial_test.go +63 −0
  • internal/core/testdata/docs_core.wasm binary
  • internal/docs/agent_access.go +265 −0
  • internal/docs/agent_access_test.go +610 −0
  • internal/docs/agent_integration_test.go +177 −0
  • internal/docs/agent_main_compat_test.go +323 −0
  • internal/docs/agent_store.go +371 −0
  • internal/docs/agent_suite_interop_test.go +87 −0
  • internal/docs/agent_update.go +248 −0
  • internal/docs/agent_update_authority_test.go +192 −0
  • internal/docs/agent_update_test.go +260 −0
  • internal/docs/app.go +17 −1
  • internal/docs/colophon.json +99 −0
  • internal/docs/identity.go +32 −0
  • internal/docs/migrations/0009_agent_access.sql +15 −0
  • internal/docs/migrations/0010_agent_document_edits.sql +13 −0
  • internal/docs/migrations/{0009_suite.sql => 0011_suite.sql} +0 −0
  • internal/docs/models.go +2 −2
  • internal/docs/store.go +4 −4
  • internal/docs/store_test.go +2 −1
  • internal/docs/suite_feed.go +1 −1
  • internal/docs/suite_test.go +13 −13
  • internal/docs/team_access.go +3 −0
  • internal/docs/team_emission.go +9 −2
  • internal/docs/team_emission_test.go +48 −0
  • internal/shipped/shipped.go +7 −6
  • scripts/wire-gate.sh +3 −0
diff --git a/.amadan/ci.d/10-gate b/.amadan/ci.d/10-gate
index d51334e..6393361 100755
--- a/.amadan/ci.d/10-gate
+++ b/.amadan/ci.d/10-gate
@@ -18,7 +18,7 @@ rustup target list --installed 2>/dev/null | grep -qx wasm32-unknown-unknown \
|| { echo "gate: wasm32-unknown-unknown target missing β€” rustup target add wasm32-unknown-unknown" >&2; exit 1; }
export CGO_ENABLED=0
-export GOPRIVATE="${GOPRIVATE:+$GOPRIVATE,}amadan.net/oficina/estilo.git"
+export GOPRIVATE="${GOPRIVATE:+$GOPRIVATE,}amadan.net/oficina/estilo.git,amadan.net/oficina/agent-access.git"
# The runner clones a fresh worktree per branch, so fixtures/node_modules
# (gitignored, like any node_modules) never carries over from a previous
diff --git a/cmd/docs-contract/main.go b/cmd/docs-contract/main.go
new file mode 100644
index 0000000..6dc3f37
--- /dev/null
+++ b/cmd/docs-contract/main.go
@@ -0,0 +1,22 @@
+// Command docs-contract exports the live delegated operation schemas.
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "github.com/carlosframework/docs/internal/docs"
+ "os"
+)
+
+func main() {
+ operations, err := docs.AgentContracts()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Could not export Docs operation contracts.")
+ os.Exit(1)
+ }
+ encoder := json.NewEncoder(os.Stdout)
+ encoder.SetIndent("", " ")
+ if encoder.Encode(operations) != nil {
+ os.Exit(1)
+ }
+}
diff --git a/cmd/docs/main.go b/cmd/docs/main.go
index 39debaa..e5ae0ad 100644
--- a/cmd/docs/main.go
+++ b/cmd/docs/main.go
@@ -274,6 +274,8 @@ func main() {
// β€” otherwise Serve would open a second connection to the file New
// already owns.
cfg := docs.Config{
+ AgentIssuer: os.Getenv("DOCS_AGENT_ISSUER"),
+ AgentTeam: os.Getenv("DOCS_AGENT_TEAM"),
DBPath: opts.DBPath,
ContentKey: os.Getenv("DOCS_CONTENT_KEY"),
Env: env,
diff --git a/core/src/abi.rs b/core/src/abi.rs
index b86b56e..48d5f62 100644
--- a/core/src/abi.rs
+++ b/core/src/abi.rs
@@ -499,3 +499,54 @@ pub unsafe extern "C" fn docs_core_verify_snapshot(handle: u32, ptr: u32, len: u
}
}
}
+
+/// Initialize a fresh document from bounded plain-text blocks.
+///
+/// # Safety
+/// `ptr` and `len` must describe memory that is not concurrently mutated.
+/// Bounds and UTF-8 are checked before constructing any document content.
+#[no_mangle]
+pub unsafe extern "C" fn docs_core_initialize(handle: u32, ptr: u32, len: u32) -> i32 {
+ if !in_bounds(ptr, len) {
+ return ERR_INVALID_LENGTH;
+ }
+ let input = std::slice::from_raw_parts(ptr as *const u8, len as usize);
+ match get_doc(handle) {
+ None => ERR_NO_DOC,
+ Some(doc) => match crate::initial::initialize(&doc, input) {
+ Ok(()) => 0,
+ Err(_) => ERR_APPLY,
+ },
+ }
+}
+
+/// 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/bin/emit_initial.rs b/core/src/bin/emit_initial.rs
new file mode 100644
index 0000000..5583d88
--- /dev/null
+++ b/core/src/bin/emit_initial.rs
@@ -0,0 +1,18 @@
+use std::io::Write;
+use yrs::{Doc, Options};
+fn main() {
+ let doc = Doc::with_options(Options::with_guid_and_client_id(
+ "initial-wire".into(),
+ u32::MAX as u64,
+ ));
+ let mut input = Vec::new();
+ for (level, text) in [(2u8, "Agenda πŸ˜€"), (0, "<script>& CafΓ©\n二")] {
+ input.push(level);
+ input.extend_from_slice(&(text.len() as u32).to_be_bytes());
+ input.extend_from_slice(text.as_bytes());
+ }
+ docs_core::initial::initialize(&doc, &input).unwrap();
+ std::io::stdout()
+ .write_all(&docs_core::snapshot_bytes(&doc))
+ .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/initial.rs b/core/src/initial.rs
new file mode 100644
index 0000000..b2a1110
--- /dev/null
+++ b/core/src/initial.rs
@@ -0,0 +1,61 @@
+//! Bounded initial content, constructed by yrs rather than a second wire encoder.
+use yrs::branch::{Branch, BranchPtr};
+use yrs::{
+ Any, Doc, Map, MapRef, ReadTxn, Transact, XmlElementPrelim, XmlElementRef, XmlFragment,
+ XmlTextPrelim,
+};
+
+// Private ABI encoding: repeated [level:u8, utf8_length:u32 big endian, text].
+// Level 0 is a paragraph; 1..6 is a heading. Parse everything before mutation.
+pub fn initialize(doc: &Doc, input: &[u8]) -> Result<(), &'static str> {
+ if doc.client_id() > u32::MAX as u64 {
+ return Err("client id limit");
+ }
+ if input.len() > 128 * 1024 + 200 * 5 {
+ return Err("input limit");
+ }
+ let mut rest = input;
+ let mut blocks = Vec::new();
+ let mut total = 0;
+ while !rest.is_empty() {
+ if blocks.len() == 200 || rest.len() < 5 || rest[0] > 6 {
+ return Err("invalid block");
+ }
+ let level = rest[0];
+ let n = u32::from_be_bytes(rest[1..5].try_into().unwrap()) as usize;
+ rest = &rest[5..];
+ if n > rest.len() {
+ return Err("invalid length");
+ }
+ total += n;
+ if total > 128 * 1024 {
+ return Err("text limit");
+ }
+ let text = std::str::from_utf8(&rest[..n]).map_err(|_| "invalid utf8")?;
+ blocks.push((level, text));
+ rest = &rest[n..];
+ }
+ if !doc.transact().state_vector().is_empty() {
+ return Err("document is not empty");
+ }
+ let root = doc.get_or_insert_xml_fragment(crate::FRAGMENT_ROOT);
+ let mut txn = doc.transact_mut();
+ for (level, text) in blocks {
+ let tag = if level == 0 { "paragraph" } else { "heading" };
+ let node = root.push_back(&mut txn, XmlElementPrelim::empty(tag));
+ if level > 0 {
+ // ProseMirror requires a NUMBER. yrs' XML convenience setter stores
+ // strings, so use the same branch attribute map with a typed value.
+ 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));
+ }
+ }
+ Ok(())
+}
diff --git a/core/src/lib.rs b/core/src/lib.rs
index e5fb37e..8efefd3 100644
--- a/core/src/lib.rs
+++ b/core/src/lib.rs
@@ -54,7 +54,9 @@
//! 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;
pub use fragment::{fragment_html, fragment_json, fragment_text, ROOT as FRAGMENT_ROOT};
pub use snapshot::{snapshot_bytes, verify_snapshot};
@@ -86,6 +88,9 @@ extern "Rust" fn __getrandom_v03_custom(
/// version has already shipped forces its own bump regardless, for the
/// 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
/// not forced by the wasm itself. It is forced by the host: the module
@@ -98,7 +103,7 @@ extern "Rust" fn __getrandom_v03_custom(
/// here.
#[no_mangle]
pub extern "C" fn docs_core_abi_version() -> u32 {
- 4
+ 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/core/tests/initial.rs b/core/tests/initial.rs
new file mode 100644
index 0000000..6a66e40
--- /dev/null
+++ b/core/tests/initial.rs
@@ -0,0 +1,62 @@
+use docs_core::{fragment_html, fragment_json, fragment_text, initial::initialize, snapshot_bytes};
+use yrs::{Doc, Options};
+
+fn doc() -> Doc {
+ Doc::with_options(Options::with_guid_and_client_id("initial-test".into(), 71))
+}
+fn block(level: u8, text: &[u8]) -> Vec<u8> {
+ let mut out = vec![level];
+ out.extend_from_slice(&(text.len() as u32).to_be_bytes());
+ out.extend_from_slice(text);
+ out
+}
+#[test]
+fn initial_content_is_real_structured_literal_text() {
+ let d = doc();
+ let mut input = block(2, "Agenda πŸ˜€".as_bytes());
+ input.extend(block(0, "<script>& Café\n二".as_bytes()));
+ initialize(&d, &input).unwrap();
+ assert!(fragment_html(&d).contains("<h2>Agenda πŸ˜€</h2>"));
+ assert!(fragment_html(&d).contains("&lt;script&gt;&amp; CafΓ©"));
+ assert!(fragment_text(&d).contains("<script>& Café\n二"));
+ let json: serde_json::Value = serde_json::from_str(&fragment_json(&d)).unwrap();
+ assert_eq!(json["content"][0]["attrs"]["level"], 2);
+ assert_eq!(json["content"][1]["type"], "paragraph");
+ let before = snapshot_bytes(&d);
+ assert!(initialize(&d, &block(0, b"replacement")).is_err());
+ assert_eq!(before, snapshot_bytes(&d));
+}
+#[test]
+fn initial_rejection_never_leaves_partial_content() {
+ let mut cases = vec![
+ block(7, b"bad"),
+ block(0, &[0xff]),
+ vec![0, 0, 0],
+ block(0, &vec![b'x'; 128 * 1024 + 1]),
+ ];
+ let mut many = Vec::new();
+ for _ in 0..201 {
+ many.extend(block(0, b""));
+ }
+ cases.push(many);
+ for invalid in cases {
+ let d = doc();
+ let before = snapshot_bytes(&d);
+ let mut input = block(0, b"valid prefix");
+ input.extend(invalid);
+ assert!(initialize(&d, &input).is_err());
+ assert_eq!(snapshot_bytes(&d), before);
+ }
+}
+
+#[test]
+fn initial_rejects_client_ids_outside_yjs_range() {
+ for client_id in [u32::MAX as u64 + 1, (1u64 << 63) - 1] {
+ let d = Doc::with_options(Options::with_guid_and_client_id(
+ "unsafe-id".into(),
+ client_id,
+ ));
+ assert!(initialize(&d, &block(0, b"unchanged")).is_err());
+ assert!(fragment_text(&d).is_empty());
+ }
+}
diff --git a/docs/agent-access.md b/docs/agent-access.md
new file mode 100644
index 0000000..bcb1696
--- /dev/null
+++ b/docs/agent-access.md
@@ -0,0 +1,67 @@
+# Delegated Docs access
+
+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.
+Addressless Home-only people retain browser access but are not supported by this
+initial agent adapter.
+
+Set `DOCS_AGENT_ISSUER` to the connection service HTTPS origin and
+`DOCS_AGENT_TEAM` to the instance team. Both are required together with the
+existing Home configuration. In team mode the team must match its provisioned
+binding. The verifier expects this app's exact origin plus `/api/v1` as audience
+and the configured Home issuer as identity authority. Browser login and native
+routes retain their existing guards.
+
+Export deployment contracts with `go run ./cmd/docs-contract`. The protected
+endpoints are `GET /api/v1/operations` and
+`POST /api/v1/operations/{name}`. App credentials come from the connection
+service; cookies and personal browser sessions do not authenticate this API.
+
+Create requires activated content sealing and a nonzero canonical UUID
+`client_id`. Supply a title and up to 200 literal paragraph/heading blocks, with
+128 KiB of text total. Paragraphs have `type: paragraph` and `text`; headings
+have `type: heading`, `text` and `level` from 1 to 6. Reuse the UUID only to retry
+the identical initial content. A successful response contains the document ID,
+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`.
+
+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
+to make retries appear new. Enabling access does not activate or convert legacy
+content storage. All content writes use the existing sealed collaborative core.
+
+See the reviewed design in
+[the agent access spec](superpowers/specs/2026-10-25-agent-access.md). This branch
+is not a claim of deployment or live client certification.
+
+October 30 compatibility: this branch includes main's one-way adoption of
+Docs links into `home_identity_links`. Use the normal boot migration; never
+restore the retired tables or deploy the October 25 binary over a migrated
+store. Agent admission, writer checks and response chunks use the shared keyed
+binding resolver. Completed retries repeat final authority checks. In team mode,
+`docs_list` returns 503 while standing is Unknown because its schema has no
+partial-result indicator; `docs_get` can still read an explicit share.
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-10-25-agent-access.md b/docs/superpowers/specs/2026-10-25-agent-access.md
new file mode 100644
index 0000000..ff0354c
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-25-agent-access.md
@@ -0,0 +1,187 @@
+# Delegated document operations
+
+Status: approved for implementation planning by GPT-6 Astra after independent
+review against baseline 5a4f6de. Source review, full CI and deployed verification
+remain separate gates. Paul
+requested one Oficina browser grant across apps, authorized a temporary Oficina
+transport pending Rastrillo, and selected CLI, Paseo, ChatGPT and Claude clients.
+
+## Boundary
+
+Opt in with DOCS_AGENT_ISSUER and DOCS_AGENT_TEAM, requiring configured Home.
+Refuse partial configuration before storage. Mount bearer-only operation routes
+outside browser sessions and CSRF, without changing native or browser routes.
+Verify each credential online for this exact app origin plus /api/v1. The
+credential introspection must include `identity_issuer`, supplied from the
+connection runtime's fixed HomeIssuer configuration. Require an exact match with
+Docs' configured Home issuer before any identity lookup. The connection service
+issuer is a different origin and must not be substituted. In team mode also
+require DOCS_AGENT_TEAM to equal the configured team binding. The opaque Home
+subject resolves through the existing local link/principal path;
+never EnsurePerson, EnsureHome, address matching, or synthetic browser cookies.
+Recheck current admission, configured team, scope and document permission on
+execution. Team-mode epoch/response guards remain part of the authorization
+path, including a final check before returning content. A Docs-local HTTP
+adapter establishes requestAccess, dispatches through the shared Registry.Call,
+serializes a bounded response, registers every returned document and required
+permission in responseDocs, and emits through writeGuardedBody on the actual
+response writer. It preserves lease deadlines and transfer-abort behavior;
+shared Registry.HTTP's direct JSON writer is not used for content responses.
+
+The first operations are docs_list and docs_get (docs:read), and docs_create
+(docs:write). List returns public Sqid identifiers, title, URL and updated_at, with default
+20/maximum 100 items ordered by (updated_at DESC, id DESC). An opaque base64url
+cursor contains the last returned timestamp and exact decimal database ID; both
+are validated and bound to that ordering. Apply current ListFor permission SQL
+before pagination. It is a current view, not a snapshot across requests.
+
+Create returns a bounded summary (public Sqid, title, URL, updated_at) and
+body_revision; it does not echo the initial body. This keeps the maximum valid
+input retryable even when JSON escaping expands content. Get returns public Sqid, title, URL, body_revision (decimal string), plain text
+and ProseMirror JSON from a single replay handle. body_revision is that replay's
+sequence; it versions body updates, not title renames. Never separately query
+currentSeq to label an earlier replay. The maximum encoded operation result is
+1 MiB (inside the shared transport's 2 MiB limit); oversize fails explicitly with
+no truncation. A replay sequence remains coherent even if the browser updates
+the document before emission. Item refusals retain Docs' 404 policy. A read
+failure never becomes empty content.
+
+## Creation and content
+
+Create accepts a title, nonzero UUID client_id and a bounded list of plain
+paragraph/heading blocks (at most 200 blocks, 128 KiB text total; heading levels
+1 through 6). Text is literal text, not HTML, Markdown or executable content.
+This is an initial content contract, not a claim that arbitrary document editing
+or Markdown import exists. No tool asks an agent to construct CRDT bytes.
+
+Add a small core primitive to produce initial ProseMirror XML fragment content
+from these validated blocks using the pinned yrs implementation. Preserve the
+root name and native editor schema. Supply GUID/client IDs from Go, never yrs
+entropy. A new wasm export requires an ABI version bump and regenerated wasm;
+test the resulting update with the existing JavaScript/Yjs wire gate and the
+real document renderer. Parse and validate the whole payload before mutation;
+refuse malformed UTF-8, invalid blocks and oversized output without a partial
+core mutation. Do not add a second CRDT encoder in Go or invoke node at runtime.
+
+Creation shares the existing document creation/store machinery. Metadata,
+initial update, attribution and receipt commit together after taking the SQLite
+writer reservation. Recheck current create authority inside the write and before
+returning a success. Outside team mode, creation requires the configured member
+allowlist; admission through an explicit document grant alone does not suffice.
+In team mode use current member authority from the existing roster lease. Use the existing content-sealing path and row AAD. Agent
+writes require activated sealed-content storage; legacy mode refuses them with
+an explicit unavailable failure. Enabling the adapter does not convert, scrub
+or change the database's content encoding state.
+
+Receipt coordinates bind identity issuer, delegation issuer, Home subject,
+OAuth client, selected team and UUID
+with a purpose-separated keyed digest derived from the stable Home integration
+key. Fingerprint the complete validated title and ordered block payload using a
+separate domain-separated HMAC over a canonical JSON encoding of a fixed typed
+struct (title plus ordered blocks, with explicit type/text/heading level).
+Neither coordinate nor payload fingerprint is an unkeyed hash. Persist a
+purpose-separated HMAC keycheck over a fixed public marker and the configured
+identity issuer, delegation issuer and team in adapter state
+on first enablement, under the SQLite writer reservation. On each startup and
+agent write, compare the derived keycheck before any receipt lookup; key or
+authority configuration mismatch
+refuses agent writes until an explicit operator-led migration. Never silently
+reset or replace that state.
+Only digests and document ID enter the receipt table. Changed retries conflict;
+identical retries recheck current access and return the existing document. A
+trashed/deleted document is never recreated by replay. Initial content is never
+reapplied on retry, including after a person edits it in the browser. Retain
+receipts across process restarts; key changes cannot be presented as safe retries.
+
+Document titles remain plaintext metadata under the existing content-sealing
+spec; this adapter does not change that explicit exception. Bodies stay sealed
+in updates/snapshots, and never enter logs, central grant storage or receipts.
+Attribution records the verified operator and an identifiable delegated client
+without turning the client into an app person or locally minted agent token.
+
+## Initial exclusions and convergence
+
+No append/replace operation until its revision/precondition and collaborative
+update behavior has its own reviewed implementation. Sharing, deletion,
+comments, export files and invitations are separate capability work. Existing
+browser/native editing and history remain authoritative. The shared Oficina
+registry exports the same schemas for HTTP, CLI and MCP; the app owns domain
+checks and content handling when the transport later moves to Rastrillo.
+
+## Required evidence
+
+Use a real linked Home identity and real SQLite/core: browser-created documents
+remain readable through current grants; unlinked, revoked delegation or lost applicable authority, wrong-team,
+wrong-scope and foreign-document requests refuse without provisioning anything.
+Explicit document grants can preserve access independently of ownership
+membership, exactly as the current app permits. Test identity-issuer mismatch
+before local lookup, team binding mismatch, revocation after invocation and
+during emission, coherent replay sequence under concurrent browser updates,
+malformed cursors and oversized reads. Test restart, changed receipt key and changed identity/delegation namespaces,
+create, concurrent retries, changed payload, deleted replay, retry after a
+browser edit, rollback on initial-update/receipt failure, and explicit legacy
+storage refusal. Confirm body canaries are absent from database, WAL, receipts
+and logs. Exercise core bounds, Unicode, literal HTML-like text, Yjs wire parity
+and existing renderer/export output. Run actual app operations through the
+shared gateway/API/MCP fixture. Every new gate must fail under a material
+mutation for the intended reason. Full repository CI and highest-capability
+whole-branch review remain separate from spec approval and deployment.
+
+## Initial-content core review (2026-10-25)
+
+GPT-6 Astra reviewed and approved the first core slice after its finding about
+JavaScript-unsafe client IDs was fixed: newly allocated IDs are nonzero uint32,
+and the initializer refuses larger IDs. This approval covers the content
+initializer, ABI 5 and wire fixture, not the pending app adapter or whole branch.
+Native Rust and Go/Wasm tests, real Yjs/ProseMirror parity and canonical Docker
+Wasm generation passed. Seven material mutations failed their intended gates:
+heading bounds, block count, total bytes, reinitialization, unsafe client ID,
+unsafe document allocation and discarded initial update. Full local CI reached
+the existing release-launch test and hit macOS's temporary socket path limit;
+rerun with TMPDIR=/tmp. Full CI and whole-branch review remain required.
+
+## Adapter review progress (2026-10-25)
+
+GPT-6 Astra's early source review found five issues, now corrected and covered:
+reverify delegation after reserving the writer and before commit; export common
+contracts across teams and enforce the target team at invocation; reject lossy
+raw JSON Unicode; return a bounded create summary; preserve recoverable client
+attribution sealed separately from digest-only receipts. The revised source
+review found no further blocker. This is not final whole-branch approval.
+
+Actual linked identity, sealed SQLite/core, concurrent retries, browser-edit
+retry, deletion, transactional failure/unlink/revocation, authority-key restart,
+foreign-document filtering, exact pagination, team-epoch refusal/partial abort,
+and independent explicit grants pass focused tests. A real HTTPS grant service,
+shared CLI/gateway and official MCP client create/read/retry Docs and revoke an
+already-open MCP connection through CLI logout. Twelve effective mutations fail
+the intended gates. A first legacy-storage mutation survived because the test
+was still using an activated database; a genuine legacy fixture corrected the
+test, and the same mutation now fails. Full CI and deployed verification remain
+separate gates.
+
+## October 30 compatibility amendment
+
+Plan independently approved by GPT-6 Astra against main 7d218bd; final source
+and deployed review remain separate gates. Main replaces Docs' private Home
+links with shared `home/connect` adoption and moves standing into `teammode`.
+Preserve its boot migration, identity namespaces, ordinary browser Home-only
+resolution, historical schema ledgers and core rendering changes.
+
+The first agent adapter is existing-linked-account-only. Every admission,
+response check and transaction check uses the shared complete keyed binding;
+inside a writer it uses `Bridge.ResolveOn` on that writer, with no HomeOnly hook
+or second SQL connection. Captured actor/address must remain identical. Shared
+identity resolution never substitutes for current app admission or standing.
+Use one request's latched `teammode.Access`, carried with `withAccess`, including
+inside writes. Completed retries repeat final delegation/identity/admission
+checks before the transaction returns. Unknown standing refuses `docs_list`
+with 503, including nonempty shares and lease loss during emission, because the
+schema has no partial-result notice; explicit-share document reads remain valid.
+Non-team empty lists and discovery do not require roster standing.
+
+Regenerate canonical Wasm from combined source, retaining ABI 5 initialization.
+Tests cover real legacy adoption/reopen/retries, ownership and grants, Home-only
+refusal without allocation, keyed-binding corruption/rollback/emission,
+completed-retry final authority, Unknown lists versus exact shares, and the
+existing HTTPS CLI/MCP fixture. Do not erase receipt markers or retry state.
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/fixtures/verify-initial.mjs b/fixtures/verify-initial.mjs
new file mode 100644
index 0000000..c73d421
--- /dev/null
+++ b/fixtures/verify-initial.mjs
@@ -0,0 +1,16 @@
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import * as Y from 'yjs'
+import { yXmlFragmentToProseMirrorRootNode } from 'y-prosemirror'
+import { schema } from 'prosemirror-schema-basic'
+const doc = new Y.Doc()
+Y.applyUpdate(doc, fs.readFileSync(0))
+const root = yXmlFragmentToProseMirrorRootNode(doc.getXmlFragment('prosemirror'), schema)
+root.check()
+assert.equal(root.childCount, 2)
+assert.equal(root.child(0).type.name, 'heading')
+assert.equal(root.child(0).attrs.level, 2)
+assert.equal(root.child(0).textContent, 'Agenda πŸ˜€')
+assert.equal(root.child(1).type.name, 'paragraph')
+assert.equal(root.child(1).textContent, '<script>& Café\n二')
+console.log('initial content: real Yjs/ProseMirror parity passed')
diff --git a/go.mod b/go.mod
index 955a72b..85516d6 100644
--- a/go.mod
+++ b/go.mod
@@ -3,7 +3,9 @@ module github.com/carlosframework/docs
go 1.26.5
require (
- amadan.net/oficina/estilo.git v0.0.0-20261026205409-aa90aaceb796
+ amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000
+ amadan.net/oficina/estilo.git v0.0.0-20261030224852-1348c4b3b407
+ amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542
amadan.net/oficina/home/dashboard v0.0.0-20261024235511-baa2503c7064
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489
amadan.net/oficina/home/roster v0.0.0-20261030153823-602f5136f9af
@@ -19,35 +21,46 @@ require (
github.com/go-text/typesetting v0.3.6-0.20261020210405-a4cf8f401e16
github.com/google/uuid v1.6.0
github.com/keymaildev/signin v0.1.1
+ github.com/modelcontextprotocol/go-sdk v1.7.0
github.com/tetratelabs/wazero v1.12.0
golang.org/x/image v0.23.0
+ golang.org/x/oauth2 v0.35.0
golang.org/x/text v0.39.0
gorm.io/gorm v1.31.2
- modernc.org/sqlite v1.55.0
)
require (
- amadan.net/oficina/home/connect v0.0.0-20261030153823-602f5136f9af // indirect
amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect
github.com/BurntSushi/toml v1.6.0 // indirect
github.com/chromedp/sysutil v1.1.0 // indirect
+ github.com/danieljoos/wincred v1.2.3 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.4.0 // indirect
+ github.com/godbus/dbus/v5 v5.2.2 // indirect
+ github.com/gofrs/flock v0.12.1 // indirect
+ github.com/google/jsonschema-go v0.4.3 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
+ github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
+ github.com/segmentio/asm v1.1.3 // indirect
+ github.com/segmentio/encoding v0.5.4 // indirect
+ github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
+ github.com/zalando/go-keyring v0.2.8 // indirect
golang.org/x/mod v0.37.0 // indirect
golang.org/x/sync v0.21.0 // indirect
golang.org/x/sys v0.46.0 // indirect
+ golang.org/x/time v0.15.0 // indirect
golang.org/x/tools v0.47.0 // indirect
gorm.io/plugin/dbresolver v1.6.2 // indirect
modernc.org/libc v1.74.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
+ modernc.org/sqlite v1.55.0 // indirect
)
tool amadan.net/rastrillo/rastrillo/cmd/rastrillo
diff --git a/go.sum b/go.sum
index 3a959b9..e530b99 100644
--- a/go.sum
+++ b/go.sum
@@ -1,19 +1,19 @@
+amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000 h1:L07nc+dmLI7c1PBkSkbnrjOK5f8p6OBbA/yTxznxCAw=
+amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000/go.mod h1:Ph9PIa3VE1IEaUzZiQH6D+IQ6HThWWGfVr0ecMMgrFA=
amadan.net/oficina/estilo.git v0.0.0-20261026205409-aa90aaceb796 h1:yj3d1pKgMbZ3e+7zTf+SWdGYux4E0hhnCOr4YJxH9VE=
amadan.net/oficina/estilo.git v0.0.0-20261026205409-aa90aaceb796/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
-amadan.net/oficina/home/connect v0.0.0-20261028165624-d942439ac4e4 h1:WQ4irMKZerybbbccJblyukiloZZ9zfIxcay4vVyVowU=
-amadan.net/oficina/home/connect v0.0.0-20261028165624-d942439ac4e4/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk=
-amadan.net/oficina/home/connect v0.0.0-20261030153823-602f5136f9af h1:jAQ3F8iqqR+z3dnkzmcMmPadX6vZ82adqGlGQMh0GkM=
-amadan.net/oficina/home/connect v0.0.0-20261030153823-602f5136f9af/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk=
+amadan.net/oficina/estilo.git v0.0.0-20261030224824-b8cad3fddfdb h1:hKhThGbsGfIiFLlFv7PeycDip0wy1J/9izkc0rC8ICM=
+amadan.net/oficina/estilo.git v0.0.0-20261030224824-b8cad3fddfdb/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
+amadan.net/oficina/estilo.git v0.0.0-20261030224852-1348c4b3b407 h1:lpD4zWYtPc77ZNpYXk54+AqQ66i5kLIP2XGa40r1Nmw=
+amadan.net/oficina/estilo.git v0.0.0-20261030224852-1348c4b3b407/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
+amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542 h1:b2JT0B0Y+5sTsCmVhX6cywCRdGd9s3lRP8wpqOytlbM=
+amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk=
amadan.net/oficina/home/dashboard v0.0.0-20261024235511-baa2503c7064 h1:2YbDksZDxpY9khlhXmTeiM89yze7w2XfYSumtrzH4tc=
amadan.net/oficina/home/dashboard v0.0.0-20261024235511-baa2503c7064/go.mod h1:+7xsX+QyVFrKy5gDAGh+FZ5+75z4CibWTL0wl9DWAw0=
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 h1:RPKtyry/71i06o8L+gjAaUyexbmG56kO1YPs601URAM=
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k=
-amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2 h1:yKUTS0nOiVw7ktHpTin0bCcUDLFjmMjpW6CsHIZzZKk=
-amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg=
amadan.net/oficina/home/roster v0.0.0-20261030153823-602f5136f9af h1:YtDEq1YUm87/v6XtP6+V32g9U3KDvKos1SdXsnOxA6A=
amadan.net/oficina/home/roster v0.0.0-20261030153823-602f5136f9af/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg=
-amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2 h1:0PQiRUkC+9cbTHE67Y4/SmW1sPH1NNWNwTceNFyMjTY=
-amadan.net/oficina/home/teammode v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:dXBZeB2ic33SIZiGUCzafmviUT8TYWgzSYZvo2rM6zA=
amadan.net/oficina/home/teammode v0.0.0-20261030153823-602f5136f9af h1:QsC+WKvYxiKipS3+J4D9YWRmKQ+cJJTevlH6kP8UVhA=
amadan.net/oficina/home/teammode v0.0.0-20261030153823-602f5136f9af/go.mod h1:dXBZeB2ic33SIZiGUCzafmviUT8TYWgzSYZvo2rM6zA=
amadan.net/oficina/suite v0.0.0-20261101215835-c38e3ad85990 h1:LXUZq/L5aJ700z9A//W5G04O/lxsUSRZrBK1mrBEIP4=
@@ -34,6 +34,12 @@ github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZ
github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo=
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
+github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
+github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
+github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
@@ -52,8 +58,16 @@ github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
-github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
-github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
+github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
+github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
+github.com/gofrs/flock v0.12.1 h1:MTLVXXHf8ekldpJk3AKicLij9MdwOWkZ+a/jHHZby9E=
+github.com/gofrs/flock v0.12.1/go.mod h1:9zxTsyu5xtJ9DK+1tFZyibEV7y3uwDxPPfbxeeHCoD0=
+github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
+github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
+github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -72,20 +86,40 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
+github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44=
+github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
+github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
+github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
+github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
+github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
+github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
+github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU=
github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0=
+github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
+github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
+github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs=
+github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0=
golang.org/x/image v0.23.0 h1:HseQ7c2OpPKTPVzNjG5fwJsOTCiiwS4QdsYi5XU6H68=
golang.org/x/image v0.23.0/go.mod h1:wJJBTdLfCCf3tiHa1fNxpZmUI4mmoZvwMCPP0ddoNKY=
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
+golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
+golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -93,8 +127,12 @@ golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
+golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
+golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
diff --git a/internal/core/core.go b/internal/core/core.go
index b817f15..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 = 4
+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>&lt;script&gt; πŸ˜€</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/initial.go b/internal/core/initial.go
new file mode 100644
index 0000000..8dbd6ee
--- /dev/null
+++ b/internal/core/initial.go
@@ -0,0 +1,67 @@
+package core
+
+import (
+ "context"
+ "encoding/binary"
+ "errors"
+ "math"
+ "unicode/utf8"
+)
+
+// InitialBlock is literal text. Level zero is a paragraph, 1..6 a heading.
+type InitialBlock struct {
+ Text string
+ Level uint8
+}
+
+// InitialUpdate builds a fresh document in the real core and returns its wire
+// update. Its handle is never exposed or reused, even after a trap or timeout.
+func (r *Runtime) InitialUpdate(ctx context.Context, guid string, clientID uint64, blocks []InitialBlock) ([]byte, error) {
+ if clientID > math.MaxUint32 {
+ return nil, errors.New("core: initial client id limit")
+ }
+ if len(blocks) > 200 {
+ return nil, errors.New("core: initial block limit")
+ }
+ raw := make([]byte, 0)
+ total := 0
+ for _, block := range blocks {
+ total += len(block.Text)
+ if block.Level > 6 || !utf8.ValidString(block.Text) || total > 128<<10 {
+ return nil, errors.New("core: invalid initial block")
+ }
+ raw = append(raw, block.Level)
+ raw = binary.BigEndian.AppendUint32(raw, uint32(len(block.Text)))
+ raw = append(raw, block.Text...)
+ }
+ h, err := r.NewDoc(ctx, guid, clientID)
+ if err != nil {
+ return nil, err
+ }
+ defer h.Close(ctx)
+ ptr, err := allocIn(ctx, r.callTimeout, h.mod, uint64(len(raw)))
+ if err != nil {
+ return nil, err
+ }
+ defer freeIn(ctx, r.callTimeout, h.mod, ptr, uint64(len(raw)))
+ if !h.mod.Memory().Write(uint32(ptr), raw) {
+ return nil, errors.New("core: initial memory write")
+ }
+ result, err := callGuest(ctx, r.callTimeout, h.mod.ExportedFunction("docs_core_initialize"), h.handle, ptr, uint64(len(raw)))
+ if err != nil {
+ return nil, err
+ }
+ if len(result) != 1 || int32(result[0]) != 0 {
+ return nil, errors.New("core: initial content refused")
+ }
+ // No retry through Handle.read: its recovery log is intentionally empty.
+ // Read directly and discard the whole handle on any uncertain outcome.
+ out, err := readOn(ctx, r.callTimeout, h.mod, h.handle, "snapshot")
+ if err != nil {
+ return nil, err
+ }
+ if len(out) > 1<<20 {
+ return nil, errors.New("core: initial output limit")
+ }
+ return []byte(out), nil
+}
diff --git a/internal/core/initial_test.go b/internal/core/initial_test.go
new file mode 100644
index 0000000..e121002
--- /dev/null
+++ b/internal/core/initial_test.go
@@ -0,0 +1,63 @@
+package core_test
+
+import (
+ "context"
+ "encoding/json"
+ "math"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/docs/internal/core"
+)
+
+func TestInitialUpdateUsesRealCollaborativeCore(t *testing.T) {
+ ctx := context.Background()
+ rt, err := core.New(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rt.Close(ctx)
+ update, err := rt.InitialUpdate(ctx, "fresh-initial", math.MaxUint32, []core.InitialBlock{{Level: 2, Text: "Agenda πŸ˜€"}, {Text: "<script>& CafΓ©\n二"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ h, err := rt.NewDoc(ctx, "fresh-initial", 42)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer h.Close(ctx)
+ if err = h.Apply(ctx, update); err != nil {
+ t.Fatal(err)
+ }
+ html, err := h.HTML(ctx)
+ if err != nil || !strings.Contains(html, "<h2>Agenda πŸ˜€</h2>") || !strings.Contains(html, "&lt;script&gt;&amp;") {
+ t.Fatal(html, err)
+ }
+ raw, err := h.JSON(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var tree struct {
+ Content []struct {
+ Type string
+ Attrs struct{ Level int }
+ Content []struct{ Text string }
+ }
+ }
+ if err = json.Unmarshal([]byte(raw), &tree); err != nil {
+ t.Fatal(err)
+ }
+ if len(tree.Content) != 2 || tree.Content[0].Attrs.Level != 2 || tree.Content[1].Content[0].Text != "<script>& Café\n二" {
+ t.Fatal(raw)
+ }
+ for _, clientID := range []uint64{uint64(math.MaxUint32) + 1, math.MaxInt64} {
+ if _, err = rt.InitialUpdate(ctx, "bad-client", clientID, []core.InitialBlock{{Text: "safe text"}}); err == nil {
+ t.Fatal("unsafe client ID accepted")
+ }
+ }
+ for _, blocks := range [][]core.InitialBlock{{{Level: 7}}, {{Text: string([]byte{255})}}, {{Text: strings.Repeat("x", 128*1024+1)}}, make([]core.InitialBlock, 201)} {
+ if _, err = rt.InitialUpdate(ctx, "bad-initial", 43, blocks); err == nil {
+ t.Fatal("invalid blocks accepted")
+ }
+ }
+}
diff --git a/internal/core/testdata/docs_core.wasm b/internal/core/testdata/docs_core.wasm
index 3418e63..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
new file mode 100644
index 0000000..9a15661
--- /dev/null
+++ b/internal/docs/agent_access.go
@@ -0,0 +1,265 @@
+package docs
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "mime"
+ "net/http"
+ "strings"
+
+ access "amadan.net/oficina/agent-access.git"
+ strictjson "github.com/go-json-experiment/json"
+ "gorm.io/gorm"
+)
+
+var errAgentConfig = errors.New("docs: invalid agent access configuration")
+
+func validatedAgentConfig(cfg Config, home *homeSettings, team *teamSettings) (*access.RemoteVerifier, error) {
+ if cfg.AgentIssuer == "" && cfg.AgentTeam == "" {
+ return nil, nil
+ }
+ if home == nil || cfg.AgentIssuer == "" || cfg.AgentTeam == "" || len(cfg.AgentTeam) > 128 || strings.TrimSpace(cfg.AgentTeam) != cfg.AgentTeam {
+ return nil, errAgentConfig
+ }
+ if team != nil && cfg.AgentTeam != team.Settings.Bindings().Team {
+ return nil, errAgentConfig
+ }
+ verifier, err := access.NewRemoteVerifier(cfg.AgentIssuer, cfg.Origin+"/api/v1", home.issuer)
+ if err != nil {
+ return nil, errAgentConfig
+ }
+ return verifier, nil
+}
+
+const agentSummaryProperties = `"id":{"type":"string"},"title":{"type":"string"},"url":{"type":"string"},"updated_at":{"type":"string"}`
+const agentCreatedSchema = `{"type":"object","required":["id","title","url","updated_at","body_revision"],"additionalProperties":false,"properties":{` + agentSummaryProperties + `,"body_revision":{"type":"string","pattern":"^[0-9]+$"}}}`
+const agentBodySchema = `{"type":"object","required":["id","title","url","updated_at","body_revision","text","content"],"additionalProperties":false,"properties":{` + agentSummaryProperties + `,"body_revision":{"type":"string","pattern":"^[0-9]+$"},"text":{"type":"string"},"content":{"type":"object"}}}`
+
+func (a *documentAgent) registry() (*access.Registry, error) {
+ input := func(properties, required string) json.RawMessage {
+ return json.RawMessage(`{"type":"object","additionalProperties":false,"required":["team"` + required + `],"properties":{"team":{"type":"string","minLength":1,"maxLength":128}` + properties + `}}`)
+ }
+ ops := []access.Operation{
+ {Name: "docs_list", Description: "List documents currently readable in this team.", Scope: "docs:read", ReadOnly: true, Idempotent: true,
+ Input: input(`,"limit":{"type":"integer","minimum":1,"maximum":100},"cursor":{"type":"string","maxLength":512}`, ""),
+ Output: json.RawMessage(`{"type":"object","required":["documents","next_cursor"],"additionalProperties":false,"properties":{"documents":{"type":"array","maxItems":100,"items":{"type":"object","additionalProperties":false,"required":["id","title","url","updated_at"],"properties":{` + agentSummaryProperties + `}}},"next_cursor":{"type":"string"}}}`),
+ Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ ctx, id, err := a.prepare(ctx, p, false)
+ if err != nil {
+ return nil, err
+ }
+ var in struct {
+ Limit int `json:"limit"`
+ Cursor string `json:"cursor"`
+ }
+ if err = json.Unmarshal(raw, &in); err != nil {
+ return nil, access.Fail("invalid", "Invalid operation arguments.")
+ }
+ return a.documents(ctx, id.Actor, in.Limit, in.Cursor)
+ }},
+ {Name: "docs_get", Description: "Read a document as plain text and structured content at one body revision.", Scope: "docs:read", ReadOnly: true, Idempotent: true,
+ Input: input(`,"id":{"type":"string","pattern":"^[23456789abcdefghjkmnpqrstuvwxyz]{10}$"}`, `,"id"`), Output: json.RawMessage(agentBodySchema),
+ Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ ctx, id, err := a.prepare(ctx, p, false)
+ if err != nil {
+ return nil, err
+ }
+ var in struct {
+ ID string `json:"id"`
+ }
+ if err = json.Unmarshal(raw, &in); err != nil {
+ return nil, access.Fail("invalid", "Invalid operation arguments.")
+ }
+ return a.body(ctx, id.Actor, in.ID)
+ }},
+ {Name: "docs_create", Description: "Create a document with literal paragraph and heading text; reuse the same client UUID only for retries.", Scope: "docs:write", Idempotent: true,
+ Input: input(`,"client_id":{"type":"string","maxLength":36},"title":{"type":"string","minLength":1,"maxLength":512},"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}}}}`, `,"client_id","title","blocks"`), Output: json.RawMessage(agentCreatedSchema),
+ Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ ctx, id, err := a.prepare(ctx, p, true)
+ if err != nil {
+ return nil, err
+ }
+ var in agentCreateInput
+ if err = json.Unmarshal(raw, &in); err != nil {
+ return nil, access.Fail("invalid", "Invalid operation arguments.")
+ }
+ 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) {
+ var parsed struct {
+ Team string `json:"team"`
+ }
+ if strictjson.Unmarshal(raw, &parsed) != nil {
+ return nil, access.Fail("invalid", "Send valid Unicode JSON.")
+ }
+ if parsed.Team != a.team {
+ return nil, access.Fail("forbidden", "This instance does not serve that team.")
+ }
+ return invoke(ctx, p, raw)
+ }
+ scope := ops[i].Scope
+ ops[i].Available = func(p access.Principal) bool { return p.Allows(a.team, scope) }
+ }
+ return access.NewRegistry(ops...)
+}
+
+func agentWriteFailure(w http.ResponseWriter, err error) {
+ f := access.SafeFailure(err)
+ status := map[string]int{"unauthenticated": 401, "forbidden": 403, "not_found": 404, "invalid": 422, "conflict": 409, "too_large": 413, "unsupported_media_type": 415, "unavailable": 503}[f.Code]
+ if status == 0 {
+ status = 500
+ }
+ if status == 401 {
+ w.Header().Set("WWW-Authenticate", "Bearer")
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(map[string]any{"error": f})
+}
+
+// httpHandler keeps final Docs permission/epoch checks on the real writer.
+func (a *documentAgent) httpHandler(verifier access.Verifier) (http.Handler, error) {
+ registry, err := a.registry()
+ if err != nil {
+ return nil, err
+ }
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ parts := strings.Fields(r.Header.Get("Authorization"))
+ if len(r.Header.Values("Authorization")) != 1 || len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
+ agentWriteFailure(w, access.Fail("unauthenticated", "Connect to Oficina first."))
+ return
+ }
+ p, err := verifier.Verify(r.Context(), parts[1])
+ if err != nil {
+ agentWriteFailure(w, err)
+ return
+ }
+ name := strings.TrimPrefix(r.URL.Path, "/api/v1/operations/")
+ 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.prepareMode(r.Context(), p, write, write && name != "docs_update")
+ if err != nil {
+ agentWriteFailure(w, err)
+ return
+ }
+ guard := ctx.Value(accessContextKey{}).(*requestAccess)
+ guard.delegationCheck = func(ctx context.Context) error {
+ current, e := verifier.Verify(ctx, parts[1])
+ if e != nil {
+ return e
+ }
+ scope := "docs:read"
+ if write {
+ scope = "docs:write"
+ }
+ if current.Subject != p.Subject || current.Client != p.Client || current.Grant != p.Grant || !current.Allows(a.team, scope) {
+ return errIdentityRefused
+ }
+ return nil
+ }
+ guard.extraCheck = func(ctx context.Context) error {
+ if err := guard.delegationCheck(ctx); err != nil {
+ return err
+ }
+ fresh, e := a.resolver.resolveHome(ctx, p.Subject)
+ if e != nil {
+ return e
+ }
+ if !sameActor(fresh.Actor, id.Actor) {
+ return errIdentityRefused
+ }
+ if a.store.team == nil {
+ allowed, e := a.list.allows(actorAddress(id.Actor))
+ if e != nil {
+ return e
+ }
+ if !allowed {
+ return errIdentityRefused
+ }
+ }
+ return nil
+ }
+ var result any
+ if discovery {
+ result = map[string]any{"operations": registry.List(p)}
+ } else {
+ if r.Method != "POST" || !strings.HasPrefix(r.URL.Path, "/api/v1/operations/") || strings.Contains(name, "/") {
+ agentWriteFailure(w, access.Fail("not_found", "This operation is unavailable."))
+ return
+ }
+ media, _, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if e != nil || media != "application/json" {
+ agentWriteFailure(w, access.Fail("unsupported_media_type", "Send application/json."))
+ return
+ }
+ raw, e := io.ReadAll(io.LimitReader(r.Body, access.MaxPayload+1))
+ if e != nil {
+ agentWriteFailure(w, access.Fail("invalid", "Could not read the request."))
+ return
+ }
+ result, err = registry.Call(ctx, p, name, raw)
+ if err != nil {
+ agentWriteFailure(w, err)
+ return
+ }
+ }
+ body, err := json.Marshal(result)
+ if err != nil {
+ agentWriteFailure(w, agentFailure(err))
+ return
+ }
+ if len(body) > agentResultLimit {
+ agentWriteFailure(w, access.Fail("too_large", "The document result exceeds 1 MiB."))
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ if err = writeGuardedBody(w, r.WithContext(ctx), http.StatusOK, body); err != nil {
+ panic(http.ErrAbortHandler)
+ }
+ }), nil
+}
+
+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
+ }
+ return a.httpHandler(verifier)
+}
+
+// AgentContracts exports identical operation contracts for every Docs team.
+func AgentContracts() ([]access.Operation, error) {
+ a := &documentAgent{team: "contract"}
+ registry, err := a.registry()
+ if err != nil {
+ return nil, err
+ }
+ return registry.List(access.Principal{Subject: "contract", Teams: []string{"contract"}, Scopes: []string{"docs:read", "docs:write"}}), nil
+}
diff --git a/internal/docs/agent_access_test.go b/internal/docs/agent_access_test.go
new file mode 100644
index 0000000..2439a0f
--- /dev/null
+++ b/internal/docs/agent_access_test.go
@@ -0,0 +1,610 @@
+package docs
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/handoff/seal"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+type docAgentFixture struct {
+ a *documentAgent
+ app *App
+ p access.Principal
+ handler http.Handler
+ revoked atomic.Bool
+ checks atomic.Int64
+ revokeAt atomic.Int64
+ verified chan struct{}
+}
+
+func TestAgentDocumentRevokedWriterNeverCommits(t *testing.T) {
+ for _, phase := range []string{"waiting", "before-commit"} {
+ t.Run(phase, func(t *testing.T) {
+ f := newDocAgentFixture(t)
+ if phase == "waiting" {
+ held, release := make(chan struct{}), make(chan struct{})
+ txDone := make(chan error, 1)
+ go func() {
+ txDone <- f.a.store.db.Transaction(func(tx *gorm.DB) error { close(held); <-release; return nil })
+ }()
+ <-held
+ f.verified = make(chan struct{})
+ result := make(chan *httptest.ResponseRecorder, 1)
+ go func() { result <- f.call(t, "docs_create", initialAgentInput()) }()
+ select {
+ case <-f.verified:
+ case <-time.After(5 * time.Second):
+ close(release)
+ t.Fatal("request never verified")
+ }
+ f.revoked.Store(true)
+ close(release)
+ if err := <-txDone; err != nil {
+ t.Fatal(err)
+ }
+ if rec := <-result; rec.Code != 401 {
+ t.Error("waiting revoked create", rec.Code, rec.Body.String())
+ }
+ } else {
+ // Initial verification, reserved writer, then final in-transaction check.
+ f.revokeAt.Store(3)
+ if rec := f.call(t, "docs_create", initialAgentInput()); rec.Code != 401 {
+ t.Error("final revoked create", rec.Code, rec.Body.String())
+ }
+ }
+ for _, model := range []any{&Document{}, &DocUpdate{}, &agentReceipt{}, &agentAttribution{}} {
+ var count int64
+ if e := f.a.store.db.Model(model).Count(&count).Error; e != nil || count != 0 {
+ t.Fatal("revoked create persisted", count, e)
+ }
+ }
+ })
+ }
+}
+
+type docAgentCredentials struct{}
+
+func (docAgentCredentials) Downstream(context.Context, access.Principal, string, string, []string) (string, error) {
+ return "test-token", nil
+}
+
+func TestAgentDocumentTeamContractsComposeAndWrongInstanceRefuses(t *testing.T) {
+ f := newDocAgentFixture(t)
+ other := *f.a
+ other.team = "green"
+ f.p.Teams = []string{"blue", "green"}
+ first, e := f.a.registry()
+ if e != nil {
+ t.Fatal(e)
+ }
+ second, e := other.registry()
+ if e != nil {
+ 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)) != 4 {
+ t.Fatal("contracts cannot compose", e)
+ }
+ in := initialAgentInput()
+ in.Team = "green"
+ if rec := f.call(t, "docs_create", in); rec.Code != 403 {
+ t.Fatal("multi-team credential crossed instance", rec.Code)
+ }
+}
+
+func TestAgentDocumentRejectsLossyJSONAndKeepsLargeCreateRetryable(t *testing.T) {
+ f := newDocAgentFixture(t)
+ for _, text := range []string{string([]byte{0xff}), `\ud800`, `\udfff`} {
+ raw := `{"team":"blue","client_id":"` + uuid.NewString() + `","title":"title","blocks":[{"type":"paragraph","text":"` + text + `"}]}`
+ req := httptest.NewRequest("POST", bridgeOrigin+"/api/v1/operations/docs_create", strings.NewReader(raw))
+ req.Header.Set("Authorization", "Bearer test-token")
+ req.Header.Set("Content-Type", "application/json")
+ w := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}
+ f.handler.ServeHTTP(w, req)
+ if w.Code != 422 {
+ t.Fatal("lossy JSON accepted", w.Code, w.Body.String())
+ }
+ }
+ var count int64
+ f.a.store.db.Model(&Document{}).Count(&count)
+ if count != 0 {
+ t.Fatal("malformed input wrote documents")
+ }
+ in := initialAgentInput()
+ in.Blocks = []agentBlock{{Type: "paragraph", Text: strings.Repeat("<", 128<<10)}}
+ body := decodeAgentBody(t, f.call(t, "docs_create", in))
+ retry := decodeAgentBody(t, f.call(t, "docs_create", in))
+ if body.ID != retry.ID || body.Revision != retry.Revision {
+ t.Fatal("large create retry changed result")
+ }
+ if rec := f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID}); rec.Code != 413 {
+ t.Fatal("oversized read was not refused", rec.Code)
+ }
+ var doc Document
+ if e := f.a.store.db.Where("sqid=?", body.ID).First(&doc).Error; e != nil {
+ t.Fatal(e)
+ }
+ var attribution agentAttribution
+ if e := f.a.store.db.First(&attribution, doc.ID).Error; e != nil {
+ t.Fatal(e)
+ }
+ sealer, e := seal.New(f.a.key, "oficina/docs")
+ if e != nil {
+ t.Fatal(e)
+ }
+ client, e := sealer.Open("agent-client/"+doc.GUID, attribution.ClientSealed)
+ if e != nil || string(client) != f.p.Client || bytes.Contains(attribution.ClientSealed, []byte(f.p.Client)) {
+ t.Fatal("client attribution not recoverable and sealed", e)
+ }
+}
+
+func TestAgentDocumentPagesUseCurrentPermissionAndExactCursor(t *testing.T) {
+ f := newDocAgentFixture(t)
+ for i := 0; i < 3; i++ {
+ decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
+ }
+ // Tie timestamps so the stable ID tiebreaker is necessary.
+ if e := f.a.store.db.Model(&Document{}).Where("id > 0").Update("updated_at", time.Date(2026, 10, 25, 0, 0, 0, 0, time.UTC)).Error; e != nil {
+ t.Fatal(e)
+ }
+ cursor := ""
+ seen := map[string]bool{}
+ for i := 0; i < 3; i++ {
+ rec := f.call(t, "docs_list", map[string]any{"team": "blue", "limit": 1, "cursor": cursor})
+ if rec.Code != 200 {
+ t.Fatal(rec.Code, rec.Body.String())
+ }
+ var page struct {
+ Documents []agentDocument `json:"documents"`
+ Next string `json:"next_cursor"`
+ }
+ if e := json.Unmarshal(rec.Body.Bytes(), &page); e != nil {
+ t.Fatal(e)
+ }
+ if len(page.Documents) != 1 || seen[page.Documents[0].ID] {
+ t.Fatal("pagination duplicated or skipped", page)
+ }
+ seen[page.Documents[0].ID] = true
+ cursor = page.Next
+ }
+ if cursor != "" {
+ t.Fatal("last page has cursor")
+ }
+ if rec := f.call(t, "docs_list", map[string]any{"team": "blue", "cursor": "not-a-cursor"}); rec.Code != 422 {
+ t.Fatal("malformed cursor accepted", rec.Code)
+ }
+ other, e := f.a.store.EnsurePerson(t.Context(), "foreign@example.com")
+ if e != nil {
+ t.Fatal(e)
+ }
+ // Private said out loud: a new document is on the team rung (Docs spec
+ // Β§8.2.1), and this test is about a document the caller may not read.
+ doc, e := f.a.store.createDocument(t.Context(), other, "Private foreign title", "", VisibilityPrivate)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if rec := f.call(t, "docs_get", map[string]any{"team": "blue", "id": doc.Sqid}); rec.Code != 404 {
+ t.Fatal("foreign document disclosed", rec.Code)
+ }
+ rec := f.call(t, "docs_list", map[string]any{"team": "blue"})
+ if rec.Code != 200 || strings.Contains(rec.Body.String(), doc.Title) {
+ t.Fatal("foreign title in list", rec.Code)
+ }
+}
+
+func newDocAgentFixture(t *testing.T, issuers ...string) *docAgentFixture {
+ t.Helper()
+ return newDocAgentFixtureWithStorage(t, true, issuers...)
+}
+func newDocAgentFixtureWithStorage(t *testing.T, activate bool, issuers ...string) *docAgentFixture {
+ t.Helper()
+ f := newBridgeFixture(t)
+ person, err := f.app.store.EnsurePerson(t.Context(), "owner@example.com")
+ if err != nil {
+ t.Fatal(err)
+ }
+ tx, err := f.app.db.Writer().BeginTx(t.Context(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = f.h.bridge.Adopt(t.Context(), tx, bridgeIssuer, "opaque-owner", person); err != nil {
+ tx.Rollback()
+ t.Fatal(err)
+ }
+ if err = tx.Commit(); err != nil {
+ t.Fatal(err)
+ }
+ cipher, err := newContentCipher("", "development")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if activate {
+ if err = convertContent(t.Context(), f.app.store.db, cipher); err != nil {
+ t.Fatal(err)
+ }
+ f.app.store.content = cipher
+ }
+ a := &documentAgent{store: f.app.store, resolver: f.h.resolver, list: allowlist{addrs: map[string]struct{}{"owner@example.com": {}}}, origin: bridgeOrigin, issuer: "https://connect.oficina.works", identityIssuer: bridgeIssuer, team: "blue", key: bytes.Repeat([]byte{41}, 32)}
+ if len(issuers) > 0 {
+ a.issuer = issuers[0]
+ }
+ a.list.granted = func(address string) (bool, error) { return a.store.HasGrant(t.Context(), address) }
+ if err = a.store.db.Transaction(func(tx *gorm.DB) error { return a.bind(tx) }); err != nil {
+ t.Fatal(err)
+ }
+ out := &docAgentFixture{a: a, app: f.app, p: access.Principal{Subject: "opaque-owner", Client: "test-client", Grant: "grant-one", Teams: []string{"blue"}, Scopes: []string{"docs:read", "docs:write"}}}
+ out.handler, err = a.httpHandler(access.VerifyFunc(func(ctx context.Context, token string) (access.Principal, error) {
+ n := out.checks.Add(1)
+ if n == 1 && out.verified != nil {
+ close(out.verified)
+ }
+ if at := out.revokeAt.Load(); at > 0 && n >= at {
+ out.revoked.Store(true)
+ }
+ if token != "test-token" || out.revoked.Load() {
+ return access.Principal{}, access.Fail("unauthenticated", "Connection expired.")
+ }
+ return out.p, nil
+ }))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return out
+}
+func (f *docAgentFixture) call(t *testing.T, name string, input any) *httptest.ResponseRecorder {
+ t.Helper()
+ body, err := json.Marshal(input)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := httptest.NewRequest("POST", bridgeOrigin+"/api/v1/operations/"+name, bytes.NewReader(body))
+ r.Header.Set("Authorization", "Bearer test-token")
+ r.Header.Set("Content-Type", "application/json")
+ w := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}
+ f.handler.ServeHTTP(w, r)
+ return w.ResponseRecorder
+}
+func initialAgentInput() agentCreateInput {
+ return agentCreateInput{Team: "blue", ClientID: uuid.NewString(), Title: "API document", Blocks: []agentBlock{{Type: "heading", Text: "Meeting", Level: 2}, {Type: "paragraph", Text: "PRIVATE_INITIAL_BODY_7f39 <script> literal βœ“"}}}
+}
+func decodeAgentBody(t *testing.T, w *httptest.ResponseRecorder) agentBody {
+ t.Helper()
+ if w.Code != 200 {
+ t.Fatalf("operation failed: %d %s", w.Code, w.Body.String())
+ }
+ var body agentBody
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatal(err)
+ }
+ return body
+}
+func TestAgentDocumentCreatesRealSealedContentAndRetries(t *testing.T) {
+ f := newDocAgentFixture(t)
+ in := initialAgentInput()
+ body := decodeAgentBody(t, f.call(t, "docs_create", in))
+ body = decodeAgentBody(t, f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID}))
+ if body.ID == "" || body.Revision != "1" || !strings.Contains(body.Text, "PRIVATE_INITIAL_BODY_7f39") || !strings.Contains(string(body.Content), `"level":2`) {
+ t.Fatalf("invalid core body: %+v", body)
+ }
+ got := decodeAgentBody(t, f.call(t, "docs_get", map[string]any{"team": "blue", "id": body.ID}))
+ if got.Text != body.Text || got.Revision != body.Revision {
+ t.Fatal("get mismatch")
+ }
+ var wg sync.WaitGroup
+ results := make(chan *httptest.ResponseRecorder, 4)
+ for i := 0; i < 4; i++ {
+ wg.Add(1)
+ go func() { defer wg.Done(); results <- f.call(t, "docs_create", in) }()
+ }
+ wg.Wait()
+ close(results)
+ for rec := range results {
+ if retry := decodeAgentBody(t, rec); retry.ID != body.ID {
+ t.Fatal("retry duplicated document")
+ }
+ }
+ changed := in
+ changed.Title = "Different"
+ if rec := f.call(t, "docs_create", changed); rec.Code != 409 {
+ t.Fatal("changed retry", rec.Code)
+ }
+ var n int64
+ if err := f.a.store.db.Model(&Document{}).Count(&n).Error; err != nil || n != 1 {
+ t.Fatal(n, err)
+ }
+ var doc Document
+ if err := f.a.store.db.Where("sqid=?", body.ID).First(&doc).Error; err != nil {
+ t.Fatal(err)
+ }
+ // Real browser-compatible update advances the body; retry must not reapply initial content.
+ ctx, id, err := f.a.prepare(t.Context(), f.p, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = f.a.store.ApplyUpdate(ctx, &doc, id.Actor, validUpdate(t)); err != nil {
+ t.Fatal(err)
+ }
+ retried := decodeAgentBody(t, f.call(t, "docs_create", in))
+ if retried.ID != body.ID || retried.Revision != "2" {
+ t.Fatal("retry reset body revision", retried.Revision)
+ }
+ for _, suffix := range []string{"", "-wal"} {
+ raw, e := os.ReadFile(f.app.cfg.DBPath + suffix)
+ if e != nil && !os.IsNotExist(e) {
+ t.Fatal(e)
+ }
+ if bytes.Contains(raw, []byte("PRIVATE_INITIAL_BODY_7f39")) {
+ t.Fatal("plaintext body in storage", suffix)
+ }
+ }
+ if err = f.a.store.db.Model(&doc).Update("deleted_at", time.Now()).Error; err != nil {
+ t.Fatal(err)
+ }
+ if rec := f.call(t, "docs_create", in); rec.Code != 404 {
+ t.Fatal("deleted retry recreated", rec.Code)
+ }
+}
+func TestAgentDocumentAtomicRollbackAndAuthorityBinding(t *testing.T) {
+ f := newDocAgentFixture(t)
+ in := initialAgentInput()
+ for _, table := range []string{"doc_updates", "docs_agent_receipts", "docs_agent_attribution"} {
+ if err := f.a.store.db.Exec("CREATE TRIGGER agent_failure BEFORE INSERT ON " + table + " BEGIN SELECT RAISE(ABORT,'injected failure'); END").Error; err != nil {
+ t.Fatal(err)
+ }
+ if rec := f.call(t, "docs_create", in); rec.Code != 503 {
+ t.Fatal("write failure not surfaced", rec.Code)
+ }
+ for _, model := range []any{&Document{}, &DocUpdate{}, &agentReceipt{}, &agentAttribution{}} {
+ var count int64
+ if e := f.a.store.db.Model(model).Count(&count).Error; e != nil || count != 0 {
+ t.Fatal("partial creation", count, e)
+ }
+ }
+ if err := f.a.store.db.Exec("DROP TRIGGER agent_failure").Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ body := decodeAgentBody(t, f.call(t, "docs_create", in))
+ for _, change := range []func(*documentAgent){func(a *documentAgent) { a.key = bytes.Repeat([]byte{42}, 32) }, func(a *documentAgent) { a.identityIssuer = "https://another-home.example" }, func(a *documentAgent) { a.issuer = "https://another-connect.example" }, func(a *documentAgent) { a.team = "other" }} {
+ copy := *f.a
+ change(&copy)
+ if err := copy.store.db.Transaction(func(tx *gorm.DB) error { return copy.bind(tx) }); err == nil {
+ t.Fatal("authority/key change accepted")
+ }
+ }
+ copy := *f.a
+
+ reopened, err := New(f.app.cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reopened.Close()
+ copy.store = reopened.store
+ if err := copy.store.db.Transaction(func(tx *gorm.DB) error { return copy.bind(tx) }); err != nil {
+ t.Fatal("same authority restart refused", err)
+ }
+ if retry := decodeAgentBody(t, f.call(t, "docs_create", in)); retry.ID != body.ID {
+ t.Fatal("same authority retry changed ID")
+ }
+ f.a.store.content = nil
+ if rec := f.call(t, "docs_create", initialAgentInput()); rec.Code != 503 {
+ t.Fatal("legacy storage write", rec.Code)
+ }
+}
+
+func TestAgentDocumentIdentityLostBeforeCommitRollsBack(t *testing.T) {
+ f := newDocAgentFixture(t)
+ if e := f.a.store.db.Exec("CREATE TRIGGER agent_unlink AFTER INSERT ON docs_agent_receipts BEGIN DELETE FROM home_identity_links; END").Error; e != nil {
+ t.Fatal(e)
+ }
+ rec := f.call(t, "docs_create", initialAgentInput())
+ for _, model := range []any{&Document{}, &DocUpdate{}, &agentReceipt{}, &agentAttribution{}} {
+ var count int64
+ if e := f.a.store.db.Model(model).Count(&count).Error; e != nil || count != 0 {
+ t.Fatal("lost identity committed creation", count, e)
+ }
+ }
+ if rec.Code != 403 {
+ t.Fatal("lost identity refusal", rec.Code)
+ }
+ var links int
+ f.a.store.db.Raw("SELECT COUNT(*) FROM home_identity_links").Scan(&links)
+ if links != 1 {
+ t.Fatal("identity deletion was not rolled back")
+ }
+}
+func TestAgentDocumentScopeIdentityAndFinalRevocation(t *testing.T) {
+ f := newDocAgentFixture(t)
+ body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
+ in := map[string]any{"team": "blue", "id": body.ID}
+ saved := f.p
+ f.p.Subject = "never-linked"
+ if rec := f.call(t, "docs_get", in); rec.Code != 403 {
+ t.Fatal("unlinked", rec.Code)
+ }
+ f.p = saved
+ f.p.Scopes = []string{"docs:write"}
+ if rec := f.call(t, "docs_get", in); rec.Code != 403 {
+ t.Fatal("wrong scope", rec.Code)
+ }
+ f.p = saved
+ in["team"] = "foreign"
+ if rec := f.call(t, "docs_get", in); rec.Code != 403 {
+ t.Fatal("wrong team", rec.Code)
+ }
+ in["team"] = "blue"
+ f.revoked.Store(true)
+ if rec := f.call(t, "docs_get", in); rec.Code != 401 {
+ t.Fatal("revoked", rec.Code)
+ }
+ f.revoked.Store(false)
+ if err := f.a.store.db.Exec("DELETE FROM home_identity_links WHERE subject=?", f.p.Subject).Error; err != nil {
+ t.Fatal(err)
+ }
+ if rec := f.call(t, "docs_get", in); rec.Code != 403 {
+ t.Fatal("unlinked existing credential", rec.Code)
+ }
+ var count int64
+ f.a.store.db.Model(&Person{}).Count(&count)
+ if count != 1 {
+ t.Fatal("agent provisioned identity")
+ }
+}
+func TestAgentDocumentHTTPAbortsRevocationDuringEmission(t *testing.T) {
+ f := newDocAgentFixture(t)
+ in := initialAgentInput()
+ in.Blocks = []agentBlock{{Type: "paragraph", Text: strings.Repeat("x", 100<<10)}}
+ body := decodeAgentBody(t, f.call(t, "docs_create", in))
+ raw, _ := json.Marshal(map[string]any{"team": "blue", "id": body.ID})
+ r := httptest.NewRequest("POST", bridgeOrigin+"/api/v1/operations/docs_get", bytes.NewReader(raw))
+ r.Header.Set("Content-Type", "application/json")
+ r.Header.Set("Authorization", "Bearer test-token")
+ w := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder(), afterWrite: func() { f.revoked.Store(true) }}
+ aborted := false
+ func() {
+ defer func() {
+ if e := recover(); e != nil {
+ if e != http.ErrAbortHandler {
+ panic(e)
+ }
+ aborted = true
+ }
+ }()
+ f.handler.ServeHTTP(w, r)
+ }()
+ if !aborted || w.Body.Len() != 64<<10 {
+ t.Fatal("revocation emitted a successful partial body", aborted, w.Body.Len())
+ }
+}
+func TestAgentDocumentHTTPWorksWithoutBrowserSession(t *testing.T) {
+ f := newDocAgentFixture(t)
+ server := httptest.NewServer(f.handler)
+ defer server.Close()
+ raw, _ := json.Marshal(initialAgentInput())
+ req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/docs_create", bytes.NewReader(raw))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer test-token")
+ response, err := server.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ body, err := io.ReadAll(response.Body)
+ if err != nil || response.StatusCode != 200 {
+ t.Fatal(response.StatusCode, string(body), err)
+ }
+}
+func TestAgentDocumentConfigRefusesPartialAndWrongIdentityNamespace(t *testing.T) {
+ home := &homeSettings{issuer: bridgeIssuer}
+ for _, cfg := range []Config{{AgentTeam: "blue"}, {AgentIssuer: "https://connect.oficina.works"}, {AgentIssuer: bridgeIssuer, AgentTeam: "blue"}, {AgentIssuer: "http://connect.oficina.works", AgentTeam: "blue"}} {
+ cfg.Origin = bridgeOrigin
+ if _, err := validatedAgentConfig(cfg, home, nil); !errors.Is(err, errAgentConfig) {
+ t.Fatal("invalid configuration accepted")
+ }
+ }
+ if _, err := validatedAgentConfig(Config{AgentIssuer: "https://connect.oficina.works", AgentTeam: "blue", Origin: bridgeOrigin}, nil, nil); err == nil {
+ t.Fatal("Home required")
+ }
+}
+
+func TestAgentDocumentTeamEpochIsCheckedDuringActualEmission(t *testing.T) {
+ for _, mode := range []string{"late", "partial", "explicit-grant"} {
+ t.Run(mode, func(t *testing.T) {
+ f := newDocAgentFixture(t)
+ in := initialAgentInput()
+ in.Blocks = []agentBlock{{Type: "paragraph", Text: strings.Repeat("z", 100<<10)}}
+ body := decodeAgentBody(t, f.call(t, "docs_create", in))
+ var doc Document
+ if e := f.a.store.db.Where("sqid=?", body.ID).First(&doc).Error; e != nil {
+ t.Fatal(e)
+ }
+ if mode == "explicit-grant" {
+ other, e := f.a.store.EnsurePerson(t.Context(), "other@example.com")
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = f.a.store.db.Model(&doc).Update("owner_id", other).Error; e != nil {
+ t.Fatal(e)
+ }
+ doc.OwnerID = other
+ if e := f.a.store.Grant(t.Context(), doc.OwnerID, doc.Sqid, "owner@example.com", RoleReader); e != nil {
+ t.Fatal(e)
+ }
+ }
+ rt, clock := configureDocAgentTestTeam(t, f)
+ calls := 0
+ handler, e := f.a.httpHandler(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ calls++
+ if mode == "late" && calls == 2 {
+ clock.step(60 * time.Second)
+ }
+ return f.p, nil
+ }))
+ if e != nil {
+ t.Fatal(e)
+ }
+ if mode == "explicit-grant" {
+ clock.step(60 * time.Second)
+ }
+ raw, _ := json.Marshal(map[string]any{"team": rt.bindings.Team, "id": doc.Sqid})
+ req := httptest.NewRequest("POST", bridgeOrigin+"/api/v1/operations/docs_get", bytes.NewReader(raw))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer token")
+ w := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}
+ if mode == "partial" {
+ w.afterWrite = func() { clock.step(60 * time.Second) }
+ }
+ aborted := false
+ func() {
+ defer func() {
+ if e := recover(); e != nil {
+ if e != http.ErrAbortHandler {
+ panic(e)
+ }
+ aborted = true
+ }
+ }()
+ handler.ServeHTTP(w, req)
+ }()
+ switch mode {
+ case "late":
+ if aborted || w.Code != 503 || strings.Contains(w.Body.String(), strings.Repeat("z", 64)) {
+ t.Fatal("late epoch leaked body", w.Code, aborted)
+ }
+ case "partial":
+ if !aborted || w.Body.Len() != 64<<10 {
+ t.Fatal("expired epoch did not abort", aborted, w.Body.Len())
+ }
+ case "explicit-grant":
+ if aborted || w.Code != 200 || !strings.Contains(w.Body.String(), strings.Repeat("z", 64)) {
+ t.Fatal("explicit grant lost independent authority", w.Code, aborted)
+ }
+ }
+ })
+ }
+}
+
+func TestAgentDocumentLegacyStorageRefusesBeforeWrite(t *testing.T) {
+ f := newDocAgentFixtureWithStorage(t, false)
+ rec := f.call(t, "docs_create", initialAgentInput())
+ var count int64
+ f.a.store.db.Model(&Document{}).Count(&count)
+ if rec.Code != 503 || count != 0 {
+ t.Fatal("legacy storage accepted agent write", rec.Code, count)
+ }
+}
diff --git a/internal/docs/agent_integration_test.go b/internal/docs/agent_integration_test.go
new file mode 100644
index 0000000..0057044
--- /dev/null
+++ b/internal/docs/agent_integration_test.go
@@ -0,0 +1,177 @@
+package docs
+
+import (
+ "context"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/agent-access.git/client"
+ "amadan.net/oficina/agent-access.git/grant"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+ "golang.org/x/oauth2"
+)
+
+type agentCredentials struct{ value client.Credentials }
+
+func (m *agentCredentials) Load() (client.Credentials, error) { return m.value, nil }
+func (m *agentCredentials) Save(v client.Credentials) error { m.value = v; return nil }
+func (m *agentCredentials) Delete() error { m.value = client.Credentials{}; return nil }
+
+type agentBearer struct {
+ base http.RoundTripper
+ token string
+}
+
+func (b agentBearer) RoundTrip(r *http.Request) (*http.Response, error) {
+ copy := r.Clone(r.Context())
+ copy.Header.Set("Authorization", "Bearer "+b.token)
+ return b.base.RoundTrip(copy)
+}
+
+// This fixture crosses real HTTPS boundaries from the shared CLI/MCP gateway
+// into Docs' real handlers, linked identity, sealed collaborative content.
+// The signed Home/browser/PKCE flow is exercised in the connection module.
+func TestAgentGatewayToRealDocs(t *testing.T) {
+ ctx := t.Context()
+ var appHandler, httpHandler http.Handler
+ appServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { appHandler.ServeHTTP(w, r) }))
+ defer appServer.Close()
+ issuer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { httpHandler.ServeHTTP(w, r) }))
+ defer issuer.Close()
+ f := newDocAgentFixture(t, issuer.URL)
+ p := f.p
+ input, _ := json.Marshal(initialAgentInput())
+ database, err := sql.Open("sqlite", filepath.Join(t.TempDir(), "grants.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer database.Close()
+ database.SetMaxOpenConns(1)
+ store, err := grant.NewStore(ctx, database)
+ if err != nil {
+ t.Fatal(err)
+ }
+ teams := func(context.Context, string) ([]grant.Team, error) {
+ return []grant.Team{{ID: "blue", Name: "Blue"}}, nil
+ }
+ grants, err := grant.NewServer(grant.Config{IdentityIssuer: bridgeIssuer, Origin: issuer.URL, Resource: issuer.URL + "/mcp", Store: store, ConsentKey: []byte(strings.Repeat("k", 32)), Clients: []grant.Client{{ID: client.ClientID, Name: "Oficina CLI", Loopback: true}}, Scopes: map[string]string{"docs:read": "Read documents", "docs:write": "Create documents"}, Subject: func(*http.Request) string { return "" }, Teams: teams, ResourceTeams: func(ctx context.Context, subject, resource string) ([]grant.Team, error) {
+ if resource != appServer.URL+"/api/v1" {
+ return nil, nil
+ }
+ return teams(ctx, subject)
+ }, SignInPath: "/signin"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ remote, err := access.NewRemoteVerifier(issuer.URL, appServer.URL+"/api/v1", bridgeIssuer)
+ if err != nil {
+ t.Fatal(err)
+ }
+ remote.Client.Transport = issuer.Client().Transport
+ f.a.origin = appServer.URL
+ appHandler, err = f.a.httpHandler(remote)
+ if err != nil {
+ t.Fatal(err)
+ }
+ contracts, err := AgentContracts()
+ if err != nil {
+ t.Fatal(err)
+ }
+ gateway, err := access.Gateway([]access.Route{{Team: "blue", Resource: appServer.URL + "/api/v1", Operations: contracts}}, store, appServer.Client().Transport)
+ if err != nil {
+ t.Fatal(err)
+ }
+ serviceMux := http.NewServeMux()
+ serviceMux.Handle("/mcp", gateway.MCP(grants))
+ serviceMux.Handle("/api/v1/operations", gateway.HTTP(grants))
+ serviceMux.Handle("/api/v1/operations/", gateway.HTTP(grants))
+ serviceMux.Handle("/", grants.Handler())
+ httpHandler = serviceMux
+ verifier := oauth2.GenerateVerifier()
+ challenge := sha256.Sum256([]byte(verifier))
+ redirect := "http://127.0.0.1:43210/callback"
+ code, err := store.CreateCode(ctx, grant.Grant{Subject: p.Subject, ClientID: client.ClientID, Teams: p.Teams, Scopes: p.Scopes}, grant.Code{Redirect: redirect, Challenge: base64.RawURLEncoding.EncodeToString(challenge[:]), Resource: issuer.URL + "/mcp"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ token, err := store.Exchange(ctx, code, client.ClientID, redirect, issuer.URL+"/mcp", verifier)
+ if err != nil {
+ t.Fatal(err)
+ }
+ credentials := &agentCredentials{client.Credentials{Server: issuer.URL, Resource: issuer.URL + "/mcp", TokenEndpoint: issuer.URL + "/oauth/token", Token: &oauth2.Token{AccessToken: token.AccessToken, TokenType: "Bearer"}}}
+ cli := client.New(credentials)
+ cli.HTTP = issuer.Client()
+ result, err := cli.Call(ctx, "docs_create", json.RawMessage(input))
+ if err != nil {
+ t.Fatal(err)
+ }
+ encoded, _ := json.Marshal(result)
+ var document agentCreated
+ if json.Unmarshal(encoded, &document) != nil || document.ID == "" {
+ t.Fatal("invalid document receipt")
+ }
+ mcpClient := mcp.NewClient(&mcp.Implementation{Name: "Docs integration", Version: "1"}, nil)
+ session, err := mcpClient.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: issuer.URL + "/mcp", HTTPClient: &http.Client{Transport: agentBearer{issuer.Client().Transport, token.AccessToken}}}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer session.Close()
+ retry, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "docs_create", Arguments: json.RawMessage(input)})
+ if err != nil || retry.IsError {
+ t.Fatal("MCP retry", retry, err)
+ }
+ search, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "docs_get", Arguments: map[string]any{"team": "blue", "id": document.ID}})
+ if err != nil || search.IsError {
+ t.Fatal("MCP search", search, err)
+ }
+ text, _ := json.Marshal(search.Content)
+ 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)
+ }
+ if err = cli.Logout(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = session.CallTool(ctx, &mcp.CallToolParams{Name: "docs_create", Arguments: initialAgentInput()}); err == nil {
+ t.Fatal("MCP survived CLI revocation")
+ }
+ if err = f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM documents").Scan(&count); err != nil || count != 1 {
+ t.Fatal("revoked call wrote document", count, err)
+ }
+}
diff --git a/internal/docs/agent_main_compat_test.go b/internal/docs/agent_main_compat_test.go
new file mode 100644
index 0000000..b88a08c
--- /dev/null
+++ b/internal/docs/agent_main_compat_test.go
@@ -0,0 +1,323 @@
+package docs
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "bytes"
+ "context"
+ "encoding/json"
+ "gorm.io/gorm"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ assertioncrypto "amadan.net/rastrillo/rastrillo/crypto"
+)
+
+// Test setup provisions a different authority with a new valid account link;
+// editing issuer/subject columns would invalidate connect's keyed binding.
+func configureDocAgentTestTeam(t *testing.T, f *docAgentFixture) (*teamRuntime, *teamTestClock) {
+ t.Helper()
+ id, err := f.a.resolver.resolveHome(t.Context(), f.p.Subject)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := f.a.store.db.Exec("DELETE FROM home_identity_links").Error; err != nil {
+ t.Fatal(err)
+ }
+ rt, clock, subject := testTeamRoster(t, f.a.store, f.app)
+ key, err := assertioncrypto.Generate()
+ if err != nil {
+ t.Fatal(err)
+ }
+ settings := &homeSettings{issuer: rt.bindings.Issuer, consumerID: rt.bindings.Consumer, keys: map[string][]byte{"key": key.SignPub()}, dek: bytes.Repeat([]byte{41}, 32)}
+ h, err := newHome(settings, bridgeOrigin, f.app.db.Writer(), f.a.store, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.team, h.resolver.team = rt, rt
+ tx, err := f.app.db.Writer().BeginTx(t.Context(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback()
+ if err = h.bridge.Adopt(t.Context(), tx, rt.bindings.Issuer, subject, id.Actor.PersonID); err != nil {
+ t.Fatal(err)
+ }
+ if err = tx.Commit(); err != nil {
+ t.Fatal(err)
+ }
+ f.a.resolver = h.resolver
+ f.a.identityIssuer, f.a.team = rt.bindings.Issuer, rt.bindings.Team
+ f.p.Subject, f.p.Teams = subject, []string{rt.bindings.Team}
+ return rt, clock
+}
+
+func TestAgentAdoptedDatabaseSurvivesCreateRetryAndReopen(t *testing.T) {
+ legacy := newLegacyLinks(t, false)
+ input := initialAgentInput()
+ attach := func() *docAgentFixture {
+ app := legacy.boot().app
+ settings, err := validatedHomeConfig(legacy.cfg.Home, legacy.cfg.Origin)
+ if err != nil {
+ t.Fatal(err)
+ }
+ h, err := newHome(settings, legacy.cfg.Origin, app.db.Writer(), app.store, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cipher, err := newContentCipher("", "development")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = convertContent(t.Context(), app.store.db, cipher); err != nil {
+ t.Fatal(err)
+ }
+ app.store.content = cipher
+ a := &documentAgent{store: app.store, resolver: h.resolver, list: allowlist{addrs: map[string]struct{}{"paul@tito.io": {}}}, origin: legacy.cfg.Origin, issuer: "https://connect.oficina.works", identityIssuer: settings.issuer, team: "blue", key: settings.dek}
+ if err = app.store.db.Transaction(func(tx *gorm.DB) error { return a.bind(tx) }); err != nil {
+ t.Fatal(err)
+ }
+ f := &docAgentFixture{a: a, app: app, p: access.Principal{Subject: paulSubject, Client: "migration-test", Grant: "grant-one", Teams: []string{"blue"}, Scopes: []string{"docs:read", "docs:write"}}}
+ f.handler, err = a.httpHandler(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return f.p, nil }))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return f
+ }
+ f := attach()
+ if tableNamed(t, f.app.db.Writer(), "docs_identity_links") {
+ t.Fatal("legacy table still present")
+ }
+ created := decodeAgentBody(t, f.call(t, "docs_create", input))
+ var before Document
+ if err := f.a.store.db.Where("sqid=?", created.ID).First(&before).Error; err != nil {
+ t.Fatal(err)
+ }
+ if before.OwnerID != legacy.paul {
+ t.Fatal("migration changed ownership", before.OwnerID)
+ }
+ 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)
+ }
+ if w := f.call(t, "docs_get", map[string]any{"team": "blue", "id": created.ID}); w.Code != 200 {
+ t.Fatal("migrated document unreadable", w.Code, w.Body.String())
+ }
+ var after Document
+ if err := f.a.store.db.First(&after, before.ID).Error; err != nil || after.Sqid != before.Sqid || after.OwnerID != before.OwnerID {
+ t.Fatal("document identity changed", after, err)
+ }
+ if granted, err := f.a.store.HasGrant(t.Context(), "carol@example.com"); err != nil || !granted {
+ t.Fatal("grant lost", granted, err)
+ }
+ var n int64
+ if err := f.a.store.db.Model(&agentReceipt{}).Count(&n).Error; err != nil || n != 1 {
+ t.Fatal("receipt lost or duplicated", n, err)
+ }
+}
+
+func TestAgentCompletedRetryChecksAuthorityInsideTransaction(t *testing.T) {
+ f := newDocAgentFixture(t)
+ input := initialAgentInput()
+ decodeAgentBody(t, f.call(t, "docs_create", input))
+ ctx, id, err := f.a.prepare(t.Context(), f.p, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ guard := ctx.Value(accessContextKey{}).(*requestAccess)
+ checks := 0
+ guard.delegationCheck = func(context.Context) error {
+ checks++
+ if checks == 2 {
+ return errIdentityRefused
+ }
+ return nil
+ }
+ // Direct invocation deliberately excludes the HTTP response guard.
+ if result, err := f.a.create(ctx, f.p, id, input); err == nil || result != nil || checks != 2 {
+ t.Fatal("completed retry skipped final authority", result, err, checks)
+ }
+}
+
+func TestAgentSharedBindingCorruptionRollsBackCreate(t *testing.T) {
+ f := newDocAgentFixture(t)
+ if err := f.a.store.db.Exec("CREATE TRIGGER agent_corrupt_link AFTER INSERT ON docs_agent_receipts BEGIN UPDATE home_identity_links SET person_binding='corrupt'; END").Error; err != nil {
+ t.Fatal(err)
+ }
+ if w := f.call(t, "docs_create", initialAgentInput()); w.Code != 403 {
+ t.Fatal("corrupt binding committed", w.Code, w.Body.String())
+ }
+ for _, model := range []any{&Document{}, &DocUpdate{}, &agentReceipt{}, &agentAttribution{}} {
+ var n int64
+ if err := f.a.store.db.Model(model).Count(&n).Error; err != nil || n != 0 {
+ t.Fatal("write survived refusal", n, err)
+ }
+ }
+ if _, err := f.a.resolver.resolveHome(t.Context(), f.p.Subject); err != nil {
+ t.Fatal("link corruption did not roll back", err)
+ }
+}
+
+func TestAgentNonTeamEmptyListAndDiscovery(t *testing.T) {
+ f := newDocAgentFixture(t)
+ if w := f.call(t, "docs_list", map[string]any{"team": "blue"}); w.Code != 200 {
+ t.Fatal("empty list refused", w.Code, w.Body.String())
+ }
+ r := httptest.NewRequest("GET", bridgeOrigin+"/api/v1/operations", nil)
+ r.Header.Set("Authorization", "Bearer test-token")
+ w := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}
+ f.handler.ServeHTTP(w, r)
+ if w.Code != 200 {
+ t.Fatal("discovery refused", w.Code, w.Body.String())
+ }
+}
+
+func TestAgentUnknownRosterNeverReturnsPartialList(t *testing.T) {
+ f := newDocAgentFixture(t)
+ created := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
+ other, err := f.a.store.EnsurePerson(t.Context(), "other@example.com")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = f.a.store.db.Model(&Document{}).Where("sqid=?", created.ID).Update("owner_id", other).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err = f.a.store.Grant(t.Context(), other, created.ID, "owner@example.com", RoleReader); err != nil {
+ t.Fatal(err)
+ }
+ rt, clock := configureDocAgentTestTeam(t, f)
+ ctx, id, err := f.a.prepare(t.Context(), f.p, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = f.a.documents(ctx, id.Actor, 20, ""); err != nil {
+ t.Fatal(err)
+ }
+ guard := ctx.Value(accessContextKey{}).(*requestAccess)
+ if len(guard.responseDocs) == 0 {
+ t.Fatal("late-expiry test needs a nonempty shared list")
+ }
+ clock.step(60 * time.Second)
+ if err := guard.checkResponse(ctx); err == nil {
+ t.Fatal("late roster expiry returned a partial list without notice")
+ }
+ if w := f.call(t, "docs_list", map[string]any{"team": rt.bindings.Team}); w.Code != 503 {
+ t.Fatal("partial list presented as complete", w.Code, w.Body.String())
+ }
+ if w := f.call(t, "docs_get", map[string]any{"team": rt.bindings.Team, "id": created.ID}); w.Code != 200 {
+ t.Fatal("independent share lost", w.Code, w.Body.String())
+ }
+}
+
+func TestAgentHomeOnlyIdentityRefusedWithoutAllocation(t *testing.T) {
+ f := newTeamHooksFixture(t)
+ person, err := f.h.unlinked(t.Context(), f.rt.bindings.Issuer, f.member)
+ if err != nil {
+ t.Fatal(err)
+ }
+ key, err := assertioncrypto.Generate()
+ if err != nil {
+ t.Fatal(err)
+ }
+ settings := &homeSettings{issuer: f.rt.bindings.Issuer, consumerID: f.rt.bindings.Consumer, keys: map[string][]byte{"key": key.SignPub()}, dek: bytes.Repeat([]byte{41}, 32)}
+ h, err := newHome(settings, bridgeOrigin, f.app.db.Writer(), f.app.store, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.team, h.resolver.team = f.rt, f.rt
+ if ordinary, err := h.bridge.Resolve(t.Context(), f.member); err != nil || ordinary.ID != person.ID || ordinary.Label != "" {
+ t.Fatal("ordinary Home-only resolution broken", ordinary, err)
+ }
+ a := &documentAgent{store: f.app.store, resolver: h.resolver, origin: bridgeOrigin, identityIssuer: settings.issuer, team: f.rt.bindings.Team}
+ p := access.Principal{Subject: f.member, Client: "test", Grant: "grant", Teams: []string{a.team}, Scopes: []string{"docs:read", "docs:write"}}
+ handler, err := a.httpHandler(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return p, nil }))
+ if err != nil {
+ t.Fatal(err)
+ }
+ beforePeople, beforeDocs := f.persons()
+ beforeCalls := f.calls
+ for _, path := range []string{"", "/docs_list", "/docs_get", "/docs_create", "/docs_update"} {
+ method := "POST"
+ if path == "" {
+ method = "GET"
+ }
+ r := httptest.NewRequest(method, bridgeOrigin+"/api/v1/operations"+path, strings.NewReader(`{"team":"TeamA"}`))
+ r.Header.Set("Authorization", "Bearer test-token")
+ r.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, r)
+ if w.Code != 403 {
+ t.Fatal("Home-only agent identity accepted", path, w.Code, w.Body.String())
+ }
+ }
+ if people, docs := f.persons(); people != beforePeople || docs != beforeDocs || f.calls != beforeCalls {
+ t.Fatal("agent allocated or admitted Home-only identity", people, docs, f.calls)
+ }
+}
+
+func TestAgentSharedIdentityChangesRefuseEveryOperation(t *testing.T) {
+ for _, change := range []string{"UPDATE home_identity_links SET person_binding='corrupt'", "UPDATE people SET email='changed@example.com'", "DELETE FROM home_identity_links"} {
+ t.Run(change, func(t *testing.T) {
+ f := newDocAgentFixture(t)
+ created := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
+ if err := f.a.store.db.Exec(change).Error; err != nil {
+ t.Fatal(err)
+ }
+ for op, input := range map[string]any{"docs_list": map[string]any{"team": "blue"}, "docs_get": map[string]any{"team": "blue", "id": created.ID}, "docs_create": initialAgentInput()} {
+ if w := f.call(t, op, input); w.Code != 403 {
+ t.Fatal("changed identity accepted", op, w.Code, w.Body.String())
+ }
+ }
+ })
+ }
+}
+
+func TestAgentSharedBindingCheckedBetweenResponseChunks(t *testing.T) {
+ f := newDocAgentFixture(t)
+ input := initialAgentInput()
+ input.Blocks = []agentBlock{{Type: "paragraph", Text: strings.Repeat("x", 100<<10)}}
+ created := decodeAgentBody(t, f.call(t, "docs_create", input))
+ raw, _ := json.Marshal(map[string]any{"team": "blue", "id": created.ID})
+ r := httptest.NewRequest("POST", bridgeOrigin+"/api/v1/operations/docs_get", bytes.NewReader(raw))
+ r.Header.Set("Authorization", "Bearer test-token")
+ r.Header.Set("Content-Type", "application/json")
+ w := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder(), afterWrite: func() {
+ if err := f.a.store.db.Exec("UPDATE home_identity_links SET person_binding='corrupt'").Error; err != nil {
+ t.Fatal(err)
+ }
+ }}
+ aborted := false
+ func() {
+ defer func() {
+ if err := recover(); err != nil {
+ if err != http.ErrAbortHandler {
+ panic(err)
+ }
+ aborted = true
+ }
+ }()
+ f.handler.ServeHTTP(w, r)
+ }()
+ if !aborted || w.Body.Len() != 64<<10 {
+ t.Fatal("corrupt identity continued response", aborted, w.Body.Len())
+ }
+}
diff --git a/internal/docs/agent_store.go b/internal/docs/agent_store.go
new file mode 100644
index 0000000..ddcbbeb
--- /dev/null
+++ b/internal/docs/agent_store.go
@@ -0,0 +1,371 @@
+package docs
+
+import (
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "strconv"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/handoff/seal"
+ "amadan.net/oficina/home/roster"
+ "github.com/carlosframework/docs/internal/core"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+const agentResultLimit = 1 << 20
+
+type documentAgent struct {
+ store *Store
+ resolver identityResolver
+ list allowlist
+ origin, issuer, identityIssuer, team string
+ key []byte
+ notify func(int64, int64)
+}
+type agentBlock struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+ Level uint8 `json:"level,omitempty"`
+}
+type agentCreateInput struct {
+ Team string `json:"team"`
+ ClientID string `json:"client_id"`
+ Title string `json:"title"`
+ Blocks []agentBlock `json:"blocks"`
+}
+type agentDocument struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ URL string `json:"url"`
+ UpdatedAt string `json:"updated_at"`
+}
+type agentBody struct {
+ agentDocument
+ Revision string `json:"body_revision"`
+ Text string `json:"text"`
+ Content json.RawMessage `json:"content"`
+}
+type agentReceipt struct {
+ Coordinate string `gorm:"primaryKey"`
+ Content string
+ DocumentID int64
+}
+type agentAttribution struct {
+ DocumentID int64 `gorm:"primaryKey"`
+ OperatorID int64
+ ClientSealed []byte
+}
+
+func (agentAttribution) TableName() string { return "docs_agent_attribution" }
+
+type agentCreated struct {
+ agentDocument
+ Revision string `json:"body_revision"`
+}
+
+func (agentReceipt) TableName() string { return "docs_agent_receipts" }
+
+func (a *documentAgent) digest(domain string, value any) string {
+ raw, _ := json.Marshal(value) // only fixed structs and string slices enter here
+ mac := hmac.New(sha256.New, a.key)
+ mac.Write([]byte("oficina/docs/agent/v1/" + domain + "\x00"))
+ mac.Write(raw)
+ return hex.EncodeToString(mac.Sum(nil))
+}
+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) 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
+ if err := tx.Raw("SELECT keycheck FROM docs_agent_state WHERE id=1").Scan(&got).Error; err != nil {
+ return err
+ }
+ if !hmac.Equal([]byte(got), []byte(want)) {
+ return access.Fail("unavailable", "Agent receipt authority requires an explicit migration.")
+ }
+ return nil
+}
+func agentFailure(err error) error {
+ if err == nil {
+ return nil
+ }
+ var failure access.Failure
+ if errors.As(err, &failure) {
+ return failure
+ }
+ if errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, ErrNotWritable) {
+ return access.Fail("not_found", "This document is unavailable.")
+ }
+ if errors.Is(err, errIdentityRefused) || errors.Is(err, errTeamNotMember) {
+ return access.Fail("forbidden", "This identity is not admitted for that operation.")
+ }
+ 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"
+ }
+ if p.Client == "" || !p.Allows(a.team, scope) {
+ return ctx, requestIdentity{}, access.Fail("forbidden", "This connection does not allow that team and operation.")
+ }
+ id, err := a.resolver.resolveHome(ctx, p.Subject)
+ if err != nil {
+ return ctx, id, agentFailure(err)
+ }
+ if a.store.team == nil {
+ admitted, e := a.list.allows(actorAddress(id.Actor))
+ if e != nil {
+ return ctx, id, agentFailure(e)
+ }
+ if !admitted || create && !a.list.configured(actorAddress(id.Actor)) {
+ return ctx, id, agentFailure(errIdentityRefused)
+ }
+ }
+ if existing, ok := ctx.Value(accessContextKey{}).(*requestAccess); ok && existing != nil {
+ if existing.runtime != a.store.team || !sameActor(existing.actor, id.Actor) {
+ return ctx, id, agentFailure(errIdentityRefused)
+ }
+ } else {
+ guard := &requestAccess{actor: id.Actor, responseStore: a.store, responseDocs: map[int64]permission{}}
+ if a.store.team != nil {
+ guard = a.store.team.resolveAccess(ctx, id)
+ guard.responseStore = a.store
+ guard.responseDocs = map[int64]permission{}
+ }
+ ctx = withAccess(ctx, guard)
+ }
+ if create {
+ if e := a.store.requireMember(ctx, id.Actor); e != nil {
+ return ctx, id, agentFailure(e)
+ }
+ }
+ return ctx, id, nil
+}
+func (a *documentAgent) remember(ctx context.Context, doc *Document) {
+ if guard, ok := ctx.Value(accessContextKey{}).(*requestAccess); ok && guard != nil {
+ guard.responseDocs[doc.ID] = permissionRead
+ }
+}
+func (a *documentAgent) summary(doc *Document) agentDocument {
+ return agentDocument{doc.Sqid, doc.Title, a.origin + "/d/" + doc.Sqid, doc.UpdatedAt.UTC().Format(time.RFC3339Nano)}
+}
+func agentBounded(value any) (any, error) {
+ body, err := json.Marshal(value)
+ if err != nil {
+ return nil, agentFailure(err)
+ }
+ if len(body) > agentResultLimit {
+ return nil, access.Fail("too_large", "The document result exceeds 1 MiB.")
+ }
+ return value, nil
+}
+func (a *documentAgent) body(ctx context.Context, actor Actor, sqid string) (any, error) {
+ doc, err := a.store.GetFor(ctx, actor, sqid)
+ if err != nil {
+ return nil, agentFailure(err)
+ }
+ h, seq, _, err := a.store.replay(ctx, doc)
+ if err != nil {
+ return nil, agentFailure(err)
+ }
+ defer h.Close(ctx)
+ text, err := h.Text(ctx)
+ if err != nil {
+ return nil, agentFailure(err)
+ }
+ content, err := h.JSON(ctx)
+ if err != nil {
+ return nil, agentFailure(err)
+ }
+ a.remember(ctx, doc)
+ return agentBounded(agentBody{a.summary(doc), strconv.FormatInt(seq, 10), text, json.RawMessage(content)})
+}
+
+type agentCursor struct {
+ At string `json:"at"`
+ ID string `json:"id"`
+}
+
+func (a *documentAgent) documents(ctx context.Context, actor Actor, limit int, cursor string) (any, error) {
+ if a.store.team != nil {
+ guard, ok := a.store.access(ctx, actor)
+ if !ok || guard.state() == roster.Unknown {
+ return nil, agentFailure(errTeamUnavailable)
+ }
+ guard.agentList = true
+ }
+ if limit == 0 {
+ limit = 20
+ }
+ if limit < 1 || limit > 100 {
+ return nil, access.Fail("invalid", "Choose a page size from 1 to 100.")
+ }
+ q := a.store.permissionScope(ctx, a.store.db.WithContext(ctx), actor, permissionRead).Where("documents.deleted_at IS NULL")
+ if cursor != "" {
+ var c agentCursor
+ raw, err := base64.RawURLEncoding.Strict().DecodeString(cursor)
+ if err != nil || len(raw) > 256 || base64.RawURLEncoding.EncodeToString(raw) != cursor || access.UniqueJSON(raw) != nil || json.Unmarshal(raw, &c) != nil {
+ return nil, access.Fail("invalid", "Invalid document cursor.")
+ }
+ at, e1 := time.Parse(time.RFC3339Nano, c.At)
+ id, e2 := strconv.ParseInt(c.ID, 10, 64)
+ if e1 != nil || e2 != nil || id <= 0 || strconv.FormatInt(id, 10) != c.ID || at.UTC().Format(time.RFC3339Nano) != c.At {
+ return nil, access.Fail("invalid", "Invalid document cursor.")
+ }
+ q = q.Where("(documents.updated_at < ? OR (documents.updated_at = ? AND documents.id < ?))", at, at, id)
+ }
+ var rows []*Document
+ if err := q.Order("documents.updated_at DESC, documents.id DESC").Limit(limit + 1).Find(&rows).Error; err != nil {
+ return nil, agentFailure(err)
+ }
+ next := ""
+ if len(rows) > limit {
+ rows = rows[:limit]
+ last := rows[len(rows)-1]
+ raw, _ := json.Marshal(agentCursor{last.UpdatedAt.UTC().Format(time.RFC3339Nano), strconv.FormatInt(last.ID, 10)})
+ next = base64.RawURLEncoding.EncodeToString(raw)
+ }
+ items := make([]agentDocument, 0, len(rows))
+ for _, doc := range rows {
+ a.remember(ctx, doc)
+ items = append(items, a.summary(doc))
+ }
+ return agentBounded(struct {
+ Documents []agentDocument `json:"documents"`
+ Next string `json:"next_cursor"`
+ }{items, next})
+}
+
+// checkCreator runs on the reserved writer. It reads the same identity tables as
+// the resolver without opening a second SQL connection inside the transaction.
+func (a *documentAgent) checkCreator(ctx context.Context, tx *gorm.DB, p access.Principal, id requestIdentity) error {
+ guard, ok := ctx.Value(accessContextKey{}).(*requestAccess)
+ if !ok || guard == nil || guard.delegationCheck == nil {
+ return errIdentityRefused
+ }
+ if err := guard.delegationCheck(ctx); err != nil {
+ return err
+ }
+
+ current, err := a.resolver.resolveHomeOn(ctx, tx.Statement.ConnPool, p.Subject)
+ if err != nil {
+ return err
+ }
+ if !sameActor(current.Actor, id.Actor) {
+ return errIdentityRefused
+ }
+ if a.store.team == nil && !a.list.configured(actorAddress(id.Actor)) {
+ return errIdentityRefused
+ }
+ return a.store.requireMember(ctx, id.Actor)
+}
+func (a *documentAgent) create(ctx context.Context, p access.Principal, id requestIdentity, input agentCreateInput) (any, error) {
+ u, err := uuid.Parse(input.ClientID)
+ if err != nil || u == uuid.Nil || u.String() != input.ClientID || !utf8.ValidString(input.Title) || strings.TrimSpace(input.Title) == "" || len(input.Title) > 512 || len(input.Blocks) > 200 {
+ return nil, access.Fail("invalid", "Invalid title, client UUID or initial content.")
+ }
+ blocks := make([]core.InitialBlock, len(input.Blocks))
+ total := 0
+ for i, b := range input.Blocks {
+ total += len(b.Text)
+ if !utf8.ValidString(b.Text) || total > 128<<10 || b.Type != "paragraph" && b.Type != "heading" || b.Type == "paragraph" && b.Level != 0 || b.Type == "heading" && (b.Level < 1 || b.Level > 6) {
+ return nil, access.Fail("invalid", "Invalid initial content.")
+ }
+ blocks[i] = core.InitialBlock{Text: b.Text, Level: b.Level}
+ }
+ if a.store.content == nil {
+ return nil, access.Fail("unavailable", "Activate sealed document storage before agent writes.")
+ }
+ coordinate := a.digest("coordinate", []string{a.identityIssuer, a.issuer, p.Subject, p.Client, a.team, input.ClientID})
+ payload := a.digest("content", struct {
+ Title string
+ Blocks []agentBlock
+ }{input.Title, input.Blocks})
+ var doc Document
+ err = a.store.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if e := a.bind(tx); e != nil {
+ return e
+ }
+ if e := a.checkCreator(ctx, tx, p, id); e != nil {
+ return e
+ }
+ var receipt agentReceipt
+ 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 initial content.")
+ }
+ if e = tx.Where("id=? AND deleted_at IS NULL", receipt.DocumentID).First(&doc).Error; e != nil {
+ return e
+ }
+ if err := a.store.checkPermission(ctx, tx, id.Actor, doc.ID, permissionRead); err != nil {
+ return err
+ }
+ return a.checkCreator(ctx, tx, p, id)
+ }
+ if !errors.Is(e, gorm.ErrRecordNotFound) {
+ return e
+ }
+ store := *a.store
+ store.db = tx
+ created, e := store.CreateDraft(ctx, id.Actor.PersonID, input.Title, "")
+ if e != nil {
+ return e
+ }
+ update, e := store.core.InitialUpdate(ctx, created.GUID, created.ClientID, blocks)
+ if e != nil {
+ return e
+ }
+ if _, e = store.ApplyUpdate(ctx, created, id.Actor, update); e != nil {
+ return e
+ }
+ sealer, e := seal.New(a.key, "oficina/docs")
+ if e != nil {
+ return e
+ }
+ client, e := sealer.Seal("agent-client/"+created.GUID, []byte(p.Client))
+ if e != nil {
+ return e
+ }
+ if e = tx.Create(&agentAttribution{created.ID, id.Actor.PersonID, client}).Error; e != nil {
+ return e
+ }
+ receipt = agentReceipt{coordinate, payload, created.ID}
+ if e = tx.Create(&receipt).Error; e != nil {
+ return e
+ }
+ doc = *created
+ return a.checkCreator(ctx, tx, p, id)
+ })
+ if err != nil {
+ return nil, agentFailure(err)
+ }
+ // A retry reads the current body, including intervening browser edits.
+ current, e := a.store.GetFor(ctx, id.Actor, doc.Sqid)
+ if e != nil {
+ return nil, agentFailure(e)
+ }
+ h, seq, _, e := a.store.replay(ctx, current)
+ if e != nil {
+ return nil, agentFailure(e)
+ }
+ defer h.Close(ctx)
+ a.remember(ctx, current)
+ return agentBounded(agentCreated{a.summary(current), strconv.FormatInt(seq, 10)})
+}
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(), &copy)
+ 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 e5e52b3..bbef648 100644
--- a/internal/docs/app.go
+++ b/internal/docs/app.go
@@ -44,7 +44,9 @@ import (
// Config configures New.
type Config struct {
- Home *HomeConfig
+ AgentIssuer string
+ AgentTeam string
+ Home *HomeConfig
// Directory is the hub directory origin ($HOME_DIRECTORY_ORIGIN): the
// app switcher's "All apps". Empty means no switcher.
Directory string
@@ -385,6 +387,10 @@ func New(cfg Config) (*App, error) {
if err != nil {
return nil, err
}
+ agentVerifier, err := validatedAgentConfig(cfg, homeSettings, teamSettings)
+ if err != nil {
+ return nil, err
+ }
instanceKey, err := resolveInstanceKey(cfg)
if err != nil {
return nil, err
@@ -797,6 +803,16 @@ func New(cfg Config) (*App, error) {
mux := http.NewServeMux()
mux.Handle("/", r)
+ if agentVerifier != nil {
+ agentHandler, e := newDocumentAgent(cfg, homeSettings, home, store, list, agentVerifier, h.hub.broadcast)
+ if e != nil {
+ rt.Close(context.Background())
+ d.Close()
+ return nil, e
+ }
+ mux.Handle("/api/v1/operations", agentHandler)
+ mux.Handle("/api/v1/operations/", agentHandler)
+ }
// The suite contract's producer half (suite.go), beside the router
// rather than in it. A grant admits its holder here exactly as it does
// at the front door, so S2 reads the same allowlist the router does.
diff --git a/internal/docs/colophon.json b/internal/docs/colophon.json
index de0cb54..ff00b57 100644
--- a/internal/docs/colophon.json
+++ b/internal/docs/colophon.json
@@ -104,6 +104,17 @@
}
]
},
+ {
+ "ecosystem": "go",
+ "name": "github.com/google/jsonschema-go",
+ "version": "v0.4.3",
+ "notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "MIT License\n\nCopyright (c) 2025 JSON Schema Go Project Authors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
+ }
+ ]
+ },
{
"ecosystem": "go",
"name": "github.com/google/uuid",
@@ -143,6 +154,17 @@
"version": "v0.1.1",
"notices": []
},
+ {
+ "ecosystem": "go",
+ "name": "github.com/modelcontextprotocol/go-sdk",
+ "version": "v1.7.0",
+ "notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 (\"Apache-2.0\"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0.\n\nContributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License.\n\nNo rights beyond those granted by the applicable original license are conveyed for such contributions.\n\n---\n\n Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright\n owner or by an individual or Legal Entity authorized to submit on behalf\n of the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n 4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n 5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n 6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n 7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n 8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n 9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability.\n\n END OF TERMS AND CONDITIONS\n\n---\n\nMIT License\n\nCopyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n---\n\nCreative Commons Attribution 4.0 International (CC-BY-4.0)\n\nDocumentation in this project (excluding specifications) is licensed under\nCC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for\nthe full license text.\n"
+ }
+ ]
+ },
{
"ecosystem": "go",
"name": "github.com/remyoudompheng/bigfft",
@@ -154,6 +176,39 @@
}
]
},
+ {
+ "ecosystem": "go",
+ "name": "github.com/santhosh-tekuri/jsonschema/v6",
+ "version": "v6.0.3",
+ "notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "\n Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n 4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n 5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n 6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n 7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n 8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n 9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability."
+ }
+ ]
+ },
+ {
+ "ecosystem": "go",
+ "name": "github.com/segmentio/asm",
+ "version": "v1.1.3",
+ "notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "MIT License\n\nCopyright (c) 2021 Segment\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
+ }
+ ]
+ },
+ {
+ "ecosystem": "go",
+ "name": "github.com/segmentio/encoding",
+ "version": "v0.5.4",
+ "notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "MIT License\n\nCopyright (c) 2019 Segment.io, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
+ }
+ ]
+ },
{
"ecosystem": "go",
"name": "github.com/tetratelabs/wazero",
@@ -169,6 +224,17 @@
}
]
},
+ {
+ "ecosystem": "go",
+ "name": "github.com/yosida95/uritemplate/v3",
+ "version": "v3.0.2",
+ "notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "Copyright (C) 2016, Kohei YOSHIDA <https://yosida95.com/>. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n * Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
+ }
+ ]
+ },
{
"ecosystem": "go",
"name": "golang.org/x/image",
@@ -180,6 +246,28 @@
}
]
},
+ {
+ "ecosystem": "go",
+ "name": "golang.org/x/oauth2",
+ "version": "v0.35.0",
+ "notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "Copyright 2009 The Go Authors.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google LLC nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
+ }
+ ]
+ },
+ {
+ "ecosystem": "go",
+ "name": "golang.org/x/sync",
+ "version": "v0.21.0",
+ "notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "Copyright 2009 The Go Authors.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google LLC nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
+ }
+ ]
+ },
{
"ecosystem": "go",
"name": "golang.org/x/sys",
@@ -202,6 +290,17 @@
}
]
},
+ {
+ "ecosystem": "go",
+ "name": "golang.org/x/time",
+ "version": "v0.15.0",
+ "notices": [
+ {
+ "Name": "LICENSE",
+ "Text": "Copyright 2009 The Go Authors.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google LLC nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
+ }
+ ]
+ },
{
"ecosystem": "go",
"name": "gorm.io/gorm",
diff --git a/internal/docs/identity.go b/internal/docs/identity.go
index 3afa353..4afe094 100644
--- a/internal/docs/identity.go
+++ b/internal/docs/identity.go
@@ -185,3 +185,35 @@ func requestActor(r *http.Request, store *Store) (Actor, error) {
id, err := (identityResolver{store: store}).resolve(r)
return id.Actor, err
}
+
+// resolveHome is the agent identity boundary. Unlike browser resolution, this
+// first integration admits only an existing linked local account. ResolveOn
+// verifies the complete keyed binding on the supplied connection and never
+// invokes addressless-person hooks outside a caller transaction.
+func (v identityResolver) resolveHome(ctx context.Context, subject string) (requestIdentity, error) {
+ if v.store == nil {
+ return requestIdentity{}, errIdentityRefused
+ }
+ return v.resolveHomeOn(ctx, v.store.db.Statement.ConnPool, subject)
+}
+
+func (v identityResolver) resolveHomeOn(ctx context.Context, q linkstore.Queryer, subject string) (requestIdentity, error) {
+ links, ok := v.links.(interface {
+ ResolveOn(context.Context, linkstore.Queryer, string) (connect.Person, error)
+ })
+ if !ok || subject == "" || v.store == nil || v.store.team != nil && v.team == nil {
+ return requestIdentity{}, errIdentityRefused
+ }
+ p, err := links.ResolveOn(ctx, q, subject)
+ if errors.Is(err, linkstore.ErrRefused) {
+ return requestIdentity{}, errIdentityRefused
+ }
+ if err != nil {
+ return requestIdentity{}, errIdentityStorage
+ }
+ address := subjectOf(p.Label)
+ if p.ID <= 0 || address == "" {
+ return requestIdentity{}, errIdentityRefused
+ }
+ return requestIdentity{Actor: localActor(p.ID, address), HomeSubject: subject}, nil
+}
diff --git a/internal/docs/migrations/0009_agent_access.sql b/internal/docs/migrations/0009_agent_access.sql
new file mode 100644
index 0000000..96b54b3
--- /dev/null
+++ b/internal/docs/migrations/0009_agent_access.sql
@@ -0,0 +1,15 @@
+CREATE TABLE docs_agent_state (
+ id INTEGER PRIMARY KEY CHECK(id=1),
+ keycheck TEXT NOT NULL
+);
+CREATE TABLE docs_agent_receipts (
+ coordinate TEXT PRIMARY KEY NOT NULL,
+ content TEXT NOT NULL,
+ document_id INTEGER NOT NULL
+);
+
+CREATE TABLE docs_agent_attribution (
+ document_id INTEGER PRIMARY KEY NOT NULL,
+ operator_id INTEGER NOT NULL,
+ client_sealed BLOB NOT NULL
+);
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/internal/docs/migrations/0009_suite.sql b/internal/docs/migrations/0011_suite.sql
similarity index 100%
rename from internal/docs/migrations/0009_suite.sql
rename to internal/docs/migrations/0011_suite.sql
diff --git a/internal/docs/models.go b/internal/docs/models.go
index bac4ec5..d3b4380 100644
--- a/internal/docs/models.go
+++ b/internal/docs/models.go
@@ -58,7 +58,7 @@ type Document struct {
// Visibility is the document's rung beside grants and links:
// VisibilityPrivate or VisibilityTeam (spec Β§8.2.1). createDocument
// always writes it; the default tag only means a row built some other way
- // (a test inserting a Document directly) is private, as 0009 makes every
+ // (a test inserting a Document directly) is private, as 0011 makes every
// existing row, rather than an empty string the CHECK refuses.
Visibility Visibility `gorm:"column:visibility;not null;default:private"`
// Revision is replaced on every change a suite consumer must re-read:
@@ -88,7 +88,7 @@ const (
func (v Visibility) valid() bool { return v == VisibilityPrivate || v == VisibilityTeam }
// SuiteFeedRow is one row of the append-only log suite S1 pages through
-// (0009_suite.sql): which document, at which revision, whether that bump
+// (0011_suite.sql): which document, at which revision, whether that bump
// deleted it, and when. Written only by bumpRevision and CreateDraft, inside
// the transaction that made the change.
type SuiteFeedRow struct {
diff --git a/internal/docs/store.go b/internal/docs/store.go
index 08e899c..eb31ce7 100644
--- a/internal/docs/store.go
+++ b/internal/docs/store.go
@@ -7,6 +7,7 @@ import (
"fmt"
"html/template"
"log/slog"
+ "math"
mrand "math/rand/v2"
"strings"
"time"
@@ -311,10 +312,9 @@ func (s *Store) createDocument(ctx context.Context, owner int64, title, token st
return nil, err
}
guid := uuid.NewString()
- // math/rand/v2's Int64 returns a non-negative value in [0, 1<<63),
- // so converting to uint64 never wraps β€” the brief's "a counter or
- // random int64 from math/rand/v2".
- clientID := uint64(mrand.Int64())
+ // Initial content authors Yjs structs under this ID. Keep it in Yjs'
+ // uint32 client-ID range; a random int64 can exceed JS integer precision.
+ clientID := uint64(mrand.Uint32N(math.MaxUint32)) + 1
now := time.Now().UTC()
revision, err := newRevision(0)
diff --git a/internal/docs/store_test.go b/internal/docs/store_test.go
index b32d74b..723fca9 100644
--- a/internal/docs/store_test.go
+++ b/internal/docs/store_test.go
@@ -2,6 +2,7 @@ package docs_test
import (
"context"
+ "math"
"net/http"
"net/http/httptest"
"testing"
@@ -25,7 +26,7 @@ func TestCreateListGetRoundTrip(t *testing.T) {
if made.Sqid == "" {
t.Fatal("Create returned an empty sqid")
}
- if made.GUID == "" || made.ClientID == 0 {
+ if made.GUID == "" || made.ClientID == 0 || made.ClientID > math.MaxUint32 {
t.Fatal("Create must assign a GUID and client id, never draw them from yrs")
}
diff --git a/internal/docs/suite_feed.go b/internal/docs/suite_feed.go
index 387cf61..277cbcf 100644
--- a/internal/docs/suite_feed.go
+++ b/internal/docs/suite_feed.go
@@ -51,7 +51,7 @@ func randomPositive() (int64, error) {
// int63, never the document's current one. Revisions are not counted up and
// not read from a clock (Astra on oficina/docs feat/suite-producer, two
// rounds, 2026-11-01): after a restore from a backup β€” including one taken
-// before migration 0009, and one restored onto a clock set back β€” a counter
+// before migration 0011, and one restored onto a clock set back β€” a counter
// or a clock issues again a revision it issued before, for different
// content, and S2 answers VISIBLE against a copy the asker may no longer
// read. A draw matches any one earlier value with probability 2^-63
diff --git a/internal/docs/suite_test.go b/internal/docs/suite_test.go
index 976822d..3e5ca4a 100644
--- a/internal/docs/suite_test.go
+++ b/internal/docs/suite_test.go
@@ -274,11 +274,11 @@ func TestSuiteConformanceTeamMode(t *testing.T) {
}
// The two halves of Paul's 2026-11-01 ruling, "New docs Team, old private":
-// a document made from now on is on the team rung, and migration 0009 leaves
+// a document made from now on is on the team rung, and migration 0011 leaves
// every existing one private. The sample library is private too.
//
// MUTATION-TESTED 2026-11-01, each reverted: CreateDraft passing
-// VisibilityPrivate β†’ "a new document"; 0009's DEFAULT 'team' β†’ "an existing
+// VisibilityPrivate β†’ "a new document"; 0011's DEFAULT 'team' β†’ "an existing
// document"; seed.go creating on the team rung β†’ "sample".
func TestSuiteNewDocumentsAreTeamAndExistingArePrivate(t *testing.T) {
app, err := NewForTest(t)
@@ -333,7 +333,7 @@ func TestSuiteNewDocumentsAreTeamAndExistingArePrivate(t *testing.T) {
}
}
for _, n := range names {
- if n < "0009" {
+ if n < "0011" {
exec(n)
}
}
@@ -351,7 +351,7 @@ func TestSuiteNewDocumentsAreTeamAndExistingArePrivate(t *testing.T) {
t.Fatal(err)
}
}
- exec("0009_suite.sql")
+ exec("0011_suite.sql")
var private, distinct, low int
db.QueryRow(`SELECT COUNT(*) FROM documents WHERE visibility = 'private'`).Scan(&private)
db.QueryRow(`SELECT COUNT(DISTINCT revision) FROM documents`).Scan(&distinct)
@@ -1029,28 +1029,28 @@ func TestSuiteRestoreNeverReissuesARevisionOrACursor(t *testing.T) {
}
}
-// Astra's second-round sequence: a backup taken BEFORE migration 0009. A
+// Astra's second-round sequence: a backup taken BEFORE migration 0011. A
// harmless document is granted to Bob and backed up; Bob is revoked and the
-// document renamed to confidential text; the suite is deployed (0009 runs)
-// and memoria holds the confidential revision; the pre-0009 backup is
-// restored and the new build boots, running 0009 again over the harmless,
+// document renamed to confidential text; the suite is deployed (0011 runs)
+// and memoria holds the confidential revision; the pre-0011 backup is
+// restored and the new build boots, running 0011 again over the harmless,
// Bob-granted document. A constant there gave it the same revision as the
// confidential copy, and S2 answered VISIBLE for Bob. No clock involved.
//
-// MUTATION-TESTED 2026-11-01, reverted: 0009 without its random UPDATE (every
+// MUTATION-TESTED 2026-11-01, reverted: 0011 without its random UPDATE (every
// existing document at revision 1, as before) β†’ Bob VISIBLE.
-func TestSuiteRestoreOfAPre0009BackupIssuesNewRevisions(t *testing.T) {
+func TestSuiteRestoreOfAPreSuiteBackupIssuesNewRevisions(t *testing.T) {
dir := t.TempDir()
path, backup := filepath.Join(dir, "docs.db"), filepath.Join(dir, "backup.db")
- // A database at 0008: the boot schema with Docs' own set cut before 0009.
+ // A database at 0010: the boot schema with Docs' own set cut before 0011.
old := fstest.MapFS{}
entries, err := fs.ReadDir(migrationFS, "migrations")
if err != nil {
t.Fatal(err)
}
for _, e := range entries {
- if e.Name() < "0009" {
+ if e.Name() < "0011" {
b, _ := fs.ReadFile(migrationFS, "migrations/"+e.Name())
old["migrations/"+e.Name()] = &fstest.MapFile{Data: b}
}
@@ -1113,7 +1113,7 @@ func TestSuiteRestoreOfAPre0009BackupIssuesNewRevisions(t *testing.T) {
t.Fatal(err)
}
if got[0] != suite.UNKNOWN {
- t.Errorf("S2 for Bob at the confidential copy's revision after restoring a pre-0009 backup: %s, want UNKNOWN", got[0])
+ t.Errorf("S2 for Bob at the confidential copy's revision after restoring a pre-0011 backup: %s, want UNKNOWN", got[0])
}
}
diff --git a/internal/docs/team_access.go b/internal/docs/team_access.go
index 645cc74..81a12c7 100644
--- a/internal/docs/team_access.go
+++ b/internal/docs/team_access.go
@@ -18,6 +18,9 @@ type accessContextKey struct{}
// NotMember or Unknown, the lease re-checked whenever it is asked and
// Unknown latched) and the actor it was decided for.
type requestAccess struct {
+ extraCheck func(context.Context) error
+ delegationCheck func(context.Context) error
+ agentList bool
*teammode.Access
responseStore *Store
responseDocs map[int64]permission
diff --git a/internal/docs/team_emission.go b/internal/docs/team_emission.go
index bd4f87b..d56b952 100644
--- a/internal/docs/team_emission.go
+++ b/internal/docs/team_emission.go
@@ -31,10 +31,15 @@ func (s *Store) rememberResponse(ctx context.Context, p permission, docs ...*Doc
}
}
func (a *requestAccess) checkResponse(ctx context.Context) error {
+ if a.extraCheck != nil {
+ if err := a.extraCheck(ctx); err != nil {
+ return err
+ }
+ }
if a.responseStore == nil {
return errTeamUnavailable
}
- if len(a.responseDocs) == 0 && a.state() == roster.Unknown && !a.partialNotice {
+ if a.runtime != nil && a.state() == roster.Unknown && (a.agentList || len(a.responseDocs) == 0 && !a.partialNotice) {
return errTeamUnavailable
}
for id, p := range a.responseDocs {
@@ -75,6 +80,7 @@ func writeGuardedBody(w http.ResponseWriter, r *http.Request, status int, parts
}
controller := http.NewResponseController(w)
prepare := func() error {
+ started := time.Now()
remaining := defaultStreamWriteDeadline
if a.state() == roster.Member {
lease := a.Remaining()
@@ -85,9 +91,10 @@ func writeGuardedBody(w http.ResponseWriter, r *http.Request, status int, parts
remaining = lease
}
}
- deadline := time.Now().Add(remaining)
+ deadline := started.Add(remaining)
ctx, cancel := context.WithDeadline(r.Context(), deadline)
defer cancel()
+ deadline, _ = ctx.Deadline()
if e := a.checkResponse(ctx); e != nil {
return e
}
diff --git a/internal/docs/team_emission_test.go b/internal/docs/team_emission_test.go
index 17f313a..d43ccae 100644
--- a/internal/docs/team_emission_test.go
+++ b/internal/docs/team_emission_test.go
@@ -80,3 +80,51 @@ func TestTeamBufferedEmissionRefusesLateAndAbortsPartial(t *testing.T) {
})
}
}
+
+// The transport must respect a caller's tighter deadline, not just the lease
+// and the standard write budget. Removing ctx.Deadline assignment is RED.
+type deadlineCapture struct {
+ *httptest.ResponseRecorder
+ deadlines []time.Time
+}
+
+func (w *deadlineCapture) SetWriteDeadline(d time.Time) error {
+ if !d.IsZero() {
+ w.deadlines = append(w.deadlines, d)
+ }
+ return nil
+}
+func TestTeamBufferedEmissionUsesShorterRequestDeadline(t *testing.T) {
+ app := newSampleDocumentsInternalTestApp(t, "0")
+ s := app.Store()
+ owner, err := s.EnsurePerson(t.Context(), "owner@example.com")
+ if err != nil {
+ t.Fatal(err)
+ }
+ doc, err := s.Create(t.Context(), owner, "owned")
+ if err != nil {
+ t.Fatal(err)
+ }
+ rt, _, subject := testTeamRoster(t, s, app)
+ actor := localActor(owner, "owner@example.com")
+ deadline := time.Now().Add(time.Second)
+ ctx, cancel := context.WithDeadline(t.Context(), deadline)
+ defer cancel()
+ ctx = context.WithValue(ctx, accessContextKey{}, rt.resolveAccess(ctx, requestIdentity{Actor: actor, HomeSubject: subject}))
+ if _, err = s.GetFor(ctx, actor, doc.Sqid); err != nil {
+ t.Fatal(err)
+ }
+ w := &deadlineCapture{ResponseRecorder: httptest.NewRecorder()}
+ r := httptest.NewRequest("GET", "https://docs.example/d/"+doc.Sqid, nil).WithContext(ctx)
+ if err = writeGuardedBody(w, r, 200, []byte("guarded")); err != nil || w.Code != 200 {
+ t.Fatal(err, w.Code)
+ }
+ if len(w.deadlines) == 0 {
+ t.Fatal("no write deadline")
+ }
+ for _, got := range w.deadlines {
+ if got.After(deadline) {
+ t.Fatal("transport outlives caller deadline", got, deadline)
+ }
+ }
+}
diff --git a/internal/shipped/shipped.go b/internal/shipped/shipped.go
index 92cca85..e42e846 100644
--- a/internal/shipped/shipped.go
+++ b/internal/shipped/shipped.go
@@ -56,12 +56,13 @@ import (
// Native's server half (amadan.net/rastrillo/native/server), which
// internal/docs links as nativeauth.
var FirstParty = map[string]bool{
- "amadan.net/oficina/estilo.git": true,
- "amadan.net/oficina/home/connect": true,
- "amadan.net/oficina/home/dashboard": true,
- "amadan.net/oficina/home/handoff": true,
- "amadan.net/oficina/home/roster": true,
- "amadan.net/oficina/home/teammode": true,
+ "amadan.net/oficina/agent-access.git": true,
+ "amadan.net/oficina/estilo.git": true,
+ "amadan.net/oficina/home/connect": true,
+ "amadan.net/oficina/home/dashboard": true,
+ "amadan.net/oficina/home/handoff": true,
+ "amadan.net/oficina/home/roster": true,
+ "amadan.net/oficina/home/teammode": true,
// The suite contract (spec Β§8.2.2): Oficina's own, like Home's modules.
"amadan.net/oficina/suite": true,
}
diff --git a/scripts/wire-gate.sh b/scripts/wire-gate.sh
index 4b41870..effe860 100755
--- a/scripts/wire-gate.sh
+++ b/scripts/wire-gate.sh
@@ -20,4 +20,7 @@ echo "--- Rust reads what JS wrote"
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"