oficina / slides Public

Add delegated slides creation, reads and revision-checked editing

Prompts:

  Maybe crack on with own-rolled and coalesce on a later Rastrillo update?

Squashed from feat/agent-access into main.
codex agent, operated by paul@keymail.dev af4f47e6b0c5cf143fd387c831f131a97ab32ca1 parent 951373f
45 files changed, +3,719 −105
  • .amadan/README.md +1 −1
  • cmd/slides-contract/main.go +22 −0
  • cmd/slides/main.go +18 −15
  • docs/agent-access.md +42 −0
  • docs/superpowers/specs/2026-10-25-agent-access.md +58 −0
  • docs/superpowers/specs/2026-11-01-agent-deck-editing.md +231 −0
  • go.mod +16 −2
  • go.sum +44 −2
  • internal/slides/agent_access.go +248 −0
  • internal/slides/agent_attribution.go +64 −0
  • internal/slides/agent_authority.go +176 −0
  • internal/slides/agent_authority_test.go +222 −0
  • internal/slides/agent_config_test.go +95 −0
  • internal/slides/agent_create.go +150 −0
  • internal/slides/agent_create_test.go +84 −0
  • internal/slides/agent_edit.go +229 −0
  • internal/slides/agent_edit_boundary_test.go +214 −0
  • internal/slides/agent_edit_contract.go +70 −0
  • internal/slides/agent_edit_test.go +339 −0
  • internal/slides/agent_fixture_test.go +94 −0
  • internal/slides/agent_integration_test.go +172 −0
  • internal/slides/agent_migrations/migrations/0001_connections.sql +3 −0
  • internal/slides/agent_migrations/migrations/0002_edits.sql +7 −0
  • internal/slides/agent_operations.go +95 −0
  • internal/slides/agent_read.go +89 −0
  • internal/slides/agent_read_test.go +148 −0
  • internal/slides/agent_response_test.go +93 −0
  • internal/slides/agent_team_compat_test.go +162 −0
  • internal/slides/agent_team_lease_test.go +80 −0
  • internal/slides/agent_wait_test.go +88 −0
  • internal/slides/agents.go +1 −1
  • internal/slides/app.go +15 −0
  • internal/slides/config.go +3 −1
  • internal/slides/core/testdata/slides_core.wasm binary
  • internal/slides/credits/assets.json +13 −2
  • internal/slides/credits/notices.json +99 −0
  • internal/slides/credits/upstream/fastrand-vendor.json +19 −0
  • internal/slides/decks.go +69 −48
  • internal/slides/handlers.go +2 −0
  • internal/slides/pdfcore/testdata/slides_pdf.wasm binary
  • internal/slides/snapshot.go +13 −4
  • internal/slides/team_guard_test.go +1 −0
  • scripts/build-pdf-wasm.sh +54 −19
  • scripts/build-wasm.sh +52 −7
  • scripts/credits.py +24 −3

CI passed — run details

landed from feat/agent-access

