Build bounded initial document content through the collaborative core
14 files changed,
+340
−11
core/src/abi.rs+20 −0core/src/bin/emit_initial.rs+18 −0core/src/initial.rs+61 −0core/src/lib.rs+4 −1core/tests/initial.rs+62 −0docs/superpowers/specs/2026-10-25-agent-access.md+20 −4fixtures/verify-initial.mjs+16 −0internal/core/core.go+1 −1internal/core/initial.go+67 −0internal/core/initial_test.go+63 −0internal/core/testdata/docs_core.wasmbinaryinternal/docs/store.go+4 −4internal/docs/store_test.go+2 −1scripts/wire-gate.sh+2 −0
CI cancelled — superseded by a newer push — run details
diff --git a/core/src/abi.rs b/core/src/abi.rs| index b86b56e..1661e21 100644 |
| --- a/core/src/abi.rs |
| +++ b/core/src/abi.rs |
| @@ -499,3 +499,23 @@ 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, |
| + }, |
| + } |
| +} |
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/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..df12264 100644 |
| --- a/core/src/lib.rs |
| +++ b/core/src/lib.rs |
| @@ -55,6 +55,7 @@ |
| //! it won't. |
| pub mod abi; |
| 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 +87,8 @@ 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. |
| +/// |
| /// 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 +101,7 @@ extern "Rust" fn __getrandom_v03_custom( |
| /// here. |
| #[no_mangle] |
| pub extern "C" fn docs_core_abi_version() -> u32 { |
| - 4 |
| + 5 |
| } |
| use yrs::updates::decoder::Decode; |
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("<script>& 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/superpowers/specs/2026-10-25-agent-access.md b/docs/superpowers/specs/2026-10-25-agent-access.md| index 525a8fb..942dafa 100644 |
| --- a/docs/superpowers/specs/2026-10-25-agent-access.md |
| +++ b/docs/superpowers/specs/2026-10-25-agent-access.md |
| @@ -71,15 +71,18 @@ 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 Home subject, OAuth client, selected team and UUID |
| +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 in adapter state |
| +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; mismatch |
| +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; |
| @@ -112,7 +115,7 @@ 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 and changed receipt key, |
| +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 |
| @@ -121,3 +124,16 @@ 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. |
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/internal/core/core.go b/internal/core/core.go| index b817f15..ac6fcb5 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 = 5 |
| // 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/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, "<script>&") { |
| + 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 53decb9..17eed73 100755 |
| Binary files a/internal/core/testdata/docs_core.wasm and b/internal/core/testdata/docs_core.wasm differ |
diff --git a/internal/docs/store.go b/internal/docs/store.go| index 414ea2c..a10b2ee 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" |
| @@ -290,10 +291,9 @@ func (s *Store) CreateDraft(ctx context.Context, owner int64, title, token strin |
| 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() |
| var lastErr error |
diff --git a/internal/docs/store_test.go b/internal/docs/store_test.go| index 679c789..daeeaac 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/scripts/wire-gate.sh b/scripts/wire-gate.sh| index 4b41870..9622315 100755 |
| --- a/scripts/wire-gate.sh |
| +++ b/scripts/wire-gate.sh |
| @@ -20,4 +20,6 @@ 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 |
| + |
| echo "wire-gate: ok" |