# 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.