diff --git a/.amadan/README.md b/.amadan/README.md
index 869296e..edffefd 100644
--- a/.amadan/README.md
+++ b/.amadan/README.md
@@ -10,7 +10,7 @@ It needs a Rust toolchain with the `wasm32-unknown-unknown` target and the
`rustfmt` and `clippy` components (`rust-toolchain.toml` pins 1.98.0 and
asks for all three), Go, and — since slice 2 — **Node 20 or newer with
`npm`**, because the editor's bundle and the fixture vectors are both
-built by JS this repo owns. `CGO_ENABLED=0` is exported for every step.
+built by JS this repo owns. Canonical Wasm builds additionally require Docker, or bubblewrap on Linux amd64. Both modules build under pinned Rust 1.98.0 at fixed Linux paths with separate target caches; a native fallback would defeat the byte comparison. `CGO_ENABLED=0` is exported for every step.
The gate sources `~/.cargo/env` itself and checks every tool up front, so
a missing dependency fails on the first line with its own name rather
than fifty lines in as `cargo: command not found`.
diff --git a/cmd/slides-contract/main.go b/cmd/slides-contract/main.go
new file mode 100644
index 0000000..6297560
--- /dev/null
+++ b/cmd/slides-contract/main.go
@@ -0,0 +1,22 @@
+// Command slides-contract exports the live delegated operation schemas.
+package main
+
+import (
+ "amadan.net/oficina/slides/internal/slides"
+ "encoding/json"
+ "fmt"
+ "os"
+)
+
+func main() {
+ operations, err := slides.AgentContracts()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Could not export Slides operation contracts.")
+ os.Exit(1)
+ }
+ encoder := json.NewEncoder(os.Stdout)
+ encoder.SetIndent("", " ")
+ if encoder.Encode(operations) != nil {
+ os.Exit(1)
+ }
+}
diff --git a/cmd/slides/main.go b/cmd/slides/main.go
index 8d591fa..90b39ec 100644
--- a/cmd/slides/main.go
+++ b/cmd/slides/main.go
@@ -211,6 +211,22 @@ func main() {
origin = "http://" + opts.Addr
}
+ var homeConfig *connect.Credentials
+ hc := connect.Credentials{Issuer: os.Getenv("SLIDES_HOME_ISSUER"), ConsumerID: os.Getenv("SLIDES_HOME_CONSUMER_ID"), KeysBase64: os.Getenv("SLIDES_HOME_KEYS_BASE64"), DEKBase64: os.Getenv("SLIDES_HOME_DEK_BASE64")}
+ if hc.Issuer != "" || hc.ConsumerID != "" || hc.KeysBase64 != "" || hc.DEKBase64 != "" {
+ // The hub directory the app switcher's "All apps" links to.
+ // Optional, and unprefixed: the same name and the same value
+ // Home itself reads (connect.CredentialsFromEnv reads it the
+ // same way; this app builds Credentials by hand). Checked by
+ // connect.DecodeCredentials, so a malformed value refuses boot.
+ hc.Directory = os.Getenv("HOME_DIRECTORY_ORIGIN")
+ homeConfig = &hc
+ }
+ if err := slides.ValidateAgentConfig(os.Getenv("SLIDES_AGENT_ISSUER"), os.Getenv("SLIDES_AGENT_TEAM"), origin, homeConfig); err != nil {
+ logger.Error("configure agent access", "err", err)
+ os.Exit(1)
+ }
+
store, err := newBlobs(env, opts.DBPath, logger)
if err != nil {
logger.Error("bind object store", "err", err)
@@ -226,21 +242,8 @@ func main() {
// Every empty value below is a startup refusal inside slides.New
// unless env is "development" — see config.go's package comment.
- var homeConfig *connect.Credentials
- hc := connect.Credentials{Issuer: os.Getenv("SLIDES_HOME_ISSUER"), ConsumerID: os.Getenv("SLIDES_HOME_CONSUMER_ID"), KeysBase64: os.Getenv("SLIDES_HOME_KEYS_BASE64"), DEKBase64: os.Getenv("SLIDES_HOME_DEK_BASE64")}
- if hc.Issuer != "" || hc.ConsumerID != "" || hc.KeysBase64 != "" || hc.DEKBase64 != "" {
- // The hub directory the app switcher's "All apps" links to.
- // Optional, and unprefixed: the same name and the same value
- // Home itself reads (connect.CredentialsFromEnv reads it the
- // same way; this app builds Credentials by hand). Checked by
- // connect.DecodeCredentials, so a malformed value refuses boot.
- hc.Directory = os.Getenv("HOME_DIRECTORY_ORIGIN")
- homeConfig = &hc
- }
- mux, a, err := slides.New(d, slides.Config{Home: homeConfig,
- // Roster team mode: the five SLIDES_TEAM_* variables, all or
- // none (nil when all are empty), verified against the Home
- // credentials above before anything migrates (team_config.go).
+
+ mux, a, err := slides.New(d, slides.Config{Home: homeConfig, AgentIssuer: os.Getenv("SLIDES_AGENT_ISSUER"), AgentTeam: os.Getenv("SLIDES_AGENT_TEAM"),
Team: teammode.ConfigFromEnv("SLIDES"),
Origin: origin,
Env: env,
diff --git a/docs/agent-access.md b/docs/agent-access.md
new file mode 100644
index 0000000..11df9a6
--- /dev/null
+++ b/docs/agent-access.md
@@ -0,0 +1,42 @@
+# Oficina delegated connection
+
+The optional adapter exposes Slides through one Oficina browser grant. Configure `SLIDES_AGENT_ISSUER` (the separate connection service) and `SLIDES_AGENT_TEAM` together, with the existing valid `SLIDES_HOME_*` configuration. Both must be empty to disable it. The app verifies its exact audience `<SLIDES_ORIGIN>/api/v1` and exact Home identity issuer, then resolves an existing linked, currently admitted local account. An agent cannot create or silently link an account.
+
+The operation descriptors are exported with `go run ./cmd/slides-contract`. Use these in the connection service's trusted team/instance directory. They drive the same API, CLI and MCP contracts:
+
+| Tool | Scope | Input |
+|---|---|---|
+| slides_list_decks | slides:read | team, optional limit (1–100), cursor |
+| slides_get_deck | slides:read | team, sqid |
+| slides_create_deck | slides:write | team, client_id UUID, title, optional theme, slides |
+| slides_update_deck | slides:write | team, sqid, expected_revision, client_id UUID, ops |
+
+Each initial slide contains `heading`, `body_markdown`, and `notes_markdown`. Supply 1–50 slides and at most 128 KiB of combined text. Titles are at most 512 UTF-8 bytes. New decks start private and use the existing collaborative block tree, so browser editing and presentation work normally. Reads include speaker notes for the same current permissions as the existing drive API. Results and input are bounded at 1 MiB. Creation returns only sqid, URL and decimal-string revision.
+
+Reuse the same nonzero canonical UUID and identical normalized payload after an uncertain response. Metadata, core update, actor attribution and receipt commit together. Retrying never overwrites later edits or recreates a deleted deck. Changing Home DEK, Home issuer, connection issuer or team after receipts exist requires an explicit migration; restarting with a new retry namespace is refused.
+
+The CLI uses `oficina call slides_create_deck --input <JSON-file>` according to the installed CLI's help. Paseo can use the CLI's local MCP bridge and credential store. ChatGPT and Claude use the public remote connection service and their separately registered OAuth callbacks. App-adapter tests are not certification of those live hosts. No production deployment is claimed by this branch.
+
+The original `/api/v1/decks` drive API remains available for its existing tokens. Asset uploads, exports, presentation control and sharing remain follow-on delegated operation contracts.
+
+In roster team mode, creating decks requires current Home membership; the local
+allowlist grants no team standing. The agent team must match the provisioned
+roster team. Full lists return a retryable failure if roster authority cannot
+be verified; exact independently shared decks remain readable. This initial
+API requires an existing Home-linked local account.
+
+`slides_update_deck` applies 1–100 semantic operations atomically. Its exported
+schema describes each operation's fields and types: metadata, slides, blocks,
+text, notes, layout and ordering use the native editor engine. Read
+`slides_get_deck`, copy its decimal-string `revision` into `expected_revision`,
+and choose a new canonical nonzero UUID for the edit. The update returns
+`sqid`, `url`, `revision` and `ids` (server-minted IDs keyed by operation index).
+A stale revision returns `conflict` without changing the deck.
+
+Keep the same UUID, expected revision and ordered payload after an uncertain
+response. A matching retry returns the original **applied** revision and IDs,
+even after somebody edits the deck later; read again for current content.
+Current access is required on every attempt and before response delivery.
+Existing independent deck grants permit document editing under the app's
+native policy; creation continues to require current membership. New edits
+never automatically rebase and never accept raw Yjs or whole-deck replacement.
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..051120d
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-25-agent-access.md
@@ -0,0 +1,58 @@
+# Delegated Oficina access for Slides
+
+Status: proposed implementation specification. User requested one browser grant across Oficina and all four first clients: CLI, Paseo, ChatGPT, Claude. This is the named MCP consumer that activates design §7.3. Transport is the temporary shared `amadan.net/oficina/agent-access.git` module at 8ed8ba8, with migration to Rastrillo after its matching capabilities ship. Existing drive API remains supported.
+
+## Initial contract
+
+Disabled unless SLIDES_AGENT_ISSUER and SLIDES_AGENT_TEAM are both set. Require a valid configured Home bridge and exact canonical HTTPS origins, with separate identity and delegation issuers. Validate before schema/storage changes. App audience is its origin plus `/api/v1`. Construct NewRemoteVerifier(delegation issuer, audience, Home issuer); introspection must return identity_issuer exactly equal to configured Home issuer, refusing missing or different namespaces. Bearer-only `/api/v1/operations` discovery and `/api/v1/operations/{name}` POST routes mount outside browser CSRF, alongside the existing drive router. No session/token creation or implicit Home linking.
+
+Three descriptors feed identical API, CLI and MCP contracts, all requiring the configured team:
+
+- `slides_list_decks`, slides:read: bounded metadata, 20 default / 100 maximum, descending internal numeric ID encoded as a canonical decimal string cursor. SQL uses existing visibleDecks owner/team/explicit-grant seam before LIMIT. Public deck identifiers remain exact ten-character sqids. Return only sqid/title/theme/revision (decimal string) and next_cursor; no eager core opens.
+- `slides_get_deck`, slides:read: exact sqid; current visibility; one replay at the selected row's seq returns the raw h.JSON canonical block-tree view (not a deck.Deck remarshal, which can truncate fractional z), including speaker notes, with sqid and decimal-string revision. No second document representation or lossy conversion. Whole result at most 1 MiB; oversize is an explicit failure.
+- `slides_create_deck`, slides:write: nonzero canonical UUID client_id, title at most 512 UTF-8 bytes, optional existing theme (default paper), 1–50 typed slides. Each slide has heading/body_markdown/notes_markdown, combined text at most 128 KiB. Build existing `set_meta`, `add_slide`, `add_block`, and `set_notes` ops with server-minted IDs, title-body template. Existing core parses Markdown; its shape check must pass before storage. New decks are private, owned by current local user. Return bounded sqid/url/revision only; no invitations/sharing/export/presentation effects.
+
+Strict Unicode and duplicate/unknown-field checks precede ordinary decoding. Shared schema validation remains authoritative for field types/bounds; bounded request and response at 1 MiB. Public machine errors use stable shared codes and no storage/credential details. Existing browser/drive behavior and content storage policy are preserved.
+
+## Identity, storage and atomic retry
+
+Resolve the exact Home issuer/subject through the existing bridge to a currently admitted existing local User. Never infer the local account from subject/email and never create one. Capture stable user ID and email and original Subject/Client/Grant. Reverify the original bearer against the original verifier, required scope/team, and all three fields after obtaining the SQLite writer and immediately before every commit, including completed retries. Inside transactions use the transaction's connection to re-read the Home link and local user/current admission; do not call a second DB connection while holding the writer.
+
+Add separate additive agent migrations for singleton authority marker, creation receipts and connection attribution. Home DEK-derived keyed fingerprints bind marker to the key and exact identity issuer, delegation issuer and team. The first marker can be established only with BOTH receipt and attribution tables empty; otherwise refuse explicitly. Check it at startup and as the transaction's first write. Changing key/namespace must refuse instead of silently starting a new retry namespace.
+
+Creation coordinate fingerprints both issuers, subject, client, team and canonical UUID; normalized typed payload (trimmed nonempty title, defaulted theme, exact ordered slide strings, never minted IDs) has its own fingerprint. Attribution fingerprints both issuers/subject/client/team/local-user ID, stores encrypted client label under the Home DEK, and uses `connection:<fingerprint>` in the existing DeckUpdate actor column. Bind ciphertext purpose to that immutable coordinate; extend actorLabels with a batched connection lookup before numeric actor parsing, recover the client label plus operator and existing agentMark for browser history attribution. No fake person or old agent token. No content/credentials in central logs or receipts.
+
+Factor the domain persistence body of applyOps into a transaction-local helper. It retains the existing optimistic seq check and DeckUpdate insertion and performs no publish or snapshot. Existing applyOps wraps it and retains postcommit view/publish/snapshot behavior. Similarly factor createDeckRow onto a supplied DB transaction, preserving sqid retries and private defaults. The new adapter's single transaction reserves writer/marker, checks authority, claims/re-reads receipt, creates row, applies the canonical op batch, explicitly runs BOTH h.Check and h.JSON plus deck.Parse before commit, writes sealed attribution and receipt, then final authority check. A failed step rolls back metadata/log/receipt/attribution together. Return sufficient parsed view/seq state from creation so postcommit parsing cannot turn a committed create into failure; preserve existing applyOps wrapper behavior for its established callers. Discard mutated handles after rollback. Publish seq and optional snapshot only after successful commit. New create response is already bounded, so a large deck read cannot turn a committed create into a failed retry.
+
+Completed receipt must match payload, still reference an existing currently visible deck, and never apply content again; deletion yields 404 and browser edits survive. Six concurrent identical first requests must converge to one deck/update/receipt. Restart must use durable receipts with the same binding.
+
+## Read emission and tests
+
+Track every returned deck and recheck original bearer, fresh Home/local identity and current visibleDecks access immediately before response headers and each at-most-64-KiB write. Use bounded verification/write deadlines and abort partial HTTP responses on loss of authority. This is shared across discovery/list/get/create responses. No response is emitted from Registry.HTTP directly.
+
+Meaningful tests use real Home link fixtures, real core replay and actual HTTP transports: disabled/partial configuration; wrong team/scope/identity namespace; private/team/granted visibility before pagination; exact large IDs; strict invalid Unicode and unknown fields; bounded create/input/output; atomic rollback at update/receipt/final authority stages; reserved-writer revocation; changed principal/local link/admission; startup and live marker tampering; independent old receipt/attribution adoption refusal; fresh restart, concurrent create, preserved subsequent browser edits and deleted retry; actual chunked response revocation. A real HTTPS grant-service/CLI/MCP fixture discovers and creates/reads/retries a deck and refuses after logout. Mutation evidence must distinguish each critical boundary from a later check masking its absence.
+
+Run the full `.amadan/ci.d/10-gate`, focused race checks, source review and remote CI before merge. No deployed or four-host certification is claimed until real tests run there. Follow-on semantic edits, assets, export/presentation/sharing require separate contract work against existing domain seams.
+
+## Build reproducibility amendment
+
+The full gate discovered that unchanged Slides Rust source rebuilt under the pinned 1.98.0 compiler differs from the committed Wasm: Cargo crate identities and symbol/code ordering vary by checkout and host despite remapped diagnostic paths. Adopt the existing Docs canonical builder for both Slides modules: Linux amd64, fixed `/work` source and fixed Cargo/Rustup roots, pinned Rust Docker image (or the same fixed-root bubblewrap environment on Linux amd64). Preserve Rust source, lockfiles, ABI and semantic behavior; regenerate committed CRDT/PDF artifacts with those builders, then require the normal byte comparisons, Rust tests and JS/core parity. Native Rust lint/tests remain native. Canonical target caches are worktree-specific; source is mounted read-only and only dedicated build caches are writable. No weakened or skipped gate.
+
+Credits regeneration additionally recognizes only the preexisting fastrand 2.5.0 vendor patch at its exact path. A reviewed upstream-archive hash manifest verifies every vendored file (only the parsed normal wasm getrandom feature differs), rejects symlink escapes and all other source replacements, and feeds actual vendored license notices. Vendor files join the credit input inventory. No dependency source or lockfile changes.
+
+## Home roster compatibility (2026-10-30)
+
+Provisioned team mode uses one Home roster Access captured for the verified
+subject. Agent team configuration must match that binding before migrations.
+Only existing Home-linked accounts resolve; the browser's Home-only fallback
+is not used by this first delegated API. Retain the same Access through
+registry calls, identity checks, writer transaction/retry and response emission.
+Creation requires Member; an allowlist cannot grant team standing. Read queries
+preserve the app's current rule: own/team-rung decks require Member, while
+independent explicit grants survive NotMember or Unknown. Query on the caller's
+transaction and recheck Unknown after selection. Full lists refuse Unknown,
+even when explicit grants remain, because this contract has no partial-list
+indicator. Socket write deadlines cannot outlive the retained membership lease
+or a shorter caller deadline. Browser write guards and non-team behavior are
+preserved. GPT-6 Astra reviewed this compatibility plan and source; full local
+checks and deployed canary review remain separate evidence.
diff --git a/docs/superpowers/specs/2026-11-01-agent-deck-editing.md b/docs/superpowers/specs/2026-11-01-agent-deck-editing.md
new file mode 100644
index 0000000..7dac0c0
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-01-agent-deck-editing.md
@@ -0,0 +1,231 @@
+# Delegated semantic deck editing
+
+Status: specification and final source independently approved by a separate
+GPT-6 Astra agent, 2026-11-01, with the machine contract clarification below.
+Validation is recorded below.
+Author: GPT-6 Astra, 2026-11-01. Paul authorized everyday editing APIs through
+the suite's existing API, CLI and MCP connection. This extends the approved
+2026-10-25 agent-access design. Its identity, namespace, privacy, roster and
+response-emission rules remain binding, and existing v1 contracts are unchanged.
+
+## Contract
+
+Add `slides_update_deck`, scope `slides:write`, readOnly false, idempotent true.
+HTTP, CLI and MCP use the same team-independent descriptor. All five fields
+below are required; unknown top-level fields are refused.
+
+```json
+{
+ "team": "team-id",
+ "sqid": "k7m2xq9dwb",
+ "expected_revision": "12",
+ "client_id": "1dc98332-7165-43c5-8f98-9546f10146a8",
+ "ops": [
+ {"op":"set_notes","id":"abcdefghijkl","markdown":"Discuss the revised estimate."},
+ {"op":"add_slide","layout":"flow","template":"title-body"}
+ ]
+}
+```
+
+Sqid retains the exact existing ten-character alphabet and revision retains
+the canonical nonnegative decimal string of `Deck.Seq`, at most MaxInt64.
+Signs, leading zeros, fractions and overflow are invalid. A new edit must
+leave room for one sequence increment. The UUID is nonzero canonical
+lowercase hyphenated form. Team is 1–128 characters and must equal the
+configured instance team. Accept 1–100 ordered semantic operations, at most
+1 MiB for the whole request. Reject malformed Unicode and duplicate JSON
+object keys before decoding op fragments; retain raw numbers and the semantic
+distinction between absent keys and null.
+
+Allowed operation names are `set_meta`, `add_slide`, `remove_slide`,
+`move_slide`, `duplicate_slide`, `set_slide`, `set_notes`, `add_block`,
+`remove_block`, `move_block`, `set_block`, `set_text` and `set_phone`.
+Their fields, references, markdown, rich text, fractional coordinates and
+ordering are the existing canonical operation vocabulary in `docs/api.md`
+and `core/src/ops.rs`, with no second Go operation interpreter. The exported
+descriptor exposes concrete argument fields and types for every supported op,
+using per-operation `oneOf` or an equivalent machine schema, so API, CLI and
+MCP callers can discover the contract without external documentation. The core
+validates operation-specific types, fields and cross-operation references.
+The envelope limit and op count are enforced before calling the engine.
+Asset registration/removal, upload, export, presentation, sharing and deck
+deletion are outside this slice. Existing registered images can still be
+referenced by ordinary block operations under their current validation.
+
+Missing slide/block IDs are minted through existing `mintOpIDs`, including
+duplicate-slide block identities. Caller-supplied IDs retain native semantics.
+The caller can provide its own IDs when later operations in the same batch
+need to refer to newly added objects. No raw Yjs updates or whole-deck JSON
+replacement are accepted.
+
+Success is a small acknowledgement:
+
+```json
+{"sqid":"k7m2xq9dwb","revision":"13","url":"https://slides.example/d/k7m2xq9dwb","ids":{"1":"mnopqrstuvwx"}}
+```
+
+All four fields are required. `ids` is the existing native operation-index
+map for server-minted slide/block IDs; duplicate-slide child block identities
+are discoverable by reading the resulting deck, as on the existing drive API.
+`revision` is the immutable sequence committed by this mutation. A completed
+retry returns the same revision and IDs even after later browser edits. It
+does not return a stale deck body; `slides_get_deck` gives current content and
+revision. Existing create responses keep their current-revision semantics.
+Bound the encoded result before commit to the existing 1 MiB result maximum.
+
+`conflict` means stale expected revision for a new mutation or a reused client
+UUID with a different target, expected revision or ordered operation payload.
+Current access is checked before disclosing conflict. A stale request never
+automatically rebases against a newer deck. The caller reads again and chooses
+a fresh UUID for its revised intent. Core refusal is `invalid`; storage,
+deadline or engine execution failures are unavailable, not partial success.
+Missing/inaccessible decks and other authority failures use existing codes.
+
+## Native authority and response boundary
+
+Only creation requires creator membership; do not treat every slides:write
+operation as create. Document editing follows the app's existing deck write
+authority: a person who can reach a deck through the native owner/team/grant
+seam may edit its document, as `apiOps` does. No new viewer/editor distinction
+is invented. Existing independent deck grants survive NotMember or Unknown;
+owner/team-rung reach requires Member from the single captured Access.
+
+At writer reservation and before commit, including completed retries,
+reverify the original delegation verifier and unchanged principal fields,
+resolve the keyed Home link on the transaction through `ResolveOn`, compare
+stable local person ID and address, and recheck live deck reach on that same
+transaction. The team write guard wraps the entire mutation/receipt decision.
+No outer-pool lookup, HomeOnly fallback, automatic provisioning or roster
+network request runs under the writer. A missing or expired required lease
+fails closed; an independent current grant is checked on the transaction.
+
+Remember the exact deck for existing before-header and per-chunk identity,
+delegation, live deck and roster checks. Preserve the standing-lease socket
+deadline clamp. Loss of authority during emission aborts it; a committed but
+unacknowledged edit is recovered through its stable retry UUID.
+
+## One canonical edit transaction
+
+Use the existing semantic engine, op ID minting, `metaRowUpdates`,
+`applyOpsOn`, core shape check and canonical projection parser. Do not call
+the legacy `applyAgentOps` retry loop: it intentionally retries a busy deck
+at its new sequence, which violates this operation's explicit precondition.
+
+Reserve the SQLite writer using the existing immutable namespace marker.
+Recheck local authority, read any existing receipt, then read the current
+deck row and compare its sequence to expected_revision. Open a fresh owned
+core handle whose snapshot and ordered log reads use the caller's transaction
+at that exact sequence; factor a transaction-aware `openDeck` seam if needed.
+Never call the outer-pool reader while holding the writer. All handles are
+closed/discarded after either commit or rollback.
+
+For a new request, mint missing IDs on a copy of its op fragments, preserving
+the original request for fingerprinting. Apply the batch once through the
+canonical engine; require both `Handle.Check` of shared-type structure and
+`deck.Parse` of `Handle.JSON` before commit. The app's transaction encloses
+the update-log insert, optimistic sequence bump, any deck-row metadata,
+actor attribution, receipt and final authority check. If the existing helper
+performs inserts before shape checking, these stay inside the uncommitted
+transaction and any failed check rolls all of them back. The resulting deck
+must also fit the existing 1 MiB canonical get result bound, so this editing
+surface cannot successfully create a deck its read operation cannot return.
+
+Preserve fractional z/box values by retaining raw op JSON and the canonical
+JSON projection; never round-trip through the simplified typed Deck struct
+as the source of persisted content. All order changes go through the engine's
+identity-preserving order keys. Both required checks remain independent gates.
+Only after commit publish the new sequence and attempt a native snapshot.
+Replays publish nothing and create no extra log entry or actor attribution.
+
+## Durable retry and attribution
+
+Add a separate additive edit-receipt table. Its unique HMAC coordinate binds
+operation name, both authority issuers, team, subject, delegated client and
+client UUID. The payload HMAC binds sqid, expected revision and ordered
+operation content before server-generated IDs. Object key order and harmless
+JSON whitespace do not change the fingerprint: canonicalize recursively with
+exact JSON numbers, without float64 conversion; number spelling may remain
+significant and is documented as requiring an exact semantic retry payload.
+Absent and null remain different. No plaintext markdown or op payload is
+persisted in the receipt or logged.
+
+Persist the target deck ID, applied sequence and a sealed acknowledgement
+containing the stable returned ID map under a receipt-specific purpose. Use
+the existing sealed connection attribution and connection actor on the update
+row. The immutable namespace marker's no-adoption checks include new edit
+receipts as well as creation receipts and attribution. Marker, receipt,
+attribution and content share one transaction and key/issuer/team continuity.
+
+A matching completed receipt is returned only after current resource and
+writer authority checks, before checking expected_revision against the now
+current deck. This is why a retry after later changes is safe. Changed payload
+conflicts. Concurrent identical submissions commit one batch and return one
+stable acknowledgement. A failed write leaves no receipt or generated IDs
+claiming a committed result. Recreated app and reopened database must replay
+the same applied revision and IDs without rerunning the semantic engine.
+
+## Review and validation gates
+
+Independent highest-capability spec approval precedes implementation and
+independent source/evidence review follows. Required gates:
+
+- Real Home grant/gateway/MCP create-read-edit-read, including text, notes,
+ slide/block reorder, add/duplicate/remove, metadata and fractional canvas
+ coordinates. Compare native `openDeck`, the canonical JSON read operation
+ and browser-rendered HTML from the same state.
+- Two concurrent edits from one sequence: one commit, one conflict; exact
+ duplicate retry after a later native edit and after app restart preserves
+ that later edit and returns original generated IDs and applied sequence.
+- Invalid later op, malformed rich text, missing reference and columns-cycle
+ rejection leave no partial updates. Independently exercise shape and
+ projection gates, not merely core input parsing.
+- SQL failures at update insert, metadata update, attribution and receipt
+ persistence roll back sequence, log, metadata and acknowledgement. A
+ fresh open reads the old deck; no seq publication or snapshot precedes
+ commit. Completed retries do not apply another op batch.
+- Initial/final revocation, unlink, binding corruption, live deck/grant loss
+ and roster lease expiry, including direct-domain completed-retry tests
+ independent of emission. Independent granted access under Unknown and
+ NotMember remains supported; create still requires current membership.
+- Exact JSON numbers, null/absence, strict Unicode/duplicate keys, revision
+ limits, unknown operation names and 100-op/1 MiB bounds. Verify sealed
+ acknowledgement/attribution and no plaintext content in receipt storage.
+- Add the delegated path to the enumerated team-write lapse test. Effective
+ runtime-failing mutants separately skip revision comparison, completed
+ receipt payload checking, final writer guard, live transactional reach,
+ one canonical shape gate and receipt atomicity.
+- Restore all mutants; run focused race tests and the full pinned
+ `.amadan/ci.d/10-gate` (canonical wasm rebuild/cmp, Rust/JS, Go and migrations)
+ on the final tree. A fast `make ci` alone does not replace this gate.
+
+This additive operation carries no canary, main-merge or deployment approval.
+
+## Independent review record
+
+On 2026-11-01 a separate GPT-6 Astra agent approved this specification before
+implementation, then independently reviewed the final source and selected
+adversarial mutations. Final source approval covers this bounded editing
+operation and its native transaction/authority integration. It does not approve
+main merge, canary behavior or deployment.
+
+Eight selected mutants failed at runtime: missing revision check, ignored
+completed receipt, missing final writer check, new IDs returned on replay,
+omitted shared-type shape check, omitted projection parsing, float64 receipt
+fingerprints, and ignored receipt persistence failure. Every original was
+restored. The exported operation contract contains concrete schemas for all
+thirteen allowed semantic operations; the canonical engine remains authoritative.
+
+Final restored-tree canonical gate passed on 2026-11-01:
+`TMPDIR=/tmp GOTOOLCHAIN=go1.26.5 ./.amadan/ci.d/10-gate`. This includes
+Rust formatting/clippy/tests, canonical WASM rebuild and byte comparison,
+JavaScript tests/vectors/bundle checks, and Go vet/formatting/tests/migrations
+and credits. The short temporary directory avoids the macOS Unix-socket path
+limit in the existing shutdown test; no application behavior or test was
+changed for that environment constraint.
+
+The final focused race check also passed (313.173s):
+`GOMAXPROCS=2 TMPDIR=/tmp GOTOOLCHAIN=go1.26.5 go test -race
+./internal/slides -run
+'TestAgentDeckEdit|TestAgentGatewayToRealSlides|TestAgentTeamSlidesMembership'
+-count=1 -timeout 1200s`. It covers the editing boundary, native semantic
+parity, real HTTPS CLI/MCP edit/read/retry, and retained roster behavior.
diff --git a/go.mod b/go.mod
index bcb5fb3..7d14ee8 100644
--- a/go.mod
+++ b/go.mod
@@ -5,8 +5,9 @@ go 1.25.0
toolchain go1.26.5
require (
+ amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000
amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d
- amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2
+ amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542
amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816
amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d
amadan.net/oficina/home/roster v0.0.0-20261028171508-67c12e39a9d2
@@ -16,9 +17,12 @@ require (
github.com/chromedp/chromedp v0.14.2
github.com/go-chi/chi/v5 v5.3.2
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2
+ github.com/google/uuid v1.6.0
+ github.com/modelcontextprotocol/go-sdk v1.7.0
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
github.com/tetratelabs/wazero v1.12.0
golang.org/x/image v0.44.0
+ golang.org/x/oauth2 v0.35.0
gorm.io/gorm v1.31.2
)
@@ -27,20 +31,30 @@ require (
github.com/BurntSushi/toml v1.6.0 // indirect
github.com/carlosframework/rastrillo v0.23.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/google/uuid v1.6.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/keymaildev/signin v0.1.1 // 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.22.0 // indirect
golang.org/x/sys v0.46.0 // indirect
golang.org/x/text v0.40.0 // indirect
+ golang.org/x/time v0.15.0 // indirect
gorm.io/plugin/dbresolver v1.6.2 // indirect
modernc.org/libc v1.74.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
diff --git a/go.sum b/go.sum
index 9ccbfea..9bd63b3 100644
--- a/go.sum
+++ b/go.sum
@@ -1,7 +1,9 @@
+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-20261025200559-260f98c42e2d h1:p9+01xRdBD7s1viTINgQ6XoDD5ghOxYubD7FNcjhBTw=
amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
-amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2 h1:MPO8MRkk+tT2k+95fZPJ0JStnmAKUCKiVoPbfBVTk6E=
-amadan.net/oficina/home/connect v0.0.0-20261028171508-67c12e39a9d2/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk=
+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-20261024234842-3774eb68f816 h1:AFDuOio0MxNxN9ZWVc3lul1QHkNjNUCO56kXpe/Fw3I=
amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816/go.mod h1:+7xsX+QyVFrKy5gDAGh+FZ5+75z4CibWTL0wl9DWAw0=
amadan.net/oficina/home/handoff v0.0.0-20261024233715-ff16bf56bc4d h1:8RTZkLQnyxvH2g0RMovhN/m2LN9D8qb+kBfqdBeqq+s=
@@ -24,6 +26,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=
@@ -38,6 +46,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/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=
@@ -56,20 +74,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.44.0 h1:+tDekMZED9+LrtB3G5xzRggpVh9CARjZqROla3R3R+I=
golang.org/x/image v0.44.0/go.mod h1:V8K3KE9KKKE+pLpQDOeN18w9oacNSvy1tDOirTu4xtY=
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.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -77,8 +115,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.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
+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/slides/agent_access.go b/internal/slides/agent_access.go
new file mode 100644
index 0000000..bed30b9
--- /dev/null
+++ b/internal/slides/agent_access.go
@@ -0,0 +1,248 @@
+package slides
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "mime"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/connect"
+ "amadan.net/oficina/home/roster"
+ "amadan.net/oficina/home/teammode"
+ "amadan.net/rastrillo/rastrillo/migrate"
+ "gorm.io/gorm"
+)
+
+var errAgentConfig = errors.New("slides: invalid agent access configuration")
+
+// ValidateAgentConfig checks delegated access before the executable opens storage.
+func ValidateAgentConfig(issuer, team, origin string, home *connect.Credentials) error {
+ return validateAgentConfig(issuer, team, origin, home)
+}
+
+func validateAgentConfig(issuer, team, origin string, home *connect.Credentials) error {
+ if issuer == "" && team == "" {
+ return nil
+ }
+ if issuer == "" || team == "" || strings.TrimSpace(team) != team || len(team) > 128 || home == nil {
+ return errAgentConfig
+ }
+ settings, e := connect.DecodeCredentials(home, origin)
+ if e != nil || settings == nil {
+ return errAgentConfig
+ }
+ if _, e = access.NewRemoteVerifier(issuer, origin+"/api/v1", settings.Issuer); e != nil {
+ return errAgentConfig
+ }
+ return nil
+}
+
+func (a *app) configureAgentAccess() error {
+ if a.cfg.AgentIssuer == "" {
+ return nil
+ }
+ settings, e := connect.DecodeCredentials(a.cfg.Home, a.cfg.Origin)
+ if e != nil {
+ return e
+ }
+ verifier, e := access.NewRemoteVerifier(a.cfg.AgentIssuer, a.cfg.Origin+"/api/v1", settings.Issuer)
+ if e != nil {
+ return e
+ }
+ agent := &slideAgent{app: a, issuer: a.cfg.AgentIssuer, identityIssuer: settings.Issuer, team: a.cfg.AgentTeam, key: append([]byte(nil), settings.DEK...)}
+ return a.mountAgent(agent, verifier)
+}
+func (a *app) mountAgent(agent *slideAgent, verifier access.Verifier) error {
+ if a.home == nil || a.team != nil && a.team.Bindings().Team != agent.team {
+ return errAgentConfig
+ }
+ if _, e := migrate.Apply(context.Background(), a.db, agentSchema); e != nil {
+ return e
+ }
+ if e := a.db.G.Transaction(func(tx *gorm.DB) error { return agent.bind(tx) }); e != nil {
+ return e
+ }
+ handler, e := agent.httpHandler(verifier)
+ if e != nil {
+ return e
+ }
+ a.agent = handler
+ a.agentAccess = agent
+ return nil
+}
+func slideAgentWriteFailure(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})
+}
+func (a *slideAgent) httpHandler(verifier access.Verifier) (http.Handler, error) {
+ registry, e := a.registry()
+ if e != nil {
+ return nil, e
+ }
+ 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") {
+ slideAgentWriteFailure(w, access.Fail("unauthenticated", "Connect to Oficina first."))
+ return
+ }
+ p, e := verifier.Verify(r.Context(), parts[1])
+ if e != nil {
+ slideAgentWriteFailure(w, e)
+ return
+ }
+ name := strings.TrimPrefix(r.URL.Path, "/api/v1/operations/")
+ write := name == "slides_create_deck" || name == "slides_update_deck"
+ discovery := r.Method == "GET" && r.URL.Path == "/api/v1/operations"
+ if discovery && !p.Allows(a.team, "slides:read") {
+ write = true
+ }
+ member, e := a.member(r.Context(), p, write)
+ if e == nil && name == "slides_create_deck" {
+ e = a.creator(member)
+ }
+ if e != nil {
+ slideAgentWriteFailure(w, e)
+ return
+ }
+ state := &slideAgentContext{member: member, slides: map[int64]bool{}}
+ state.verify = func(ctx context.Context) error {
+ current, e := verifier.Verify(ctx, parts[1])
+ if e != nil {
+ return e
+ }
+ scope := "slides:read"
+ if write {
+ scope = "slides:write"
+ }
+ if current.Subject != p.Subject || current.Client != p.Client || current.Grant != p.Grant || !current.Allows(a.team, scope) {
+ return access.Fail("forbidden", "This connection is no longer authorized.")
+ }
+ return nil
+ }
+ ctx := context.WithValue(r.Context(), slideAgentKey{}, state)
+ if member.team != nil {
+ ctx = teammode.WithAccess(ctx, member.team.access())
+ }
+ 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, "/") {
+ slideAgentWriteFailure(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" {
+ slideAgentWriteFailure(w, access.Fail("unsupported_media_type", "Send application/json."))
+ return
+ }
+ raw, e := io.ReadAll(io.LimitReader(r.Body, slideAgentLimit+1))
+ if e != nil {
+ slideAgentWriteFailure(w, access.Fail("invalid", "Could not read the request."))
+ return
+ }
+ if len(raw) > slideAgentLimit {
+ slideAgentWriteFailure(w, access.Fail("too_large", "The operation input exceeds 1 MiB."))
+ return
+ }
+ result, e = registry.Call(ctx, p, name, raw)
+ if e != nil {
+ slideAgentWriteFailure(w, e)
+ return
+ }
+ }
+ body, e := json.Marshal(result)
+ if e != nil {
+ slideAgentWriteFailure(w, slideAgentFailure(e))
+ return
+ }
+ if len(body) > slideAgentLimit {
+ slideAgentWriteFailure(w, access.Fail("too_large", "The deck result exceeds 1 MiB."))
+ return
+ }
+ controller := http.NewResponseController(w)
+ check := func() error {
+ now := time.Now()
+ deadline := now.Add(5 * time.Second)
+ if a.app.team != nil && state.member.team.state() == roster.Member {
+ remaining := state.member.team.Remaining()
+ if remaining <= 0 {
+ return access.Fail("unavailable", "Team membership cannot be verified now.")
+ }
+ if lease := now.Add(remaining); lease.Before(deadline) {
+ deadline = lease
+ }
+ }
+ if d, ok := ctx.Deadline(); ok && d.Before(deadline) {
+ deadline = d
+ }
+ checkCtx, cancel := context.WithDeadline(ctx, deadline)
+ defer cancel()
+ if e := state.verify(checkCtx); e != nil {
+ return e
+ }
+ fresh, e := a.member(checkCtx, p, write)
+ if e == nil && name == "slides_create_deck" {
+ e = a.creator(fresh)
+ }
+ if e != nil {
+ return e
+ }
+ if fresh.ID != member.ID || fresh.Email != member.Email {
+ return access.Fail("forbidden", "The current identity changed.")
+ }
+ for id := range state.slides {
+ var d Deck
+ if e := a.visible(checkCtx, a.app.db.G, fresh, "decks.id=?", id, &d); e != nil {
+ return slideAgentFailure(e)
+ }
+ }
+
+ if state.list && a.app.team != nil && fresh.team.state() == roster.Unknown {
+ return access.Fail("unavailable", "The complete deck list cannot be verified now.")
+ }
+ if e := checkCtx.Err(); e != nil {
+ return slideAgentFailure(e)
+ }
+ if e := controller.SetWriteDeadline(deadline); e != nil {
+ return slideAgentFailure(e)
+ }
+ return nil
+ }
+ if e = check(); e != nil {
+ slideAgentWriteFailure(w, e)
+ return
+ }
+ defer controller.SetWriteDeadline(time.Time{})
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Content-Length", strconv.Itoa(len(body)))
+ w.WriteHeader(http.StatusOK)
+ for len(body) > 0 {
+ if e = check(); e != nil {
+ panic(http.ErrAbortHandler)
+ }
+ n := min(len(body), 64<<10)
+ wrote, e := w.Write(body[:n])
+ if e != nil || wrote != n {
+ panic(http.ErrAbortHandler)
+ }
+ body = body[n:]
+ }
+ }), nil
+}
diff --git a/internal/slides/agent_attribution.go b/internal/slides/agent_attribution.go
new file mode 100644
index 0000000..519562f
--- /dev/null
+++ b/internal/slides/agent_attribution.go
@@ -0,0 +1,64 @@
+package slides
+
+import (
+ "context"
+ "strconv"
+ "strings"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/connect"
+ "amadan.net/oficina/home/handoff/seal"
+ "gorm.io/gorm"
+)
+
+func (a *slideAgent) actor(tx *gorm.DB, p access.Principal, u User) (string, error) {
+ coordinate := a.digest("actor", []string{a.identityIssuer, a.issuer, p.Subject, p.Client, a.team, strconv.FormatInt(u.ID, 10)})
+ sealer, e := seal.New(a.key, "oficina/slides/agent/v1")
+ if e != nil {
+ return "", e
+ }
+ ciphertext, e := sealer.Seal("client/"+coordinate, []byte(p.Client))
+ if e != nil {
+ return "", e
+ }
+ e = tx.Exec("INSERT INTO slides_connections(coordinate,operator_id,client_sealed) VALUES(?,?,?) ON CONFLICT(coordinate) DO NOTHING", coordinate, u.ID, ciphertext).Error
+ return "connection:" + coordinate, e
+}
+func (a *app) connectionLabels(ctx context.Context, actors []string) map[string]string {
+ out := map[string]string{}
+ if a.cfg.Home == nil {
+ return out
+ }
+ keys := []string{}
+ for _, actor := range actors {
+ if key, ok := strings.CutPrefix(actor, "connection:"); ok {
+ keys = append(keys, key)
+ }
+ }
+ if len(keys) == 0 {
+ return out
+ }
+ var rows []struct {
+ Coordinate string
+ ClientSealed []byte
+ Email string
+ }
+ if e := a.db.G.WithContext(ctx).Raw("SELECT c.coordinate,c.client_sealed,u.email FROM slides_connections c JOIN users u ON u.id=c.operator_id WHERE c.coordinate IN ?", keys).Scan(&rows).Error; e != nil {
+ return out
+ }
+ settings, e := connect.DecodeCredentials(a.cfg.Home, a.cfg.Origin)
+ if e != nil || settings == nil {
+ return out
+ }
+ sealer, e := seal.New(settings.DEK, "oficina/slides/agent/v1")
+ if e != nil {
+ return out
+ }
+ for _, r := range rows {
+ client, e := sealer.Open("client/"+r.Coordinate, r.ClientSealed)
+ if e == nil {
+ out["connection:"+r.Coordinate] = agentMark + agentPrincipal(string(client), r.Email)
+ }
+ }
+ return out
+}
diff --git a/internal/slides/agent_authority.go b/internal/slides/agent_authority.go
new file mode 100644
index 0000000..1971637
--- /dev/null
+++ b/internal/slides/agent_authority.go
@@ -0,0 +1,176 @@
+package slides
+
+import (
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "embed"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "io/fs"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/oficina/home/roster"
+ "amadan.net/rastrillo/rastrillo/migrate"
+ "gorm.io/gorm"
+)
+
+//go:embed agent_migrations/migrations/*.sql
+var agentMigrationFS embed.FS
+var agentSchema = func() *migrate.Set {
+ sub, _ := fs.Sub(agentMigrationFS, "agent_migrations")
+ return migrate.MustFromFS(sub, "slides_agent")
+}()
+
+const slideAgentLimit = 1 << 20
+
+type slideAgent struct {
+ app *app
+ issuer, identityIssuer, team string
+ key []byte
+}
+type slideAgentContext struct {
+ list bool
+ member User
+ verify func(context.Context) error
+ slides map[int64]bool
+}
+type slideAgentKey struct{}
+
+func slideAgentFailure(err error) error {
+ if err == nil {
+ return nil
+ }
+ var f access.Failure
+ if errors.As(err, &f) {
+ return f
+ }
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return access.Fail("not_found", "This deck is unavailable.")
+ }
+ if errors.Is(err, linkstore.ErrRefused) {
+ return access.Fail("forbidden", "This Home identity is not admitted.")
+ }
+ return access.Fail("unavailable", "Deck authority or storage is unavailable.")
+}
+func (a *slideAgent) digest(domain string, value any) string {
+ raw, _ := json.Marshal(value)
+ mac := hmac.New(sha256.New, a.key)
+ mac.Write([]byte("oficina/slides/agent/v1/" + domain + "\x00"))
+ mac.Write(raw)
+ return hex.EncodeToString(mac.Sum(nil))
+}
+func (a *slideAgent) bind(tx *gorm.DB) error {
+ want := a.digest("keycheck", []string{"immutable-authority", a.identityIssuer, a.issuer, a.team})
+ if e := tx.Exec("INSERT INTO slides_agent_state(id,keycheck) SELECT 1,? WHERE NOT EXISTS(SELECT 1 FROM slides_agent_receipts) AND NOT EXISTS(SELECT 1 FROM slides_connections) AND NOT EXISTS(SELECT 1 FROM slides_agent_edits) ON CONFLICT(id) DO NOTHING", want).Error; e != nil {
+ return e
+ }
+ var got string
+ if e := tx.Raw("SELECT keycheck FROM slides_agent_state WHERE id=1").Scan(&got).Error; e != nil {
+ return e
+ }
+ if !hmac.Equal([]byte(got), []byte(want)) {
+ return access.Fail("unavailable", "Agent receipt authority requires an explicit migration.")
+ }
+ return nil
+}
+func (a *slideAgent) member(ctx context.Context, p access.Principal, write bool) (User, error) {
+ scope := "slides:read"
+ if write {
+ scope = "slides:write"
+ }
+ if p.Subject == "" || p.Client == "" || len(p.Client) > 256 || p.Grant == "" || !p.Allows(a.team, scope) {
+ return User{}, access.Fail("forbidden", "This connection does not allow that team and operation.")
+ }
+ if a.app.home == nil {
+ return User{}, access.Fail("unavailable", "Home identity resolution is unavailable.")
+ }
+ person, e := a.app.home.ResolveOn(ctx, a.app.db.G.Statement.ConnPool, p.Subject)
+ if e != nil {
+ return User{}, slideAgentFailure(e)
+ }
+ var u User
+ if e = a.app.db.G.WithContext(ctx).First(&u, person.ID).Error; e != nil {
+ return User{}, slideAgentFailure(e)
+ }
+ if u.ID <= 0 || person.Label == "" || u.Email != person.Label || a.app.team == nil && !a.app.allowed.allows(u.Email) {
+ return User{}, slideAgentFailure(linkstore.ErrRefused)
+ }
+ if a.app.team != nil {
+ if state, ok := ctx.Value(slideAgentKey{}).(*slideAgentContext); ok && state != nil {
+ u.team = state.member.team
+ if u.team == nil || u.team.Subject() != p.Subject {
+ return User{}, slideAgentFailure(linkstore.ErrRefused)
+ }
+ } else {
+ u.team = &teamAccess{Access: a.app.team.Access(ctx, p.Subject)}
+ }
+ }
+ return u, nil
+}
+func (a *slideAgent) creator(u User) error {
+ if a.app.team == nil {
+ if a.app.allowed.allows(u.Email) {
+ return nil
+ }
+ return linkstore.ErrRefused
+ }
+ switch u.team.state() {
+ case roster.Member:
+ return nil
+ case roster.NotMember:
+ return access.Fail("forbidden", "Creating a deck requires current team membership.")
+ default:
+ return access.Fail("unavailable", "Team membership cannot be verified now.")
+ }
+}
+func slideAgentMember(ctx context.Context) User {
+ if state, ok := ctx.Value(slideAgentKey{}).(*slideAgentContext); ok && state != nil {
+ return state.member
+ }
+ return User{}
+}
+func (a *slideAgent) remember(ctx context.Context, id int64) {
+ if state, ok := ctx.Value(slideAgentKey{}).(*slideAgentContext); ok && state != nil {
+ state.slides[id] = true
+ }
+}
+func (a *slideAgent) writer(ctx context.Context, tx *gorm.DB, p access.Principal, u User) error {
+ state, ok := ctx.Value(slideAgentKey{}).(*slideAgentContext)
+ if !ok || state == nil || state.verify == nil {
+ return linkstore.ErrRefused
+ }
+ if e := state.verify(ctx); e != nil {
+ return e
+ }
+ person, e := a.app.home.ResolveOn(ctx, tx.Statement.ConnPool, p.Subject)
+ if e != nil {
+ return e
+ }
+ if person.ID != u.ID || person.Label != u.Email {
+ return linkstore.ErrRefused
+ }
+ id := person.ID
+
+ var current User
+ if e := tx.First(&current, id).Error; e != nil {
+ return e
+ }
+ if current.Email != u.Email {
+ return linkstore.ErrRefused
+ }
+ current.team = u.team
+ return a.creator(current)
+}
+func slideAgentBounded(value any) (any, error) {
+ body, e := json.Marshal(value)
+ if e != nil {
+ return nil, slideAgentFailure(e)
+ }
+ if len(body) > slideAgentLimit {
+ return nil, access.Fail("too_large", "The deck result exceeds 1 MiB.")
+ }
+ return value, nil
+}
diff --git a/internal/slides/agent_authority_test.go b/internal/slides/agent_authority_test.go
new file mode 100644
index 0000000..c21c560
--- /dev/null
+++ b/internal/slides/agent_authority_test.go
@@ -0,0 +1,222 @@
+package slides
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/rastrillo/rastrillo/db"
+ "bytes"
+ "context"
+ "encoding/json"
+ "gorm.io/gorm"
+ "strings"
+ "sync/atomic"
+ "testing"
+)
+
+func TestAgentDeckAtomicAuthority(t *testing.T) {
+ for _, mode := range []string{"reserved", "final", "unlink", "binding", "member", "update", "receipt"} {
+ t.Run(mode, func(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ trigger := ""
+ switch mode {
+ case "reserved":
+ f.revokeAt.Store(2)
+ trigger = "CREATE TRIGGER body_trap BEFORE INSERT ON decks BEGIN SELECT RAISE(ABORT,'body attempted'); END"
+ case "final":
+ f.revokeAt.Store(3)
+ case "unlink":
+ trigger = "CREATE TRIGGER lose_link AFTER UPDATE OF deck_id ON slides_agent_receipts BEGIN DELETE FROM home_identity_links; END"
+ case "binding":
+ trigger = "CREATE TRIGGER lose_binding AFTER INSERT ON deck_updates BEGIN UPDATE home_identity_links SET person_binding='broken'; END"
+ case "member":
+ trigger = "CREATE TRIGGER lose_member AFTER UPDATE OF deck_id ON slides_agent_receipts BEGIN UPDATE users SET email='removed@example.com'; END"
+ case "update":
+ trigger = "CREATE TRIGGER fail_update BEFORE INSERT ON deck_updates BEGIN SELECT RAISE(ABORT,'write failed'); END"
+ case "receipt":
+ trigger = "CREATE TRIGGER fail_receipt BEFORE UPDATE OF deck_id ON slides_agent_receipts BEGIN SELECT RAISE(ABORT,'receipt failed'); END"
+ }
+ if trigger != "" {
+ if e := f.a.app.db.G.Exec(trigger).Error; e != nil {
+ t.Fatal(e)
+ }
+ }
+ r := f.call(t, "slides_create_deck", initialSlideAgentInput())
+ want := 503
+ if mode == "reserved" || mode == "final" {
+ want = 401
+ }
+ if mode == "unlink" || mode == "member" || mode == "binding" {
+ want = 403
+ }
+ if r.Code != want {
+ t.Fatal(mode, r.Code, r.Body.String())
+ }
+ for _, table := range []string{"decks", "deck_updates", "slides_agent_receipts", "slides_connections"} {
+ var n int
+ if e := f.a.app.db.G.Raw("SELECT COUNT(*) FROM " + table).Scan(&n).Error; e != nil || n != 0 {
+ t.Fatal("partial create", table, n, e)
+ }
+ }
+ })
+ }
+}
+func TestAgentDeckRetryAndMarker(t *testing.T) {
+ for _, mode := range []string{"retry-final", "marker-create", "marker-retry"} {
+ t.Run(mode, func(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ in := initialSlideAgentInput()
+ slideCreated(t, f.call(t, "slides_create_deck", in))
+ want := 503
+ if mode == "retry-final" {
+ f.checks.Store(0)
+ f.revokeAt.Store(3)
+ want = 401
+ } else {
+ if e := f.a.app.db.G.Exec("UPDATE slides_agent_state SET keycheck='damaged'").Error; e != nil {
+ t.Fatal(e)
+ }
+ if mode == "marker-create" {
+ in.ClientID = initialSlideAgentInput().ClientID
+ }
+ }
+ if r := f.call(t, "slides_create_deck", in); r.Code != want {
+ t.Fatal(mode, r.Code)
+ }
+ var n int
+ f.a.app.db.G.Raw("SELECT COUNT(*) FROM decks").Scan(&n)
+ if n != 1 {
+ t.Fatal(n)
+ }
+ })
+ }
+}
+func TestAgentDeckPrincipalContinuity(t *testing.T) {
+ for _, field := range []string{"subject", "client", "grant", "team", "scope"} {
+ t.Run(field, func(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ var checks atomic.Int64
+ e := f.a.app.mountAgent(f.a, access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ p := f.p
+ if checks.Add(1) > 1 {
+ switch field {
+ case "subject":
+ p.Subject = "other"
+ case "client":
+ p.Client = "other"
+ case "grant":
+ p.Grant = "other"
+ case "team":
+ p.Teams = []string{"other"}
+ case "scope":
+ p.Scopes = []string{"slides:read"}
+ }
+ }
+ return p, nil
+ }))
+ if e != nil {
+ t.Fatal(e)
+ }
+ if r := f.call(t, "slides_create_deck", initialSlideAgentInput()); r.Code != 403 {
+ t.Fatal(r.Code)
+ }
+ var n int
+ f.a.app.db.G.Raw("SELECT COUNT(*) FROM decks").Scan(&n)
+ if n != 0 {
+ t.Fatal(n)
+ }
+ })
+ }
+}
+func TestAgentDeckDurableBinding(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ in := initialSlideAgentInput()
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", in))
+ var path string
+ if e := f.a.app.db.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path); e != nil {
+ t.Fatal(e)
+ }
+ f.a.app.Close()
+ f.a.app.db.Close()
+ d, e := db.Open(path, quietLogger())
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer d.Close()
+ _, app, e := New(d, f.a.app.cfg)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer app.Close()
+ f.a.app = app
+ f.install(t)
+ if retry := slideCreated(t, f.call(t, "slides_create_deck", in)); retry != sqid {
+ t.Fatal("restart lost receipt")
+ }
+ for _, mode := range []string{"home", "issuer", "team", "key"} {
+ t.Run(mode, func(t *testing.T) {
+ copy := *f.a
+ switch mode {
+ case "home":
+ copy.identityIssuer = "https://other-home.test"
+ case "issuer":
+ copy.issuer = "https://other-connect.test"
+ case "team":
+ copy.team = "other"
+ case "key":
+ copy.key = bytes.Repeat([]byte{41}, 32)
+ }
+ if e := app.db.G.Transaction(copy.bind); e == nil {
+ t.Fatal("rebound authority")
+ }
+ })
+ }
+ if e := app.db.G.Exec("DELETE FROM slides_agent_state").Error; e != nil {
+ t.Fatal(e)
+ }
+ for _, table := range []string{"slides_connections", "slides_agent_receipts"} {
+ t.Run(table, func(t *testing.T) {
+ e := app.db.G.Transaction(func(tx *gorm.DB) error {
+ if e := tx.Exec("DELETE FROM " + table).Error; e != nil {
+ return e
+ }
+ if e := f.a.bind(tx); e == nil {
+ t.Fatal("adopted old state")
+ }
+ return gorm.ErrInvalidTransaction
+ })
+ if e != gorm.ErrInvalidTransaction {
+ t.Fatal(e)
+ }
+ })
+ }
+}
+func TestAgentDeckMalformedUnicode(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ in := initialSlideAgentInput()
+ in.Title = "REPLACEME"
+ raw, _ := json.Marshal(in)
+ for _, bad := range []string{`\ud800`, string([]byte{255})} {
+ if r := f.raw(t, "slides_create_deck", []byte(strings.Replace(string(raw), "REPLACEME", bad, 1))); r.Code != 422 {
+ t.Fatal(r.Code)
+ }
+ }
+}
+
+// Call the transaction body directly so a later response check cannot mask
+// omission of the completed receipt's final in-transaction guard.
+func TestAgentDeckCompletedRetryWriterGuard(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ in := initialSlideAgentInput()
+ slideCreated(t, f.call(t, "slides_create_deck", in))
+ var checks int
+ state := &slideAgentContext{member: f.u, slides: map[int64]bool{}, verify: func(context.Context) error {
+ checks++
+ if checks >= 2 {
+ return access.Fail("unauthenticated", "Revoked.")
+ }
+ return nil
+ }}
+ ctx := context.WithValue(t.Context(), slideAgentKey{}, state)
+ if _, e := f.a.create(ctx, f.p, f.u, in); e == nil || access.SafeFailure(e).Code != "unauthenticated" {
+ t.Fatal("completed retry omitted final writer guard", e)
+ }
+}
diff --git a/internal/slides/agent_config_test.go b/internal/slides/agent_config_test.go
new file mode 100644
index 0000000..d5368b9
--- /dev/null
+++ b/internal/slides/agent_config_test.go
@@ -0,0 +1,95 @@
+package slides
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http/httptest"
+ "testing"
+
+ access "amadan.net/oficina/agent-access.git"
+)
+
+func TestAgentDeckConfigurationAndRouter(t *testing.T) {
+ _, base, _ := homeFixture(t)
+ for _, mode := range []string{"issuer-only", "team-only", "no-home", "same-issuer"} {
+ t.Run(mode, func(t *testing.T) {
+ cfg := base.cfg
+ cfg.AgentIssuer = "https://connect.example.com"
+ cfg.AgentTeam = "blue"
+ switch mode {
+ case "issuer-only":
+ cfg.AgentTeam = ""
+ case "team-only":
+ cfg.AgentIssuer = ""
+ case "no-home":
+ cfg.Home = nil
+ case "same-issuer":
+ cfg.AgentIssuer = cfg.Home.Issuer
+ }
+ d := testDB(t)
+ if _, a, e := New(d, cfg); e == nil {
+ a.Close()
+ t.Fatal("partial authority accepted")
+ }
+ var n int
+ if e := d.Writer().QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='decks'").Scan(&n); e != nil || n != 0 {
+ t.Fatal("mutated database on invalid config", n, e)
+ }
+ })
+ }
+ cfg := base.cfg
+ cfg.AgentIssuer = "https://connect.example.com"
+ cfg.AgentTeam = "blue"
+ mux, a, e := New(testDB(t), cfg)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer a.Close()
+ u := User{ID: 72, Email: "owner@example.com"}
+ if e = a.db.G.Create(&u).Error; e != nil {
+ t.Fatal(e)
+ }
+ homeLinked(t, a, u)
+ if e = a.mountAgent(a.agentAccess, access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ return access.Principal{Subject: "home-person", Client: "fixture", Grant: "grant", Teams: []string{"blue"}, Scopes: []string{"slides:read", "slides:write"}}, nil
+ })); e != nil {
+ t.Fatal(e)
+ }
+ // The production mux captured the startup handler; use an introspection server
+ // test separately for actual remote verification. The specific operation paths
+ // must nevertheless be outside browser CSRF and reject an absent bearer as JSON.
+ r := httptest.NewRequest("POST", homeTestOrigin+"/api/v1/operations/slides_create_deck", bytes.NewReader([]byte(`{}`)))
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, r)
+ if w.Code != 401 || !json.Valid(w.Body.Bytes()) {
+ t.Fatal("bearer route hidden by browser CSRF", w.Code, w.Body.String())
+ }
+ disabled, app, e := New(testDB(t), base.cfg)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer app.Close()
+ w = httptest.NewRecorder()
+ disabled.ServeHTTP(w, r)
+ if app.agent != nil || w.Code == 200 {
+ t.Fatal("disabled connection active", w.Code)
+ }
+}
+func TestAgentDeckHistoricalAttributionAndSealBinding(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput()))
+ var update DeckUpdate
+ f.a.app.db.G.Take(&update)
+ f.a.app.agentAccess = nil
+ f.a.app.agent = nil
+ if label := f.a.app.actorLabels(t.Context(), []string{update.Actor})[update.Actor]; label == "" {
+ t.Fatal("disabled connection erased history")
+ }
+ if e := f.a.app.db.G.Exec("UPDATE slides_connections SET coordinate='other'").Error; e != nil {
+ t.Fatal(e)
+ }
+ if label := f.a.app.actorLabels(t.Context(), []string{"connection:other"})["connection:other"]; label != "" {
+ t.Fatal("ciphertext moved to unrelated actor", label)
+ }
+}
diff --git a/internal/slides/agent_create.go b/internal/slides/agent_create.go
new file mode 100644
index 0000000..536cbec
--- /dev/null
+++ b/internal/slides/agent_create.go
@@ -0,0 +1,150 @@
+package slides
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "strconv"
+ "strings"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/slides/internal/slides/core"
+ "amadan.net/oficina/slides/internal/slides/deck"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+type slideAgentInitial struct {
+ Heading string `json:"heading"`
+ Body string `json:"body_markdown"`
+ Notes string `json:"notes_markdown"`
+}
+type slideAgentCreate struct {
+ Team string `json:"team"`
+ ClientID string `json:"client_id"`
+ Title string `json:"title"`
+ Theme string `json:"theme,omitempty"`
+ Slides []slideAgentInitial `json:"slides"`
+}
+
+func (a *slideAgent) create(ctx context.Context, p access.Principal, u User, in slideAgentCreate) (any, error) {
+ if err := a.creator(u); err != nil {
+ return nil, slideAgentFailure(err)
+ }
+ id, e := uuid.Parse(in.ClientID)
+ if e != nil || id == uuid.Nil || id.String() != in.ClientID {
+ return nil, access.Fail("invalid", "Supply a canonical nonzero UUID client_id.")
+ }
+ in.Title = strings.TrimSpace(in.Title)
+ if in.Theme == "" {
+ in.Theme = defaultTheme
+ }
+ if in.Title == "" || len(in.Title) > 512 || !validTheme(in.Theme) || len(in.Slides) < 1 || len(in.Slides) > 50 {
+ return nil, access.Fail("invalid", "Supply a title, supported theme and one to fifty slides.")
+ }
+ n := 0
+ for _, s := range in.Slides {
+ n += len(s.Heading) + len(s.Body) + len(s.Notes)
+ }
+ if n > 128<<10 {
+ return nil, access.Fail("too_large", "Initial slide text exceeds 128 KiB.")
+ }
+ coordinate := a.digest("receipt", []string{a.identityIssuer, a.issuer, p.Subject, p.Client, a.team, in.ClientID})
+ content := a.digest("content", in)
+ var d Deck
+ var h *core.Handle
+ created := false
+ defer func() {
+ if h != nil {
+ h.Close(ctx)
+ }
+ }()
+ e = a.app.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if e := a.bind(tx); e != nil {
+ return e
+ }
+ if e := a.writer(ctx, tx, p, u); e != nil {
+ return e
+ }
+ if e := tx.Exec("INSERT INTO slides_agent_receipts(coordinate,content) VALUES(?,?) ON CONFLICT(coordinate) DO NOTHING", coordinate, content).Error; e != nil {
+ return e
+ }
+ var saved string
+ var deckID sql.NullInt64
+ if e := tx.Raw("SELECT content,deck_id FROM slides_agent_receipts WHERE coordinate=?", coordinate).Row().Scan(&saved, &deckID); e != nil {
+ return e
+ }
+ if saved != content {
+ return access.Fail("conflict", "This client_id was already used with different deck content.")
+ }
+ if deckID.Valid {
+ if e := a.app.visibleDecksOn(tx, u).Where("decks.id=?", deckID.Int64).Take(&d).Error; e != nil {
+ return e
+ }
+ return a.writer(ctx, tx, p, u)
+ }
+ var e error
+ d, e = createDeckRowOn(ctx, tx, u, in.Title, in.Theme)
+ if e != nil {
+ return e
+ }
+ h, e = a.app.core.NewDoc(ctx, d.Sqid, serverClientID)
+ if e != nil {
+ return e
+ }
+ ops, e := slideAgentOps(in)
+ if e != nil {
+ return e
+ }
+ actor, e := a.actor(tx, p, u)
+ if e != nil {
+ return e
+ }
+ if e = applyOpsOn(ctx, tx, h, &d, actor, ops, nil); e != nil {
+ return e
+ }
+ if e = h.Check(ctx); e != nil {
+ return e
+ }
+ raw, e := h.JSON(ctx)
+ if e != nil {
+ return e
+ }
+ if _, e = deck.Parse(raw); e != nil {
+ return e
+ }
+ done := tx.Exec("UPDATE slides_agent_receipts SET deck_id=? WHERE coordinate=? AND deck_id IS NULL", d.ID, coordinate)
+ if done.Error != nil {
+ return done.Error
+ }
+ if done.RowsAffected != 1 {
+ return access.Fail("unavailable", "The creation receipt could not be completed.")
+ }
+ if e = a.writer(ctx, tx, p, u); e != nil {
+ return e
+ }
+ d.Seq++
+ created = true
+ return nil
+ })
+ if e != nil {
+ return nil, slideAgentFailure(e)
+ }
+ if created {
+ a.app.live.PublishSeq(d.Sqid, d.Seq)
+ a.app.maybeSnapshot(ctx, d, h, d.Seq)
+ }
+ a.remember(ctx, d.ID)
+ return map[string]any{"sqid": d.Sqid, "url": a.app.cfg.Origin + "/d/" + d.Sqid, "revision": strconv.FormatInt(d.Seq, 10)}, nil
+}
+func slideAgentOps(in slideAgentCreate) ([]byte, error) {
+ ops := []op{{"op": "set_meta", "title": in.Title, "theme": in.Theme}}
+ for _, s := range in.Slides {
+ id, blocks, e := slideIDs(2)
+ if e != nil {
+ return nil, e
+ }
+ ops = append(ops, addSlide(id, "title-body"), addBlock(id, blocks[0], "heading", "heading", s.Heading, map[string]any{"level": 1}), addBlock(id, blocks[1], "text", "body", s.Body, nil), op{"op": "set_notes", "id": id, "markdown": s.Notes})
+ }
+ return json.Marshal(ops)
+}
diff --git a/internal/slides/agent_create_test.go b/internal/slides/agent_create_test.go
new file mode 100644
index 0000000..a40da9d
--- /dev/null
+++ b/internal/slides/agent_create_test.go
@@ -0,0 +1,84 @@
+package slides
+
+import (
+ "encoding/json"
+ "strings"
+ "sync"
+ "testing"
+)
+
+func TestAgentDeckCreateRealCoreAndRetry(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ in := initialSlideAgentInput()
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", in))
+ get := func() string {
+ r := f.call(t, "slides_get_deck", map[string]any{"team": "blue", "sqid": sqid})
+ if r.Code != 200 {
+ t.Fatal(r.Code, r.Body.String())
+ }
+ return r.Body.String()
+ }
+ if b := get(); !strings.Contains(b, "REAL_DECK_CANARY") || !strings.Contains(b, "Speaker notes") {
+ t.Fatal(b)
+ }
+ var d Deck
+ if e := f.a.app.db.G.Where("sqid=?", sqid).Take(&d).Error; e != nil {
+ t.Fatal(e)
+ }
+ var update DeckUpdate
+ f.a.app.db.G.Where("deck_id=?", d.ID).Take(&update)
+ if !strings.HasPrefix(update.Actor, "connection:") {
+ t.Fatal(update.Actor)
+ }
+ if label := f.a.app.actorLabels(t.Context(), []string{update.Actor})[update.Actor]; !strings.Contains(label, "test-client") || !strings.Contains(label, f.u.Email) {
+ t.Fatal("attribution missing", label)
+ }
+ ops, _ := json.Marshal([]op{{"op": "set_meta", "title": "Later browser edit"}})
+ if e := f.a.app.editDeck(t.Context(), &d, actorFor(f.u), ops, map[string]any{"title": "Later browser edit"}, nil); e != nil {
+ t.Fatal(e)
+ }
+ if retry := slideCreated(t, f.call(t, "slides_create_deck", in)); retry != sqid {
+ t.Fatal("new deck on retry")
+ }
+ if !strings.Contains(get(), "Later browser edit") {
+ t.Fatal("retry overwrote content")
+ }
+ in.Title = "different"
+ if r := f.call(t, "slides_create_deck", in); r.Code != 409 {
+ t.Fatal(r.Code)
+ }
+ in.Title = "Deck ✓"
+ if e := f.a.app.db.G.Delete(&d).Error; e != nil {
+ t.Fatal(e)
+ }
+ if r := f.call(t, "slides_create_deck", in); r.Code != 404 {
+ t.Fatal("deleted deck recreated", r.Code)
+ }
+}
+func TestAgentDeckConcurrentFirstCreate(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ in := initialSlideAgentInput()
+ var wg sync.WaitGroup
+ ids := make(chan string, 6)
+ for i := 0; i < 6; i++ {
+ wg.Add(1)
+ go func() { defer wg.Done(); ids <- slideCreated(t, f.call(t, "slides_create_deck", in)) }()
+ }
+ wg.Wait()
+ close(ids)
+ first := ""
+ for id := range ids {
+ if first == "" {
+ first = id
+ }
+ if id != first {
+ t.Fatal("duplicate deck")
+ }
+ }
+ for _, table := range []string{"decks", "deck_updates", "slides_agent_receipts", "slides_connections"} {
+ var n int
+ if e := f.a.app.db.G.Raw("SELECT COUNT(*) FROM " + table).Scan(&n).Error; e != nil || n != 1 {
+ t.Fatal(table, n, e)
+ }
+ }
+}
diff --git a/internal/slides/agent_edit.go b/internal/slides/agent_edit.go
new file mode 100644
index 0000000..ce2e497
--- /dev/null
+++ b/internal/slides/agent_edit.go
@@ -0,0 +1,229 @@
+package slides
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "math"
+ "strconv"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/oficina/home/handoff/seal"
+ "amadan.net/oficina/slides/internal/slides/core"
+ "amadan.net/oficina/slides/internal/slides/deck"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+type slideAgentEdit struct {
+ Coordinate string `gorm:"primaryKey"`
+ Content string
+ DeckID int64
+ Revision int64
+ ResultSealed []byte
+}
+
+func (slideAgentEdit) TableName() string { return "slides_agent_edits" }
+
+type slideAgentUpdate struct {
+ Team string `json:"team"`
+ Sqid string `json:"sqid"`
+ ExpectedRevision string `json:"expected_revision"`
+ ClientID string `json:"client_id"`
+ Ops []map[string]json.RawMessage `json:"ops"`
+}
+type slideAgentUpdated struct {
+ Sqid string `json:"sqid"`
+ Revision string `json:"revision"`
+ URL string `json:"url"`
+ IDs map[string]string `json:"ids"`
+}
+
+func (a *slideAgent) editorInTx(ctx context.Context, tx *gorm.DB, p access.Principal, u User, sqid string, d *Deck) error {
+ state, ok := ctx.Value(slideAgentKey{}).(*slideAgentContext)
+ if !ok || state == nil || state.verify == nil {
+ return linkstore.ErrRefused
+ }
+ if err := state.verify(ctx); err != nil {
+ return err
+ }
+ person, err := a.app.home.ResolveOn(ctx, tx.Statement.ConnPool, p.Subject)
+ if err != nil {
+ return err
+ }
+ if person.ID != u.ID || person.Label != u.Email {
+ return linkstore.ErrRefused
+ }
+ var current User
+ if err = tx.First(&current, person.ID).Error; err != nil {
+ return err
+ }
+ if current.Email != u.Email || a.app.team == nil && !a.app.allowed.allows(current.Email) {
+ return linkstore.ErrRefused
+ }
+ current.team = u.team
+ return a.visible(ctx, tx, current, "sqid=?", sqid, d)
+}
+
+func (a *slideAgent) update(ctx context.Context, p access.Principal, u User, in slideAgentUpdate) (any, error) {
+ expected, err := strconv.ParseInt(in.ExpectedRevision, 10, 64)
+ if err != nil || expected < 0 || strconv.FormatInt(expected, 10) != in.ExpectedRevision {
+ return nil, access.Fail("invalid", "Use a canonical nonnegative decimal revision.")
+ }
+ id, err := uuid.Parse(in.ClientID)
+ if err != nil || id == uuid.Nil || id.String() != in.ClientID {
+ return nil, access.Fail("invalid", "Use a canonical nonzero client UUID.")
+ }
+ if len(in.Ops) < 1 || len(in.Ops) > 100 {
+ return nil, access.Fail("invalid", "Supply one to one hundred semantic operations.")
+ }
+ for _, op := range in.Ops {
+ if !slideAgentEditableOp(rawString(op, "op")) {
+ return nil, access.Fail("invalid", "Unsupported deck operation.")
+ }
+ }
+ // Decode numbers as Number, not float64. Marshal sorts object keys recursively
+ // and keeps ordered arrays, exact number spelling and absent versus null.
+ original, err := json.Marshal(in)
+ if err != nil {
+ return nil, slideAgentFailure(err)
+ }
+ var canonical any
+ decoder := json.NewDecoder(bytes.NewReader(original))
+ decoder.UseNumber()
+ if err = decoder.Decode(&canonical); err != nil {
+ return nil, slideAgentFailure(err)
+ }
+ coordinate := a.digest("edit-coordinate", []string{"slides_update_deck", a.identityIssuer, a.issuer, a.team, p.Subject, p.Client, in.ClientID})
+ content := a.digest("edit-content", canonical)
+ var initial Deck
+ if err = a.visible(ctx, a.app.db.G, u, "sqid=?", in.Sqid, &initial); err != nil {
+ return nil, slideAgentFailure(err)
+ }
+ sealer, err := seal.New(a.key, "oficina/slides/agent/v1")
+ if err != nil {
+ return nil, slideAgentFailure(err)
+ }
+ var result slideAgentUpdated
+ var d Deck
+ var h *core.Handle
+ fresh := false
+ defer func() {
+ if h != nil {
+ h.Close(context.WithoutCancel(ctx))
+ }
+ }()
+ guard := a.app.deckGuard(ctx, u, initial)
+ err = a.app.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if e := a.bind(tx); e != nil {
+ return e
+ }
+ return guard.run(func() error {
+ if e := a.editorInTx(ctx, tx, p, u, in.Sqid, &d); e != nil {
+ return e
+ }
+ var receipt slideAgentEdit
+ e := tx.Where("coordinate=?", coordinate).Take(&receipt).Error
+ if e == nil {
+ if receipt.Content != content || receipt.DeckID != d.ID {
+ return access.Fail("conflict", "This client UUID already names a different edit.")
+ }
+ plain, e := sealer.Open("edit-result/"+coordinate, receipt.ResultSealed)
+ if e != nil {
+ return e
+ }
+ if e = json.Unmarshal(plain, &result); e != nil {
+ return e
+ }
+ if result.Sqid != in.Sqid || result.Revision != strconv.FormatInt(receipt.Revision, 10) || result.IDs == nil {
+ return access.Fail("unavailable", "The edit receipt is unavailable.")
+ }
+ return a.editorInTx(ctx, tx, p, u, in.Sqid, &d)
+ }
+ if !errors.Is(e, gorm.ErrRecordNotFound) {
+ return e
+ }
+ if d.Seq != expected {
+ return access.Fail("conflict", "This deck changed. Read it again before editing.")
+ }
+ if d.Seq == math.MaxInt64 {
+ return access.Fail("unavailable", "This deck's revision cannot advance.")
+ }
+ var view *deck.Deck
+ h, view, e = a.app.openDeckOn(ctx, tx, d)
+ if e != nil {
+ return e
+ }
+ var copied slideAgentUpdate
+ if e = json.Unmarshal(original, &copied); e != nil {
+ return e
+ }
+ ids, e := mintOpIDs(copied.Ops, view)
+ if e != nil {
+ return e
+ }
+ encoded, e := json.Marshal(copied.Ops)
+ if e != nil {
+ return e
+ }
+ actor, e := a.actor(tx, p, u)
+ if e != nil {
+ return e
+ }
+ if e = applyOpsOn(ctx, tx, h, &d, actor, encoded, metaRowUpdates(copied.Ops)); e != nil {
+ return e
+ }
+ if e = h.Check(ctx); e != nil {
+ return e
+ }
+ raw, e := h.JSON(ctx)
+ if e != nil {
+ return e
+ }
+ if _, e = deck.Parse(raw); e != nil {
+ return e
+ }
+ if _, e = slideAgentBounded(map[string]any{"sqid": d.Sqid, "revision": strconv.FormatInt(d.Seq+1, 10), "deck": json.RawMessage(raw)}); e != nil {
+ return e
+ }
+ result = slideAgentUpdated{Sqid: d.Sqid, Revision: strconv.FormatInt(d.Seq+1, 10), URL: a.app.cfg.Origin + "/d/" + d.Sqid, IDs: ids}
+ if _, e = slideAgentBounded(result); e != nil {
+ return e
+ }
+ encoded, e = json.Marshal(result)
+ if e != nil {
+ return e
+ }
+ ciphertext, e := sealer.Seal("edit-result/"+coordinate, encoded)
+ if e != nil {
+ return e
+ }
+ if e = tx.Create(&slideAgentEdit{Coordinate: coordinate, Content: content, DeckID: d.ID, Revision: d.Seq + 1, ResultSealed: ciphertext}).Error; e != nil {
+ return e
+ }
+ if e = a.editorInTx(ctx, tx, p, u, in.Sqid, &d); e != nil {
+ return e
+ }
+ fresh = true
+ return nil
+ })
+ })
+ if err != nil {
+ var rejected *core.RejectedError
+ if errors.As(err, &rejected) {
+ return nil, access.Fail("invalid", "The semantic operation batch was refused.")
+ }
+ if errors.Is(err, errDeckBusy) {
+ return nil, access.Fail("conflict", "This deck changed. Read it again before editing.")
+ }
+ return nil, slideAgentFailure(err)
+ }
+ if fresh {
+ a.app.live.PublishSeq(d.Sqid, d.Seq)
+ a.app.maybeSnapshot(ctx, d, h, d.Seq)
+ }
+ a.remember(ctx, d.ID)
+ return slideAgentBounded(result)
+}
diff --git a/internal/slides/agent_edit_boundary_test.go b/internal/slides/agent_edit_boundary_test.go
new file mode 100644
index 0000000..de75eb5
--- /dev/null
+++ b/internal/slides/agent_edit_boundary_test.go
@@ -0,0 +1,214 @@
+package slides
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/home/roster"
+ "amadan.net/oficina/home/teammode"
+ "amadan.net/rastrillo/rastrillo/db"
+)
+
+func TestAgentDeckEditRestart(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput()))
+ in := updateDeckInput(t, f, sqid, []op{{"op": "add_slide", "layout": "flow"}})
+ ack := updatedDeck(t, f.call(t, "slides_update_deck", in))
+ var path string
+ if e := f.a.app.db.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path); e != nil {
+ t.Fatal(e)
+ }
+ f.a.app.Close()
+ f.a.app.db.Close()
+ d, e := db.Open(path, quietLogger())
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer d.Close()
+ _, app, e := New(d, f.a.app.cfg)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer app.Close()
+ f.a.app = app
+ f.install(t)
+ if got := updatedDeck(t, f.call(t, "slides_update_deck", in)); !reflect.DeepEqual(got, ack) {
+ t.Fatal("reopened edit receipt", got, ack)
+ }
+}
+func TestAgentDeckEditLimitsAndSchema(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput()))
+ in := updateDeckInput(t, f, sqid, []op{{"op": "add_slide", "layout": "flow"}})
+ for _, rev := range []string{"01", "-1", "1.0", "9223372036854775808"} {
+ bad := in
+ bad.ExpectedRevision = rev
+ if r := f.call(t, "slides_update_deck", bad); r.Code != 422 {
+ t.Fatal(rev, r.Code)
+ }
+ }
+ for _, ops := range [][]op{nil, {{"op": "register_asset", "id": "image"}}, {{"op": "add_slide", "layout": "nonsense"}}, {{"op": "set_notes", "id": "x", "markdown": 3}}, {{"op": "set_phone", "slide": "s", "id": "b", "phone": map[string]any{"unknown": true}}}} {
+ bad := updateDeckInput(t, f, sqid, ops)
+ if r := f.call(t, "slides_update_deck", bad); r.Code != 422 {
+ t.Fatal("schema", r.Code, r.Body.String())
+ }
+ }
+ many := in
+ many.Ops = nil
+ for range 101 {
+ many.Ops = append(many.Ops, in.Ops[0])
+ }
+ if r := f.call(t, "slides_update_deck", many); r.Code != 422 {
+ t.Fatal("op cap", r.Code)
+ }
+ raw, _ := json.Marshal(in)
+ raw = bytes.Replace(raw, []byte(`"flow"`), []byte(`"\ud800"`), 1)
+ if r := f.raw(t, "slides_update_deck", raw); r.Code != 422 {
+ t.Fatal("invalid Unicode", r.Code)
+ }
+ raw, _ = json.Marshal(in)
+ raw = bytes.Replace(raw, []byte(`"layout":"flow"`), []byte(`"layout":"flow","layout":"canvas"`), 1)
+ if r := f.raw(t, "slides_update_deck", raw); r.Code != 422 {
+ t.Fatal("duplicate keys", r.Code)
+ }
+ enormous := updateDeckInput(t, f, sqid, []op{{"op": "set_meta", "title": strings.Repeat("a", slideAgentLimit)}})
+ if r := f.call(t, "slides_update_deck", enormous); r.Code != 413 {
+ t.Fatal("request cap", r.Code)
+ }
+ var n int64
+ f.a.app.db.G.Model(&slideAgentEdit{}).Count(&n)
+ if n != 0 {
+ t.Fatal("invalid request left receipt")
+ }
+}
+func TestAgentDeckEditResultRemainsReadable(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ initial := initialSlideAgentInput()
+ initial.Slides[0].Body = strings.Repeat("x", 120<<10)
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", initial))
+ _, v, _ := readEditedDeck(t, f, sqid)
+ var ops []op
+ for range 10 {
+ ops = append(ops, op{"op": "duplicate_slide", "id": v.Slides[0].ID})
+ }
+ in := updateDeckInput(t, f, sqid, ops)
+ before := editDeckCounts(t, f)
+ if r := f.call(t, "slides_update_deck", in); r.Code != 413 {
+ t.Fatal("unreadable result committed", r.Code, r.Body.String())
+ }
+ if !reflect.DeepEqual(before, editDeckCounts(t, f)) {
+ t.Fatal("oversized result effects")
+ }
+}
+func TestAgentDeckEditChecksWholeSharedTypeShape(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput()))
+ var d Deck
+ if e := f.a.app.db.G.Where("sqid=?", sqid).Take(&d).Error; e != nil {
+ t.Fatal(e)
+ }
+ // Simulate an old, invalid stored document whose tolerant JSON view still
+ // parses. A harmless edit must not append on top of an unknown shared mark.
+ poison, e := os.ReadFile("../slidestest/testdata/poison/unknownmark.yjs")
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = f.a.app.db.G.Create(&DeckUpdate{DeckID: d.ID, Seq: d.Seq + 1, Actor: "legacy", Bytes: poison}).Error; e != nil {
+ t.Fatal(e)
+ }
+ if e = f.a.app.db.G.Model(&Deck{}).Where("id=?", d.ID).Update("seq", d.Seq+1).Error; e != nil {
+ t.Fatal(e)
+ }
+ in := updateDeckInput(t, f, sqid, []op{{"op": "set_meta", "title": "Must not commit"}})
+ before := editDeckCounts(t, f)
+ r := f.call(t, "slides_update_deck", in)
+ if r.Code != 422 {
+ t.Fatal("shared-type shape gate", r.Code, r.Body.String())
+ }
+ if !reflect.DeepEqual(before, editDeckCounts(t, f)) {
+ t.Fatal("shape-invalid edit committed")
+ }
+}
+func testAgentDeckEditGuardLapse(t *testing.T) {
+ f, af := newTeamSlideAgent(t)
+ sqid := slideCreated(t, af.call(t, "slides_create_deck", teamSlideInput(af)))
+ in := updateDeckInput(t, af, sqid, []op{{"op": "add_slide", "layout": "flow"}})
+ counts := editDeckCounts(t, af)
+ old := teamGuard
+ t.Cleanup(func() { teamGuard = old })
+ teamGuard = func(ctx context.Context, authorize func(roster.State) error, write func() error) error {
+ return teammode.Guard(ctx, authorize, func() error {
+ if e := write(); e != nil {
+ return e
+ }
+ f.expired()
+ return nil
+ })
+ }
+ if r := af.call(t, "slides_update_deck", in); r.Code != 503 || !reflect.DeepEqual(counts, editDeckCounts(t, af)) {
+ t.Fatal("last team guard omitted", r.Code, r.Body.String())
+ }
+}
+
+func TestAgentDeckEditExactNumberRetryFingerprint(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput()))
+ _, v, _ := readEditedDeck(t, f, sqid)
+ s := v.Slides[0]
+ in := updateDeckInput(t, f, sqid, []op{{"op": "set_block", "slide": s.ID, "id": s.Blocks[0].ID, "props": map[string]any{"custom_number": json.Number("9007199254740993")}}})
+ ack := updatedDeck(t, f.call(t, "slides_update_deck", in))
+ same, _ := json.Marshal(in)
+ // Object whitespace is irrelevant, but adjacent integers above 2^53 must
+ // not collapse to the same retry fingerprint through float64 decoding.
+ if got := updatedDeck(t, f.raw(t, "slides_update_deck", append([]byte(" \n"), same...))); !reflect.DeepEqual(got, ack) {
+ t.Fatal("whitespace changed retry")
+ }
+ changed := bytes.Replace(same, []byte("9007199254740993"), []byte("9007199254740992"), 1)
+ if r := f.raw(t, "slides_update_deck", changed); r.Code != 409 {
+ t.Fatal("rounded retry identity", r.Code, r.Body.String())
+ }
+}
+func TestAgentDeckEditRejectsInvalidNativeProjection(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput()))
+ before, v, raw := readEditedDeck(t, f, sqid)
+ s := v.Slides[0]
+ // The native op accepts int64, but Yjs stores a Number: MaxInt64 rounds
+ // past the host's integer field. Shared rich-text shape remains valid.
+ in := updateDeckInput(t, f, sqid, []op{{"op": "set_phone", "slide": s.ID, "id": s.Blocks[0].ID, "phone": map[string]any{"order": json.Number("9223372036854775807")}}})
+ counts := editDeckCounts(t, f)
+ r := f.call(t, "slides_update_deck", in)
+ if r.Code != 503 {
+ t.Fatal("invalid projection accepted", r.Code, r.Body.String())
+ }
+ after, _, got := readEditedDeck(t, f, sqid)
+ if after.Seq != before.Seq || !bytes.Equal(raw, got) || !reflect.DeepEqual(counts, editDeckCounts(t, f)) {
+ t.Fatal("invalid projection persisted")
+ }
+}
+
+func TestAgentDeckEditWriteScopeAndUnboundReceipt(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput()))
+ in := updateDeckInput(t, f, sqid, []op{{"op": "add_slide", "layout": "flow"}})
+ f.p.Scopes = []string{"slides:write"}
+ updatedDeck(t, f.call(t, "slides_update_deck", in))
+ f.p.Scopes = []string{"slides:read"}
+ if r := f.call(t, "slides_update_deck", in); r.Code != 403 {
+ t.Fatal("read scope edited", r.Code)
+ }
+ f.p.Scopes = []string{"slides:write"}
+ for _, table := range []string{"slides_agent_receipts", "slides_connections", "slides_agent_state"} {
+ if e := f.a.app.db.G.Exec("DELETE FROM " + table).Error; e != nil {
+ t.Fatal(e)
+ }
+ }
+ if r := f.call(t, "slides_update_deck", in); r.Code != 503 {
+ t.Fatal("unbound edit receipt adopted", r.Code)
+ }
+}
diff --git a/internal/slides/agent_edit_contract.go b/internal/slides/agent_edit_contract.go
new file mode 100644
index 0000000..201d48d
--- /dev/null
+++ b/internal/slides/agent_edit_contract.go
@@ -0,0 +1,70 @@
+package slides
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "context"
+ "encoding/json"
+ strictjson "github.com/go-json-experiment/json"
+)
+
+// These are discoverable argument schemas, not a second operation interpreter.
+// core/src/ops.rs owns validation and execution. Contract tests exercise every
+// advertised variant against that engine to keep the public vocabulary honest.
+func slideAgentEditVariants() []any {
+ str := func() any { return map[string]any{"type": "string"} }
+ nullable := func(v any) any { return map[string]any{"anyOf": []any{v, map[string]any{"type": "null"}}} }
+ object := func(p map[string]any, required ...string) any {
+ if required == nil {
+ required = []string{}
+ }
+ return slideAgentObject(p, required...)
+ }
+ enumeration := func(values ...string) any { return map[string]any{"enum": values} }
+ num := map[string]any{"type": "number"}
+ box := object(map[string]any{"x": num, "y": num, "w": num, "h": num}, "x", "y", "w", "h")
+ fonts := object(map[string]any{"heading": str(), "body": str()}, "heading", "body")
+ background := object(map[string]any{"kind": enumeration("theme", "color", "image"), "value": str()}, "kind")
+ phone := object(map[string]any{"hidden": map[string]any{"type": "boolean"}, "order": map[string]any{"type": "integer"}, "size": enumeration("s", "m", "l"), "box": box})
+ props := map[string]any{"type": "object", "description": "Canonical properties for the block type, as exposed in slides_get_deck. Passed unchanged to the semantic engine."}
+ layout := enumeration("flow", "canvas")
+ template := enumeration("title", "title-body", "two-column", "section", "image-full", "quote", "blank")
+ region := enumeration("heading", "body", "aside", "media")
+ variant := func(name string, p map[string]any, required ...string) any {
+ p["op"] = map[string]any{"const": name}
+ return object(p, append([]string{"op"}, required...)...)
+ }
+ return []any{
+ variant("set_meta", map[string]any{"title": str(), "theme": str(), "accent": nullable(str()), "fonts": nullable(fonts)}),
+ variant("add_slide", map[string]any{"id": str(), "after": nullable(str()), "layout": layout, "template": template}, "layout"),
+ variant("remove_slide", map[string]any{"id": str()}, "id"),
+ variant("move_slide", map[string]any{"id": str(), "after": nullable(str())}, "id"),
+ variant("duplicate_slide", map[string]any{"id": str(), "new_id": str(), "new_block_ids": map[string]any{"type": "array", "items": str()}}, "id"),
+ variant("set_slide", map[string]any{"id": str(), "layout": layout, "template": template, "background": background, "phone": enumeration("inherit", "reflow"), "transition": enumeration("none", "fade")}, "id"),
+ variant("set_notes", map[string]any{"id": str(), "markdown": str()}, "id", "markdown"),
+ variant("add_block", map[string]any{"slide": str(), "id": str(), "type": enumeration("heading", "text", "list", "quote", "image", "columns", "code", "shape", "table", "divider", "spacer"), "props": props, "region": region, "box": box, "z": num, "after": nullable(str()), "markdown": str()}, "slide", "type"),
+ variant("remove_block", map[string]any{"slide": str(), "id": str()}, "slide", "id"),
+ variant("move_block", map[string]any{"slide": str(), "id": str(), "after": nullable(str())}, "slide", "id"),
+ variant("set_block", map[string]any{"slide": str(), "id": str(), "props": props, "region": nullable(region), "box": nullable(box), "z": num}, "slide", "id"),
+ variant("set_text", map[string]any{"slide": str(), "id": str(), "markdown": str()}, "slide", "id", "markdown"),
+ variant("set_phone", map[string]any{"slide": str(), "id": str(), "phone": phone}, "slide", "id", "phone"),
+ }
+}
+func slideAgentEditableOp(name string) bool {
+ switch name {
+ case "set_meta", "add_slide", "remove_slide", "move_slide", "duplicate_slide", "set_slide", "set_notes", "add_block", "remove_block", "move_block", "set_block", "set_text", "set_phone":
+ return true
+ }
+ return false
+}
+func (a *slideAgent) updateOperation(input func(map[string]any, ...string) json.RawMessage, sqid, revision map[string]any) access.Operation {
+ return access.Operation{Name: "slides_update_deck", Description: "Atomically apply one to one hundred canonical semantic operations at expected_revision. Keep the same client UUID and payload on retry. The returned revision and generated IDs name the original commit; read again for current content.", Scope: "slides:write", Idempotent: true,
+ Input: input(map[string]any{"sqid": sqid, "expected_revision": revision, "client_id": slideAgentString(36), "ops": map[string]any{"type": "array", "minItems": 1, "maxItems": 100, "items": map[string]any{"oneOf": slideAgentEditVariants()}}}, "sqid", "expected_revision", "client_id", "ops"),
+ Output: slideAgentObject(map[string]any{"sqid": sqid, "revision": revision, "url": slideAgentString(4096), "ids": map[string]any{"type": "object", "additionalProperties": map[string]any{"type": "string"}}}, "sqid", "revision", "url", "ids"),
+ Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ var in slideAgentUpdate
+ if err := strictjson.Unmarshal(raw, &in); err != nil {
+ return nil, access.Fail("invalid", "Invalid semantic deck edit arguments.")
+ }
+ return a.update(ctx, p, slideAgentMember(ctx), in)
+ }}
+}
diff --git a/internal/slides/agent_edit_test.go b/internal/slides/agent_edit_test.go
new file mode 100644
index 0000000..915b647
--- /dev/null
+++ b/internal/slides/agent_edit_test.go
@@ -0,0 +1,339 @@
+package slides
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http/httptest"
+ "reflect"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/teammode"
+ "amadan.net/oficina/slides/internal/slides/deck"
+ deckrender "amadan.net/oficina/slides/internal/slides/render"
+ "github.com/google/uuid"
+)
+
+func updateDeckInput(t *testing.T, f *slideAgentFixture, sqid string, ops []op) slideAgentUpdate {
+ t.Helper()
+ var d Deck
+ if e := f.a.app.db.G.Where("sqid=?", sqid).Take(&d).Error; e != nil {
+ t.Fatal(e)
+ }
+ b, e := json.Marshal(ops)
+ if e != nil {
+ t.Fatal(e)
+ }
+ var raw []map[string]json.RawMessage
+ if e = json.Unmarshal(b, &raw); e != nil {
+ t.Fatal(e)
+ }
+ return slideAgentUpdate{Team: f.a.team, Sqid: sqid, ExpectedRevision: strconv.FormatInt(d.Seq, 10), ClientID: uuid.NewString(), Ops: raw}
+}
+func updatedDeck(t *testing.T, r *httptest.ResponseRecorder) slideAgentUpdated {
+ t.Helper()
+ var result slideAgentUpdated
+ if r.Code != 200 {
+ t.Fatal(r.Code, r.Body.String())
+ }
+ if e := json.Unmarshal(r.Body.Bytes(), &result); e != nil {
+ t.Fatal(e)
+ }
+ return result
+}
+func editDeckCounts(t *testing.T, f *slideAgentFixture) []int64 {
+ t.Helper()
+ var counts []int64
+ for _, name := range []string{"decks", "deck_updates", "deck_snapshots", "slides_agent_edits", "slides_connections"} {
+ var n int64
+ if e := f.a.app.db.G.Table(name).Count(&n).Error; e != nil {
+ t.Fatal(e)
+ }
+ counts = append(counts, n)
+ }
+ return counts
+}
+func readEditedDeck(t *testing.T, f *slideAgentFixture, sqid string) (Deck, *deck.Deck, []byte) {
+ t.Helper()
+ var d Deck
+ if e := f.a.app.db.G.Where("sqid=?", sqid).Take(&d).Error; e != nil {
+ t.Fatal(e)
+ }
+ h, v, e := f.a.app.openDeck(t.Context(), d)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer h.Close(t.Context())
+ raw, e := h.JSON(t.Context())
+ if e != nil {
+ t.Fatal(e)
+ }
+ return d, v, raw
+}
+func TestAgentDeckEditCanonicalParityAndLaterRetry(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput()))
+ _, before, _ := readEditedDeck(t, f, sqid)
+ s := before.Slides[0]
+ heading, body := s.Blocks[0].ID, s.Blocks[1].ID
+ in := updateDeckInput(t, f, sqid, []op{
+ {"op": "set_meta", "title": "Edited title", "theme": "ink"},
+ {"op": "set_slide", "id": s.ID, "layout": "canvas"},
+ {"op": "set_notes", "id": s.ID, "markdown": "EDITED_NOTES"},
+ {"op": "set_text", "slide": s.ID, "id": heading, "markdown": "EDITED_HEADING"},
+ {"op": "set_block", "slide": s.ID, "id": heading, "z": 0.25, "box": map[string]any{"x": 0.1, "y": 0.2, "w": 0.5, "h": 0.4}},
+ {"op": "set_phone", "slide": s.ID, "id": heading, "phone": map[string]any{"size": "l", "hidden": false}},
+ {"op": "move_block", "slide": s.ID, "id": body, "after": nil},
+ {"op": "add_slide", "id": "newslideabcd", "layout": "flow", "template": "blank"},
+ {"op": "add_block", "slide": "newslideabcd", "id": "newblockabcd", "type": "text", "region": "body", "markdown": "Temporary"},
+ {"op": "move_slide", "id": "newslideabcd", "after": nil},
+ {"op": "duplicate_slide", "id": s.ID},
+ {"op": "remove_block", "slide": "newslideabcd", "id": "newblockabcd"},
+ {"op": "remove_slide", "id": "newslideabcd"},
+ })
+ events, cancel := f.a.app.live.Subscribe(sqid)
+ defer cancel()
+ ack := updatedDeck(t, f.call(t, "slides_update_deck", in))
+ if ack.IDs["10"] == "" {
+ t.Fatal("missing duplicate ID", ack)
+ }
+ select {
+ case <-events:
+ default:
+ t.Fatal("committed edit not published")
+ }
+ d, view, raw := readEditedDeck(t, f, sqid)
+ if d.Title != "Edited title" || d.Theme != "ink" || d.Seq != 2 || len(view.Slides) != 2 || !bytes.Contains(raw, []byte(`"z":0.25`)) || !bytes.Contains(raw, []byte("EDITED_NOTES")) {
+ t.Fatal("canonical mismatch", d, string(raw))
+ }
+ html, e := deckrender.Slide(view, 0, deckrender.Desktop)
+ if e != nil || !strings.Contains(string(html), "EDITED_HEADING") {
+ t.Fatal("native render mismatch", e, string(html))
+ }
+ get := f.call(t, "slides_get_deck", map[string]any{"team": f.a.team, "sqid": sqid})
+ if get.Code != 200 || !bytes.Contains(get.Body.Bytes(), []byte(`"z":0.25`)) {
+ t.Fatal("API rounded native content", get.Body.String())
+ }
+ ops, _ := opsJSON([]op{{"op": "set_notes", "id": s.ID, "markdown": "LATER_NATIVE_EDIT"}})
+ if e = f.a.app.editDeck(t.Context(), &d, actorFor(f.u), ops, nil, nil); e != nil {
+ t.Fatal(e)
+ }
+ // Discard the native seq notification; replay itself must publish nothing.
+ select {
+ case <-events:
+ default:
+ }
+ counts := editDeckCounts(t, f)
+ if replay := updatedDeck(t, f.call(t, "slides_update_deck", in)); !reflect.DeepEqual(replay, ack) {
+ t.Fatal("unstable retry", replay, ack)
+ }
+ if !reflect.DeepEqual(counts, editDeckCounts(t, f)) {
+ t.Fatal("retry wrote log/receipt")
+ }
+ select {
+ case <-events:
+ t.Fatal("retry published another edit")
+ default:
+ }
+ _, _, raw = readEditedDeck(t, f, sqid)
+ if !bytes.Contains(raw, []byte("LATER_NATIVE_EDIT")) {
+ t.Fatal("retry overwrote later edit")
+ }
+ stale := in
+ stale.ClientID = uuid.NewString()
+ if r := f.call(t, "slides_update_deck", stale); r.Code != 409 {
+ t.Fatal("stale edit", r.Code)
+ }
+ mismatch := in
+ mismatch.ExpectedRevision = "3"
+ if r := f.call(t, "slides_update_deck", mismatch); r.Code != 409 {
+ t.Fatal("changed retry", r.Code)
+ }
+}
+func TestAgentDeckEditAtomicRefusals(t *testing.T) {
+ for _, sql := range []string{
+ `CREATE TRIGGER edit_fail BEFORE INSERT ON slides_agent_edits BEGIN SELECT RAISE(ABORT,'receipt failure'); END`,
+ `CREATE TRIGGER edit_fail AFTER INSERT ON slides_agent_edits BEGIN DELETE FROM home_identity_links; END`,
+ `CREATE TRIGGER edit_fail AFTER INSERT ON slides_agent_edits BEGIN UPDATE home_identity_links SET person_binding=zeroblob(32); END`,
+ `CREATE TRIGGER edit_fail BEFORE UPDATE OF title ON decks BEGIN SELECT RAISE(ABORT,'metadata failure'); END`,
+ } {
+ t.Run(sql, func(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput()))
+ before, _, raw := readEditedDeck(t, f, sqid)
+ counts := editDeckCounts(t, f)
+ in := updateDeckInput(t, f, sqid, []op{{"op": "set_meta", "title": "Should roll back"}, {"op": "add_slide", "layout": "flow"}})
+ events, cancel := f.a.app.live.Subscribe(sqid)
+ defer cancel()
+ if e := f.a.app.db.G.Exec(sql).Error; e != nil {
+ t.Fatal(e)
+ }
+ if r := f.call(t, "slides_update_deck", in); r.Code == 200 {
+ t.Fatal("failed write acknowledged")
+ }
+ after, _, got := readEditedDeck(t, f, sqid)
+ if before.Seq != after.Seq || before.Title != after.Title || !bytes.Equal(raw, got) || !reflect.DeepEqual(counts, editDeckCounts(t, f)) {
+ t.Fatal("atomic rollback failed")
+ }
+ select {
+ case <-events:
+ t.Fatal("rolled-back seq published")
+ default:
+ }
+ if e := f.a.app.db.G.Exec("DROP TRIGGER edit_fail").Error; e != nil {
+ t.Fatal(e)
+ }
+ updatedDeck(t, f.call(t, "slides_update_deck", in))
+ })
+ }
+}
+func TestAgentDeckEditInvalidLaterOperation(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput()))
+ before, _, raw := readEditedDeck(t, f, sqid)
+ counts := editDeckCounts(t, f)
+ in := updateDeckInput(t, f, sqid, []op{{"op": "set_meta", "title": "Partial title"}, {"op": "remove_slide", "id": "nonexistent"}})
+ r := f.call(t, "slides_update_deck", in)
+ if r.Code != 422 {
+ t.Fatal("invalid semantic batch", r.Code, r.Body.String())
+ }
+ after, _, got := readEditedDeck(t, f, sqid)
+ if before.Seq != after.Seq || !bytes.Equal(raw, got) || !reflect.DeepEqual(counts, editDeckCounts(t, f)) {
+ t.Fatal("partial semantic batch")
+ }
+}
+func TestAgentDeckEditConcurrency(t *testing.T) {
+ for _, same := range []bool{true, false} {
+ t.Run(strconv.FormatBool(same), func(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput()))
+ in := updateDeckInput(t, f, sqid, []op{{"op": "add_slide", "layout": "flow"}})
+ var wg sync.WaitGroup
+ codes := make(chan int, 4)
+ for range 4 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ v := in
+ if !same {
+ v.ClientID = uuid.NewString()
+ }
+ codes <- f.call(t, "slides_update_deck", v).Code
+ }()
+ }
+ wg.Wait()
+ close(codes)
+ ok, conflict := 0, 0
+ for n := range codes {
+ switch n {
+ case 200:
+ ok++
+ case 409:
+ conflict++
+ default:
+ t.Fatal(n)
+ }
+ }
+ if same && ok != 4 || !same && (ok != 1 || conflict != 3) {
+ t.Fatal(ok, conflict)
+ }
+ d, _, _ := readEditedDeck(t, f, sqid)
+ if d.Seq != 2 {
+ t.Fatal("more than one edit", d.Seq)
+ }
+ })
+ }
+}
+func TestAgentDeckEditWriterGuardsWithoutEmission(t *testing.T) {
+ for _, retry := range []bool{false, true} {
+ for _, phase := range []int{1, 2} {
+ t.Run(fmt.Sprintf("retry=%v/phase=%d", retry, phase), func(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput()))
+ in := updateDeckInput(t, f, sqid, []op{{"op": "add_slide", "layout": "flow"}})
+ if retry {
+ updatedDeck(t, f.call(t, "slides_update_deck", in))
+ }
+ if !retry && phase == 1 {
+ if e := f.a.app.db.G.Exec(`CREATE TRIGGER trap BEFORE INSERT ON deck_updates BEGIN SELECT RAISE(ABORT,'early guard omitted'); END`).Error; e != nil {
+ t.Fatal(e)
+ }
+ }
+ u, e := f.a.member(t.Context(), f.p, true)
+ if e != nil {
+ t.Fatal(e)
+ }
+ n := 0
+ state := &slideAgentContext{member: u, slides: map[int64]bool{}, verify: func(context.Context) error {
+ n++
+ if n == phase {
+ return access.Fail("unauthenticated", "Revoked")
+ }
+ return nil
+ }}
+ counts := editDeckCounts(t, f)
+ ctx := context.WithValue(t.Context(), slideAgentKey{}, state)
+ _, e = f.a.update(ctx, f.p, u, in)
+ if access.SafeFailure(e).Code != "unauthenticated" || n != phase {
+ t.Fatal("writer guard", e, n)
+ }
+ if !reflect.DeepEqual(counts, editDeckCounts(t, f)) {
+ t.Fatal("revoked edit committed")
+ }
+ })
+ }
+ }
+}
+func TestAgentDeckEditTeamSharesAndLapse(t *testing.T) {
+ f, af := newTeamSlideAgent(t)
+ sqid := slideCreated(t, af.call(t, "slides_create_deck", teamSlideInput(af)))
+ var d Deck
+ if e := f.d.G.Where("sqid=?", sqid).Take(&d).Error; e != nil {
+ t.Fatal(e)
+ }
+ other := f.localUser("other@example.com")
+ f.grant(d, af.u, other)
+ in := updateDeckInput(t, af, sqid, []op{{"op": "add_slide", "layout": "flow"}})
+ f.dir.Set(af.p.Subject, "")
+ f.refreshed()
+ ack := updatedDeck(t, af.call(t, "slides_update_deck", in))
+ in.ClientID = uuid.NewString()
+ in.ExpectedRevision = ack.Revision
+ f.expired()
+ updatedDeck(t, af.call(t, "slides_update_deck", in))
+ for _, retry := range []bool{false, true} {
+ t.Run(strconv.FormatBool(retry), func(t *testing.T) {
+ f, af := newTeamSlideAgent(t)
+ sqid := slideCreated(t, af.call(t, "slides_create_deck", teamSlideInput(af)))
+ in := updateDeckInput(t, af, sqid, []op{{"op": "add_slide", "layout": "flow"}})
+ if retry {
+ updatedDeck(t, af.call(t, "slides_update_deck", in))
+ }
+ u, e := af.a.member(t.Context(), af.p, true)
+ if e != nil {
+ t.Fatal(e)
+ }
+ n := 0
+ state := &slideAgentContext{member: u, slides: map[int64]bool{}, verify: func(context.Context) error {
+ n++
+ if n == 2 {
+ f.expired()
+ }
+ return nil
+ }}
+ ctx := teammode.WithAccess(context.WithValue(t.Context(), slideAgentKey{}, state), u.team.Access)
+ counts := editDeckCounts(t, af)
+ if _, e = af.a.update(ctx, af.p, u, in); e == nil {
+ t.Fatal("expired writer accepted")
+ }
+ if !reflect.DeepEqual(counts, editDeckCounts(t, af)) {
+ t.Fatal("expired edit effects")
+ }
+ })
+ }
+}
diff --git a/internal/slides/agent_fixture_test.go b/internal/slides/agent_fixture_test.go
new file mode 100644
index 0000000..efe047b
--- /dev/null
+++ b/internal/slides/agent_fixture_test.go
@@ -0,0 +1,94 @@
+package slides
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "bytes"
+ "context"
+ "encoding/json"
+ "github.com/google/uuid"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+type slideAgentFixture struct {
+ a *slideAgent
+ u User
+ p access.Principal
+ checks atomic.Int64
+ revokeAt atomic.Int64
+}
+type agentDeadlineRecorder struct {
+ *httptest.ResponseRecorder
+ afterWrite func()
+}
+
+func (*agentDeadlineRecorder) SetWriteDeadline(time.Time) error { return nil }
+func (w *agentDeadlineRecorder) Write(b []byte) (int, error) {
+ n, e := w.ResponseRecorder.Write(b)
+ if w.afterWrite != nil {
+ f := w.afterWrite
+ w.afterWrite = nil
+ f()
+ }
+ return n, e
+}
+func newSlideAgentFixture(t *testing.T, issuers ...string) *slideAgentFixture {
+ _, app, u := homeFixture(t)
+ homeLinked(t, app, u)
+ issuer := "https://connect.example.com"
+ if len(issuers) > 0 {
+ issuer = issuers[0]
+ }
+ a := &slideAgent{app: app, issuer: issuer, identityIssuer: app.cfg.Home.Issuer, team: "blue", key: bytes.Repeat([]byte{8}, 32)}
+ f := &slideAgentFixture{a: a, u: u, p: access.Principal{Subject: "home-person", Client: "test-client", Grant: "grant-one", Teams: []string{"blue"}, Scopes: []string{"slides:read", "slides:write"}}}
+ f.install(t)
+ return f
+}
+func (f *slideAgentFixture) install(t *testing.T) {
+ t.Helper()
+ e := f.a.app.mountAgent(f.a, access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ n := f.checks.Add(1)
+ if at := f.revokeAt.Load(); at > 0 && n >= at {
+ return access.Principal{}, access.Fail("unauthenticated", "Revoked.")
+ }
+ return f.p, nil
+ }))
+ if e != nil {
+ t.Fatal(e)
+ }
+}
+func (f *slideAgentFixture) raw(t *testing.T, name string, raw []byte) *httptest.ResponseRecorder {
+ t.Helper()
+ r := httptest.NewRequest("POST", homeTestOrigin+"/api/v1/operations/"+name, bytes.NewReader(raw))
+ r.Header.Set("Authorization", "Bearer test-token")
+ r.Header.Set("Content-Type", "application/json")
+ w := &agentDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}
+ f.a.app.agent.ServeHTTP(w, r)
+ return w.ResponseRecorder
+}
+func (f *slideAgentFixture) call(t *testing.T, name string, input any) *httptest.ResponseRecorder {
+ t.Helper()
+ b, e := json.Marshal(input)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return f.raw(t, name, b)
+}
+func initialSlideAgentInput() slideAgentCreate {
+ return slideAgentCreate{Team: "blue", ClientID: uuid.NewString(), Title: "Deck ✓", Slides: []slideAgentInitial{{Heading: "Welcome", Body: "**REAL_DECK_CANARY**", Notes: "Speaker notes"}}}
+}
+func slideCreated(t *testing.T, r *httptest.ResponseRecorder) string {
+ t.Helper()
+ if r.Code != 200 {
+ t.Fatal(r.Code, r.Body.String())
+ }
+ var v struct {
+ Sqid string `json:"sqid"`
+ }
+ if e := json.Unmarshal(r.Body.Bytes(), &v); e != nil || v.Sqid == "" {
+ t.Fatal(e, r.Body.String())
+ }
+ return v.Sqid
+}
diff --git a/internal/slides/agent_integration_test.go b/internal/slides/agent_integration_test.go
new file mode 100644
index 0000000..c99600f
--- /dev/null
+++ b/internal/slides/agent_integration_test.go
@@ -0,0 +1,172 @@
+package slides
+
+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 Slides' real handlers, linked identity, canonical deck content.
+// The signed Home/browser/PKCE flow is exercised in the connection module.
+func TestAgentGatewayToRealSlides(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 := newSlideAgentFixture(t, issuer.URL)
+ p := f.p
+ input, _ := json.Marshal(initialSlideAgentInput())
+ 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: "https://home.example.com", 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{"slides:read": "Read presentations", "slides:write": "Create presentations"}, 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", "https://home.example.com")
+ if err != nil {
+ t.Fatal(err)
+ }
+ remote.Client.Transport = issuer.Client().Transport
+ f.a.app.cfg.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, "slides_create_deck", json.RawMessage(input))
+ if err != nil {
+ t.Fatal(err)
+ }
+ encoded, _ := json.Marshal(result)
+ var deck struct {
+ Sqid string `json:"sqid"`
+ }
+ if json.Unmarshal(encoded, &deck) != nil || deck.Sqid == "" {
+ t.Fatal("invalid deck receipt")
+ }
+ mcpClient := mcp.NewClient(&mcp.Implementation{Name: "Slides 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: "slides_create_deck", Arguments: json.RawMessage(input)})
+ if err != nil || retry.IsError {
+ t.Fatal("MCP retry", retry, err)
+ }
+ search, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "slides_get_deck", Arguments: map[string]any{"team": "blue", "sqid": deck.Sqid}})
+ if err != nil || search.IsError {
+ t.Fatal("MCP search", search, err)
+ }
+ text, _ := json.Marshal(search.Content)
+ if !strings.Contains(string(text), "REAL_DECK_CANARY") {
+ t.Fatal("MCP could not read created deck")
+ }
+
+ edit := updateDeckInput(t, f, deck.Sqid, []op{{"op": "set_meta", "title": "CLI_EDITED_DECK"}})
+ rawEdit, _ := json.Marshal(edit)
+ if _, err = cli.Call(ctx, "slides_update_deck", json.RawMessage(rawEdit)); err != nil {
+ t.Fatal("CLI edit", err)
+ }
+ replayEdit, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "slides_update_deck", Arguments: json.RawMessage(rawEdit)})
+ if err != nil || replayEdit.IsError {
+ t.Fatal("MCP edit retry", replayEdit, err)
+ }
+ afterEdit, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "slides_get_deck", Arguments: map[string]any{"team": "blue", "sqid": deck.Sqid}})
+ if err != nil || afterEdit.IsError {
+ t.Fatal("MCP edited read", afterEdit, err)
+ }
+ editedText, _ := json.Marshal(afterEdit.Content)
+ if !strings.Contains(string(editedText), "CLI_EDITED_DECK") {
+ t.Fatal("semantic edit did not reach MCP read", string(editedText))
+ }
+ var count int
+ if err = f.a.app.db.G.Raw("SELECT COUNT(*) FROM decks").Scan(&count).Error; err != nil || count != 1 {
+ t.Fatal("transport retry duplicated deck", count, err)
+ }
+ if err = cli.Logout(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = session.CallTool(ctx, &mcp.CallToolParams{Name: "slides_create_deck", Arguments: initialSlideAgentInput()}); err == nil {
+ t.Fatal("MCP survived CLI revocation")
+ }
+ if err = f.a.app.db.G.Raw("SELECT COUNT(*) FROM decks").Scan(&count).Error; err != nil || count != 1 {
+ t.Fatal("revoked call wrote deck", count, err)
+ }
+}
diff --git a/internal/slides/agent_migrations/migrations/0001_connections.sql b/internal/slides/agent_migrations/migrations/0001_connections.sql
new file mode 100644
index 0000000..66e9e63
--- /dev/null
+++ b/internal/slides/agent_migrations/migrations/0001_connections.sql
@@ -0,0 +1,3 @@
+CREATE TABLE slides_agent_state(id INTEGER PRIMARY KEY, keycheck TEXT NOT NULL);
+CREATE TABLE slides_agent_receipts(coordinate TEXT PRIMARY KEY, content TEXT NOT NULL, deck_id INTEGER);
+CREATE TABLE slides_connections(coordinate TEXT PRIMARY KEY, operator_id INTEGER NOT NULL, client_sealed BLOB NOT NULL);
diff --git a/internal/slides/agent_migrations/migrations/0002_edits.sql b/internal/slides/agent_migrations/migrations/0002_edits.sql
new file mode 100644
index 0000000..74e3410
--- /dev/null
+++ b/internal/slides/agent_migrations/migrations/0002_edits.sql
@@ -0,0 +1,7 @@
+CREATE TABLE slides_agent_edits (
+ coordinate TEXT PRIMARY KEY NOT NULL,
+ content TEXT NOT NULL,
+ deck_id INTEGER NOT NULL,
+ revision INTEGER NOT NULL,
+ result_sealed BLOB NOT NULL
+);
diff --git a/internal/slides/agent_operations.go b/internal/slides/agent_operations.go
new file mode 100644
index 0000000..ff45d72
--- /dev/null
+++ b/internal/slides/agent_operations.go
@@ -0,0 +1,95 @@
+package slides
+
+import (
+ "context"
+ "encoding/json"
+
+ access "amadan.net/oficina/agent-access.git"
+ strictjson "github.com/go-json-experiment/json"
+)
+
+func slideAgentObject(props map[string]any, required ...string) json.RawMessage {
+ b, _ := json.Marshal(map[string]any{"type": "object", "properties": props, "required": required, "additionalProperties": false})
+ return b
+}
+func slideAgentString(max int) map[string]any {
+ return map[string]any{"type": "string", "maxLength": max}
+}
+func (a *slideAgent) registry() (*access.Registry, error) {
+ input := func(props map[string]any, required ...string) json.RawMessage {
+ props["team"] = map[string]any{"type": "string", "minLength": 1, "maxLength": 128}
+ return slideAgentObject(props, append([]string{"team"}, required...)...)
+ }
+ sqid := map[string]any{"type": "string", "pattern": "^[23456789abcdefghjkmnpqrstuvwxyz]{10}$"}
+ revision := map[string]any{"type": "string", "pattern": "^(0|[1-9][0-9]{0,18})$"}
+ summary := slideAgentObject(map[string]any{"sqid": sqid, "title": slideAgentString(slideAgentLimit), "theme": slideAgentString(128), "revision": revision}, "sqid", "title", "theme", "revision")
+ initial := slideAgentObject(map[string]any{"heading": slideAgentString(128 << 10), "body_markdown": slideAgentString(128 << 10), "notes_markdown": slideAgentString(128 << 10)}, "heading", "body_markdown", "notes_markdown")
+ ops := []access.Operation{
+ {Name: "slides_list_decks", Description: "List currently readable presentations in this team.", Scope: "slides:read", ReadOnly: true, Idempotent: true, Input: input(map[string]any{"limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 100}, "cursor": map[string]any{"type": "string", "pattern": "^[1-9][0-9]{0,18}$"}}), Output: slideAgentObject(map[string]any{"decks": map[string]any{"type": "array", "maxItems": 100, "items": summary}, "next_cursor": slideAgentString(19)}, "decks", "next_cursor"), Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ var in struct {
+ Limit int `json:"limit"`
+ Cursor string `json:"cursor"`
+ }
+ if json.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Invalid pagination arguments.")
+ }
+ return a.list(ctx, slideAgentMember(ctx), in.Limit, in.Cursor)
+ }},
+ {Name: "slides_get_deck", Description: "Read a presentation's canonical block tree and speaker notes at one revision.", Scope: "slides:read", ReadOnly: true, Idempotent: true, Input: input(map[string]any{"sqid": sqid}, "sqid"), Output: slideAgentObject(map[string]any{"sqid": sqid, "revision": revision, "deck": map[string]any{"type": "object"}}, "sqid", "revision", "deck"), Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ var in struct {
+ Sqid string `json:"sqid"`
+ }
+ if json.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Invalid deck identifier.")
+ }
+ return a.get(ctx, slideAgentMember(ctx), in.Sqid)
+ }},
+ {Name: "slides_create_deck", Description: "Create a private presentation with up to fifty initial slides. Reuse the same client UUID only for retries.", Scope: "slides:write", Idempotent: true, Input: input(map[string]any{"client_id": slideAgentString(36), "title": map[string]any{"type": "string", "minLength": 1, "maxLength": 512}, "theme": map[string]any{"enum": themeIDs}, "slides": map[string]any{"type": "array", "minItems": 1, "maxItems": 50, "items": initial}}, "client_id", "title", "slides"), Output: slideAgentObject(map[string]any{"sqid": sqid, "url": slideAgentString(4096), "revision": revision}, "sqid", "url", "revision"), Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ var in slideAgentCreate
+ if json.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Invalid initial deck arguments.")
+ }
+ return a.create(ctx, p, slideAgentMember(ctx), in)
+ }},
+ }
+ ops = append(ops, a.updateOperation(input, sqid, revision))
+ for i := range ops {
+ scope, invoke := ops[i].Scope, ops[i].Invoke
+ ops[i].Available = func(p access.Principal) bool { return p.Allows(a.team, scope) }
+ ops[i].Invoke = func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ if len(raw) > slideAgentLimit {
+ return nil, access.Fail("too_large", "The operation input exceeds 1 MiB.")
+ }
+ var in struct {
+ Team string `json:"team"`
+ }
+ if strictjson.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Send valid Unicode JSON.")
+ }
+ if in.Team != a.team {
+ return nil, access.Fail("forbidden", "This instance does not serve that team.")
+ }
+ u, e := a.member(ctx, p, scope == "slides:write")
+ if e != nil {
+ return nil, e
+ }
+ state, ok := ctx.Value(slideAgentKey{}).(*slideAgentContext)
+ if !ok || state == nil {
+ return nil, access.Fail("unavailable", "Request authority is unavailable.")
+ }
+ if state.member.ID != u.ID || state.member.Email != u.Email {
+ return nil, access.Fail("forbidden", "The current identity changed.")
+ }
+ return invoke(ctx, p, raw)
+ }
+ }
+ return access.NewRegistry(ops...)
+}
+func AgentContracts() ([]access.Operation, error) {
+ a := &slideAgent{team: "contract"}
+ r, e := a.registry()
+ if e != nil {
+ return nil, e
+ }
+ return r.List(access.Principal{Subject: "contract", Teams: []string{"contract"}, Scopes: []string{"slides:read", "slides:write"}}), nil
+}
diff --git a/internal/slides/agent_read.go b/internal/slides/agent_read.go
new file mode 100644
index 0000000..5b61e69
--- /dev/null
+++ b/internal/slides/agent_read.go
@@ -0,0 +1,89 @@
+package slides
+
+import (
+ "amadan.net/oficina/home/roster"
+ "context"
+ "encoding/json"
+ "errors"
+ "gorm.io/gorm"
+ "strconv"
+
+ access "amadan.net/oficina/agent-access.git"
+)
+
+func (a *slideAgent) list(ctx context.Context, u User, limit int, cursor string) (any, error) {
+ if state, ok := ctx.Value(slideAgentKey{}).(*slideAgentContext); ok && state != nil {
+ state.list = true
+ }
+ if a.app.team != nil && u.team.state() == roster.Unknown {
+ return nil, access.Fail("unavailable", "The complete deck list cannot be verified now.")
+ }
+ if limit == 0 {
+ limit = 20
+ }
+ if limit < 1 || limit > 100 {
+ return nil, access.Fail("invalid", "Limit must be one to one hundred.")
+ }
+ q := a.app.visibleDecks(ctx, u)
+ if cursor != "" {
+ id, e := strconv.ParseInt(cursor, 10, 64)
+ if e != nil || id <= 0 || strconv.FormatInt(id, 10) != cursor {
+ return nil, access.Fail("invalid", "Use a canonical positive decimal cursor.")
+ }
+ q = q.Where("decks.id<?", id)
+ }
+ rows := []Deck{}
+ if e := q.Order("decks.id DESC").Limit(limit + 1).Find(&rows).Error; e != nil {
+ return nil, slideAgentFailure(e)
+ }
+ next := ""
+ if len(rows) > limit {
+ rows = rows[:limit]
+ next = strconv.FormatInt(rows[len(rows)-1].ID, 10)
+ }
+ out := []map[string]any{}
+ for _, d := range rows {
+ a.remember(ctx, d.ID)
+ out = append(out, map[string]any{"sqid": d.Sqid, "title": d.Title, "theme": d.Theme, "revision": strconv.FormatInt(d.Seq, 10)})
+ }
+ return slideAgentBounded(map[string]any{"decks": out, "next_cursor": next})
+}
+func (a *slideAgent) get(ctx context.Context, u User, sqid string) (any, error) {
+ var d Deck
+ if e := a.visible(ctx, a.app.db.G, u, "sqid=?", sqid, &d); e != nil {
+ return nil, slideAgentFailure(e)
+ }
+ h, _, e := a.app.openDeck(ctx, d)
+ if e != nil {
+ return nil, slideAgentFailure(e)
+ }
+ defer h.Close(ctx)
+ raw, e := h.JSON(ctx)
+ if e != nil {
+ return nil, slideAgentFailure(e)
+ }
+ a.remember(ctx, d.ID)
+ return slideAgentBounded(map[string]any{"sqid": d.Sqid, "revision": strconv.FormatInt(d.Seq, 10), "deck": json.RawMessage(raw)})
+}
+
+// visible preserves the app's roster/grant query on the caller's connection.
+// Recheck after the query: a lease may expire while SQLite reads the row.
+func (a *slideAgent) visible(ctx context.Context, db *gorm.DB, u User, predicate string, id any, d *Deck) error {
+ err := a.app.visibleDecksOn(db.WithContext(ctx), u).Where(predicate, id).Take(d).Error
+ if a.app.team == nil || u.team.state() != roster.Unknown {
+ return err
+ }
+ if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ return err
+ }
+ if err == nil {
+ var n int64
+ if e := db.WithContext(ctx).Model(&DeckGrant{}).Where("deck_id=? AND user_id=?", d.ID, u.ID).Count(&n).Error; e != nil {
+ return e
+ }
+ if n > 0 {
+ return nil
+ }
+ }
+ return access.Fail("unavailable", "Deck visibility cannot be verified now.")
+}
diff --git a/internal/slides/agent_read_test.go b/internal/slides/agent_read_test.go
new file mode 100644
index 0000000..ee729d2
--- /dev/null
+++ b/internal/slides/agent_read_test.go
@@ -0,0 +1,148 @@
+package slides
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "encoding/json"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+func TestAgentDeckVisibilityAndExactCursor(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ const base = int64(9007199254740992)
+ rows := []Deck{{ID: base + 1, Sqid: "23456789ab", Title: "owned", OwnerID: f.u.ID, Rung: rungPrivate, Theme: "paper"}, {ID: base + 2, Sqid: "23456789ac", Title: "team", OwnerID: 99, Rung: rungTeam, Theme: "paper"}, {ID: base + 3, Sqid: "23456789ad", Title: "granted", OwnerID: 99, Rung: rungGranted, Theme: "paper"}, {ID: base + 4, Sqid: "23456789ae", Title: "PRIVATE_DENIED", OwnerID: 99, Rung: rungPrivate, Theme: "paper"}}
+ if e := f.a.app.db.G.Create(&rows).Error; e != nil {
+ t.Fatal(e)
+ }
+ if e := f.a.app.db.G.Exec("INSERT INTO deck_grants(deck_id,user_id) VALUES(?,?)", base+3, f.u.ID).Error; e != nil {
+ t.Fatal(e)
+ }
+ var page struct {
+ Decks []struct {
+ Sqid string `json:"sqid"`
+ }
+ Next string `json:"next_cursor"`
+ }
+ r := f.call(t, "slides_list_decks", map[string]any{"team": "blue", "limit": 1})
+ if e := json.Unmarshal(r.Body.Bytes(), &page); e != nil || r.Code != 200 || len(page.Decks) != 1 || page.Decks[0].Sqid != rows[2].Sqid || page.Next != strconv.FormatInt(base+3, 10) {
+ t.Fatal(r.Code, r.Body.String(), e)
+ }
+ r = f.call(t, "slides_list_decks", map[string]any{"team": "blue", "limit": 1, "cursor": page.Next})
+ if e := json.Unmarshal(r.Body.Bytes(), &page); e != nil || r.Code != 200 || len(page.Decks) != 1 || page.Decks[0].Sqid != rows[1].Sqid || page.Next != strconv.FormatInt(base+2, 10) {
+ t.Fatal(r.Code, r.Body.String(), e)
+ }
+ if r := f.call(t, "slides_get_deck", map[string]any{"team": "blue", "sqid": rows[3].Sqid}); r.Code != 404 {
+ t.Fatal(r.Code)
+ }
+ for _, cursor := range []string{"09223372036854775807", "9223372036854775808"} {
+ if r := f.call(t, "slides_list_decks", map[string]any{"team": "blue", "cursor": cursor}); r.Code != 422 {
+ t.Fatal(r.Code)
+ }
+ }
+}
+func TestAgentDeckRawCorePrecision(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput()))
+ var d Deck
+ f.a.app.db.G.Where("sqid=?", sqid).Take(&d)
+ h, view, e := f.a.app.openDeck(t.Context(), d)
+ if e != nil {
+ t.Fatal(e)
+ }
+ h.Close(t.Context())
+ ops, _ := json.Marshal([]op{{"op": "set_slide", "id": view.Slides[0].ID, "layout": "canvas"}, {"op": "set_block", "slide": view.Slides[0].ID, "id": view.Slides[0].Blocks[0].ID, "z": 1.75}})
+ if e = f.a.app.editDeck(t.Context(), &d, actorFor(f.u), ops, nil, nil); e != nil {
+ t.Fatal(e)
+ }
+ r := f.call(t, "slides_get_deck", map[string]any{"team": "blue", "sqid": sqid})
+ if r.Code != 200 || !strings.Contains(r.Body.String(), `"z":1.75`) {
+ t.Fatal("core precision lost", r.Code, r.Body.String())
+ }
+}
+func TestAgentDeckLimitsAndAuthorization(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ for _, mode := range []string{"team", "scope", "uuid", "unknown", "title", "text", "input"} {
+ t.Run(mode, func(t *testing.T) {
+ in := initialSlideAgentInput()
+ want := 422
+ switch mode {
+ case "team":
+ in.Team = "other"
+ f.p.Teams = []string{"blue", "other"}
+ defer func() { f.p.Teams = []string{"blue"} }()
+ want = 403
+ case "scope":
+ f.p.Scopes = []string{"slides:read"}
+ defer func() { f.p.Scopes = []string{"slides:read", "slides:write"} }()
+ want = 403
+ case "uuid":
+ in.ClientID = strings.ReplaceAll(in.ClientID, "-", "")
+ case "title":
+ in.Title = strings.Repeat("界", 200)
+ case "text":
+ in.Slides[0].Body = strings.Repeat("x", 128<<10)
+ in.Slides[0].Heading = "x"
+ want = 413
+ case "input":
+ in.Slides[0].Body = strings.Repeat("x", slideAgentLimit)
+ want = 413
+ }
+ raw, _ := json.Marshal(in)
+ if mode == "unknown" {
+ raw = append(raw[:len(raw)-1], []byte(`,"unrecognized":true}`)...)
+ }
+ if r := f.raw(t, "slides_create_deck", raw); r.Code != want {
+ t.Fatal(mode, r.Code, r.Body.String())
+ }
+ })
+ }
+ // A committed creation always has a small result, even if a later read is too large.
+ in := initialSlideAgentInput()
+ in.Slides[0] = slideAgentInitial{Heading: "Large", Body: strings.Repeat("&", 100000)}
+ for i := 0; i < 3; i++ {
+ in.Slides = append(in.Slides, slideAgentInitial{Heading: "More", Body: "Small initial text"})
+ }
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", in))
+ slideCreated(t, f.call(t, "slides_create_deck", in))
+ var d Deck
+ f.a.app.db.G.Where("sqid=?", sqid).Take(&d)
+ h, view, e := f.a.app.openDeck(t.Context(), d)
+ if e != nil {
+ t.Fatal(e)
+ }
+ h.Close(t.Context())
+ // Grow the aggregate result through bounded ordinary edits. One 1.1MB
+ // Markdown parse hits the unchanged one-second guest budget under -race,
+ // testing the CPU limit instead of the response-size limit asserted below.
+ for _, slide := range view.Slides {
+ ops, _ := json.Marshal([]op{{"op": "set_text", "slide": slide.ID, "id": slide.Blocks[1].ID, "markdown": strings.Repeat("z", 280000)}})
+ if e = f.a.app.editDeck(t.Context(), &d, actorFor(f.u), ops, nil, nil); e != nil {
+ t.Fatal(e)
+ }
+ }
+ h, _, e = f.a.app.openDeck(t.Context(), d)
+ if e != nil {
+ t.Fatal(e)
+ }
+ raw, e := h.JSON(t.Context())
+ h.Close(t.Context())
+ if e != nil || len(raw) <= slideAgentLimit {
+ t.Fatal("oversize fixture is not large enough", len(raw), e)
+ }
+ if _, e := f.a.get(t.Context(), f.u, sqid); e == nil || access.SafeFailure(e).Code != "too_large" {
+ t.Fatal("operation itself did not bound canonical get", e)
+ }
+ r := f.call(t, "slides_get_deck", map[string]any{"team": "blue", "sqid": sqid})
+ if r.Code != 413 {
+ t.Fatal("oversize canonical get", r.Code)
+ }
+
+ // Legacy content can be larger than the new creation contract.
+ if e := f.a.app.db.G.Model(&Deck{}).Where("sqid=?", sqid).Update("title", strings.Repeat("x", slideAgentLimit)).Error; e != nil {
+ t.Fatal(e)
+ }
+ if r := f.call(t, "slides_list_decks", map[string]any{"team": "blue"}); r.Code != 413 {
+ t.Fatal("oversize result", r.Code)
+ }
+}
diff --git a/internal/slides/agent_response_test.go b/internal/slides/agent_response_test.go
new file mode 100644
index 0000000..76d605e
--- /dev/null
+++ b/internal/slides/agent_response_test.go
@@ -0,0 +1,93 @@
+package slides
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+type agentRevokingWriter struct {
+ http.ResponseWriter
+ revoke func()
+}
+
+func (w *agentRevokingWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+func (w *agentRevokingWriter) Write(b []byte) (int, error) {
+ n, e := w.ResponseWriter.Write(b)
+ if w.revoke != nil {
+ f := w.revoke
+ w.revoke = nil
+ f()
+ }
+ return n, e
+}
+func TestAgentDeckResponseRevocation(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ in := initialSlideAgentInput()
+ in.Slides[0].Body = strings.Repeat("z", 80000)
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", in))
+ args := map[string]any{"team": "blue", "sqid": sqid}
+ f.checks.Store(0)
+ f.revokeAt.Store(2)
+ if r := f.call(t, "slides_get_deck", args); r.Code != 401 || strings.Contains(r.Body.String(), "zzzz") {
+ t.Fatal("response leaked", r.Code)
+ }
+ f.revokeAt.Store(0)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ f.a.app.agent.ServeHTTP(&agentRevokingWriter{w, func() { f.revokeAt.Store(1) }}, r)
+ }))
+ defer server.Close()
+ raw, _ := json.Marshal(args)
+ req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/slides_get_deck", bytes.NewReader(raw))
+ req.Header.Set("Authorization", "Bearer test-token")
+ req.Header.Set("Content-Type", "application/json")
+ res, e := server.Client().Do(req)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer res.Body.Close()
+ b, e := io.ReadAll(res.Body)
+ if !errors.Is(e, io.ErrUnexpectedEOF) || res.StatusCode != 200 || len(b) == 0 || len(b) > 64<<10 || json.Valid(b) {
+ t.Fatal("revoked stream completed", res.StatusCode, len(b), e)
+ }
+}
+func TestAgentDeckResponseLocalAuthority(t *testing.T) {
+ for _, mode := range []string{"link", "permission"} {
+ t.Run(mode, func(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ sqid := slideCreated(t, f.call(t, "slides_create_deck", initialSlideAgentInput()))
+ // The second credential verification is the final read-emission boundary.
+ var checks int
+ handler, e := f.a.httpHandler(verifyAgentFunc(func() {
+ checks++
+ if checks == 2 {
+ sql := "DELETE FROM home_identity_links"
+ if mode == "permission" {
+ sql = "UPDATE decks SET owner_id=99,rung='private'"
+ }
+ if e := f.a.app.db.G.Exec(sql).Error; e != nil {
+ t.Fatal(e)
+ }
+ }
+ }, f.p))
+ if e != nil {
+ t.Fatal(e)
+ }
+ f.a.app.agent = handler
+ if r := f.call(t, "slides_get_deck", map[string]any{"team": "blue", "sqid": sqid}); r.Code != 403 && r.Code != 404 {
+ t.Fatal("local authority lost", r.Code)
+ }
+ })
+ }
+}
+
+func verifyAgentFunc(before func(), p access.Principal) access.Verifier {
+ return access.VerifyFunc(func(context.Context, string) (access.Principal, error) { before(); return p, nil })
+}
diff --git a/internal/slides/agent_team_compat_test.go b/internal/slides/agent_team_compat_test.go
new file mode 100644
index 0000000..3589854
--- /dev/null
+++ b/internal/slides/agent_team_compat_test.go
@@ -0,0 +1,162 @@
+package slides
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "strconv"
+ "strings"
+ "testing"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/teammode"
+)
+
+func newTeamSlideAgent(t *testing.T) (*teamFixture, *slideAgentFixture) {
+ t.Helper()
+ f := newTeamFixture(t, "writer@example.com")
+ u := f.localUser("writer@example.com")
+ subject := teamSubject('a')
+ homeLinkedSubject(t, f.a, u, subject)
+ f.dir.Set(subject, "member")
+ f.refreshed()
+ team := f.a.team.Bindings().Team
+ a := &slideAgent{app: f.a, issuer: "https://connect.example.com", identityIssuer: teamTestIssuer, team: team, key: bytes.Repeat([]byte{8}, 32)}
+ af := &slideAgentFixture{a: a, u: u, p: access.Principal{Subject: subject, Client: "test-client", Grant: "grant-one", Teams: []string{team}, Scopes: []string{"slides:read", "slides:write"}}}
+ af.install(t)
+ return f, af
+}
+func teamSlideInput(af *slideAgentFixture) slideAgentCreate {
+ in := initialSlideAgentInput()
+ in.Team = af.a.team
+ return in
+}
+func teamSlideCounts(t *testing.T, f *teamFixture) []int64 {
+ t.Helper()
+ out := []int64{}
+ for _, table := range []string{"decks", "deck_updates", "slides_agent_receipts", "slides_connections"} {
+ var n int64
+ if e := f.d.G.Table(table).Count(&n).Error; e != nil {
+ t.Fatal(e)
+ }
+ out = append(out, n)
+ }
+ return out
+}
+func TestAgentTeamSlidesMembershipAndIndependentShares(t *testing.T) {
+ f, af := newTeamSlideAgent(t)
+ f.a.allowed = allowlist{}
+ mine := slideCreated(t, af.call(t, "slides_create_deck", teamSlideInput(af)))
+ other := f.localUser("colleague@example.com")
+ shared := f.deck(other, "Independent deck", rungPrivate)
+ teamDeck := f.deck(other, "Team-only deck", rungTeam)
+ f.grant(shared, af.u, other)
+ f.dir.Set(af.p.Subject, "")
+ f.refreshed()
+ if w := af.call(t, "slides_create_deck", teamSlideInput(af)); w.Code != 403 {
+ t.Fatal("removed creator", w.Code, w.Body.String())
+ }
+ for _, sqid := range []string{mine, teamDeck.Sqid} {
+ if w := af.call(t, "slides_get_deck", map[string]any{"team": af.a.team, "sqid": sqid}); w.Code != 404 {
+ t.Fatal("team rung survived removal", w.Code, w.Body.String())
+ }
+ }
+ if w := af.call(t, "slides_get_deck", map[string]any{"team": af.a.team, "sqid": shared.Sqid}); w.Code != 200 {
+ t.Fatal("share lost", w.Code, w.Body.String())
+ }
+ if w := af.call(t, "slides_list_decks", map[string]any{"team": af.a.team, "limit": 1}); w.Code != 200 || !strings.Contains(w.Body.String(), "Independent deck") {
+ t.Fatal("list grants", w.Code, w.Body.String())
+ }
+ f.expired()
+ if w := af.call(t, "slides_get_deck", map[string]any{"team": af.a.team, "sqid": shared.Sqid}); w.Code != 200 {
+ t.Fatal("Unknown share", w.Code, w.Body.String())
+ }
+ if w := af.call(t, "slides_get_deck", map[string]any{"team": af.a.team, "sqid": mine}); w.Code != 503 {
+ t.Fatal("Unknown own", w.Code, w.Body.String())
+ }
+ if w := af.call(t, "slides_list_decks", map[string]any{"team": af.a.team}); w.Code != 503 {
+ t.Fatal("partial list", w.Code, w.Body.String())
+ }
+ if w := af.call(t, "slides_create_deck", teamSlideInput(af)); w.Code != 503 {
+ t.Fatal("Unknown create", w.Code, w.Body.String())
+ }
+}
+func TestAgentTeamSlidesWriterExpiryAndCompletedRetry(t *testing.T) {
+ for _, retry := range []bool{false, true} {
+ t.Run(strconv.FormatBool(retry), func(t *testing.T) {
+ f, af := newTeamSlideAgent(t)
+ in := teamSlideInput(af)
+ if retry {
+ slideCreated(t, af.call(t, "slides_create_deck", in))
+ }
+ before, _ := json.Marshal(teamSlideCounts(t, f))
+ u, err := af.a.member(t.Context(), af.p, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ n := 0
+ state := &slideAgentContext{member: u, slides: map[int64]bool{}, verify: func(context.Context) error {
+ n++
+ if n == 2 {
+ f.expired()
+ }
+ return nil
+ }}
+ ctx := teammode.WithAccess(context.WithValue(t.Context(), slideAgentKey{}, state), u.team.Access)
+ if _, err = af.a.create(ctx, af.p, u, in); err == nil {
+ t.Fatal("expired writer accepted")
+ }
+ after, _ := json.Marshal(teamSlideCounts(t, f))
+ if !bytes.Equal(before, after) {
+ t.Fatal("expired write committed", string(before), string(after))
+ }
+ })
+ }
+}
+func TestAgentTeamSlidesHomeOnlyAndBindingRefused(t *testing.T) {
+ f, af := newTeamSlideAgent(t)
+ subject := teamSubject('b')
+ f.dir.Set(subject, "member")
+ f.refreshed()
+ f.freshHomeSignIn(subject)
+ var before, after int64
+ f.d.G.Model(&User{}).Count(&before)
+ af.p.Subject = subject
+ if w := af.call(t, "slides_list_decks", map[string]any{"team": af.a.team}); w.Code != 403 {
+ t.Fatal("HomeOnly accepted", w.Code, w.Body.String())
+ }
+ f.d.G.Model(&User{}).Count(&after)
+ if before != after {
+ t.Fatal("allocated identity")
+ }
+ fresh := newTeamFixture(t)
+ bad := &slideAgent{app: fresh.a, issuer: "https://connect.example.com", identityIssuer: teamTestIssuer, team: "foreign", key: bytes.Repeat([]byte{8}, 32)}
+ if err := fresh.a.mountAgent(bad, access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return af.p, nil })); err == nil {
+ t.Fatal("foreign binding accepted")
+ }
+ var n int64
+ if err := fresh.d.G.Raw("SELECT count(*) FROM sqlite_master WHERE name LIKE 'slides_agent_%'").Scan(&n).Error; err != nil || n != 0 {
+ t.Fatal("foreign binding installed agent schema", n, err)
+ }
+}
+func TestAgentTeamSlidesLateUnknownListWithShares(t *testing.T) {
+ f, af := newTeamSlideAgent(t)
+ other := f.localUser("other@example.com")
+ shared := f.deck(other, "Independent deck", rungPrivate)
+ f.grant(shared, af.u, other)
+ n := 0
+ h, err := af.a.httpHandler(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ n++
+ if n == 2 {
+ f.expired()
+ }
+ return af.p, nil
+ }))
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.a.agent = h
+ if w := af.call(t, "slides_list_decks", map[string]any{"team": af.a.team}); w.Code != 503 || strings.Contains(w.Body.String(), "Independent deck") {
+ t.Fatal("late partial list escaped", w.Code, w.Body.String())
+ }
+}
diff --git a/internal/slides/agent_team_lease_test.go b/internal/slides/agent_team_lease_test.go
new file mode 100644
index 0000000..666f27c
--- /dev/null
+++ b/internal/slides/agent_team_lease_test.go
@@ -0,0 +1,80 @@
+package slides
+
+import (
+ "amadan.net/oficina/home/roster"
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "testing"
+ "time"
+)
+
+type agentLeaseObserver struct {
+ http.ResponseWriter
+ budgets chan time.Duration
+}
+
+func (w *agentLeaseObserver) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+func (w *agentLeaseObserver) SetWriteDeadline(d time.Time) error {
+ if !d.IsZero() {
+ w.budgets <- time.Until(d)
+ }
+ return http.NewResponseController(w.ResponseWriter).SetWriteDeadline(d)
+}
+
+// Removing only the lease clamp must fail this real-transport test, even while
+// the membership checks themselves continue to pass.
+func TestAgentTeamLeaseBoundsSocketDeadline(t *testing.T) {
+ for _, short := range []bool{false, true} {
+ t.Run(strconv.FormatBool(short), func(t *testing.T) {
+ f, af := newTeamSlideAgent(t)
+ u, err := af.a.member(t.Context(), af.p, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.dir.SetDown(true)
+ f.clock.Step(u.team.Remaining() - 250*time.Millisecond)
+ if u.team.state() != roster.Member {
+ t.Fatal("fixture lease expired")
+ }
+ budgets := make(chan time.Duration, 16)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if short {
+ ctx, cancel := context.WithTimeout(r.Context(), 50*time.Millisecond)
+ defer cancel()
+ r = r.WithContext(ctx)
+ }
+ f.a.agent.ServeHTTP(&agentLeaseObserver{w, budgets}, r)
+ }))
+ defer server.Close()
+ raw, _ := json.Marshal(map[string]any{"team": af.a.team})
+ req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/slides_list_decks", bytes.NewReader(raw))
+ req.Header.Set("Authorization", "Bearer test-token")
+ req.Header.Set("Content-Type", "application/json")
+ res, err := server.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ _, err = io.ReadAll(res.Body)
+ if err != nil || res.StatusCode != 200 {
+ t.Fatal(res.StatusCode, err)
+ }
+ close(budgets)
+ n := 0
+ for d := range budgets {
+ n++
+ if d <= 0 || d > 300*time.Millisecond || short && d > 60*time.Millisecond {
+ t.Fatalf("write deadline outlives lease: %s", d)
+ }
+ }
+ if n == 0 {
+ t.Fatal("no transport deadline")
+ }
+ })
+ }
+}
diff --git a/internal/slides/agent_wait_test.go b/internal/slides/agent_wait_test.go
new file mode 100644
index 0000000..ce47534
--- /dev/null
+++ b/internal/slides/agent_wait_test.go
@@ -0,0 +1,88 @@
+package slides
+
+import (
+ "context"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/rastrillo/rastrillo/db"
+ "gorm.io/gorm"
+)
+
+func TestAgentDeckRevocationWhileWaitingForWriter(t *testing.T) {
+ f := newSlideAgentFixture(t)
+ var revoked atomic.Bool
+ if e := f.a.app.mountAgent(f.a, access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ if revoked.Load() {
+ return access.Principal{}, access.Fail("unauthenticated", "Revoked.")
+ }
+ return f.p, nil
+ })); e != nil {
+ t.Fatal(e)
+ }
+ // If authorization is moved after body work, this fault wins and produces503.
+ if _, e := f.a.app.db.Writer().Exec("CREATE TRIGGER body_must_not_run BEFORE INSERT ON decks BEGIN SELECT RAISE(ABORT,'body attempted'); END"); e != nil {
+ t.Fatal(e)
+ }
+ var path string
+ if e := f.a.app.db.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path); e != nil {
+ t.Fatal(e)
+ }
+ other, e := db.Open(path, f.a.app.logger)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer other.Close()
+ held, e := other.Writer().BeginTx(t.Context(), nil)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer held.Rollback()
+ if _, e = held.Exec("UPDATE slides_agent_state SET keycheck=keycheck"); e != nil {
+ t.Fatal(e)
+ }
+ // The separate SQLite connection holds the writer; WAL identity reads finish.
+ // Observe entry into the real reservation statement after BOTH Home lookups.
+ attempted := make(chan struct{})
+ var once atomic.Bool
+ if e = f.a.app.db.G.Callback().Raw().Before("gorm:raw").Register("test:agent_writer", func(tx *gorm.DB) {
+ if strings.HasPrefix(tx.Statement.SQL.String(), "INSERT INTO slides_agent_state") && once.CompareAndSwap(false, true) {
+ close(attempted)
+ }
+ }); e != nil {
+ t.Fatal(e)
+ }
+ defer f.a.app.db.G.Callback().Raw().Remove("test:agent_writer")
+ result := make(chan int, 1)
+ go func() { result <- f.call(t, "slides_create_deck", initialSlideAgentInput()).Code }()
+ select {
+ case <-attempted:
+ case <-time.After(3 * time.Second):
+ t.Fatal("request never reached reserved-writer statement")
+ }
+ select {
+ case code := <-result:
+ t.Fatal("writer did not block", code)
+ case <-time.After(20 * time.Millisecond):
+ }
+ revoked.Store(true)
+ if e = held.Commit(); e != nil {
+ t.Fatal(e)
+ }
+ select {
+ case code := <-result:
+ if code != 401 {
+ t.Fatal("body attempted before fresh delegation check", code)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("writer did not resume")
+ }
+ var n int
+ f.a.app.db.G.Raw("SELECT COUNT(*) FROM decks").Scan(&n)
+ if n != 0 {
+ t.Fatal(n)
+ }
+}
diff --git a/internal/slides/agents.go b/internal/slides/agents.go
index c3d3ff3..9ba39a3 100644
--- a/internal/slides/agents.go
+++ b/internal/slides/agents.go
@@ -304,7 +304,7 @@ func (a *app) actorLabels(ctx context.Context, actors []string) map[string]strin
}
}
- out := map[string]string{}
+ out := a.connectionLabels(ctx, actors)
if len(personIDs) > 0 {
var people []User
if err := a.db.G.WithContext(ctx).Where("id IN ?", personIDs).Find(&people).Error; err != nil {
diff --git a/internal/slides/app.go b/internal/slides/app.go
index 8f28cad..f082bc6 100644
--- a/internal/slides/app.go
+++ b/internal/slides/app.go
@@ -271,6 +271,10 @@ func New(d *db.DB, cfg Config) (*http.ServeMux, *app, error) {
// surface will authenticate, which is what CSRF is an attack on.
// api.go's package comment says the same thing at length, and
// docs/api.md says it to the person reading the API.
+ if a.agent != nil {
+ mux.Handle("/api/v1/operations", a.agent)
+ mux.Handle("/api/v1/operations/", a.agent)
+ }
mux.Handle(apiPrefix+"/", a.apiRouter())
mux.Handle("/", r)
return mux, a, nil
@@ -305,6 +309,9 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) {
if err != nil {
return nil, nil, err
}
+ if err := validateAgentConfig(cfg.AgentIssuer, cfg.AgentTeam, cfg.Origin, cfg.Home); err != nil {
+ return nil, nil, err
+ }
boot := BootSchema
if homeConfig != nil {
boot = migrate.Merge(BootSchema, homeSchema)
@@ -318,6 +325,9 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) {
if err != nil {
return nil, nil, err
}
+ if team != nil && cfg.AgentIssuer != "" && cfg.AgentTeam != team.Bindings().Team {
+ return nil, nil, errAgentConfig
+ }
boot, err = teamBootSchema(context.Background(), d.Writer(), team, boot)
if err != nil {
return nil, nil, err
@@ -404,6 +414,11 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) {
return nil, nil, err
}
+ if err := a.configureAgentAccess(); err != nil {
+ a.Close()
+ return nil, nil, err
+ }
+
// The export's status page, its polled fragment and its SSE stream
// (exports.go). rastrillo/jobs owns the lifecycle and the
// owner-only lookup; the two renderers are this app's, so the page
diff --git a/internal/slides/config.go b/internal/slides/config.go
index cdaed02..cb9407b 100644
--- a/internal/slides/config.go
+++ b/internal/slides/config.go
@@ -44,7 +44,9 @@ const DefaultOrigin = "http://localhost:8091"
// Config is what New needs to build the app. cmd/slides/main.go fills
// it from the environment; the test harness fills it directly.
type Config struct {
- Home *connect.Credentials
+ AgentIssuer string
+ AgentTeam string
+ Home *connect.Credentials
// Team is roster team mode's configuration (teammode.ConfigFromEnv
// with prefix SLIDES: the five SLIDES_TEAM_* variables, all or none),
diff --git a/internal/slides/core/testdata/slides_core.wasm b/internal/slides/core/testdata/slides_core.wasm
index 111db4d..8488e81 100755
Binary files a/internal/slides/core/testdata/slides_core.wasm and b/internal/slides/core/testdata/slides_core.wasm differ
diff --git a/internal/slides/credits/assets.json b/internal/slides/credits/assets.json
index 19d1098..7b299f4 100644
--- a/internal/slides/credits/assets.json
+++ b/internal/slides/credits/assets.json
@@ -4,9 +4,20 @@
"core/Cargo.toml": "b0df969e01d7ba4711abe0f71dfede1174b640fe06440cd26738ca903e67d391",
"core/pdf/Cargo.lock": "9c9d1eb3c9d6cc0ba477ec19db6f240c3e22285354b85e9194fb6c36c7a88369",
"core/pdf/Cargo.toml": "f6d65a503805403ea73112c78408caf0505f06a3b6df4ba2d04374c4dea8c3bb",
+ "core/vendor/fastrand-2.5.0/CHANGELOG.md": "d0ecc653658392738be0daccc920a5c3ffe6996c328a9aa8f26ce897a5db7293",
+ "core/vendor/fastrand-2.5.0/Cargo.toml": "bff7c012eceb24c4e87e288fffc9216933d2fb5c4c14d0f992363800ccc9501c",
+ "core/vendor/fastrand-2.5.0/LICENSE-APACHE": "a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2",
+ "core/vendor/fastrand-2.5.0/LICENSE-MIT": "23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3",
+ "core/vendor/fastrand-2.5.0/README.md": "5f3d251d8bc1c793284f4cc720453b280c1c04f968a70b7b36b78d6c1e5c9973",
+ "core/vendor/fastrand-2.5.0/benches/bench.rs": "9613f3e9f893ef0c227c158be2c91d766e60b80ce11faf226ac490057ee38546",
+ "core/vendor/fastrand-2.5.0/src/global_rng.rs": "f14c504601f9273bf6fa49621cc9dad2329092fd87d35fe8963e55d99f597de2",
+ "core/vendor/fastrand-2.5.0/src/lib.rs": "858da6a3831589762ec2214df3f8e8b09a1262708fb08072f1cf13c1260d6ce1",
+ "core/vendor/fastrand-2.5.0/tests/char.rs": "a530b41837f5bf43701d983ef0267d9b44779d455f24cbf30b881cd348de9ee1",
+ "core/vendor/fastrand-2.5.0/tests/smoke.rs": "0f40e5fd5f382de66cf8ddb7f7e0b3e968d979de75d3658a185d22b11e8e5fc2",
"fixtures/package-lock.json": "5c3ece3771aaa28f34777fdd2532c68b87621fc6c6f449153ca875326f206718",
"fixtures/package.json": "6011e9f29799410f7e9ea8057b88376a7d80f7d2d122e5e113453845c9590f1a",
- "internal/slides/core/testdata/slides_core.wasm": "90efd37fc0a94fdbdfd93c7c5327d9329f3fcdd28bb26d3801e41bed9eb1bd37",
+ "internal/slides/core/testdata/slides_core.wasm": "e29842bf8249f3c981590288d48964b9207941da0524bdd731894da598656470",
+ "internal/slides/credits/upstream/fastrand-vendor.json": "77953165e6238d83c12eb4fb419d100cf11cc8e54ae57291a386dc7667e58365",
"internal/slides/credits/upstream/krilla-LICENSE_APACHE": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30",
"internal/slides/credits/upstream/krilla-LICENSE_MIT": "9d1eb142840c7acfd5511b4dd298cece3f0053f5809228906445cd8a3365592f",
"internal/slides/credits/upstream/krilla-NOTICE.md": "7aa87a70e18c9c160b5a14e24b46a8e407858b21fed635920c701657b4bd7976",
@@ -25,7 +36,7 @@
"internal/slides/fonts/files/LiberationSerif-BoldItalic.ttf": "4b2635d2ec4d992373dcae577c742a98ecfd841ffc1b8a103b5f10db163dbc7a",
"internal/slides/fonts/files/LiberationSerif-Italic.ttf": "de18fe26337e03241952dca46398d5b66f3c5738d080bfd284f66e67b926f597",
"internal/slides/fonts/files/LiberationSerif-Regular.ttf": "9caef765d2e891c10dd73658894f01e660fe0c1c83e0bda7d6edf561d8f623d4",
- "internal/slides/pdfcore/testdata/slides_pdf.wasm": "38c9c096a704eb93bf68f63ec1e2fdd3fa603474fe3c0ecfc1827d7d9fb91a3d",
+ "internal/slides/pdfcore/testdata/slides_pdf.wasm": "78f7dcd8e7fabeb1eef2b857ae432e681b176661c8b58d6b82b38621a1cf356b",
"internal/slides/static/busy.js": "b5be5c1c7239b066ec5d13e0c9a21a06c7c7a448542dc7d664a989f4589bae02",
"internal/slides/static/calendar.js": "dfa06d84768b8e99d1e50d9dca81caadacf2412db74ac4e432d78c29680bbdd2",
"internal/slides/static/datetime.js": "5aea0521b14f9164c14b75fdcc1ff9a5429d2f51d8d78161a4eebba0e41a1ea1",
diff --git a/internal/slides/credits/notices.json b/internal/slides/credits/notices.json
index ed4da1d..0721ef5 100644
--- a/internal/slides/credits/notices.json
+++ b/internal/slides/credits/notices.json
@@ -626,6 +626,17 @@
}
]
},
+ {
+ "Name": "github.com/google/jsonschema-go",
+ "Version": "v0.4.3",
+ "SourceURL": "https://pkg.go.dev/github.com/google/jsonschema-go@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"
+ }
+ ]
+ },
{
"Name": "github.com/google/uuid",
"Version": "v1.6.0",
@@ -665,6 +676,17 @@
"SourceURL": "https://pkg.go.dev/github.com/keymaildev/signin@v0.1.1",
"Notices": []
},
+ {
+ "Name": "github.com/modelcontextprotocol/go-sdk",
+ "Version": "v1.7.0",
+ "SourceURL": "https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk@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"
+ }
+ ]
+ },
{
"Name": "github.com/remyoudompheng/bigfft",
"Version": "v0.0.0-20230129092748-24d4a6f8daec",
@@ -676,6 +698,39 @@
}
]
},
+ {
+ "Name": "github.com/santhosh-tekuri/jsonschema/v6",
+ "Version": "v6.0.3",
+ "SourceURL": "https://pkg.go.dev/github.com/santhosh-tekuri/jsonschema/v6@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."
+ }
+ ]
+ },
+ {
+ "Name": "github.com/segmentio/asm",
+ "Version": "v1.1.3",
+ "SourceURL": "https://pkg.go.dev/github.com/segmentio/asm@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"
+ }
+ ]
+ },
+ {
+ "Name": "github.com/segmentio/encoding",
+ "Version": "v0.5.4",
+ "SourceURL": "https://pkg.go.dev/github.com/segmentio/encoding@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"
+ }
+ ]
+ },
{
"Name": "github.com/skip2/go-qrcode",
"Version": "v0.0.0-20200617195104-da1b6568686e",
@@ -702,6 +757,17 @@
}
]
},
+ {
+ "Name": "github.com/yosida95/uritemplate/v3",
+ "Version": "v3.0.2",
+ "SourceURL": "https://pkg.go.dev/github.com/yosida95/uritemplate/v3@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"
+ }
+ ]
+ },
{
"Name": "golang.org/x/image",
"Version": "v0.44.0",
@@ -713,6 +779,28 @@
}
]
},
+ {
+ "Name": "golang.org/x/oauth2",
+ "Version": "v0.35.0",
+ "SourceURL": "https://pkg.go.dev/golang.org/x/oauth2@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"
+ }
+ ]
+ },
+ {
+ "Name": "golang.org/x/sync",
+ "Version": "v0.22.0",
+ "SourceURL": "https://pkg.go.dev/golang.org/x/sync@v0.22.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"
+ }
+ ]
+ },
{
"Name": "golang.org/x/sys",
"Version": "v0.46.0",
@@ -735,6 +823,17 @@
}
]
},
+ {
+ "Name": "golang.org/x/time",
+ "Version": "v0.15.0",
+ "SourceURL": "https://pkg.go.dev/golang.org/x/time@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"
+ }
+ ]
+ },
{
"Name": "gorm.io/gorm",
"Version": "v1.31.2",
diff --git a/internal/slides/credits/upstream/fastrand-vendor.json b/internal/slides/credits/upstream/fastrand-vendor.json
new file mode 100644
index 0000000..257059d
--- /dev/null
+++ b/internal/slides/credits/upstream/fastrand-vendor.json
@@ -0,0 +1,19 @@
+{
+ "name": "fastrand",
+ "version": "2.5.0",
+ "directory": "core/vendor/fastrand-2.5.0",
+ "archive_sha256": "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223",
+ "patch": "Parsed Cargo.toml removes only normal wasm-target getrandom features=[wasm_js]; dev dependency unchanged. All other vendored files match the upstream archive.",
+ "files": {
+ "CHANGELOG.md": "d0ecc653658392738be0daccc920a5c3ffe6996c328a9aa8f26ce897a5db7293",
+ "Cargo.toml": "bff7c012eceb24c4e87e288fffc9216933d2fb5c4c14d0f992363800ccc9501c",
+ "LICENSE-APACHE": "a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2",
+ "LICENSE-MIT": "23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3",
+ "README.md": "5f3d251d8bc1c793284f4cc720453b280c1c04f968a70b7b36b78d6c1e5c9973",
+ "benches/bench.rs": "9613f3e9f893ef0c227c158be2c91d766e60b80ce11faf226ac490057ee38546",
+ "src/global_rng.rs": "f14c504601f9273bf6fa49621cc9dad2329092fd87d35fe8963e55d99f597de2",
+ "src/lib.rs": "858da6a3831589762ec2214df3f8e8b09a1262708fb08072f1cf13c1260d6ce1",
+ "tests/char.rs": "a530b41837f5bf43701d983ef0267d9b44779d455f24cbf30b881cd348de9ee1",
+ "tests/smoke.rs": "0f40e5fd5f382de66cf8ddb7f7e0b3e968d979de75d3658a185d22b11e8e5fc2"
+ }
+}
diff --git a/internal/slides/decks.go b/internal/slides/decks.go
index 9b1d381..68c6cec 100644
--- a/internal/slides/decks.go
+++ b/internal/slides/decks.go
@@ -162,7 +162,11 @@ func opsJSON(ops []op) ([]byte, error) {
// deck is on the team rung" — the whole seam defeated by operator
// precedence.
func (a *app) visibleDecks(ctx context.Context, viewer User) *gorm.DB {
- g := a.db.G.WithContext(ctx).Model(&Deck{})
+ return a.visibleDecksOn(a.db.G.WithContext(ctx), viewer)
+}
+
+func (a *app) visibleDecksOn(db *gorm.DB, viewer User) *gorm.DB {
+ g := db.Model(&Deck{})
if viewer.ID <= 0 {
// Never reached past RequireSession; refusing outright beats
// trusting every caller to have checked, because the value
@@ -196,12 +200,17 @@ func (a *app) visibleDecks(ctx context.Context, viewer User) *gorm.DB {
// deck with none, or one whose snapshot row could not be read, opens
// from the plain log and is exactly the same deck, only slower.
func (a *app) openDeck(ctx context.Context, d Deck) (*core.Handle, *deck.Deck, error) {
+ return a.openDeckOn(ctx, a.db.G, d)
+}
+
+// openDeckOn reads every snapshot and log page on the caller's connection.
+func (a *app) openDeckOn(ctx context.Context, db *gorm.DB, d Deck) (*core.Handle, *deck.Deck, error) {
h, err := a.core.NewDoc(ctx, d.Sqid, serverClientID)
if err != nil {
return nil, nil, fmt.Errorf("slides: open deck %s: %w", d.Sqid, err)
}
- snap, updates, err := a.replayPlan(ctx, d)
+ snap, updates, err := a.replayPlanOn(ctx, db, d)
if err != nil {
h.Close(ctx)
return nil, nil, err
@@ -221,7 +230,7 @@ func (a *app) openDeck(ctx context.Context, d Deck) (*core.Handle, *deck.Deck, e
}
since = 0
retained = 0
- updates, err = a.replayLog(ctx, d, 0)
+ updates, err = replayLogOn(ctx, db, d, 0)
if err != nil {
h.Close(ctx)
return nil, nil, err
@@ -258,7 +267,7 @@ func (a *app) openDeck(ctx context.Context, d Deck) (*core.Handle, *deck.Deck, e
since = u.Seq
retained++
}
- updates, err = a.replayLog(ctx, d, since)
+ updates, err = replayLogOn(ctx, db, d, since)
if err != nil {
h.Close(ctx)
return nil, nil, err
@@ -331,46 +340,7 @@ var errDeckBusy = errors.New("slides: the deck moved while this update was being
// then the transaction is exactly what it always was.
func (a *app) applyOps(ctx context.Context, h *core.Handle, d *Deck, actor string, ops []byte, rowUpdates map[string]any, g writeGuard) (*deck.Deck, error) {
err := a.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- return g.run(func() error {
- update, err := h.Ops(ctx, ops)
- if err != nil {
- return fmt.Errorf("slides: apply ops to deck %s: %w", d.Sqid, err)
- }
-
- next := d.Seq + 1
- if err := tx.Create(&DeckUpdate{
- DeckID: d.ID,
- Seq: next,
- Actor: actor,
- Bytes: update,
- CreatedAt: time.Now().UTC(),
- }).Error; err != nil {
- if errors.Is(err, gorm.ErrDuplicatedKey) {
- // Somebody else's update is already sitting at this
- // seq: the lost race, reported as the lost race.
- return errDeckBusy
- }
- return fmt.Errorf("slides: record deck %s update %d: %w", d.Sqid, next, err)
- }
-
- // Named columns off a map, never a bound struct (SKILL.md §4):
- // "seq" is always present so the WHERE ... AND seq = ? clause
- // above stays the sole optimistic lock, whether or not this
- // call is also renaming the deck.
- fields := map[string]any{"seq": next}
- for k, v := range rowUpdates {
- fields[k] = v
- }
- res := tx.Model(&Deck{}).Where("id = ? AND seq = ?", d.ID, d.Seq).
- Updates(fields)
- if res.Error != nil {
- return fmt.Errorf("slides: bump deck %s seq: %w", d.Sqid, res.Error)
- }
- if res.RowsAffected != 1 {
- return errDeckBusy
- }
- return nil
- })
+ return g.run(func() error { return applyOpsOn(ctx, tx, h, d, actor, ops, rowUpdates) })
})
if err != nil {
return nil, err
@@ -402,6 +372,50 @@ func (a *app) applyOps(ctx context.Context, h *core.Handle, d *Deck, actor strin
return view, nil
}
+// applyOpsOn persists one canonical batch in its caller's transaction.
+// The caller owns the handle and discards it after rollback. No publication
+// or snapshots may occur here: the transaction has not committed.
+func applyOpsOn(ctx context.Context, tx *gorm.DB, h *core.Handle, d *Deck, actor string, ops []byte, rowUpdates map[string]any) error {
+ update, err := h.Ops(ctx, ops)
+ if err != nil {
+ return fmt.Errorf("slides: apply ops to deck %s: %w", d.Sqid, err)
+ }
+
+ next := d.Seq + 1
+ if err := tx.Create(&DeckUpdate{
+ DeckID: d.ID,
+ Seq: next,
+ Actor: actor,
+ Bytes: update,
+ CreatedAt: time.Now().UTC(),
+ }).Error; err != nil {
+ if errors.Is(err, gorm.ErrDuplicatedKey) {
+ // Somebody else's update is already sitting at this
+ // seq: the lost race, reported as the lost race.
+ return errDeckBusy
+ }
+ return fmt.Errorf("slides: record deck %s update %d: %w", d.Sqid, next, err)
+ }
+
+ // Named columns off a map, never a bound struct (SKILL.md §4):
+ // "seq" is always present so the WHERE ... AND seq = ? clause
+ // above stays the sole optimistic lock, whether or not this
+ // call is also renaming the deck.
+ fields := map[string]any{"seq": next}
+ for k, v := range rowUpdates {
+ fields[k] = v
+ }
+ res := tx.Model(&Deck{}).Where("id = ? AND seq = ?", d.ID, d.Seq).
+ Updates(fields)
+ if res.Error != nil {
+ return fmt.Errorf("slides: bump deck %s seq: %w", d.Sqid, res.Error)
+ }
+ if res.RowsAffected != 1 {
+ return errDeckBusy
+ }
+ return nil
+}
+
// editDeck is applyOps with the handle's whole life around it: open the
// deck, apply, close. One retry on errDeckBusy, from a freshly opened
// document — the batch applied nothing, so replaying it against the
@@ -434,10 +448,17 @@ func (a *app) editDeck(ctx context.Context, d *Deck, actor string, ops []byte, r
// createDeckRow inserts the row, retrying on a sqid collision. The
// document itself is empty at this point — the caller's first op batch
// is what puts anything in it.
-//
-// g is the team-mode guard (memberGuard: making a deck rests on standing
-// alone); nil outside team mode.
func (a *app) createDeckRow(ctx context.Context, owner User, title, theme string, g writeGuard) (Deck, error) {
+ var d Deck
+ err := a.guarded(ctx, g, func(db *gorm.DB) error {
+ var err error
+ d, err = createDeckRowOn(ctx, db, owner, title, theme)
+ return err
+ })
+ return d, err
+}
+
+func createDeckRowOn(ctx context.Context, db *gorm.DB, owner User, title, theme string) (Deck, error) {
now := time.Now().UTC()
var lastErr error
for attempt := 0; attempt < maxSqidAttempts; attempt++ {
@@ -454,7 +475,7 @@ func (a *app) createDeckRow(ctx context.Context, owner User, title, theme string
CreatedAt: now,
UpdatedAt: now,
}
- err = a.guarded(ctx, g, func(db *gorm.DB) error { return db.Create(&d).Error })
+ err = db.WithContext(ctx).Create(&d).Error
if err == nil {
return d, nil
}
diff --git a/internal/slides/handlers.go b/internal/slides/handlers.go
index e2f432d..a90f951 100644
--- a/internal/slides/handlers.go
+++ b/internal/slides/handlers.go
@@ -28,6 +28,8 @@ import (
// The handlers themselves live beside what they serve: sign-in in
// auth.go, the deck screens in decks.go.
type app struct {
+ agent http.Handler
+ agentAccess *slideAgent
// draining is closed by Drain, as the process stops (drain.go).
draining drain
diff --git a/internal/slides/pdfcore/testdata/slides_pdf.wasm b/internal/slides/pdfcore/testdata/slides_pdf.wasm
index f46e7e9..49b1bcb 100755
Binary files a/internal/slides/pdfcore/testdata/slides_pdf.wasm and b/internal/slides/pdfcore/testdata/slides_pdf.wasm differ
diff --git a/internal/slides/snapshot.go b/internal/slides/snapshot.go
index 04cd3df..1b71165 100644
--- a/internal/slides/snapshot.go
+++ b/internal/slides/snapshot.go
@@ -44,8 +44,11 @@ const replayCheckpointCadence = core.MaxRetainedUpdates / 2
// the tie resolves to the last row written rather than being treated as
// an error worth reporting.
func (a *app) latestSnapshot(ctx context.Context, deckID int64) (*DeckSnapshot, error) {
+ return latestSnapshotOn(ctx, a.db.G, deckID)
+}
+func latestSnapshotOn(ctx context.Context, db *gorm.DB, deckID int64) (*DeckSnapshot, error) {
var row DeckSnapshot
- err := a.db.G.WithContext(ctx).
+ err := db.WithContext(ctx).
Where("deck_id = ?", deckID).
Order("seq DESC, id DESC").
Take(&row).Error
@@ -71,7 +74,10 @@ func (a *app) latestSnapshot(ctx context.Context, deckID int64) (*DeckSnapshot,
// as "no snapshot" plus a log line, and the deck opens slowly rather
// than not at all.
func (a *app) replayPlan(ctx context.Context, d Deck) (*DeckSnapshot, []DeckUpdate, error) {
- snap, err := a.latestSnapshot(ctx, d.ID)
+ return a.replayPlanOn(ctx, a.db.G, d)
+}
+func (a *app) replayPlanOn(ctx context.Context, db *gorm.DB, d Deck) (*DeckSnapshot, []DeckUpdate, error) {
+ snap, err := latestSnapshotOn(ctx, db, d.ID)
if err != nil {
a.logger.Error("slides: read a deck's newest snapshot, replaying the plain log instead",
"deck", d.Sqid, "err", err)
@@ -85,13 +91,16 @@ func (a *app) replayPlan(ctx context.Context, d Deck) (*DeckSnapshot, []DeckUpda
if snap != nil {
since = snap.Seq
}
- updates, err := a.replayLog(ctx, d, since)
+ updates, err := replayLogOn(ctx, db, d, since)
return snap, updates, err
}
func (a *app) replayLog(ctx context.Context, d Deck, since int64) ([]DeckUpdate, error) {
+ return replayLogOn(ctx, a.db.G, d, since)
+}
+func replayLogOn(ctx context.Context, db *gorm.DB, d Deck, since int64) ([]DeckUpdate, error) {
var updates []DeckUpdate
- if err := a.db.G.WithContext(ctx).
+ if err := db.WithContext(ctx).
Where("deck_id = ? AND seq > ? AND seq <= ?", d.ID, since, d.Seq).
Order("seq").Limit(replayBatchSize).Find(&updates).Error; err != nil {
return nil, fmt.Errorf("slides: read deck %s log: %w", d.Sqid, err)
diff --git a/internal/slides/team_guard_test.go b/internal/slides/team_guard_test.go
index 834bdd2..7912d1f 100644
--- a/internal/slides/team_guard_test.go
+++ b/internal/slides/team_guard_test.go
@@ -132,6 +132,7 @@ func (f *teamFixture) snapshot(d Deck) teamSnapshot {
// survived (Fable's #53 required test 2, for Slides: the database is
// read back, not just the status).
func TestTeamEveryWriteRouteRefusesALapseBeforeCommit(t *testing.T) {
+ t.Run("delegated deck edit", testAgentDeckEditGuardLapse)
f := newTeamFixture(t)
store, err := blobs.Dir(t.TempDir())
if err != nil {
diff --git a/scripts/build-pdf-wasm.sh b/scripts/build-pdf-wasm.sh
index 95e2ed0..2ed0659 100755
--- a/scripts/build-pdf-wasm.sh
+++ b/scripts/build-pdf-wasm.sh
@@ -1,27 +1,62 @@
#!/usr/bin/env bash
-# Build the PDF crate (core/pdf) for wazero, the same way build-wasm.sh
-# builds the CRDT core: plain wasm32 with a C ABI, no wasm-bindgen, no
-# wasm-pack, no host imports.
+# Build the core crate for wazero. No wasm-bindgen, no wasm-pack: the Go host
+# provides no JS glue, so the module must be plain wasm32 with a C ABI.
set -euo pipefail
cd "$(dirname "$0")/.."
-cargo clippy --manifest-path core/pdf/Cargo.toml --all-targets -- -D warnings
-# --lib only: the module shipped to wazero is the library crate.
-#
-# --remap-path-prefix (x2): see build-wasm.sh. rustc bakes the absolute
-# path of every panic site into the binary; remapping the registry and
-# this checkout to fixed placeholders makes the artefact reproducible
-# across machines and $HOMEs, which the gate's byte comparison against
-# the committed copy depends on.
-#
-# The root .cargo/config.toml's rustflags for this target (the getrandom
-# custom-backend cfg) are replaced, not extended, by an env RUSTFLAGS, so
-# they are repeated here. This crate has no getrandom in its graph (see
-# core/pdf/Cargo.toml) and the cfg is inert for it, but keeping the flags
-# identical to build-wasm.sh means the two modules are built under one set
-# of rules rather than two that could drift.
+# Lint the PDF renderer before building its standalone C ABI module.
+if [[ "${1:-}" != "--build-only" && "${1:-}" != "--canonical-build" ]]; then
+ cargo clippy --manifest-path core/pdf/Cargo.toml --all-targets -- -D warnings
+fi
+# Rust/Cargo crate identities affect code ordering even after path remapping.
+# Build on Linux amd64 at fixed source/toolchain paths on every host.
+if [[ "${1:-}" == "--canonical-build" ]]; then
+ [[ "$(uname -s)/$(uname -m)" == "Linux/x86_64" && "$(pwd)" == /work \
+ && "$CARGO_HOME" == /usr/local/cargo && "$RUSTUP_HOME" == /usr/local/rustup ]] \
+ || { echo "build-pdf-wasm: invalid canonical build environment" >&2; exit 1; }
+ export CARGO_TARGET_DIR=/work/core/pdf/target RUSTUP_TOOLCHAIN=1.98.0
+else
+ out="core/pdf/target/wasm32-unknown-unknown/release/slides_pdf.wasm"
+ mkdir -p "$(dirname "$out")"
+ temporary=$(mktemp "${out}.XXXXXX")
+ trap 'rm -f "$temporary"' EXIT
+ if [[ "$(uname -s)/$(uname -m)" == "Linux/x86_64" ]] && command -v bwrap >/dev/null; then
+ cargo_home=$(cd "${CARGO_HOME:-$HOME/.cargo}" && pwd)
+ rustup_home=$(cd "${RUSTUP_HOME:-$HOME/.rustup}" && pwd)
+ mkdir -p core/pdf/target/canonical-linux-amd64
+ bwrap --tmpfs / \
+ --ro-bind /usr /usr --tmpfs /usr/local \
+ --ro-bind /bin /bin --ro-bind /lib /lib --ro-bind /lib64 /lib64 \
+ --ro-bind /etc /etc --bind /tmp /tmp --proc /proc --dev /dev \
+ --ro-bind "$(pwd)" /work \
+ --bind "$(pwd)/core/pdf/target/canonical-linux-amd64" /work/core/pdf/target \
+ --bind "$cargo_home" /usr/local/cargo --ro-bind "$rustup_home" /usr/local/rustup \
+ --chdir /work --setenv CARGO_HOME /usr/local/cargo --setenv RUSTUP_HOME /usr/local/rustup \
+ --setenv PATH /usr/local/cargo/bin:/usr/local/bin:/usr/bin:/bin \
+ bash -ec './scripts/build-pdf-wasm.sh --canonical-build >&2; cat core/pdf/target/wasm32-unknown-unknown/release/slides_pdf.wasm' > "$temporary"
+ else
+ command -v docker >/dev/null || { echo "build-pdf-wasm: install Docker, or bubblewrap on Linux amd64" >&2; exit 1; }
+ target_key=$(printf %s "$(pwd)" | shasum -a 256 | cut -c1-16)
+ docker run --rm --platform linux/amd64 \
+ --mount "type=bind,source=$(pwd),target=/work,readonly" \
+ --mount "type=volume,source=oficina-slides-pdf-wasm-target-${target_key},target=/work/core/pdf/target" \
+ --mount type=volume,source=oficina-slides-pdf-wasm-cargo,target=/usr/local/cargo \
+ --mount type=volume,source=oficina-slides-pdf-wasm-rustup,target=/usr/local/rustup \
+ --workdir /work \
+ rust@sha256:8aea3a845c48caac4091a8d0e6494d213061f8f014dc2f5a5f1a88a1a8c9f301 \
+ bash -ec 'rustup target add wasm32-unknown-unknown >&2; ./scripts/build-pdf-wasm.sh --canonical-build >&2; cat core/pdf/target/wasm32-unknown-unknown/release/slides_pdf.wasm' > "$temporary"
+ fi
+ mv "$temporary" "$out"
+ exit 0
+fi
+# Ship only the PDF library. Fixed path remapping and stripped symbols keep
+# diagnostics and local crate identities independent of the checkout location.
+# The custom getrandom cfg is inert for the PDF dependency graph, but retains
+# the workspace wasm configuration when RUSTFLAGS replaces config-file flags.
registry_root="${CARGO_HOME:-$HOME/.cargo}/registry/src"
workspace_root="$(pwd)"
-export RUSTFLAGS="--cfg getrandom_backend=\"custom\" --remap-path-prefix=${registry_root}=/cargo-registry-src --remap-path-prefix=${workspace_root}=/slides-pdf"
+# Cargo also puts local path dependency identities into mangled debug names.
+# Remove that optional symbol section so identical code reproduces across worktrees.
+export RUSTFLAGS="-C strip=symbols --cfg getrandom_backend=\"custom\" --remap-path-prefix=${registry_root}=/cargo-registry-src --remap-path-prefix=${workspace_root}=/slides-pdf"
cargo build --release --manifest-path core/pdf/Cargo.toml --target wasm32-unknown-unknown --locked --lib
out="core/pdf/target/wasm32-unknown-unknown/release/slides_pdf.wasm"
[ -f "$out" ] || { echo "build-pdf-wasm: no artifact at $out" >&2; exit 1; }
diff --git a/scripts/build-wasm.sh b/scripts/build-wasm.sh
index c56cdfe..dbd11b1 100755
--- a/scripts/build-wasm.sh
+++ b/scripts/build-wasm.sh
@@ -8,12 +8,55 @@ cd "$(dirname "$0")/.."
# Doc::with_client_id() both draw entropy this build has no safe source
# for. A doc comment alone has been wrong, or gotten around, more than
# once; this is the actual enforcement.
-cargo clippy --manifest-path core/Cargo.toml --all-targets -- -D warnings -D clippy::disallowed_methods
-# --lib only: the wasm module shipped to wazero is the library crate. Any
-# native tooling this crate ever grows under src/bin would not be part of
-# that artifact and would not define the __getrandom_v03_custom symbol
-# itself, so building it for wasm32 would fail to link -- it isn't meant to
-# run there.
+if [[ "${1:-}" != "--build-only" && "${1:-}" != "--canonical-build" ]]; then
+ cargo clippy --manifest-path core/Cargo.toml --all-targets -- -D warnings -D clippy::disallowed_methods
+fi
+# Rust/Cargo crate identities affect code ordering even after path remapping.
+# Build on Linux amd64 at fixed source/toolchain paths on every host.
+if [[ "${1:-}" == "--canonical-build" ]]; then
+ [[ "$(uname -s)/$(uname -m)" == "Linux/x86_64" && "$(pwd)" == /work \
+ && "$CARGO_HOME" == /usr/local/cargo && "$RUSTUP_HOME" == /usr/local/rustup ]] \
+ || { echo "build-wasm: invalid canonical build environment" >&2; exit 1; }
+ export CARGO_TARGET_DIR=/work/core/target RUSTUP_TOOLCHAIN=1.98.0
+else
+ out="core/target/wasm32-unknown-unknown/release/slides_core.wasm"
+ mkdir -p "$(dirname "$out")"
+ temporary=$(mktemp "${out}.XXXXXX")
+ trap 'rm -f "$temporary"' EXIT
+ if [[ "$(uname -s)/$(uname -m)" == "Linux/x86_64" ]] && command -v bwrap >/dev/null; then
+ cargo_home=$(cd "${CARGO_HOME:-$HOME/.cargo}" && pwd)
+ rustup_home=$(cd "${RUSTUP_HOME:-$HOME/.rustup}" && pwd)
+ mkdir -p core/target/canonical-linux-amd64
+ bwrap --tmpfs / \
+ --ro-bind /usr /usr --tmpfs /usr/local \
+ --ro-bind /bin /bin --ro-bind /lib /lib --ro-bind /lib64 /lib64 \
+ --ro-bind /etc /etc --bind /tmp /tmp --proc /proc --dev /dev \
+ --ro-bind "$(pwd)" /work \
+ --bind "$(pwd)/core/target/canonical-linux-amd64" /work/core/target \
+ --bind "$cargo_home" /usr/local/cargo --ro-bind "$rustup_home" /usr/local/rustup \
+ --chdir /work --setenv CARGO_HOME /usr/local/cargo --setenv RUSTUP_HOME /usr/local/rustup \
+ --setenv PATH /usr/local/cargo/bin:/usr/local/bin:/usr/bin:/bin \
+ bash -ec './scripts/build-wasm.sh --canonical-build >&2; cat core/target/wasm32-unknown-unknown/release/slides_core.wasm' > "$temporary"
+ else
+ command -v docker >/dev/null || { echo "build-wasm: install Docker, or bubblewrap on Linux amd64" >&2; exit 1; }
+ target_key=$(printf %s "$(pwd)" | shasum -a 256 | cut -c1-16)
+ docker run --rm --platform linux/amd64 \
+ --mount "type=bind,source=$(pwd),target=/work,readonly" \
+ --mount "type=volume,source=oficina-slides-core-wasm-target-${target_key},target=/work/core/target" \
+ --mount type=volume,source=oficina-slides-core-wasm-cargo,target=/usr/local/cargo \
+ --mount type=volume,source=oficina-slides-core-wasm-rustup,target=/usr/local/rustup \
+ --workdir /work \
+ rust@sha256:8aea3a845c48caac4091a8d0e6494d213061f8f014dc2f5a5f1a88a1a8c9f301 \
+ bash -ec 'rustup target add wasm32-unknown-unknown >&2; ./scripts/build-wasm.sh --canonical-build >&2; cat core/target/wasm32-unknown-unknown/release/slides_core.wasm' > "$temporary"
+ fi
+ mv "$temporary" "$out"
+ exit 0
+fi
+# --lib only: the wasm module shipped to wazero is the library crate. Native
+# tooling under src/bin (e.g. emit_update, used from the host side of
+# wire-gate.sh) is never part of that artifact and does not define the
+# __getrandom_v03_custom symbol itself, so building it for wasm32 fails to
+# link -- it was never meant to run there.
#
# --remap-path-prefix (x2): rustc embeds the absolute source path of every
# panic site (Location::caller()) into the binary. Left alone, that means
@@ -36,7 +79,9 @@ cargo clippy --manifest-path core/Cargo.toml --all-targets -- -D warnings -D cli
# it has to be repeated here alongside the remap flags.
registry_root="${CARGO_HOME:-$HOME/.cargo}/registry/src"
workspace_root="$(pwd)"
-export RUSTFLAGS="--cfg getrandom_backend=\"custom\" --remap-path-prefix=${registry_root}=/cargo-registry-src --remap-path-prefix=${workspace_root}=/slides-core"
+# Cargo also puts local path dependency identities into mangled debug names.
+# Remove that optional symbol section so identical code reproduces across worktrees.
+export RUSTFLAGS="-C strip=symbols --cfg getrandom_backend=\"custom\" --remap-path-prefix=${registry_root}=/cargo-registry-src --remap-path-prefix=${workspace_root}=/slides-core"
cargo build --release --manifest-path core/Cargo.toml --target wasm32-unknown-unknown --locked --lib
out="core/target/wasm32-unknown-unknown/release/slides_core.wasm"
[ -f "$out" ] || { echo "build-wasm: no artifact at $out" >&2; exit 1; }
diff --git a/scripts/credits.py b/scripts/credits.py
index ebe2f0c..228932a 100755
--- a/scripts/credits.py
+++ b/scripts/credits.py
@@ -12,7 +12,7 @@ from html.parser import HTMLParser
ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / 'internal/slides/credits'
ENV = os.environ | {'GOPRIVATE': 'amadan.net/oficina/estilo.git'}
-EXCLUDE = ','.join(['amadan.net/oficina/home/dashboard', 'amadan.net/oficina/estilo.git', 'amadan.net/oficina/home/handoff', 'amadan.net/oficina/home/connect', 'amadan.net/oficina/home/roster', 'amadan.net/oficina/home/teammode'])
+EXCLUDE = ','.join(['amadan.net/oficina/agent-access.git', 'amadan.net/oficina/home/dashboard', 'amadan.net/oficina/estilo.git', 'amadan.net/oficina/home/handoff', 'amadan.net/oficina/home/connect', 'amadan.net/oficina/home/roster', 'amadan.net/oficina/home/teammode'])
def run(args, cwd=ROOT, env=ENV):
@@ -25,7 +25,7 @@ def digest(path):
def inputs():
files = [ROOT / p for p in ['core/Cargo.toml', 'core/Cargo.lock', 'core/pdf/Cargo.toml', 'core/pdf/Cargo.lock', 'rust-toolchain.toml', 'fixtures/package.json', 'fixtures/package-lock.json', 'internal/slides/core/testdata/slides_core.wasm', 'internal/slides/pdfcore/testdata/slides_pdf.wasm']]
- for pattern in ['internal/slides/static/*.js', 'internal/slides/fonts/files/*', 'internal/slides/static/fonts/*', 'internal/slides/credits/upstream/*']:
+ for pattern in ['internal/slides/static/*.js', 'internal/slides/fonts/files/*', 'internal/slides/static/fonts/*', 'internal/slides/credits/upstream/*', 'core/vendor/fastrand-2.5.0/**/*']:
files.extend(ROOT.glob(pattern))
return {str(p.relative_to(ROOT)): digest(p) for p in sorted(files) if p.is_file()}
@@ -67,6 +67,27 @@ class NoticeText(HTMLParser):
self.parts.append('\n')
+def verified_vendor(package):
+ record = json.loads((OUT / 'upstream/fastrand-vendor.json').read_text())
+ directory = ROOT / 'core/vendor/fastrand-2.5.0'
+ manifest = Path(package['manifest_path'])
+ if (package['source'] is not None or package['name'] != 'fastrand'
+ or package['version'] != '2.5.0'
+ or manifest != directory / 'Cargo.toml'
+ or manifest.resolve() != directory / 'Cargo.toml'):
+ raise ValueError('unverified Cargo source replacement')
+ files = {}
+ for path in directory.rglob('*'):
+ if path.is_symlink():
+ raise ValueError('vendored source must not contain symlinks')
+ if path.is_file():
+ files[str(path.relative_to(directory))] = digest(path)
+ # This reviewed manifest is anchored to the recorded upstream crate archive.
+ # Its only source difference is the documented Cargo feature patch.
+ if files != record['files']:
+ raise ValueError('vendored source differs from verified upstream patch')
+
+
def asset_inventory():
fixtures = ROOT / 'fixtures'
run(['npm', 'ci', '--ignore-scripts', '--no-audit', '--no-fund'], cwd=fixtures)
@@ -119,7 +140,7 @@ console.log(JSON.stringify([...inputs]));
package = packages[identity]
if identity != metadata['resolve']['root']:
if package['source'] != 'registry+https://github.com/rust-lang/crates.io-index':
- raise ValueError('unverified Cargo source replacement')
+ verified_vendor(package)
selected[(package['name'], package['version'])] = package
for key in sorted(selected):
package = selected[key]