oficina / sheets Public

Add delegated sheets 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 701f4fd0a0f9fc08c7d84a645eca30ac9bd0cb0a parent 35dd773
43 files changed, +3,825 −73
  • Makefile +1 −1
  • cmd/sheets-contract/main.go +22 −0
  • cmd/sheets/main.go +19 −12
  • docs/agent-access.md +63 −0
  • docs/superpowers/specs/2026-10-25-agent-access.md +158 −0
  • docs/superpowers/specs/2026-11-01-agent-range-editing.md +206 −0
  • go.mod +16 −2
  • go.sum +36 −2
  • internal/sheets/agent_access.go +243 −0
  • internal/sheets/agent_authority.go +240 −0
  • internal/sheets/agent_authority_test.go +134 −0
  • internal/sheets/agent_create.go +150 −0
  • internal/sheets/agent_create_test.go +140 −0
  • internal/sheets/agent_edit.go +183 −0
  • internal/sheets/agent_edit_boundary_test.go +205 −0
  • internal/sheets/agent_edit_test.go +294 −0
  • internal/sheets/agent_fixture_test.go +115 −0
  • internal/sheets/agent_integration_test.go +171 −0
  • internal/sheets/agent_limits_test.go +128 −0
  • internal/sheets/agent_operations.go +146 −0
  • internal/sheets/agent_read.go +180 −0
  • internal/sheets/agent_response.go +28 −0
  • internal/sheets/agent_response_test.go +95 −0
  • internal/sheets/agent_storage_test.go +118 −0
  • internal/sheets/agent_team_compat_test.go +219 −0
  • internal/sheets/agent_team_lease_test.go +80 −0
  • internal/sheets/app.go +3 −5
  • internal/sheets/auth.go +8 −1
  • internal/sheets/auth_test.go +1 −0
  • internal/sheets/migrations.go +1 −0
  • internal/sheets/migrations/0011_agent_access.sql +14 −0
  • internal/sheets/migrations/0012_create_sheets_agent_edits.sql +2 −0
  • internal/sheets/migrations/schema.sql +19 −0
  • internal/sheets/sheetsvc.go +8 −2
  • internal/sheets/store/handle_blank_cap_test.go +21 −0
  • internal/sheets/store/handle_range.go +50 −0
  • internal/sheets/store/handle_write_batch.go +95 −48
  • internal/sheets/store/handle_write_batch_test.go +19 −0
  • internal/sheets/store/initial_export_test.go +10 −0
  • internal/sheets/store/initial_tab.go +40 −0
  • internal/sheets/store/initial_tab_test.go +127 −0
  • internal/sheets/store/metadata_read.go +16 −0
  • internal/sheets/team_guard_test.go +1 −0

CI passed — run details

landed from feat/agent-access

diff --git a/Makefile b/Makefile
index 3a1b696..60f5dcc 100644
--- a/Makefile
+++ b/Makefile
@@ -1,5 +1,5 @@
comma := ,
-export GOPRIVATE := $(if $(GOPRIVATE),$(GOPRIVATE)$(comma))amadan.net/oficina/estilo.git
+export GOPRIVATE := $(if $(GOPRIVATE),$(GOPRIVATE)$(comma))amadan.net/oficina/estilo.git,amadan.net/oficina/agent-access.git
.PHONY: build release test test-vet test-fmt test-build test-migrations test-go test-race test-browser
diff --git a/cmd/sheets-contract/main.go b/cmd/sheets-contract/main.go
new file mode 100644
index 0000000..52a75f4
--- /dev/null
+++ b/cmd/sheets-contract/main.go
@@ -0,0 +1,22 @@
+// Command sheets-contract exports the live delegated operation schemas.
+package main
+
+import (
+ "amadan.net/oficina/sheets/internal/sheets"
+ "encoding/json"
+ "fmt"
+ "os"
+)
+
+func main() {
+ operations, err := sheets.AgentContracts()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Could not export Sheets operation contracts.")
+ os.Exit(1)
+ }
+ encoder := json.NewEncoder(os.Stdout)
+ encoder.SetIndent("", " ")
+ if encoder.Encode(operations) != nil {
+ os.Exit(1)
+ }
+}
diff --git a/cmd/sheets/main.go b/cmd/sheets/main.go
index 4a89a0a..3b04f1f 100644
--- a/cmd/sheets/main.go
+++ b/cmd/sheets/main.go
@@ -43,35 +43,37 @@ func main() {
os.Exit(1)
}
- d, err := rdb.Open(opts.DBPath, logger)
- if err != nil {
- logger.Error("open db", "err", err)
- os.Exit(1)
- }
- defer d.Close()
-
// Sign-in configuration is validated before anything serves. Every
// failure here is one where continuing would produce an instance
// that looks like it works: no mailer means magic links get written
// to platform-held logs instead of emailed, and an empty allowlist
// means anyone who can receive mail can hold a session. Both answer
// /healthz perfectly well, which is why this is a hard exit and not
- // a warning. It reads the environment only, so it runs before the
- // schema is chosen: team mode's configuration decides that.
+ // a warning.
authEnv, err := sheets.LoadAuthEnv(logger)
if err != nil {
logger.Error("sign-in", "err", err)
os.Exit(1)
}
- // Team mode's provisioning record is verified against configuration
- // alone (home/teammode), before anything migrates. nil with team
- // mode off.
+
+ d, err := rdb.Open(opts.DBPath, logger)
+ if err != nil {
+ logger.Error("open db", "err", err)
+ os.Exit(1)
+ }
+ defer d.Close()
+
team, err := sheets.TeamSettings(authEnv.Team, authEnv.Home, authEnv.Origin)
if err != nil {
logger.Error("team mode unavailable")
os.Exit(1)
}
+ if authEnv.AgentIssuer != "" && team != nil && authEnv.AgentTeam != team.Bindings().Team {
+ logger.Error("agent team does not match provisioned team")
+ os.Exit(1)
+ }
+
// Ledgered, once-at-boot, never re-run or reversed — see
// internal/sheets/migrations.go's Schema/BootSchema/Models and
// AGENTS.md's additive-only constraint. A boot that can't reconcile
@@ -137,6 +139,11 @@ func main() {
os.Exit(1)
}
+ if err := app.ConfigureAgentAccess(authEnv.AgentIssuer, authEnv.AgentTeam, authEnv.Home); err != nil {
+ logger.Error("agent configuration unavailable")
+ os.Exit(1)
+ }
+
if err := app.ConfigureNative(); err != nil {
logger.Error("native configuration unavailable")
os.Exit(1)
diff --git a/docs/agent-access.md b/docs/agent-access.md
new file mode 100644
index 0000000..c897c9c
--- /dev/null
+++ b/docs/agent-access.md
@@ -0,0 +1,63 @@
+# Delegated Sheets access
+
+The Oficina connection exposes `sheets_list`, `sheets_list_tabs`,
+`sheets_get_range`, `sheets_create` and `sheets_set_range`. CLI, Paseo, ChatGPT and Claude use the
+same contracts. Existing Home links and current app permissions are required.
+
+Set `SHEETS_AGENT_ISSUER` to the HTTPS connection-service origin and
+`SHEETS_AGENT_TEAM` to this instance's team, alongside existing Home settings.
+Both settings are required together. Credentials must target this app's exact
+origin plus `/api/v1` and name the configured Home identity issuer.
+
+Export contracts with `go run ./cmd/sheets-contract`. The bearer endpoints are
+`GET /api/v1/operations` and `POST /api/v1/operations/{name}`. The connection
+service obtains app credentials; browser cookies do not authenticate them.
+Read operations require `sheets:read`; create requires `sheets:write` and current
+team membership. Explicitly granted guests can read their permitted sheets. In roster team mode,
+creation uses current Home membership; stored local roles do not grant standing.
+The configured agent team must match the provisioned roster team. Full lists
+return a retryable failure when roster authority is unavailable, while exact
+items independently shared with the caller remain readable. This initial API
+requires an existing Home-linked local account.
+
+IDs, revisions and pagination cursors are decimal JSON strings. IDs must be
+positive, canonical and at most 9223372036854775807. Omit the cursor on the first
+page. Sheet listing descends by ID; tab listing ascends. Both default to 20
+items and permit at most 100.
+
+Create accepts a nonzero canonical UUID `client_id`, a title and `tab_name`
+(up to 200 Unicode characters each), and `cells` containing up to 500 distinct
+`row`, `column`, `raw` entries. Coordinates are zero-based: rows 0–4999 and
+columns 0–599. Raw cell input is at most 8 KiB and uses the browser's formula
+parser and calculator. The entire sheet, first tab, owner grant, initial cells,
+sealed attribution and receipt commit together. Create returns sheet/tab IDs,
+a browser URL and current revision; reuse the UUID only for an identical retry.
+A retry preserves intervening browser edits and never recreates a deleted sheet.
+
+Range reads return raw input, calculated value/type, default display text and a
+coherent revision for at most 500 cells. Incomplete calculation is an explicit
+failure. Inputs and encoded responses are capped at 1 MiB; oversized results
+fail without truncation. Formula error values are returned as cell errors.
+The revision is the store's next-stamp watermark, shared with range reads.
+
+The receipt marker binds the Home key, Home issuer, connection issuer and team.
+Changes require an explicit operator migration. Never delete the marker or
+receipts to make old requests appear new. Creation does not send invitations.
+Formatting, additional tabs, comments, sharing and import/export remain
+separate capability slices.
+
+See [the reviewed specification](superpowers/specs/2026-10-25-agent-access.md).
+This branch does not claim deployment or live client certification.
+
+`sheets_set_range` requires `team`, `sheet_id`, `tab_id`, `expected_revision`,
+`client_id` and an ordered `cells` array of 1–500 `{row,column,raw}` entries.
+Read a range first and copy its revision string into `expected_revision`.
+The native batch updates exactly those cells, recalculates formulas atomically
+and blanks a cell when raw is empty. Current editor permission is required;
+an independent editor share works under the same roster rules as browser edits.
+
+A stale revision returns `conflict` without changing cells. After an uncertain
+response, repeat the same UUID, revision and ordered cell values. The response
+contains sheet/tab IDs, URL and the original **applied** revision, even when
+later edits advanced the tab. It never replays the cell writes; read again for
+current values and revision. Choose a new UUID for a changed edit.
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..392476e
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-25-agent-access.md
@@ -0,0 +1,158 @@
+# Delegated spreadsheet operations
+
+Status: approved by GPT-6 Astra after independent design review against
+baseline 6d700d6. Source review, tests, CI and deployed verification remain
+separate gates. Paul requested
+suite-wide API, CLI and MCP access after browser permission, authorized a
+transport owned by Oficina until Rastrillo converges, and selected CLI, Paseo,
+ChatGPT and Claude as the first clients.
+
+## Authority and transport
+
+Opt in with SHEETS_AGENT_ISSUER and SHEETS_AGENT_TEAM alongside Home. Validate
+complete configuration before storage. An online verifier checks a short-lived
+app-audience credential for this exact origin plus /api/v1. Introspection's
+identity_issuer must exactly match configured Home.Issuer before resolving its
+opaque subject through the existing connection bridge to an existing member.
+No EnsureMember, address matching, synthetic browser cookie or local agent key.
+Recheck current admission and sheet grants for every operation. Grant admission
+alone never grants create authority. Existing explicit-grant/team-role semantics
+remain authoritative; preserve roleFor precedence in new error-returning authority and tab-ownership
+helpers, and use grant-scoped queries, never scope.Owned. The existing boolean
+helpers erase storage errors and cannot satisfy the unavailable contract.
+Revoked delegation, unlinked identities and lost applicable permission refuse.
+
+The shared Oficina registry defines identical HTTP, CLI and MCP contracts.
+Bearer routes are separate from browser CSRF/session routes. Sanitized errors
+contain no values, formulas, sheet titles or tab names. Unknown or inaccessible
+items both return 404; infrastructure failure returns unavailable, not empty
+results. Request bodies are at most 1 MiB; every encoded result is at most 1 MiB, with
+an explicit oversize failure and no partial success. Metadata enumeration is
+bounded before decryption/materialization: list returns sheet metadata only;
+tab discovery is a separate bounded sheets_list_tabs (sheets:read) operation (default 20,
+maximum 100, ascending exact ID cursor) on one currently readable sheet.
+
+## First operations
+
+- sheets_list (sheets:read): live/non-filling permitted sheets, default 20 and
+ maximum 100 per page, descending numeric ID cursor decoded exactly. Return
+ canonical decimal ID strings, title and URL. Decode sealed titles/names
+ through store helpers and fail if opening fails. A grant join filters before
+ pagination; guests see only explicitly granted sheets.
+- sheets_get_range (sheets:read): one tab, integer start row/column and height/
+ width, at most 500 cells. Return coordinates, raw input, calculated display
+ value/error, and the tab revision as a decimal string. Read from a single
+ current handle while its mutex is held so values and revision are coherent.
+ A content-bearing result larger than 1 MiB fails explicitly without truncation.
+- sheets_create (sheets:write): nonzero UUID client_id, title, first tab name,
+ and up to 500 unique cell coordinates/raw inputs, within existing row/column,
+ raw-input, total-cell and calculation limits. Accept the same formulas and
+ value rules as the browser. The response contains the sheet/tab identifiers,
+ member URL, and a current coherent snapshot revision. This is Handle.Version's
+ next-stamp watermark, matching range reads, not SetBatch.Report.Version's last
+ assigned stamp; a retry after a browser edit returns the current watermark. It sends no invitation.
+
+This initial creation path supports a populated budget or table directly.
+Editing existing sheets, formatting, extra tabs, comments, sharing and import/
+export are later capability slices. Editing will require a reviewed revision
+precondition and guarded SetBatch transaction, rather than optimistic read then
+unconditional write. These omissions remain visible in the capability matrix.
+
+## Atomic creation and retries
+
+Refactor the existing newSheet creation service only as needed to reuse its
+sealed title/tab name and owner grant invariants inside an outer transaction.
+A receipt insertion first takes SQLite's writer reservation. Recheck the
+existing local operator and current create membership inside that transaction.
+Create metadata, first tab, owner grant, cells through the existing parser/
+calculation/store machinery, attribution and receipt in that same transaction.
+Add an unregistered transaction-local handle constructor: store.Open currently
+registers a handle and must not be used with tx. Discard this transaction handle
+on both success and failure; it retains tx and must never be cached even after
+commit. If needed, open a fresh canonical app-DB handle after commit. A rollback
+must not leave in-memory phantom cells.
+Reuse SetBatch's parser, calculator, shape limits and version assignment. All
+raw values, calculated strings, titles and tab names remain sealed on disk.
+
+Receipt coordinates use a purpose-separated HMAC over an unambiguous encoding
+of identity_issuer, delegation issuer, Home subject, OAuth client, selected team
+and UUID. Attribution uses the same authority namespace. Payload fingerprint uses
+a separate HMAC over canonical typed title/tab/cells, sorted by coordinate so
+cell ordering alone does not change meaning. Only digests and sheet ID enter
+receipts. Persist a keyed marker at first enablement and verify on startup and
+before each agent write; the marker also binds identity issuer, delegation
+issuer and configured team. A changed key or authority configuration refuses
+writes until explicit operator migration. Never reset the marker to make old retries appear new.
+
+Identical retries recheck current authority and return the existing sheet;
+changed input conflicts. A deleted sheet is never recreated. A retry after a
+browser cell edit returns the existing sheet without applying initial values
+again. Client/operator attribution identifies the existing member and sealed
+client label, and does not mint a local agent/person. Commit precedes any cache
+insertion or publish notification. New sheet creation needs no preexisting
+subscriber content broadcast.
+
+## Evidence and release
+
+Test linked Home identity, identity-issuer mismatch before local lookup,
+current team and sheet role enforcement, an authorized sheet paired with a
+foreign tab, authority storage failures, explicit guest grants, no provisioning,
+cookie-only refusal, lost authority, expired/revoked credentials, exact cursors,
+read bounds and coherent revision. Real SQLite and calculation fixtures cover
+Unicode, formulas, dependent values, concurrent retry, changed payload, deleted
+replay, browser edits before retry, restarted process, changed receipt key, and equal subject/client/team/UUID under a changed issuer
+namespace (refused without migration).
+Inject failure after cells and grant creation to prove the whole transaction
+rolls back and no cached handle survives. Inspect database/WAL/receipt/log bytes
+for title, tab-name, raw-value and calculated-string canaries. Exercise actual
+operations through the suite HTTP/MCP gateway. New gates must fail against
+material adverse mutations. Run complete CI, highest-capability branch review,
+and deployed canary verification before merge. Source/spec approval does not
+claim deployment.
+
+## Store foundation review (2026-10-25)
+
+GPT-6 Astra approved the first store slice after two calculation-completeness
+findings were fixed. ReadRange holds one handle lock for raw/calculated values
+and revision, refuses a tab with durable dirty markers, and refuses nonempty
+inputs with missing caches. Capped browser recalculation and unrecoverable
+corrupt cache states therefore produce explicit failure rather than old or
+empty values at a new revision. InitializeTab never registers its transaction
+handle and shares the caller's atomic commit/rollback. Focused race tests passed.
+Five effective mutations failed: cache transaction handle, remove range lock,
+remove initial-tab emptiness guard, ignore dirty markers, ignore missing cache.
+This is store-slice approval; app adapter, full CI, whole-branch review and
+deployed canary remain required.
+
+## Identifier and write-boundary amendment (2026-10-25)
+
+GPT-6 Astra approved correction of the original Sqid wording: this baseline's
+browser routes use decimal sheet/tab IDs. Expose IDs and cursors as JSON strings
+containing canonical positive decimals up to 9223372036854775807. Reject signs,
+leading zeroes, whitespace and overflow; omit the cursor for the first page.
+Do not introduce a second ID scheme.
+
+Contracts must be identical across teams; enforce the selected target team at
+invocation. Reject malformed Unicode before lossy decoding. Reverify delegation
+at the reserved writer boundary and before commit, preserving subject, client,
+grant, team and scope; failure rolls back creation. Keep those network checks
+separate from transaction-local identity queries. Validate the bounded create
+result before commit, and preserve recoverable client attribution sealed outside
+the digest-only receipt. These amendments are approved design, not source
+approval for the forthcoming app adapter.
+
+## Home roster compatibility (2026-10-30)
+
+In provisioned team mode the roster replaces stored team_role and the local
+allowlist as standing. Agent configuration must match the verified roster team.
+Resolve only an existing Home link, without the browser's Home-only fallback.
+Capture one Access for the verified Home subject and retain it through registry
+checks, the writer transaction, completed retries and every response chunk;
+Unknown is latched and never refreshed within a request. Creation requires
+Member. Read permissions retain explicit-grant precedence, including refusal of
+unknown roles: a creator's self-grant needs membership, an independent share
+survives removal. Filter these grants before pagination. Unknown full lists
+return unavailable even when independent shares remain; an exact shared item
+can still be read. Socket deadlines cannot exceed the captured membership lease
+or a shorter caller deadline. Non-team behavior is unchanged. GPT-6 Astra
+reviewed this compatibility plan; final source/evidence review is separate.
diff --git a/docs/superpowers/specs/2026-11-01-agent-range-editing.md b/docs/superpowers/specs/2026-11-01-agent-range-editing.md
new file mode 100644
index 0000000..786c198
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-01-agent-range-editing.md
@@ -0,0 +1,206 @@
+# Delegated range editing
+
+Status: specification and final source independently approved by a separate
+GPT-6 Astra agent, 2026-11-01. 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 requirements remain binding. Existing v1 operations and
+their response shapes do not change.
+
+## Contract
+
+Add `sheets_set_range`, scope `sheets:write`, readOnly false, idempotent true.
+The same registry descriptor serves HTTP, CLI and MCP, independent of the
+configured team. All six top-level fields below are required; unknown
+top-level and cell fields are refused.
+
+```json
+{
+ "team": "team-id",
+ "sheet_id": "42",
+ "tab_id": "43",
+ "expected_revision": "17",
+ "client_id": "1dc98332-7165-43c5-8f98-9546f10146a8",
+ "cells": [
+ {"row": 0, "column": 0, "raw": "21"},
+ {"row": 0, "column": 1, "raw": "=A1*2"}
+ ]
+}
+```
+
+Sheet and tab IDs retain their canonical positive decimal string form, at
+most MaxInt64. Revision is the existing tab snapshot's positive decimal
+next-stamp watermark, also at most MaxInt64; never a JSON number or a cell's
+last-written stamp. Leading zeros, signs, fractions and overflow are invalid.
+The nonzero UUID must be its canonical lowercase hyphenated spelling.
+Team is 1–128 characters and must equal the instance's configured team.
+
+`cells` is an ordered sparse batch of 1–500 distinct coordinates, with rows
+0–4999, columns 0–599 and raw input at most 8192 UTF-8 bytes per cell. The
+operation updates exactly those cells; omitted coordinates are unchanged.
+An empty raw string blanks a cell. Formula text uses the current store
+parser and recalculation engine, with exactly `SetBatch` semantics. This is
+literal raw input, without clipboard reference translation. Preserve input
+order, since it determines native batch stamps and intermediate evaluation.
+Malformed Unicode, invalid formulas as judged by `ValidateCellWrites`,
+duplicate coordinates and requests above 1 MiB are refused before writing.
+Existing store limits, including the 5000-cell recalculation cap and maximum
+cells per tab, still refuse the entire batch.
+
+Success is a small acknowledgement, never a cached range:
+
+```json
+{"sheet_id":"42","tab_id":"43","revision":"19","url":"https://sheets.example/sheets/42"}
+```
+
+All four response fields are required. `revision` is the immutable next-stamp
+watermark immediately after this mutation committed. A completed retry
+returns that same revision, even if later browser edits advanced the tab.
+Read `sheets_get_range` for current cells and current revision. Existing
+`sheets_create` retry semantics remain unchanged. Output is bounded by the
+existing 1 MiB limit before commit.
+
+`conflict` covers a new request against a stale revision, or reuse of a
+client UUID with different target, expected revision, cell order or content.
+The caller re-reads and chooses a new mutation UUID after a stale revision;
+the service never rebases or automatically retries an edit at a newer
+revision. Invalid input, unavailable storage/authority, unauthorized scope
+and missing/inaccessible targets retain the existing error vocabulary.
+Authority is checked before revealing a revision conflict.
+
+## Authority and visibility
+
+Separate the registry's creation-membership requirement from `sheets:write`:
+only create needs creator eligibility. Range editing requires current
+`SheetEditor` reach to the existing sheet and a tab belonging to that sheet.
+Use existing explicit-grant precedence, invalid-grant refusal, deletion and
+filling predicates. A viewer cannot edit. Independent editor shares continue
+to work under NotMember or Unknown exactly as browser writes do. A self-grant
+or team rung still needs Member from the request's one retained Access.
+
+At writer reservation and immediately before commit, reverify only the
+original delegation verifier, require unchanged subject/client/grant/team/
+scope, resolve the keyed Home link through `ResolveOn` on the caller's
+transaction, compare stable local person ID and address, and check current
+sheet editor reach and tab ownership on that transaction. Never invoke a
+HomeOnly fallback, create a person, refresh the roster under the writer or
+query through the outer database pool. Both fresh writes and completed
+receipt retries pass these checks and the existing team write guard.
+
+Remember the target sheet for the existing final/per-chunk response checks;
+the mutation acknowledgement additionally requires current editor reach at
+emission, including an intervening editor-to-viewer downgrade. Preserve the
+retained-lease socket deadline clamp. A failed emission after a committed
+write is recoverable using the same UUID; it cannot roll back a commit.
+
+## Native transaction and cache discipline
+
+Extend the store's existing `SetBatch` seam with a bounded conditional batch
+entrypoint; keep existing browser callers and their behavior unchanged.
+The canonical handle mutex covers the revision decision, transaction and
+post-commit cache adoption. One SQLite writer transaction contains the
+namespace check/reservation, current authority, receipt decision, precondition,
+all native SetBatch input/cache/event writes, receipt/attribution and final
+authority check. Reserve the writer before reading the transactional state.
+
+Store code owns the lock and transaction; app-owned callbacks receive that
+transaction for authorization and receipts. They must not call `store.Open`,
+another locking handle method or an outer-pool lookup while the lock/writer
+is held. The native batch implementation is factored and reused, not copied
+into the adapter. A fresh unregistered staged handle is built on the writer
+transaction. Its next stamp is at least the canonical handle's watermark,
+matching existing SetBatch recovery semantics. Compare expected_revision to
+that authoritative current watermark before allocating coordinates or applying
+inputs. No staged mutation reaches the canonical handle on any rollback.
+
+After a successful fresh commit, adopt the staged graph, raw values, axes,
+keys and next stamp into the canonical handle exactly as SetBatch does.
+Release the lock before app-level reads. Publish the native complete batch
+report (including derived cells, actor, final stamp and stamp count) to the
+existing browser live channel only after commit, and touch the sheet's list
+activity timestamp using the existing behavior. A completed retry publishes
+no duplicate report, consumes no stamps and creates no new native events.
+Never report a truncated calculation as a successful edit.
+
+## Durable retries and attribution
+
+Add an additive edit-receipt table, separate from creation receipts. Its
+unique coordinate is an HMAC over the operation name, both authority issuers,
+team, subject, delegated client and client UUID. Its content fingerprint
+includes target IDs, expected revision and the exact ordered decoded cell
+values. No raw cells or formulas are stored in receipts or logs. Store target
+IDs, the immutable applied revision and the authenticated local member ID;
+seal the recoverable delegated client attribution with a receipt-specific
+purpose. The native events continue to name their real local actor; the
+receipt's tab-filtered first/last native input-event IDs tie this edit to that
+client. Capture the range around SetBatch under the reserved writer and require
+one input event per requested cell. Preserve it on replay. Native anonymous
+recalc markers remain unchanged; no new correlation is claimed for those rows.
+
+The existing immutable key/issuer/team marker must refuse adoption when
+either creation receipts or edit receipts exist without its binding. All
+receipt and attribution writes share the cell transaction. Completed receipt
+lookup precedes the expected-current-revision comparison, after current
+authority, so retries still succeed following unrelated later edits. A
+payload mismatch conflicts and never changes the stored receipt. A failed
+transaction leaves no receipt and no partial input/cache/event/axis changes.
+Concurrent identical submissions result in one edit and one acknowledgement.
+Reopening the database and app preserves replay behavior.
+
+## Review and validation gates
+
+Independent highest-capability spec approval precedes implementation and
+independent source/evidence review follows it. Required meaningful gates:
+
+- Real linked-account HTTPS grant/gateway/MCP read-edit-read; compare raw and
+ calculated formulas, blanking, events and native UI-store reads. Observe
+ the complete live report after commit and none on refusal or replay.
+- Two editors starting from one revision: exactly one succeeds, the other
+ conflicts without overwriting. Exact retry after a later native edit returns
+ the original revision and preserves that edit, including after app restart.
+- Duplicate concurrent first requests, changed payload/target/order/revision,
+ foreign tab, viewer and invalid explicit grant; editor share under removed
+ or Unknown membership, and team-rung lease expiry.
+- Real SQL-trigger failures after partial native writes or receipt insertion
+ roll back cells, caches, events, axes, receipt and attribution; canonical
+ cached handle and a freshly reopened handle agree afterward.
+- Initial and final token revoke, keyed-link corruption, unlink and editor
+ downgrade, tested at the domain method independently of emission. Direct
+ completed-retry final guard tests prevent an HTTP guard masking omissions.
+- Revision boundaries, batch/parser/recalculation limits, malformed Unicode,
+ request/output bounds, immutable namespace and raw-database privacy checks.
+- Add the delegated path to `TestTeamEveryWriteRouteRefusesALapseBeforeCommit`
+ or its shared enumerated helper with equivalent transaction assertions.
+- Effective runtime-failing mutants independently bypass revision comparison,
+ receipt payload comparison, final writer guard, transaction-local editor
+ permission, receipt persistence, and rollback-safe cache adoption. Restore
+ every mutant; focused race and the full pinned `make test` gate must pass
+ on the restored final tree.
+
+This slice changes cell inputs only. Formatting, row/column structure, tabs,
+sharing, deletion and imports retain their existing surfaces. It carries no
+merge, canary 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.
+
+The reviewer also approved the additive first/last input-event receipt range:
+only this tab's native input events, with an exact per-cell count and real
+local actor assertions. Seven selected mutants failed at runtime: missing
+revision check, repeated edit on retry, missing final writer check, cache
+adoption after rollback, omitted native recalculation, missing editor authority
+at emission, and swallowed batch-apply failure. Every original was restored.
+
+Final restored-tree validation on 2026-11-01 passed with Go 1.26.5:
+`GOTOOLCHAIN=go1.26.5 make test` (including store/live race checks), followed
+by `GOTOOLCHAIN=go1.26.5 go test -race ./internal/sheets -run
+'TestAgentRangeEdit|TestAgentGatewayToRealSheets|TestTeamEveryWrite' -count=1
+-timeout 240s` (22.207s). The full gate also checked the additive migration
+against the generated schema. The real HTTPS CLI/MCP integration covers the
+new operation and its calculated read result.
diff --git a/go.mod b/go.mod
index 33648a6..f605222 100644
--- a/go.mod
+++ b/go.mod
@@ -3,8 +3,9 @@ module amadan.net/oficina/sheets
go 1.25.0
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
@@ -14,8 +15,10 @@ require (
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327
github.com/chromedp/chromedp v0.14.2
github.com/go-chi/chi/v5 v5.3.2
+ github.com/modelcontextprotocol/go-sdk v1.7.0
github.com/xuri/excelize/v2 v2.11.0
golang.org/x/crypto v0.55.0
+ golang.org/x/oauth2 v0.35.0
gorm.io/gorm v1.31.2
)
@@ -23,17 +26,28 @@ require (
amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect
github.com/BurntSushi/toml v1.6.0 // indirect
github.com/chromedp/sysutil v1.1.0 // indirect
+ github.com/danieljoos/wincred v1.2.3 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.4.0 // indirect
+ github.com/godbus/dbus/v5 v5.2.2 // indirect
+ github.com/gofrs/flock v0.12.1 // indirect
+ github.com/google/jsonschema-go v0.4.3 // indirect
+ github.com/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.38.0 // indirect
+ golang.org/x/sync v0.22.0 // indirect
+ golang.org/x/time v0.15.0 // indirect
)
require (
amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2
- github.com/google/uuid v1.6.0 // indirect
+ github.com/google/uuid v1.6.0
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/keymaildev/signin v0.1.1 // indirect
diff --git a/go.sum b/go.sum
index 8d2415a..953c2b5 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=
@@ -26,8 +28,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=
@@ -42,6 +48,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=
@@ -60,6 +76,8 @@ 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=
@@ -72,8 +90,16 @@ github.com/richardlehane/mscfb v1.0.7 h1:oeoiM0WE79vHwE8RpIYYvIAc8ajTH2mb6UZm55/
github.com/richardlehane/mscfb v1.0.7/go.mod h1:pe0+IUIc0AHh0+teNzBlJCtSyZdFOGgV4ZK9bsoV+Jo=
github.com/richardlehane/msoleps v1.0.6 h1:9BvkpjvD+iUBalUY4esMwv6uBkfOip/Lzvd93jvR9gg=
github.com/richardlehane/msoleps v1.0.6/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
+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/tiendc/go-deepcopy v1.7.2 h1:Ut2yYR7W9tWjTQitganoIue4UGxZwCcJy3orjrrIj44=
@@ -84,6 +110,10 @@ github.com/xuri/excelize/v2 v2.11.0 h1:HxaEFl6sRN2+8J5a8HaKq+0M4FsjBGMnWWtjOCPSG
github.com/xuri/excelize/v2 v2.11.0/go.mod h1:jxFLbzaIwGQ5ufFNvYfUOHqXhfPaNmP14KWfmNz2Uak=
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBLbf3WdLgC29pgyhTjAT/0nuE=
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
+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/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/image v0.38.0 h1:5l+q+Y9JDC7mBOMjo4/aPhMDcxEptsX+Tt3GgRQRPuE=
@@ -92,6 +122,8 @@ golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
+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=
@@ -99,6 +131,8 @@ golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
+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.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
diff --git a/internal/sheets/agent_access.go b/internal/sheets/agent_access.go
new file mode 100644
index 0000000..a694814
--- /dev/null
+++ b/internal/sheets/agent_access.go
@@ -0,0 +1,243 @@
+package sheets
+
+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"
+ "gorm.io/gorm"
+)
+
+var errAgentConfig = errors.New("sheets: invalid agent access configuration")
+
+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
+}
+
+// ConfigureAgentAccess is called after Home and before Router. The same config
+// is validated before opening storage by LoadAuthEnv in the executable.
+func (a *App) ConfigureAgentAccess(issuer, team string, home *connect.Credentials) error {
+ if e := validateAgentConfig(issuer, team, a.origin, home); e != nil {
+ return e
+ }
+ if issuer == "" {
+ return nil
+ }
+ if a.home == nil || a.db == nil || a.sealer == nil {
+ return errAgentConfig
+ }
+ if a.team != nil && a.team.Bindings().Team != team {
+ return errAgentConfig
+ }
+ settings, e := connect.DecodeCredentials(home, a.origin)
+ if e != nil || settings == nil {
+ return errAgentConfig
+ }
+ verifier, e := access.NewRemoteVerifier(issuer, a.origin+"/api/v1", settings.Issuer)
+ if e != nil {
+ return errAgentConfig
+ }
+ agent := &sheetAgent{app: a, issuer: issuer, identityIssuer: settings.Issuer, team: team, key: append([]byte(nil), settings.DEK...)}
+ if e = a.db.Transaction(func(tx *gorm.DB) error { return agent.bind(tx) }); e != nil {
+ return e
+ }
+ a.agent, e = agent.httpHandler(verifier)
+ return e
+}
+func sheetAgentWriteFailure(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 *sheetAgent) 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") {
+ sheetAgentWriteFailure(w, access.Fail("unauthenticated", "Connect to Oficina first."))
+ return
+ }
+ p, e := verifier.Verify(r.Context(), parts[1])
+ if e != nil {
+ sheetAgentWriteFailure(w, e)
+ return
+ }
+ name := strings.TrimPrefix(r.URL.Path, "/api/v1/operations/")
+ write := name == "sheets_create" || name == "sheets_set_range"
+ discovery := r.Method == "GET" && r.URL.Path == "/api/v1/operations"
+ if discovery && !p.Allows(a.team, "sheets:read") {
+ write = true
+ }
+ member, e := a.member(r.Context(), p, write)
+ if e == nil && name == "sheets_create" {
+ e = a.requireCreator(member)
+ }
+ if e != nil {
+ sheetAgentWriteFailure(w, e)
+ return
+ }
+ state := &sheetAgentContext{member: member, sheets: map[uint64]bool{}}
+ state.verify = func(ctx context.Context) error {
+ current, e := verifier.Verify(ctx, parts[1])
+ if e != nil {
+ return e
+ }
+ scope := "sheets:read"
+ if write {
+ scope = "sheets: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(), sheetAgentKey{}, 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, "/") {
+ sheetAgentWriteFailure(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" {
+ sheetAgentWriteFailure(w, access.Fail("unsupported_media_type", "Send application/json."))
+ return
+ }
+ raw, e := io.ReadAll(io.LimitReader(r.Body, sheetAgentLimit+1))
+ if e != nil {
+ sheetAgentWriteFailure(w, access.Fail("invalid", "Could not read the request."))
+ return
+ }
+ if len(raw) > sheetAgentLimit {
+ sheetAgentWriteFailure(w, access.Fail("too_large", "The operation input exceeds 1 MiB."))
+ return
+ }
+ result, e = registry.Call(ctx, p, name, raw)
+ if e != nil {
+ sheetAgentWriteFailure(w, e)
+ return
+ }
+ }
+ body, e := json.Marshal(result)
+ if e != nil {
+ sheetAgentWriteFailure(w, sheetAgentFailure(e))
+ return
+ }
+ if len(body) > sheetAgentLimit {
+ sheetAgentWriteFailure(w, access.Fail("too_large", "The sheet 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 == "sheets_create" {
+ e = a.requireCreator(fresh)
+ }
+ if e != nil {
+ return e
+ }
+ if fresh.ID != member.ID || fresh.Address != member.Address {
+ return access.Fail("forbidden", "The current identity changed.")
+ }
+ if e := a.checkVisible(checkCtx, state, fresh); e != nil {
+ return sheetAgentFailure(e)
+ }
+ if e := checkCtx.Err(); e != nil {
+ return sheetAgentFailure(e)
+ }
+ if e := controller.SetWriteDeadline(deadline); e != nil {
+ return sheetAgentFailure(e)
+ }
+ return nil
+ }
+ if e = check(); e != nil {
+ sheetAgentWriteFailure(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
+}
+
+func (a *App) agentRoutes(browser http.Handler) http.Handler {
+ if a.agent == nil {
+ return browser
+ }
+ mux := http.NewServeMux()
+ mux.Handle("/api/v1/operations", a.agent)
+ mux.Handle("/api/v1/operations/", a.agent)
+ mux.Handle("/", browser)
+ return mux
+}
diff --git a/internal/sheets/agent_authority.go b/internal/sheets/agent_authority.go
new file mode 100644
index 0000000..af6a5be
--- /dev/null
+++ b/internal/sheets/agent_authority.go
@@ -0,0 +1,240 @@
+package sheets
+
+import (
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "strconv"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/oficina/home/roster"
+ "amadan.net/oficina/sheets/internal/sheets/store"
+ "gorm.io/gorm"
+)
+
+const sheetAgentLimit = 1 << 20
+
+type sheetAgent struct {
+ app *App
+ issuer, identityIssuer, team string
+ key []byte
+}
+type sheetAgentState struct {
+ ID int `gorm:"primaryKey"`
+ Keycheck string `gorm:"not null"`
+}
+
+func (sheetAgentState) TableName() string { return "sheets_agent_state" }
+
+type sheetAgentReceipt struct {
+ Coordinate string `gorm:"primaryKey"`
+ Content string `gorm:"not null"`
+ SheetID uint64 `gorm:"not null"`
+}
+
+func (sheetAgentReceipt) TableName() string { return "sheets_agent_receipts" }
+
+type sheetAgentAttribution struct {
+ SheetID uint64 `gorm:"primaryKey"`
+ MemberID uint64 `gorm:"not null"`
+ ClientSealed []byte `gorm:"not null"`
+}
+
+func (sheetAgentAttribution) TableName() string { return "sheets_agent_attribution" }
+
+type sheetAgentContext struct {
+ list bool
+ member Member
+ verify func(context.Context) error
+ sheets map[uint64]bool
+ edits map[uint64]bool
+}
+type sheetAgentKey struct{}
+
+func sheetAgentFailure(err error) error {
+ if err == nil {
+ return nil
+ }
+ var failure access.Failure
+ if errors.As(err, &failure) {
+ return failure
+ }
+ if errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, errNoAccess) {
+ return access.Fail("not_found", "This sheet or tab is unavailable.")
+ }
+ if errors.Is(err, linkstore.ErrRefused) {
+ return access.Fail("forbidden", "This Home identity is not admitted.")
+ }
+ return access.Fail("unavailable", "Sheet authority, calculation or storage is unavailable.")
+}
+func sheetAgentID(raw string) (uint64, error) {
+ id, err := strconv.ParseUint(raw, 10, 63)
+ if err != nil || id == 0 || strconv.FormatUint(id, 10) != raw {
+ return 0, access.Fail("invalid", "Use a canonical positive decimal identifier.")
+ }
+ return id, nil
+}
+func (a *sheetAgent) digest(domain string, value any) string {
+ raw, _ := json.Marshal(value)
+ mac := hmac.New(sha256.New, a.key)
+ mac.Write([]byte("oficina/sheets/agent/v1/" + domain + "\x00"))
+ mac.Write(raw)
+ return hex.EncodeToString(mac.Sum(nil))
+}
+func (a *sheetAgent) bind(tx *gorm.DB) error {
+ want := a.digest("keycheck", []string{"immutable-authority", a.identityIssuer, a.issuer, a.team})
+ if e := tx.Exec("INSERT INTO sheets_agent_state(id,keycheck) SELECT 1,? WHERE NOT EXISTS(SELECT 1 FROM sheets_agent_receipts) AND NOT EXISTS(SELECT 1 FROM sheets_agent_edits) ON CONFLICT(id) DO NOTHING", want).Error; e != nil {
+ return e
+ }
+ var got string
+ if e := tx.Raw("SELECT keycheck FROM sheets_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 *sheetAgent) member(ctx context.Context, p access.Principal, write bool) (Member, error) {
+ scope := "sheets:read"
+ if write {
+ scope = "sheets:write"
+ }
+ if p.Client == "" || !p.Allows(a.team, scope) {
+ return Member{}, access.Fail("forbidden", "This connection does not allow that team and operation.")
+ }
+ if a.app.home == nil {
+ return Member{}, access.Fail("unavailable", "Home identity resolution is unavailable.")
+ }
+ person, err := a.app.home.ResolveOn(ctx, a.app.db.Statement.ConnPool, p.Subject)
+ if err != nil {
+ return Member{}, sheetAgentFailure(err)
+ }
+ var member Member
+ if err = a.app.db.WithContext(ctx).First(&member, person.ID).Error; err != nil {
+ return Member{}, sheetAgentFailure(err)
+ }
+ if member.ID == 0 || person.Label == "" || member.Address != person.Label {
+ return Member{}, sheetAgentFailure(linkstore.ErrRefused)
+ }
+ if a.app.team != nil {
+ if state, ok := ctx.Value(sheetAgentKey{}).(*sheetAgentContext); ok && state != nil {
+ member.team = state.member.team
+ if member.team == nil || member.team.Subject() != p.Subject {
+ return Member{}, sheetAgentFailure(linkstore.ErrRefused)
+ }
+ } else {
+ member.team = &teamAccess{member: member, Access: a.app.team.Access(ctx, p.Subject)}
+ }
+ }
+ return member, nil
+}
+func (a *sheetAgent) requireCreator(member Member) error {
+ if a.app.team != nil && member.team.state() == roster.Unknown {
+ return sheetAgentFailure(errTeamUnavailable)
+ }
+ if !a.creator(member) {
+ return access.Fail("forbidden", "Creating a sheet requires current team membership.")
+ }
+ return nil
+}
+func (a *sheetAgent) creator(member Member) bool {
+ if a.app.team != nil {
+ return member.team != nil && member.team.state() == roster.Member
+ }
+ return a.app.admit != nil && a.app.admit(member.Address) && (a.app.teamRole(member) == TeamOwner || a.app.teamRole(member) == TeamMember)
+}
+
+// role preserves explicit-grant precedence, including unknown-role refusal,
+// while distinguishing missing permission from an unavailable authority store.
+func (a *sheetAgent) role(ctx context.Context, db *gorm.DB, id uint64, member Member) (SheetRole, error) {
+ var sheet store.Sheet
+ if e := db.WithContext(ctx).Where("id=? AND deleted_at IS NULL AND filling_since IS NULL", id).First(&sheet).Error; e != nil {
+ return "", e
+ }
+ var grant Grant
+ err := db.WithContext(ctx).Where("sheet_id=? AND member_id=?", id, member.ID).First(&grant).Error
+ if err == nil {
+ role := SheetRole(grant.Role)
+ if !role.Valid() {
+ return "", errNoAccess
+ }
+ if !a.app.ownGrantIgnored(grant, member) {
+ return role, nil
+ }
+ if member.team != nil && member.team.state() == roster.Unknown {
+ return "", errTeamUnavailable
+ }
+ return "", errNoAccess
+ }
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return "", err
+ }
+ if a.app.teamRole(member) == TeamOwner || a.app.teamRole(member) == TeamMember {
+ return SheetEditor, nil
+ }
+ if a.app.team != nil && member.team.state() == roster.Unknown {
+ return "", errTeamUnavailable
+ }
+ return "", errNoAccess
+}
+func (a *sheetAgent) tab(ctx context.Context, db *gorm.DB, sheetID, tabID uint64, member Member) error {
+ role, err := a.role(ctx, db, sheetID, member)
+ if err != nil {
+ return err
+ }
+ if !role.Allows(SheetViewer) {
+ return errNoAccess
+ }
+ var tab store.Tab
+ return db.WithContext(ctx).Where("id=? AND sheet_id=?", tabID, sheetID).First(&tab).Error
+}
+func (a *sheetAgent) remember(ctx context.Context, id uint64) {
+ if state, ok := ctx.Value(sheetAgentKey{}).(*sheetAgentContext); ok && state != nil {
+ state.sheets[id] = true
+ }
+}
+func (a *sheetAgent) creatorInTx(ctx context.Context, tx *gorm.DB, p access.Principal, expected Member) error {
+ state, ok := ctx.Value(sheetAgentKey{}).(*sheetAgentContext)
+ 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 <= 0 || uint64(person.ID) != expected.ID || person.Label != expected.Address {
+ return linkstore.ErrRefused
+ }
+ id := person.ID
+
+ var member Member
+ if e := tx.First(&member, id).Error; e != nil {
+ return e
+ }
+ member.team = expected.team
+ if a.app.team != nil && member.team.state() == roster.Unknown {
+ return errTeamUnavailable
+ }
+ if member.Address != expected.Address || !a.creator(member) {
+ return linkstore.ErrRefused
+ }
+ return nil
+}
+func sheetAgentBounded(value any) (any, error) {
+ body, err := json.Marshal(value)
+ if err != nil {
+ return nil, sheetAgentFailure(err)
+ }
+ if len(body) > sheetAgentLimit {
+ return nil, access.Fail("too_large", "The sheet result exceeds 1 MiB.")
+ }
+ return value, nil
+}
diff --git a/internal/sheets/agent_authority_test.go b/internal/sheets/agent_authority_test.go
new file mode 100644
index 0000000..3b6a351
--- /dev/null
+++ b/internal/sheets/agent_authority_test.go
@@ -0,0 +1,134 @@
+package sheets
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/sheets/internal/sheets/store"
+)
+
+func assertAgentSheetEmpty(t *testing.T, f *sheetAgentFixture) {
+ t.Helper()
+ for _, model := range []any{&store.Sheet{}, &store.Tab{}, &Grant{}, &store.Cell{}, &store.Row{}, &store.Col{}, &sheetAgentReceipt{}, &sheetAgentAttribution{}} {
+ var n int64
+ if e := f.a.app.db.Model(model).Count(&n).Error; e != nil || n != 0 {
+ t.Fatalf("partial creation %T: %d %v", model, n, e)
+ }
+ }
+}
+func TestAgentSheetPrecommitAuthorityRollback(t *testing.T) {
+ for _, change := range []string{"revoke", "unlink", "binding", "downgrade"} {
+ t.Run(change, func(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ if change == "revoke" {
+ f.revokeAt.Store(3)
+ } else {
+ sql := "DELETE FROM home_identity_links"
+ if change == "binding" {
+ sql = "UPDATE home_identity_links SET person_binding='broken'"
+ }
+ if change == "downgrade" {
+ sql = "UPDATE members SET team_role='guest'"
+ }
+ if e := f.a.app.db.Exec("CREATE TRIGGER agent_revoke AFTER INSERT ON sheets_agent_receipts BEGIN " + sql + "; END").Error; e != nil {
+ t.Fatal(e)
+ }
+ }
+ rec := f.call(t, "sheets_create", initialSheetAgentInput())
+ if rec.Code != 401 && rec.Code != 403 {
+ t.Fatal(rec.Code, rec.Body.String())
+ }
+ assertAgentSheetEmpty(t, f)
+ })
+ }
+}
+func TestAgentSheetCurrentPermissionsAndForeignTab(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ first := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
+ second := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
+ mixed := f.rangeInput(first)
+ mixed["tab_id"] = second.TabID
+ if rec := f.call(t, "sheets_get_range", mixed); rec.Code != 404 {
+ t.Fatal("foreign tab", rec.Code)
+ }
+ member, e := f.a.member(t.Context(), f.p, false)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = f.a.app.db.Model(&Grant{}).Where("sheet_id=? AND member_id=?", first.SheetID, member.ID).Update("role", "invalid").Error; e != nil {
+ t.Fatal(e)
+ }
+ if rec := f.call(t, "sheets_get_range", f.rangeInput(first)); rec.Code != 404 {
+ t.Fatal("invalid explicit grant fell back to team", rec.Code)
+ }
+ rec := f.call(t, "sheets_list", map[string]any{"team": "blue", "limit": 1})
+ var page struct {
+ Sheets []agentSheetSummary `json:"sheets"`
+ Next string `json:"next_cursor"`
+ }
+ if e = json.Unmarshal(rec.Body.Bytes(), &page); e != nil || rec.Code != 200 || len(page.Sheets) != 1 || page.Sheets[0].ID != second.SheetID || page.Next != "" {
+ t.Fatal("permission before pagination", rec.Code, rec.Body.String())
+ }
+ // An explicitly granted guest can read, but cannot create.
+ if e = f.a.app.db.Model(&Member{}).Where("id=?", member.ID).Update("team_role", "guest").Error; e != nil {
+ t.Fatal(e)
+ }
+ if rec = f.call(t, "sheets_get_range", f.rangeInput(second)); rec.Code != 200 {
+ t.Fatal("guest grant", rec.Code, rec.Body.String())
+ }
+ if rec = f.call(t, "sheets_create", initialSheetAgentInput()); rec.Code != 403 {
+ t.Fatal("guest create", rec.Code)
+ }
+ if e = f.a.app.db.Where("sheet_id=? AND member_id=?", second.SheetID, member.ID).Delete(&Grant{}).Error; e != nil {
+ t.Fatal(e)
+ }
+ if rec = f.call(t, "sheets_get_range", f.rangeInput(second)); rec.Code != 404 {
+ t.Fatal("revoked guest grant", rec.Code)
+ }
+}
+func TestAgentSheetInputAuthorityAndSealedMetadataFailures(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ input := initialSheetAgentInput()
+ raw, _ := json.Marshal(input)
+ for _, bad := range [][]byte{[]byte(strings.Replace(string(raw), "21", `\ud800`, 1)), []byte(strings.Replace(string(raw), "21", string([]byte{255}), 1))} {
+ if rec := f.raw(t, "sheets_create", bad); rec.Code != 422 {
+ t.Fatal("malformed Unicode", rec.Code, rec.Body.String())
+ }
+ }
+ for _, change := range []func(){func() { f.p.Scopes = []string{"sheets:read"} }, func() { f.p.Teams = []string{"green"} }, func() { f.p.Subject = "unlinked" }} {
+ original := f.p
+ change()
+ if rec := f.call(t, "sheets_create", input); rec.Code != 403 {
+ t.Fatal("invalid authority", rec.Code)
+ }
+ f.p = original
+ }
+ input.Team = "green"
+ f.p.Teams = []string{"blue", "green"}
+ if rec := f.call(t, "sheets_create", input); rec.Code != 403 {
+ t.Fatal("wrong instance", rec.Code)
+ }
+ assertAgentSheetEmpty(t, f)
+ input.Team = "blue"
+ made := decodeSheetCreated(t, f.call(t, "sheets_create", input))
+ for _, id := range []any{"01", "0", "-1", "9223372036854775808", 9007199254740993} {
+ in := f.rangeInput(made)
+ in["sheet_id"] = id
+ if rec := f.call(t, "sheets_get_range", in); rec.Code != 422 {
+ t.Fatal("noncanonical id", id, rec.Code)
+ }
+ }
+ if e := f.a.app.db.Model(&store.Sheet{}).Where("id=?", made.SheetID).Update("title_sealed", []byte("damaged")).Error; e != nil {
+ t.Fatal(e)
+ }
+ if rec := f.call(t, "sheets_list", map[string]any{"team": "blue"}); rec.Code != 503 {
+ t.Fatal("corrupt title hidden", rec.Code)
+ }
+ if e := f.a.app.db.Model(&store.Tab{}).Where("id=?", made.TabID).Update("name_sealed", []byte("damaged")).Error; e != nil {
+ t.Fatal(e)
+ }
+ if rec := f.call(t, "sheets_list_tabs", map[string]any{"team": "blue", "sheet_id": made.SheetID}); rec.Code != 503 {
+ t.Fatal("corrupt tab name hidden", rec.Code)
+ }
+}
diff --git a/internal/sheets/agent_create.go b/internal/sheets/agent_create.go
new file mode 100644
index 0000000..f6d099b
--- /dev/null
+++ b/internal/sheets/agent_create.go
@@ -0,0 +1,150 @@
+package sheets
+
+import (
+ "context"
+ "errors"
+ "sort"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/sheets/internal/sheets/store"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+type sheetAgentCell struct {
+ Row int `json:"row"`
+ Column int `json:"column"`
+ Raw string `json:"raw"`
+}
+type sheetAgentCreate struct {
+ Team string `json:"team"`
+ ClientID string `json:"client_id"`
+ Title string `json:"title"`
+ TabName string `json:"tab_name"`
+ Cells []sheetAgentCell `json:"cells"`
+}
+type sheetAgentCreated struct {
+ SheetID string `json:"sheet_id"`
+ TabID string `json:"tab_id"`
+ URL string `json:"url"`
+ Revision string `json:"revision"`
+}
+
+func (a *sheetAgent) create(ctx context.Context, p access.Principal, member Member, input sheetAgentCreate) (any, error) {
+ if err := a.requireCreator(member); err != nil {
+ return nil, err
+ }
+ id, err := uuid.Parse(input.ClientID)
+ input.Title = strings.TrimSpace(input.Title)
+ input.TabName = strings.TrimSpace(input.TabName)
+ if err != nil || id == uuid.Nil || id.String() != input.ClientID || input.Title == "" || input.TabName == "" || !utf8.ValidString(input.Title) || !utf8.ValidString(input.TabName) || utf8.RuneCountInString(input.Title) > maxTitleRunes || utf8.RuneCountInString(input.TabName) > maxTitleRunes || len(input.Cells) > store.MaxCellBatch {
+ return nil, access.Fail("invalid", "Invalid initial sheet, tab name or client UUID.")
+ }
+ sort.Slice(input.Cells, func(i, j int) bool {
+ if input.Cells[i].Row != input.Cells[j].Row {
+ return input.Cells[i].Row < input.Cells[j].Row
+ }
+ return input.Cells[i].Column < input.Cells[j].Column
+ })
+ writes := make([]store.CellWrite, len(input.Cells))
+ for i, cell := range input.Cells {
+ if !inCellRange(cell.Row, cell.Column) || len(cell.Raw) > maxRawBytes || !utf8.ValidString(cell.Raw) || i > 0 && cell.Row == input.Cells[i-1].Row && cell.Column == input.Cells[i-1].Column {
+ return nil, access.Fail("invalid", "Invalid initial cell coordinate or input.")
+ }
+ writes[i] = store.CellWrite{Row: cell.Row, Col: cell.Column, Raw: cell.Raw}
+ }
+ if len(writes) > 0 {
+ if err := store.ValidateCellWrites(writes); err != nil {
+ return nil, access.Fail("invalid", "Invalid initial cell input.")
+ }
+ }
+ coordinate := a.digest("coordinate", []string{a.identityIssuer, a.issuer, p.Subject, p.Client, a.team, input.ClientID})
+ payload := a.digest("content", struct {
+ Title, TabName string
+ Cells []sheetAgentCell
+ }{input.Title, input.TabName, input.Cells})
+ var sheetID, tabID uint64
+ err = a.app.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if e := a.bind(tx); e != nil {
+ return e
+ }
+ if e := a.creatorInTx(ctx, tx, p, member); e != nil {
+ return e
+ }
+ var receipt sheetAgentReceipt
+ e := tx.Where("coordinate=?", coordinate).First(&receipt).Error
+ if e == nil {
+ if receipt.Content != payload {
+ return access.Fail("conflict", "This client UUID already names different initial content.")
+ }
+ role, e := a.role(ctx, tx, receipt.SheetID, member)
+ if e != nil {
+ return e
+ }
+ if !role.Allows(SheetViewer) {
+ return errNoAccess
+ }
+ sheetID = receipt.SheetID
+ var tab store.Tab
+ if e = tx.Where("sheet_id=?", sheetID).Order("position ASC,id ASC").First(&tab).Error; e != nil {
+ return e
+ }
+ tabID = tab.ID
+ return a.creatorInTx(ctx, tx, p, member)
+ }
+ if !errors.Is(e, gorm.ErrRecordNotFound) {
+ return e
+ }
+ app := *a.app
+ app.db = tx
+ summary, e := app.newSheetWithTab(a.app.memberGuard(ctx), input.Title, input.TabName, member, false)
+ if e != nil {
+ return e
+ }
+ sheetID, tabID = summary.ID, summary.TabID
+ if e = store.InitializeTab(tx, a.app.sealer, tabID, writes, member.ID); e != nil {
+ return e
+ }
+ client, e := a.app.sealer.Seal("agent.client/"+strconv.FormatUint(sheetID, 10), []byte(p.Client))
+ if e != nil {
+ return e
+ }
+ if e = tx.Create(&sheetAgentAttribution{sheetID, member.ID, client}).Error; e != nil {
+ return e
+ }
+ if e = tx.Create(&sheetAgentReceipt{coordinate, payload, sheetID}).Error; e != nil {
+ return e
+ }
+ var tab store.Tab
+ if e = tx.First(&tab, tabID).Error; e != nil {
+ return e
+ }
+ // A fresh tab's persisted watermark is the last assigned stamp; a fresh
+ // canonical handle will expose the next one. Check output size before commit.
+ if _, e = sheetAgentBounded(a.created(sheetID, tabID, tab.ContentVersion+1)); e != nil {
+ return e
+ }
+ return a.creatorInTx(ctx, tx, p, member)
+ })
+ if err != nil {
+ return nil, sheetAgentFailure(err)
+ }
+ // Only a committed tab can enter the canonical cache. Retries observe edits.
+ if err = a.tab(ctx, a.app.db, sheetID, tabID, member); err != nil {
+ return nil, sheetAgentFailure(err)
+ }
+ handle, err := store.Open(a.app.db, a.app.sealer, tabID)
+ if err != nil {
+ return nil, sheetAgentFailure(err)
+ }
+ defer handle.Release()
+ a.remember(ctx, sheetID)
+ return sheetAgentBounded(a.created(sheetID, tabID, handle.Version()))
+}
+func (a *sheetAgent) created(sheetID, tabID, revision uint64) sheetAgentCreated {
+ id := strconv.FormatUint(sheetID, 10)
+ return sheetAgentCreated{id, strconv.FormatUint(tabID, 10), a.app.origin + "/sheets/" + id, strconv.FormatUint(revision, 10)}
+}
diff --git a/internal/sheets/agent_create_test.go b/internal/sheets/agent_create_test.go
new file mode 100644
index 0000000..b0b7f5b
--- /dev/null
+++ b/internal/sheets/agent_create_test.go
@@ -0,0 +1,140 @@
+package sheets
+
+import (
+ "bytes"
+ "encoding/json"
+ "os"
+ "strconv"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/sheets/internal/sheets/store"
+ "gorm.io/gorm"
+)
+
+func TestAgentSheetCreateRangeRetryAndBrowserEdit(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ input := initialSheetAgentInput()
+ created := decodeSheetCreated(t, f.call(t, "sheets_create", input))
+ rec := f.call(t, "sheets_get_range", f.rangeInput(created))
+ if rec.Code != 200 {
+ t.Fatal(rec.Code, rec.Body.String())
+ }
+ var snapshot agentRange
+ if e := json.Unmarshal(rec.Body.Bytes(), &snapshot); e != nil {
+ t.Fatal(e)
+ }
+ if snapshot.Revision != created.Revision || len(snapshot.Cells) != 4 || snapshot.Cells[0].Value != float64(21) || snapshot.Cells[2].Value != float64(42) {
+ t.Fatal("incoherent formula result", snapshot)
+ }
+ var wg sync.WaitGroup
+ results := make(chan sheetAgentCreated, 4)
+ for i := 0; i < 4; i++ {
+ wg.Add(1)
+ go func() { defer wg.Done(); results <- decodeSheetCreated(t, f.call(t, "sheets_create", input)) }()
+ }
+ wg.Wait()
+ close(results)
+ for got := range results {
+ if got != created {
+ t.Fatal("retry changed receipt", got)
+ }
+ }
+ reversed := input
+ reversed.Cells = append([]sheetAgentCell(nil), input.Cells...)
+ reversed.Cells[0], reversed.Cells[2] = reversed.Cells[2], reversed.Cells[0]
+ if got := decodeSheetCreated(t, f.call(t, "sheets_create", reversed)); got != created {
+ t.Fatal("cell order changed meaning")
+ }
+ changed := input
+ changed.Title = "Changed title"
+ if rec = f.call(t, "sheets_create", changed); rec.Code != 409 {
+ t.Fatal("changed retry", rec.Code)
+ }
+ tab, _ := strconv.ParseUint(created.TabID, 10, 64)
+ h, e := store.Open(f.a.app.db, f.a.app.sealer, tab)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer h.Release()
+ member, e := f.a.member(t.Context(), f.p, true)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, e = h.SetBatch([]store.CellWrite{{Row: 0, Col: 0, Raw: "8"}}, member.ID); e != nil {
+ t.Fatal(e)
+ }
+ retried := decodeSheetCreated(t, f.call(t, "sheets_create", input))
+ if retried.SheetID != created.SheetID || retried.Revision == created.Revision || retried.Revision != strconv.FormatUint(h.Version(), 10) {
+ t.Fatal("retry reset or mislabelled revision", retried)
+ }
+ var count int64
+ f.a.app.db.Model(&store.Sheet{}).Count(&count)
+ if count != 1 {
+ t.Fatal("duplicate sheet", count)
+ }
+ // Query actual database paths; plaintext authored data must not reach DB/WAL.
+ var dbs []struct {
+ Seq int
+ Name, File string
+ }
+ if e = f.a.app.db.Raw("PRAGMA database_list").Scan(&dbs).Error; e != nil {
+ t.Fatal(e)
+ }
+ for _, db := range dbs {
+ if db.Name != "main" {
+ continue
+ }
+ for _, suffix := range []string{"", "-wal"} {
+ raw, e := os.ReadFile(db.File + suffix)
+ if e != nil && !os.IsNotExist(e) {
+ t.Fatal(e)
+ }
+ for _, canary := range []string{input.Title, input.TabName, "PRIVATE_CELL_CANARY_42"} {
+ if bytes.Contains(raw, []byte(canary)) {
+ t.Fatal("plaintext persisted", canary, suffix)
+ }
+ }
+ }
+ }
+ if e = f.a.app.db.Model(&store.Sheet{}).Where("id=?", created.SheetID).Update("deleted_at", time.Now()).Error; e != nil {
+ t.Fatal(e)
+ }
+ if rec = f.call(t, "sheets_create", input); rec.Code != 404 {
+ t.Fatal("deleted replay recreated", rec.Code)
+ }
+}
+
+func TestAgentSheetAtomicRollbackAndKeyAuthority(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ input := initialSheetAgentInput()
+ for _, table := range []string{"grants", "cells", "sheets_agent_attribution", "sheets_agent_receipts"} {
+ if e := f.a.app.db.Exec("CREATE TRIGGER agent_failure BEFORE INSERT ON " + table + " BEGIN SELECT RAISE(ABORT,'injected failure'); END").Error; e != nil {
+ t.Fatal(e)
+ }
+ if rec := f.call(t, "sheets_create", input); rec.Code != 503 {
+ t.Error("write failure not surfaced", rec.Code)
+ }
+ for _, model := range []any{&store.Sheet{}, &store.Tab{}, &Grant{}, &store.Cell{}, &store.Row{}, &store.Col{}, &sheetAgentReceipt{}, &sheetAgentAttribution{}} {
+ var count int64
+ if e := f.a.app.db.Model(model).Count(&count).Error; e != nil || count != 0 {
+ t.Fatal("partial sheet persisted", count, e)
+ }
+ }
+ if e := f.a.app.db.Exec("DROP TRIGGER agent_failure").Error; e != nil {
+ t.Fatal(e)
+ }
+ }
+ decodeSheetCreated(t, f.call(t, "sheets_create", input))
+ for _, change := range []func(*sheetAgent){func(a *sheetAgent) { a.key = bytes.Repeat([]byte{19}, 32) }, func(a *sheetAgent) { a.identityIssuer = "https://other-home.example" }, func(a *sheetAgent) { a.issuer = "https://other-connect.example" }, func(a *sheetAgent) { a.team = "green" }} {
+ copy := *f.a
+ change(&copy)
+ if e := copy.app.db.Transaction(func(tx *gorm.DB) error { return copy.bind(tx) }); e == nil {
+ t.Fatal("authority/key change accepted")
+ }
+ }
+ if e := f.a.app.db.Transaction(func(tx *gorm.DB) error { return f.a.bind(tx) }); e != nil {
+ t.Fatal("same authority refused", e)
+ }
+}
diff --git a/internal/sheets/agent_edit.go b/internal/sheets/agent_edit.go
new file mode 100644
index 0000000..3b012db
--- /dev/null
+++ b/internal/sheets/agent_edit.go
@@ -0,0 +1,183 @@
+package sheets
+
+import (
+ "context"
+ "errors"
+ "unicode/utf8"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/oficina/sheets/internal/sheets/store"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+// Only hashes, coordinates and sealed client attribution reach the receipt.
+type sheetAgentEdit struct {
+ Coordinate string `gorm:"primaryKey"`
+ Content string `gorm:"not null"`
+ SheetID uint64 `gorm:"not null"`
+ TabID uint64 `gorm:"not null"`
+ Before uint64 `gorm:"not null"`
+ Revision uint64 `gorm:"not null"`
+ MemberID uint64 `gorm:"not null"`
+ FirstEventID uint64 `gorm:"not null"`
+ LastEventID uint64 `gorm:"not null"`
+ ClientSealed []byte `gorm:"not null"`
+}
+
+func (sheetAgentEdit) TableName() string { return "sheets_agent_edits" }
+
+type sheetAgentSetRange struct {
+ Team string `json:"team"`
+ SheetID string `json:"sheet_id"`
+ TabID string `json:"tab_id"`
+ ExpectedRevision string `json:"expected_revision"`
+ ClientID string `json:"client_id"`
+ Cells []sheetAgentCell `json:"cells"`
+}
+
+func (a *sheetAgent) editor(ctx context.Context, db *gorm.DB, member Member, sheetID, tabID uint64) error {
+ role, err := a.role(ctx, db, sheetID, member)
+ if err != nil {
+ return err
+ }
+ if !role.Allows(SheetEditor) {
+ return errNoAccess
+ }
+ var tab store.Tab
+ return db.WithContext(ctx).Where("id=? AND sheet_id=?", tabID, sheetID).Take(&tab).Error
+}
+
+func (a *sheetAgent) editorInTx(ctx context.Context, tx *gorm.DB, p access.Principal, expected Member, sheetID, tabID uint64) error {
+ state, ok := ctx.Value(sheetAgentKey{}).(*sheetAgentContext)
+ 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 <= 0 || uint64(person.ID) != expected.ID || person.Label != expected.Address {
+ return linkstore.ErrRefused
+ }
+ var current Member
+ if err = tx.First(&current, person.ID).Error; err != nil {
+ return err
+ }
+ if current.Address != expected.Address {
+ return linkstore.ErrRefused
+ }
+ current.team = expected.team
+ return a.editor(ctx, tx, current, sheetID, tabID)
+}
+
+func (a *sheetAgent) setRange(ctx context.Context, p access.Principal, member Member, input sheetAgentSetRange) (any, error) {
+ sheetID, err := sheetAgentID(input.SheetID)
+ if err != nil {
+ return nil, err
+ }
+ tabID, err := sheetAgentID(input.TabID)
+ if err != nil {
+ return nil, err
+ }
+ expected, err := sheetAgentID(input.ExpectedRevision)
+ if err != nil {
+ return nil, err
+ }
+ id, err := uuid.Parse(input.ClientID)
+ if err != nil || id == uuid.Nil || id.String() != input.ClientID {
+ return nil, access.Fail("invalid", "Use a canonical nonzero client UUID.")
+ }
+ writes := make([]store.CellWrite, len(input.Cells))
+ for i, cell := range input.Cells {
+ if !inCellRange(cell.Row, cell.Column) || len(cell.Raw) > maxRawBytes || !utf8.ValidString(cell.Raw) {
+ return nil, access.Fail("invalid", "Invalid cell coordinate or input.")
+ }
+ writes[i] = store.CellWrite{Row: cell.Row, Col: cell.Column, Raw: cell.Raw}
+ }
+ if err = store.ValidateCellWrites(writes); err != nil {
+ return nil, access.Fail("invalid", "Invalid cell batch.")
+ }
+ if err = a.editor(ctx, a.app.db, member, sheetID, tabID); err != nil {
+ return nil, sheetAgentFailure(err)
+ }
+ h, err := store.Open(a.app.db, a.app.sealer, tabID)
+ if err != nil {
+ return nil, sheetAgentFailure(err)
+ }
+ defer h.Release()
+ coordinate := a.digest("edit-coordinate", []string{"sheets_set_range", a.identityIssuer, a.issuer, a.team, p.Subject, p.Client, input.ClientID})
+ payload := a.digest("edit-content", input)
+ var applied uint64
+ report, err := h.SetBatchInTransaction(ctx, a.app.writeGuard(ctx, sheetID, member, SheetEditor), writes, member.ID, func(tx *gorm.DB, apply func(uint64) (uint64, error)) error {
+ if e := a.bind(tx); e != nil {
+ return e
+ }
+ if e := a.editorInTx(ctx, tx, p, member, sheetID, tabID); e != nil {
+ return e
+ }
+ var receipt sheetAgentEdit
+ e := tx.Where("coordinate=?", coordinate).Take(&receipt).Error
+ if e == nil {
+ if receipt.Content != payload || receipt.SheetID != sheetID || receipt.TabID != tabID {
+ return access.Fail("conflict", "This client UUID already names a different edit.")
+ }
+ applied = receipt.Revision
+ return a.editorInTx(ctx, tx, p, member, sheetID, tabID)
+ }
+ if !errors.Is(e, gorm.ErrRecordNotFound) {
+ return e
+ }
+ var previousEvent uint64
+ if e = tx.Model(&store.Event{}).Where("tab_id=? AND kind=?", tabID, store.KindInput).Select("COALESCE(MAX(id),0)").Scan(&previousEvent).Error; e != nil {
+ return e
+ }
+ applied, e = apply(expected)
+ if e != nil {
+ return e
+ }
+ var events struct {
+ First, Last uint64
+ Count int64
+ }
+ if e = tx.Model(&store.Event{}).Where("tab_id=? AND kind=? AND id>?", tabID, store.KindInput, previousEvent).Select("COALESCE(MIN(id),0) AS first, COALESCE(MAX(id),0) AS last, COUNT(*) AS count").Scan(&events).Error; e != nil {
+ return e
+ }
+ if events.First == 0 || events.Last < events.First || events.Count != int64(len(writes)) {
+ return access.Fail("unavailable", "The edit's native event attribution is incomplete.")
+ }
+ client, e := a.app.sealer.Seal("agent.edit.client/"+coordinate, []byte(p.Client))
+ if e != nil {
+ return e
+ }
+ receipt = sheetAgentEdit{Coordinate: coordinate, Content: payload, SheetID: sheetID, TabID: tabID, Before: expected, Revision: applied, MemberID: member.ID, FirstEventID: events.First, LastEventID: events.Last, ClientSealed: client}
+ if e = tx.Create(&receipt).Error; e != nil {
+ return e
+ }
+ if _, e = sheetAgentBounded(a.created(sheetID, tabID, applied)); e != nil {
+ return e
+ }
+ return a.editorInTx(ctx, tx, p, member, sheetID, tabID)
+ })
+ if errors.Is(err, store.ErrRevisionConflict) {
+ return nil, access.Fail("conflict", "This tab changed. Read it again before editing.")
+ }
+ if err != nil {
+ return nil, sheetAgentFailure(err)
+ }
+ if report.Stamps > 0 {
+ a.app.publishReport(SheetSummary{ID: sheetID, TabID: tabID}, h, report)
+ }
+ a.remember(ctx, sheetID)
+ if state, ok := ctx.Value(sheetAgentKey{}).(*sheetAgentContext); ok && state != nil {
+ if state.edits == nil {
+ state.edits = make(map[uint64]bool)
+ }
+ state.edits[sheetID] = true
+ }
+ return sheetAgentBounded(a.created(sheetID, tabID, applied))
+}
diff --git a/internal/sheets/agent_edit_boundary_test.go b/internal/sheets/agent_edit_boundary_test.go
new file mode 100644
index 0000000..e527f86
--- /dev/null
+++ b/internal/sheets/agent_edit_boundary_test.go
@@ -0,0 +1,205 @@
+package sheets
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "reflect"
+ "strings"
+ "testing"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/roster"
+ "amadan.net/oficina/home/teammode"
+ "amadan.net/oficina/sheets/internal/sheets/seal"
+ rdb "amadan.net/rastrillo/rastrillo/db"
+)
+
+func TestAgentRangeEditLimitsAndTarget(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ made := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
+ other := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
+ for _, rev := range []string{"0", "01", "-1", "1.0", "9223372036854775808"} {
+ in := rangeEdit(made)
+ in.ExpectedRevision = rev
+ if r := f.call(t, "sheets_set_range", in); r.Code != 422 {
+ t.Fatal("revision", rev, r.Code)
+ }
+ }
+ for _, cells := range [][]sheetAgentCell{nil, make([]sheetAgentCell, 501), {{Row: 5000, Column: 0, Raw: "1"}}, {{Row: 0, Column: 600, Raw: "1"}}, {{Raw: strings.Repeat("a", 8193)}}, {{Raw: "=SUM(("}}, {{Raw: "1"}, {Raw: "2"}}} {
+ in := rangeEdit(made)
+ in.Cells = cells
+ if r := f.call(t, "sheets_set_range", in); r.Code != 422 {
+ t.Fatal("invalid batch", r.Code)
+ }
+ }
+ in := rangeEdit(made)
+ in.TabID = other.TabID
+ if r := f.call(t, "sheets_set_range", in); r.Code != 404 {
+ t.Fatal("foreign tab", r.Code)
+ }
+ in = rangeEdit(made)
+ in.Team = "wrong"
+ if r := f.call(t, "sheets_set_range", in); r.Code != 403 {
+ t.Fatal("wrong team", r.Code)
+ }
+ in = rangeEdit(made)
+ raw, _ := json.Marshal(in)
+ raw = bytes.Replace(raw, []byte(`"32"`), []byte(`"\ud800"`), 1)
+ if r := f.raw(t, "sheets_set_range", raw); r.Code != 422 {
+ t.Fatal("Unicode", r.Code)
+ }
+ in.Cells = []sheetAgentCell{}
+ for i := 0; i < 500; i++ {
+ in.Cells = append(in.Cells, sheetAgentCell{Row: i, Column: 0, Raw: strings.Repeat("x", 3000)})
+ }
+ if r := f.call(t, "sheets_set_range", in); r.Code != 413 {
+ t.Fatal("request cap", r.Code)
+ }
+ var n int64
+ f.a.app.db.Model(&sheetAgentEdit{}).Count(&n)
+ if n != 0 {
+ t.Fatal("invalid input wrote receipts")
+ }
+}
+func TestAgentRangeEditEmissionRequiresEditor(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ made := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
+ in := rangeEdit(made)
+ checks := 0
+ handler, e := f.a.httpHandler(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ checks++
+ if checks == 4 {
+ if e := f.a.app.db.Model(&Grant{}).Where("sheet_id=?", made.SheetID).Update("role", SheetViewer).Error; e != nil {
+ t.Fatal(e)
+ }
+ }
+ return f.p, nil
+ }))
+ if e != nil {
+ t.Fatal(e)
+ }
+ f.a.app.agent = handler
+ if r := f.call(t, "sheets_set_range", in); r.Code != 404 {
+ t.Fatal("viewer received edit acknowledgement", r.Code, r.Body.String())
+ }
+ var n int64
+ f.a.app.db.Model(&sheetAgentEdit{}).Count(&n)
+ if n != 1 {
+ t.Fatal("test did not revoke after commit")
+ }
+}
+func TestAgentRangeEditRestart(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ made := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
+ in := rangeEdit(made)
+ ack := decodeSheetCreated(t, f.call(t, "sheets_set_range", in))
+ var path string
+ if e := f.a.app.db.Raw("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path).Error; e != nil {
+ t.Fatal(e)
+ }
+ writer, e := f.a.app.db.DB()
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = writer.Close(); e != nil {
+ t.Fatal(e)
+ }
+ reopened, e := rdb.Open(path, quietLogger())
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer reopened.Close()
+ sealer, e := seal.New(make([]byte, dekBytes))
+ if e != nil {
+ t.Fatal(e)
+ }
+ app := New(Config{DB: reopened.G, Sealer: sealer, Origin: testOrigin, Admit: Admits([]string{signedInAddress})})
+ cfg := f.credentials()
+ auth, e := NewAuth(reopened.Writer(), AuthEnv{Origin: testOrigin, InstanceKey: "test-instance-key", Owners: []string{signedInAddress}, Home: cfg, Mailer: f.home.app.testMailer(t)}, quietLogger(), app)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer CloseSigninMail(auth)
+ app.UseAuth(auth)
+ if e = app.ConfigureHome(cfg); e != nil {
+ t.Fatal(e)
+ }
+ if e = app.ConfigureAgentAccess(f.a.issuer, f.a.team, cfg); e != nil {
+ t.Fatal(e)
+ }
+ a := *f.a
+ a.app = app
+ fresh := &sheetAgentFixture{home: f.home, a: &a, p: f.p}
+ fresh.install(t)
+ if got := decodeSheetCreated(t, fresh.call(t, "sheets_set_range", in)); got != ack {
+ t.Fatal("reopened receipt changed", got, ack)
+ }
+}
+func testAgentRangeEditGuardLapse(t *testing.T) {
+ f, af, _ := newTeamSheetAgent(t)
+ made := decodeSheetCreated(t, af.call(t, "sheets_create", teamSheetInput()))
+ in := rangeEdit(made)
+ in.Team = teamTestTeam
+ before := editCounts(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(t)
+ return nil
+ })
+ }
+ r := af.call(t, "sheets_set_range", in)
+ if r.Code != 503 || !reflect.DeepEqual(before, editCounts(t, af)) {
+ t.Fatal("last team guard omitted", r.Code, r.Body.String())
+ }
+}
+
+func TestAgentRangeEditUsesWriteScope(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ made := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
+ in := rangeEdit(made)
+ f.p.Scopes = []string{"sheets:write"}
+ decodeSheetCreated(t, f.call(t, "sheets_set_range", in))
+ f.p.Scopes = []string{"sheets:read"}
+ if r := f.call(t, "sheets_set_range", in); r.Code != 403 {
+ t.Fatal("read scope edited", r.Code)
+ }
+ f.p.Scopes = []string{"sheets:write"}
+ n := 0
+ handler, e := f.a.httpHandler(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ n++
+ p := f.p
+ if n > 1 {
+ p.Scopes = []string{"sheets:read"}
+ }
+ return p, nil
+ }))
+ if e != nil {
+ t.Fatal(e)
+ }
+ f.a.app.agent = handler
+ if r := f.call(t, "sheets_set_range", in); r.Code != 403 {
+ t.Fatal("lost write scope replayed", r.Code)
+ }
+}
+
+func TestAgentRangeEditUnboundReceiptRefused(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ made := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
+ in := rangeEdit(made)
+ decodeSheetCreated(t, f.call(t, "sheets_set_range", in))
+ // Isolate edit receipts: creation state cannot mask a missing adoption gate.
+ for _, table := range []string{"sheets_agent_receipts", "sheets_agent_attribution", "sheets_agent_state"} {
+ if e := f.a.app.db.Exec("DELETE FROM " + table).Error; e != nil {
+ t.Fatal(e)
+ }
+ }
+ if r := f.call(t, "sheets_set_range", in); r.Code != 503 {
+ t.Fatal("unbound old edit adopted", r.Code)
+ }
+}
diff --git a/internal/sheets/agent_edit_test.go b/internal/sheets/agent_edit_test.go
new file mode 100644
index 0000000..3ae6ef2
--- /dev/null
+++ b/internal/sheets/agent_edit_test.go
@@ -0,0 +1,294 @@
+package sheets
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "reflect"
+ "strconv"
+ "sync"
+ "testing"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/teammode"
+ "amadan.net/oficina/sheets/internal/sheets/store"
+ "github.com/google/uuid"
+)
+
+func rangeEdit(m sheetAgentCreated) sheetAgentSetRange {
+ return sheetAgentSetRange{Team: "blue", SheetID: m.SheetID, TabID: m.TabID, ExpectedRevision: m.Revision, ClientID: uuid.NewString(), Cells: []sheetAgentCell{{Row: 0, Column: 0, Raw: "32"}, {Row: 0, Column: 1, Raw: ""}}}
+}
+func editCounts(t *testing.T, f *sheetAgentFixture) []int64 {
+ t.Helper()
+ var out []int64
+ for _, name := range []string{"cells", "rows", "cols", "events", "sheets_agent_edits"} {
+ var n int64
+ if e := f.a.app.db.Table(name).Count(&n).Error; e != nil {
+ t.Fatal(e)
+ }
+ out = append(out, n)
+ }
+ return out
+}
+func TestAgentRangeEditParityAndLaterRetry(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ made := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
+ id, _ := sheetAgentID(made.TabID)
+ h, e := store.Open(f.a.app.db, f.a.app.sealer, id)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer h.Release()
+ in := rangeEdit(made)
+ sub := f.a.app.hub.Subscribe(id)
+ defer sub.Close()
+ ack := decodeSheetCreated(t, f.call(t, "sheets_set_range", in))
+ select {
+ case msg := <-sub.C():
+ if !bytes.Contains(msg.Data, []byte("64")) {
+ t.Fatal("incomplete native publication", string(msg.Data))
+ }
+ default:
+ t.Fatal("missing native publication")
+ }
+ snap, e := h.ReadRange(0, 0, 2, 2)
+ if e != nil {
+ t.Fatal(e)
+ }
+ b, _ := json.Marshal(snap)
+ if !bytes.Contains(b, []byte("64")) || snap.Version != h.Version() || ack.Revision != strconv.FormatUint(snap.Version, 10) {
+ t.Fatal("native formula/revision mismatch", string(b), ack)
+ }
+ // A browser's native batch after our commit must never be overwritten by replay.
+ if _, e = h.SetBatch([]store.CellWrite{{Row: 0, Col: 0, Raw: "75"}}, 1); e != nil {
+ t.Fatal(e)
+ }
+ before := editCounts(t, f)
+ version := h.Version()
+ if replay := decodeSheetCreated(t, f.call(t, "sheets_set_range", in)); replay != ack {
+ t.Fatal("receipt changed", replay, ack)
+ }
+ select {
+ case <-sub.C():
+ t.Fatal("retry published a duplicate edit")
+ default:
+ }
+ if !reflect.DeepEqual(before, editCounts(t, f)) || h.Version() != version {
+ t.Fatal("retry applied another edit")
+ }
+ read := f.call(t, "sheets_get_range", f.rangeInput(made))
+ if read.Code != 200 || !bytes.Contains(read.Body.Bytes(), []byte("150")) {
+ t.Fatal("later browser value lost", read.Body.String())
+ }
+ stale := in
+ stale.ClientID = uuid.NewString()
+ if r := f.call(t, "sheets_set_range", stale); r.Code != 409 {
+ t.Fatal("stale overwrite", r.Code, r.Body.String())
+ }
+ changed := in
+ changed.Cells = append([]sheetAgentCell(nil), in.Cells...)
+ changed.Cells[0].Raw = "90"
+ if r := f.call(t, "sheets_set_range", changed); r.Code != 409 {
+ t.Fatal("payload reuse", r.Code)
+ }
+ var receipt sheetAgentEdit
+ if e = f.a.app.db.First(&receipt).Error; e != nil {
+ t.Fatal(e)
+ }
+ var attributed []store.Event
+ if e = f.a.app.db.Where("tab_id=? AND kind=? AND id>=? AND id<=?", id, store.KindInput, receipt.FirstEventID, receipt.LastEventID).Order("id").Find(&attributed).Error; e != nil {
+ t.Fatal(e)
+ }
+ if len(attributed) != len(in.Cells) || receipt.FirstEventID == 0 || attributed[0].ID != receipt.FirstEventID || attributed[len(attributed)-1].ID != receipt.LastEventID {
+ t.Fatal("receipt does not name the exact native input events", receipt, attributed)
+ }
+ for _, event := range attributed {
+ if event.ActorID != receipt.MemberID {
+ t.Fatal("connection and native actor disagree")
+ }
+ }
+ plain, e := f.a.app.sealer.Open("agent.edit.client/"+receipt.Coordinate, receipt.ClientSealed)
+ if e != nil || string(plain) != f.p.Client || bytes.Contains(receipt.ClientSealed, []byte(f.p.Client)) {
+ t.Fatal("attribution", e)
+ }
+}
+func TestAgentRangeEditAtomicFailures(t *testing.T) {
+ for _, sql := range []string{
+ `CREATE TRIGGER edit_fail BEFORE INSERT ON sheets_agent_edits BEGIN SELECT RAISE(ABORT,'receipt failure'); END`,
+ `CREATE TRIGGER edit_fail AFTER INSERT ON sheets_agent_edits BEGIN DELETE FROM home_identity_links; END`,
+ `CREATE TRIGGER edit_fail AFTER INSERT ON sheets_agent_edits BEGIN UPDATE home_identity_links SET person_binding=zeroblob(32); END`,
+ `CREATE TRIGGER edit_fail AFTER INSERT ON sheets_agent_edits BEGIN UPDATE grants SET role='viewer'; END`,
+ } {
+ t.Run(sql, func(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ made := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
+ in := rangeEdit(made)
+ in.Cells = append(in.Cells, sheetAgentCell{Row: 30, Column: 40, Raw: "secret-new-axis"})
+ id, _ := sheetAgentID(made.TabID)
+ h, e := store.Open(f.a.app.db, f.a.app.sealer, id)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer h.Release()
+ before, e := h.ReadRange(0, 0, 2, 2)
+ if e != nil {
+ t.Fatal(e)
+ }
+ counts := editCounts(t, f)
+ if e = f.a.app.db.Exec(sql).Error; e != nil {
+ t.Fatal(e)
+ }
+ r := f.call(t, "sheets_set_range", in)
+ if r.Code == 200 {
+ t.Fatal("failed edit acknowledged")
+ }
+ after, e := h.ReadRange(0, 0, 2, 2)
+ if e != nil || !reflect.DeepEqual(before, after) || !reflect.DeepEqual(counts, editCounts(t, f)) {
+ t.Fatal("rollback leaked graph/storage", e, r.Code)
+ }
+ if e = f.a.app.db.Exec("DROP TRIGGER edit_fail").Error; e != nil {
+ t.Fatal(e)
+ }
+ decodeSheetCreated(t, f.call(t, "sheets_set_range", in))
+ })
+ }
+}
+func TestAgentRangeEditConcurrency(t *testing.T) {
+ for _, same := range []bool{true, false} {
+ t.Run(strconv.FormatBool(same), func(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ made := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
+ in := rangeEdit(made)
+ 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, "sheets_set_range", 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)
+ }
+ var n int64
+ f.a.app.db.Model(&sheetAgentEdit{}).Count(&n)
+ if n != 1 {
+ t.Fatal(n)
+ }
+ })
+ }
+}
+func TestAgentRangeEditWriterGuardsWithoutEmission(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 := newSheetAgentFixture(t)
+ made := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
+ in := rangeEdit(made)
+ if retry {
+ decodeSheetCreated(t, f.call(t, "sheets_set_range", in))
+ }
+ // If the early guard is removed, a fresh edit hits 503 before the final guard.
+ if !retry && phase == 1 {
+ if e := f.a.app.db.Exec(`CREATE TRIGGER trap BEFORE INSERT ON events BEGIN SELECT RAISE(ABORT,'early guard omitted'); END`).Error; e != nil {
+ t.Fatal(e)
+ }
+ }
+ m, e := f.a.member(t.Context(), f.p, true)
+ if e != nil {
+ t.Fatal(e)
+ }
+ n := 0
+ state := &sheetAgentContext{member: m, sheets: map[uint64]bool{}, verify: func(context.Context) error {
+ n++
+ if n == phase {
+ return access.Fail("unauthenticated", "Revoked")
+ }
+ return nil
+ }}
+ counts := editCounts(t, f)
+ ctx := context.WithValue(t.Context(), sheetAgentKey{}, state)
+ _, e = f.a.setRange(ctx, f.p, m, in)
+ if access.SafeFailure(e).Code != "unauthenticated" || n != phase {
+ t.Fatal("writer boundary", e, n)
+ }
+ if !reflect.DeepEqual(counts, editCounts(t, f)) {
+ t.Fatal("revoked writer committed")
+ }
+ })
+ }
+ }
+}
+func TestAgentRangeEditTeamSharesAndLapse(t *testing.T) {
+ f, af, m := newTeamSheetAgent(t)
+ made := decodeSheetCreated(t, af.call(t, "sheets_create", teamSheetInput()))
+ in := rangeEdit(made)
+ in.Team = teamTestTeam
+ // Independent editor grant, not the creator's self-grant.
+ if e := f.app.db.Model(&Grant{}).Where("sheet_id=?", made.SheetID).Update("granted_by", m.ID+1).Error; e != nil {
+ t.Fatal(e)
+ }
+ f.dir.Set(af.p.Subject, "")
+ f.refreshed(t)
+ ack := decodeSheetCreated(t, af.call(t, "sheets_set_range", in))
+ in.ClientID = uuid.NewString()
+ in.ExpectedRevision = ack.Revision
+ f.expired(t)
+ decodeSheetCreated(t, af.call(t, "sheets_set_range", in))
+ if e := f.app.db.Model(&Grant{}).Where("sheet_id=?", made.SheetID).Update("role", SheetViewer).Error; e != nil {
+ t.Fatal(e)
+ }
+ if r := af.call(t, "sheets_set_range", in); r.Code != 404 {
+ t.Fatal("viewer edit", r.Code)
+ }
+ for _, retry := range []bool{false, true} {
+ t.Run(strconv.FormatBool(retry), func(t *testing.T) {
+ f, af, _ := newTeamSheetAgent(t)
+ made := decodeSheetCreated(t, af.call(t, "sheets_create", teamSheetInput()))
+ in := rangeEdit(made)
+ in.Team = teamTestTeam
+ if retry {
+ decodeSheetCreated(t, af.call(t, "sheets_set_range", in))
+ }
+ m, e := af.a.member(t.Context(), af.p, true)
+ if e != nil {
+ t.Fatal(e)
+ }
+ n := 0
+ state := &sheetAgentContext{member: m, sheets: map[uint64]bool{}, verify: func(context.Context) error {
+ n++
+ if n == 2 {
+ f.expired(t)
+ }
+ return nil
+ }}
+ ctx := teammode.WithAccess(context.WithValue(t.Context(), sheetAgentKey{}, state), m.team.Access)
+ before := editCounts(t, af)
+ if _, e = af.a.setRange(ctx, af.p, m, in); e == nil {
+ t.Fatal("expired writer")
+ }
+ if !reflect.DeepEqual(before, editCounts(t, af)) {
+ t.Fatal("expired write effects")
+ }
+ })
+ }
+}
diff --git a/internal/sheets/agent_fixture_test.go b/internal/sheets/agent_fixture_test.go
new file mode 100644
index 0000000..09d0119
--- /dev/null
+++ b/internal/sheets/agent_fixture_test.go
@@ -0,0 +1,115 @@
+package sheets
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+type sheetAgentFixture struct {
+ home *homeFixture
+ a *sheetAgent
+ p access.Principal
+ revoked atomic.Bool
+ checks atomic.Int64
+ revokeAt atomic.Int64
+ verified chan struct{}
+}
+type agentDeadlineRecorder struct {
+ *httptest.ResponseRecorder
+ afterWrite func()
+}
+
+func (*agentDeadlineRecorder) SetWriteDeadline(time.Time) error { return nil }
+func (w *agentDeadlineRecorder) Write(body []byte) (int, error) {
+ n, e := w.ResponseRecorder.Write(body)
+ if w.afterWrite != nil {
+ f := w.afterWrite
+ w.afterWrite = nil
+ f()
+ }
+ return n, e
+}
+func newSheetAgentFixture(t *testing.T, issuers ...string) *sheetAgentFixture {
+ t.Helper()
+ home := newHomeFixture(t)
+ home.local(t, signedInAddress)
+ home.link(t, "opaque-owner")
+ issuer := "https://connect.oficina.works"
+ if len(issuers) > 0 {
+ issuer = issuers[0]
+ }
+ a := &sheetAgent{app: home.app, issuer: issuer, identityIssuer: homeTestIssuer, team: "blue", key: bytes.Repeat([]byte{81}, 32)}
+ if e := a.app.db.Transaction(func(tx *gorm.DB) error { return a.bind(tx) }); e != nil {
+ t.Fatal(e)
+ }
+ f := &sheetAgentFixture{home: home, a: a, p: access.Principal{Subject: "opaque-owner", Client: "test-client", Grant: "grant-one", Teams: []string{"blue"}, Scopes: []string{"sheets:read", "sheets:write"}}}
+ f.install(t)
+ return f
+}
+func (f *sheetAgentFixture) install(t *testing.T) {
+ t.Helper()
+ a := f.a
+ handler, e := a.httpHandler(access.VerifyFunc(func(ctx context.Context, token string) (access.Principal, error) {
+ n := f.checks.Add(1)
+ if n == 1 && f.verified != nil {
+ close(f.verified)
+ }
+ if at := f.revokeAt.Load(); at > 0 && n >= at {
+ f.revoked.Store(true)
+ }
+ if token != "test-token" || f.revoked.Load() {
+ return access.Principal{}, access.Fail("unauthenticated", "Connection expired.")
+ }
+ return f.p, nil
+ }))
+ if e != nil {
+ t.Fatal(e)
+ }
+ a.app.agent = handler
+}
+func (f *sheetAgentFixture) call(t *testing.T, name string, input any) *httptest.ResponseRecorder {
+ t.Helper()
+ raw, e := json.Marshal(input)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return f.raw(t, name, raw)
+}
+func (f *sheetAgentFixture) raw(t *testing.T, name string, raw []byte) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest("POST", testOrigin+"/api/v1/operations/"+name, bytes.NewReader(raw))
+ req.Header.Set("Authorization", "Bearer test-token")
+ req.Header.Set("Content-Type", "application/json")
+ w := &agentDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}
+ f.a.app.Router().ServeHTTP(w, req)
+ return w.ResponseRecorder
+}
+func initialSheetAgentInput() sheetAgentCreate {
+ return sheetAgentCreate{Team: "blue", ClientID: uuid.NewString(), Title: "PRIVATE_BUDGET_TITLE_42", TabName: "PRIVATE_TAB_NAME_42", Cells: []sheetAgentCell{{Row: 0, Column: 0, Raw: "21"}, {Row: 1, Column: 0, Raw: "=A1*2"}, {Row: 0, Column: 1, Raw: "PRIVATE_CELL_CANARY_42 ✓"}}}
+}
+func decodeSheetCreated(t *testing.T, rec *httptest.ResponseRecorder) sheetAgentCreated {
+ t.Helper()
+ if rec.Code != 200 {
+ t.Fatalf("create: %d %s", rec.Code, rec.Body.String())
+ }
+ var out sheetAgentCreated
+ if e := json.Unmarshal(rec.Body.Bytes(), &out); e != nil {
+ t.Fatal(e)
+ }
+ if out.SheetID == "" || out.TabID == "" || out.Revision == "" {
+ t.Fatal("incomplete creation receipt")
+ }
+ return out
+}
+func (f *sheetAgentFixture) rangeInput(created sheetAgentCreated) map[string]any {
+ return map[string]any{"team": "blue", "sheet_id": created.SheetID, "tab_id": created.TabID, "row": 0, "column": 0, "height": 2, "width": 2}
+}
diff --git a/internal/sheets/agent_integration_test.go b/internal/sheets/agent_integration_test.go
new file mode 100644
index 0000000..d2853dd
--- /dev/null
+++ b/internal/sheets/agent_integration_test.go
@@ -0,0 +1,171 @@
+package sheets
+
+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 Sheets' real handlers, linked identity, sealed spreadsheet content.
+// The signed Home/browser/PKCE flow is exercised in the connection module.
+func TestAgentGatewayToRealSheets(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 := newSheetAgentFixture(t, issuer.URL)
+ p := f.p
+ input, _ := json.Marshal(initialSheetAgentInput())
+ 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: homeTestIssuer, 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{"sheets:read": "Read spreadsheets", "sheets:write": "Create spreadsheets"}, 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", homeTestIssuer)
+ if err != nil {
+ t.Fatal(err)
+ }
+ remote.Client.Transport = issuer.Client().Transport
+ f.a.app.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, "sheets_create", json.RawMessage(input))
+ if err != nil {
+ t.Fatal(err)
+ }
+ encoded, _ := json.Marshal(result)
+ var spreadsheet sheetAgentCreated
+ if json.Unmarshal(encoded, &spreadsheet) != nil || spreadsheet.SheetID == "" {
+ t.Fatal("invalid spreadsheet receipt")
+ }
+ mcpClient := mcp.NewClient(&mcp.Implementation{Name: "Sheets 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: "sheets_create", Arguments: json.RawMessage(input)})
+ if err != nil || retry.IsError {
+ t.Fatal("MCP retry", retry, err)
+ }
+ search, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "sheets_get_range", Arguments: f.rangeInput(spreadsheet)})
+ if err != nil || search.IsError {
+ t.Fatal("MCP search", search, err)
+ }
+ text, _ := json.Marshal(search.Content)
+ if !strings.Contains(string(text), "PRIVATE_CELL_CANARY_42") {
+ t.Fatal("MCP could not read created spreadsheet")
+ }
+
+ edit := rangeEdit(spreadsheet)
+ edit.Cells = []sheetAgentCell{{Row: 0, Column: 0, Raw: "64"}}
+ rawEdit, _ := json.Marshal(edit)
+ if _, err = cli.Call(ctx, "sheets_set_range", json.RawMessage(rawEdit)); err != nil {
+ t.Fatal("CLI edit", err)
+ }
+ replayEdit, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "sheets_set_range", Arguments: json.RawMessage(rawEdit)})
+ if err != nil || replayEdit.IsError {
+ t.Fatal("MCP edit retry", replayEdit, err)
+ }
+ afterEdit, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "sheets_get_range", Arguments: f.rangeInput(spreadsheet)})
+ if err != nil || afterEdit.IsError {
+ t.Fatal("MCP edited read", afterEdit, err)
+ }
+ editedText, _ := json.Marshal(afterEdit.Content)
+ if !strings.Contains(string(editedText), "128") {
+ t.Fatal("formula edit did not reach MCP read", string(editedText))
+ }
+ var count int
+ if err = f.a.app.db.Raw("SELECT COUNT(*) FROM sheets").Scan(&count).Error; err != nil || count != 1 {
+ t.Fatal("transport retry duplicated spreadsheet", count, err)
+ }
+ if err = cli.Logout(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = session.CallTool(ctx, &mcp.CallToolParams{Name: "sheets_create", Arguments: initialSheetAgentInput()}); err == nil {
+ t.Fatal("MCP survived CLI revocation")
+ }
+ if err = f.a.app.db.Raw("SELECT COUNT(*) FROM sheets").Scan(&count).Error; err != nil || count != 1 {
+ t.Fatal("revoked call wrote spreadsheet", count, err)
+ }
+}
diff --git a/internal/sheets/agent_limits_test.go b/internal/sheets/agent_limits_test.go
new file mode 100644
index 0000000..20fb749
--- /dev/null
+++ b/internal/sheets/agent_limits_test.go
@@ -0,0 +1,128 @@
+package sheets
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/json"
+ "strings"
+ "sync"
+ "testing"
+
+ "amadan.net/oficina/home/connect"
+ "amadan.net/oficina/sheets/internal/sheets/store"
+)
+
+func (f *sheetAgentFixture) credentials() *connect.Credentials {
+ keys, _ := json.Marshal(map[string]string{"key": base64.StdEncoding.EncodeToString(f.home.key.SignPub())})
+ return &connect.Credentials{Issuer: homeTestIssuer, ConsumerID: "sheets-preview", KeysBase64: base64.StdEncoding.EncodeToString(keys), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{81}, 32))}
+}
+func TestAgentSheetProductionConfiguration(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ cfg := f.credentials()
+ if e := f.a.app.ConfigureAgentAccess(f.a.issuer, "blue", cfg); e != nil {
+ t.Fatal(e)
+ }
+ for _, pair := range [][2]string{{f.a.issuer, ""}, {"", "blue"}, {"http://insecure.example", "blue"}, {homeTestIssuer, "blue"}, {f.a.issuer, " blue"}} {
+ if e := f.a.app.ConfigureAgentAccess(pair[0], pair[1], cfg); e == nil {
+ t.Fatal("invalid enabled configuration", pair)
+ }
+ }
+ if e := f.a.app.ConfigureAgentAccess(f.a.issuer, "blue", nil); e == nil {
+ t.Fatal("enabled without Home")
+ }
+ for _, missing := range []string{"", "SHEETS_AGENT_ISSUER", "SHEETS_AGENT_TEAM", "SHEETS_HOME_ISSUER"} {
+ t.Run(missing, func(t *testing.T) {
+ env := goodEnv()
+ env["SHEETS_AGENT_ISSUER"] = f.a.issuer
+ env["SHEETS_AGENT_TEAM"] = "blue"
+ env["SHEETS_HOME_ISSUER"] = cfg.Issuer
+ env["SHEETS_HOME_CONSUMER_ID"] = cfg.ConsumerID
+ env["SHEETS_HOME_KEYS_BASE64"] = cfg.KeysBase64
+ env["SHEETS_HOME_DEK_BASE64"] = cfg.DEKBase64
+ if missing != "" {
+ delete(env, missing)
+ }
+ setEnv(t, env)
+ _, e := LoadAuthEnv(quietLogger())
+ if (e == nil) != (missing == "") {
+ t.Fatal("environment acceptance", missing, e)
+ }
+ })
+ }
+}
+func TestAgentSheetConcurrentFirstCreation(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ input := initialSheetAgentInput()
+ start := make(chan struct{})
+ responses := make(chan []byte, 6)
+ codes := make(chan int, 6)
+ var wg sync.WaitGroup
+ for i := 0; i < 6; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ rec := f.call(t, "sheets_create", input)
+ codes <- rec.Code
+ responses <- rec.Body.Bytes()
+ }()
+ }
+ close(start)
+ wg.Wait()
+ close(codes)
+ close(responses)
+ for code := range codes {
+ if code != 200 {
+ t.Fatal("concurrent initial request", code)
+ }
+ }
+ var first sheetAgentCreated
+ for raw := range responses {
+ var got sheetAgentCreated
+ if e := json.Unmarshal(raw, &got); e != nil {
+ t.Fatal(e)
+ }
+ if first.SheetID == "" {
+ first = got
+ }
+ if got != first || got.SheetID == "" {
+ t.Fatal("divergent first receipts", got, first)
+ }
+ }
+ for _, model := range []any{&store.Sheet{}, &store.Tab{}, &sheetAgentReceipt{}, &sheetAgentAttribution{}} {
+ var n int64
+ if e := f.a.app.db.Model(model).Count(&n).Error; e != nil || n != 1 {
+ t.Fatal("duplicate first creation", n, e)
+ }
+ }
+}
+func TestAgentSheetInputAndResultLimits(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ if rec := f.raw(t, "sheets_create", bytes.Repeat([]byte(" "), sheetAgentLimit+1)); rec.Code != 413 {
+ t.Fatal("oversize request", rec.Code)
+ }
+ input := initialSheetAgentInput()
+ input.Cells = nil
+ for i := 0; i < 20; i++ {
+ input.Cells = append(input.Cells, sheetAgentCell{Row: i, Column: 0, Raw: strings.Repeat("<", 4000)})
+ }
+ made := decodeSheetCreated(t, f.call(t, "sheets_create", input))
+ if got := decodeSheetCreated(t, f.call(t, "sheets_create", input)); got != made {
+ t.Fatal("large create not retryable")
+ }
+ args := f.rangeInput(made)
+ args["height"] = 20
+ args["width"] = 1
+ if rec := f.call(t, "sheets_get_range", args); rec.Code != 413 || strings.Contains(rec.Body.String(), "<<<<") {
+ t.Fatal("oversize result", rec.Code)
+ }
+ for _, change := range []map[string]any{{"height": 0}, {"width": 0}, {"height": 501}, {"height": 25, "width": 25}, {"row": 4999, "height": 2}, {"column": 599, "width": 2}} {
+ in := f.rangeInput(made)
+ for key, value := range change {
+ in[key] = value
+ }
+ if rec := f.call(t, "sheets_get_range", in); rec.Code != 422 {
+ t.Fatal("invalid range", change, rec.Code)
+ }
+ }
+}
diff --git a/internal/sheets/agent_operations.go b/internal/sheets/agent_operations.go
new file mode 100644
index 0000000..5d2808d
--- /dev/null
+++ b/internal/sheets/agent_operations.go
@@ -0,0 +1,146 @@
+package sheets
+
+import (
+ "context"
+ "encoding/json"
+
+ access "amadan.net/oficina/agent-access.git"
+ strictjson "github.com/go-json-experiment/json"
+)
+
+func sheetAgentObject(properties map[string]any, required ...string) json.RawMessage {
+ raw, _ := json.Marshal(map[string]any{"type": "object", "properties": properties, "required": required, "additionalProperties": false})
+ return raw
+}
+func sheetAgentString(max int) map[string]any {
+ return map[string]any{"type": "string", "maxLength": max}
+}
+func sheetAgentInteger(max int) map[string]any {
+ return map[string]any{"type": "integer", "minimum": 0, "maximum": max}
+}
+func sheetAgentIDSchema() map[string]any {
+ return map[string]any{"type": "string", "pattern": "^[1-9][0-9]{0,18}$"}
+}
+func (a *sheetAgent) registry() (*access.Registry, error) {
+ input := func(properties map[string]any, required ...string) json.RawMessage {
+ properties["team"] = map[string]any{"type": "string", "minLength": 1, "maxLength": 128}
+ return sheetAgentObject(properties, append([]string{"team"}, required...)...)
+ }
+ page := func(field string, item json.RawMessage) json.RawMessage {
+ return sheetAgentObject(map[string]any{field: map[string]any{"type": "array", "maxItems": 100, "items": item}, "next_cursor": sheetAgentString(19)}, field, "next_cursor")
+ }
+ summary := sheetAgentObject(map[string]any{"id": sheetAgentIDSchema(), "title": sheetAgentString(1024), "url": sheetAgentString(4096)}, "id", "title", "url")
+ tab := sheetAgentObject(map[string]any{"id": sheetAgentIDSchema(), "name": sheetAgentString(1024)}, "id", "name")
+ cell := sheetAgentObject(map[string]any{"row": sheetAgentInteger(4999), "column": sheetAgentInteger(599), "raw": sheetAgentString(8192)}, "row", "column", "raw")
+ value := sheetAgentObject(map[string]any{"row": sheetAgentInteger(4999), "column": sheetAgentInteger(599), "raw": sheetAgentString(8192), "kind": map[string]any{"enum": []string{"empty", "number", "string", "boolean", "error"}}, "value": map[string]any{"type": []string{"null", "number", "string", "boolean"}}, "display": sheetAgentString(sheetAgentLimit)}, "row", "column", "raw", "kind", "value", "display")
+ ops := []access.Operation{
+ {Name: "sheets_set_range", Description: "Atomically edit 1–500 cells at expected_revision. Keep cell order and client UUID on retry; revision in the acknowledgement is the original committed revision. Read again for current values.", Scope: "sheets:write", Idempotent: true, Input: input(map[string]any{"sheet_id": sheetAgentIDSchema(), "tab_id": sheetAgentIDSchema(), "expected_revision": sheetAgentIDSchema(), "client_id": sheetAgentString(36), "cells": map[string]any{"type": "array", "minItems": 1, "maxItems": 500, "items": cell}}, "sheet_id", "tab_id", "expected_revision", "client_id", "cells"), Output: sheetAgentObject(map[string]any{"sheet_id": sheetAgentIDSchema(), "tab_id": sheetAgentIDSchema(), "revision": sheetAgentIDSchema(), "url": sheetAgentString(4096)}, "sheet_id", "tab_id", "revision", "url"), Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ var in sheetAgentSetRange
+ if err := strictjson.Unmarshal(raw, &in); err != nil {
+ return nil, access.Fail("invalid", "Invalid range edit arguments.")
+ }
+ return a.setRange(ctx, p, sheetAgentMember(ctx), in)
+ }},
+ {Name: "sheets_list", Description: "List spreadsheets currently readable in this team.", Scope: "sheets:read", ReadOnly: true, Idempotent: true, Input: input(map[string]any{"limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 100}, "cursor": sheetAgentIDSchema()}), Output: page("sheets", summary), 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, sheetAgentMember(ctx), in.Limit, in.Cursor)
+ }},
+ {Name: "sheets_list_tabs", Description: "List tabs in one currently readable spreadsheet.", Scope: "sheets:read", ReadOnly: true, Idempotent: true, Input: input(map[string]any{"sheet_id": sheetAgentIDSchema(), "limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 100}, "cursor": sheetAgentIDSchema()}, "sheet_id"), Output: page("tabs", tab), Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ var in struct {
+ SheetID string `json:"sheet_id"`
+ Limit int `json:"limit"`
+ Cursor string `json:"cursor"`
+ }
+ if json.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Invalid tab pagination arguments.")
+ }
+ id, err := sheetAgentID(in.SheetID)
+ if err != nil {
+ return nil, err
+ }
+ return a.tabs(ctx, sheetAgentMember(ctx), id, in.Limit, in.Cursor)
+ }},
+ {Name: "sheets_get_range", Description: "Read at most 500 cells with raw input, calculated values and one coherent tab revision.", Scope: "sheets:read", ReadOnly: true, Idempotent: true, Input: input(map[string]any{"sheet_id": sheetAgentIDSchema(), "tab_id": sheetAgentIDSchema(), "row": sheetAgentInteger(4999), "column": sheetAgentInteger(599), "height": map[string]any{"type": "integer", "minimum": 1, "maximum": 500}, "width": map[string]any{"type": "integer", "minimum": 1, "maximum": 500}}, "sheet_id", "tab_id", "row", "column", "height", "width"), Output: sheetAgentObject(map[string]any{"sheet_id": sheetAgentIDSchema(), "tab_id": sheetAgentIDSchema(), "revision": sheetAgentIDSchema(), "cells": map[string]any{"type": "array", "maxItems": 500, "items": value}}, "sheet_id", "tab_id", "revision", "cells"), Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ var in struct {
+ SheetID string `json:"sheet_id"`
+ TabID string `json:"tab_id"`
+ Row int `json:"row"`
+ Column int `json:"column"`
+ Height int `json:"height"`
+ Width int `json:"width"`
+ }
+ if json.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Invalid range arguments.")
+ }
+ sheet, e := sheetAgentID(in.SheetID)
+ if e != nil {
+ return nil, e
+ }
+ tab, e := sheetAgentID(in.TabID)
+ if e != nil {
+ return nil, e
+ }
+ return a.readRange(ctx, sheetAgentMember(ctx), sheet, tab, in.Row, in.Column, in.Height, in.Width)
+ }},
+ {Name: "sheets_create", Description: "Create a spreadsheet and first tab with up to 500 initial cells; reuse the same client UUID only for retries.", Scope: "sheets:write", Idempotent: true, Input: input(map[string]any{"client_id": sheetAgentString(36), "title": map[string]any{"type": "string", "minLength": 1, "maxLength": 200}, "tab_name": map[string]any{"type": "string", "minLength": 1, "maxLength": 200}, "cells": map[string]any{"type": "array", "maxItems": 500, "items": cell}}, "client_id", "title", "tab_name", "cells"), Output: sheetAgentObject(map[string]any{"sheet_id": sheetAgentIDSchema(), "tab_id": sheetAgentIDSchema(), "revision": sheetAgentIDSchema(), "url": sheetAgentString(4096)}, "sheet_id", "tab_id", "revision", "url"), Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
+ var in sheetAgentCreate
+ if json.Unmarshal(raw, &in) != nil {
+ return nil, access.Fail("invalid", "Invalid initial sheet arguments.")
+ }
+ return a.create(ctx, p, sheetAgentMember(ctx), in)
+ }},
+ }
+ for i := range ops {
+ scope := ops[i].Scope
+ invoke := 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) > sheetAgentLimit {
+ 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.")
+ }
+ member, err := a.member(ctx, p, scope == "sheets:write")
+ if err != nil {
+ return nil, err
+ }
+ state, ok := ctx.Value(sheetAgentKey{}).(*sheetAgentContext)
+ if !ok || state == nil {
+ return nil, access.Fail("unavailable", "Request authority is unavailable.")
+ }
+ if state.member.ID != member.ID || state.member.Address != member.Address {
+ return nil, access.Fail("forbidden", "The current identity changed.")
+ }
+ state.member = member
+ return invoke(ctx, p, raw)
+ }
+ }
+ return access.NewRegistry(ops...)
+}
+func sheetAgentMember(ctx context.Context) Member {
+ if state, ok := ctx.Value(sheetAgentKey{}).(*sheetAgentContext); ok && state != nil {
+ return state.member
+ }
+ return Member{}
+}
+func AgentContracts() ([]access.Operation, error) {
+ a := &sheetAgent{team: "contract"}
+ registry, err := a.registry()
+ if err != nil {
+ return nil, err
+ }
+ return registry.List(access.Principal{Subject: "contract", Teams: []string{"contract"}, Scopes: []string{"sheets:read", "sheets:write"}}), nil
+}
diff --git a/internal/sheets/agent_read.go b/internal/sheets/agent_read.go
new file mode 100644
index 0000000..0eb037f
--- /dev/null
+++ b/internal/sheets/agent_read.go
@@ -0,0 +1,180 @@
+package sheets
+
+import (
+ "context"
+ "math"
+ "strconv"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/roster"
+ "amadan.net/oficina/sheets/internal/sheets/calc"
+ "amadan.net/oficina/sheets/internal/sheets/store"
+)
+
+type agentSheetSummary struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ URL string `json:"url"`
+}
+type agentTabSummary struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+}
+
+func agentPageSize(limit int) (int, error) {
+ if limit == 0 {
+ return 20, nil
+ }
+ if limit < 1 || limit > 100 {
+ return 0, access.Fail("invalid", "Choose a page size from 1 to 100.")
+ }
+ return limit, nil
+}
+func (a *sheetAgent) list(ctx context.Context, member Member, limit int, cursor string) (any, error) {
+ limit, err := agentPageSize(limit)
+ if err != nil {
+ return nil, err
+ }
+ if a.app.team != nil && member.team.state() == roster.Unknown {
+ return nil, sheetAgentFailure(errTeamUnavailable)
+ }
+ if state, ok := ctx.Value(sheetAgentKey{}).(*sheetAgentContext); ok {
+ state.list = true
+ }
+ team := a.app.teamRole(member) == TeamOwner || a.app.teamRole(member) == TeamMember
+ selfGrant := a.app.team == nil || team
+ q := a.app.db.WithContext(ctx).Model(&store.Sheet{}).Where("sheets.deleted_at IS NULL AND sheets.filling_since IS NULL").Where(`EXISTS(SELECT 1 FROM grants g WHERE g.sheet_id=sheets.id AND g.member_id=? AND g.role IN ('owner','editor','commenter','viewer') AND (? OR g.granted_by != g.member_id)) OR (? AND NOT EXISTS(SELECT 1 FROM grants g WHERE g.sheet_id=sheets.id AND g.member_id=?))`, member.ID, selfGrant, team, member.ID)
+ if cursor != "" {
+ id, e := sheetAgentID(cursor)
+ if e != nil {
+ return nil, e
+ }
+ q = q.Where("sheets.id < ?", id)
+ }
+ var rows []store.Sheet
+ if err = q.Order("sheets.id DESC").Limit(limit + 1).Find(&rows).Error; err != nil {
+ return nil, sheetAgentFailure(err)
+ }
+ next := ""
+ if len(rows) > limit {
+ rows = rows[:limit]
+ next = strconv.FormatUint(rows[len(rows)-1].ID, 10)
+ }
+ out := make([]agentSheetSummary, 0, len(rows))
+ for _, row := range rows {
+ title, e := store.ReadTitle(a.app.sealer, row)
+ if e != nil {
+ return nil, sheetAgentFailure(e)
+ }
+ a.remember(ctx, row.ID)
+ id := strconv.FormatUint(row.ID, 10)
+ out = append(out, agentSheetSummary{id, string(title), a.app.origin + "/sheets/" + id})
+ }
+ return sheetAgentBounded(struct {
+ Sheets []agentSheetSummary `json:"sheets"`
+ Next string `json:"next_cursor"`
+ }{out, next})
+}
+func (a *sheetAgent) tabs(ctx context.Context, member Member, sheetID uint64, limit int, cursor string) (any, error) {
+ role, err := a.role(ctx, a.app.db, sheetID, member)
+ if err != nil {
+ return nil, sheetAgentFailure(err)
+ }
+ if !role.Allows(SheetViewer) {
+ return nil, sheetAgentFailure(errNoAccess)
+ }
+ limit, err = agentPageSize(limit)
+ if err != nil {
+ return nil, err
+ }
+ q := a.app.db.WithContext(ctx).Where("sheet_id=?", sheetID)
+ if cursor != "" {
+ id, e := sheetAgentID(cursor)
+ if e != nil {
+ return nil, e
+ }
+ q = q.Where("id > ?", id)
+ }
+ var rows []store.Tab
+ if err = q.Order("id ASC").Limit(limit + 1).Find(&rows).Error; err != nil {
+ return nil, sheetAgentFailure(err)
+ }
+ next := ""
+ if len(rows) > limit {
+ rows = rows[:limit]
+ next = strconv.FormatUint(rows[len(rows)-1].ID, 10)
+ }
+ out := make([]agentTabSummary, 0, len(rows))
+ for _, row := range rows {
+ name, e := store.ReadTabName(a.app.sealer, row)
+ if e != nil {
+ return nil, sheetAgentFailure(e)
+ }
+ out = append(out, agentTabSummary{strconv.FormatUint(row.ID, 10), string(name)})
+ }
+ a.remember(ctx, sheetID)
+ return sheetAgentBounded(struct {
+ Tabs []agentTabSummary `json:"tabs"`
+ Next string `json:"next_cursor"`
+ }{out, next})
+}
+
+type agentRangeCell struct {
+ Row int `json:"row"`
+ Column int `json:"column"`
+ Raw string `json:"raw"`
+ Kind string `json:"kind"`
+ Value any `json:"value"`
+ Display string `json:"display"`
+}
+type agentRange struct {
+ SheetID string `json:"sheet_id"`
+ TabID string `json:"tab_id"`
+ Revision string `json:"revision"`
+ Cells []agentRangeCell `json:"cells"`
+}
+
+func (a *sheetAgent) readRange(ctx context.Context, member Member, sheetID, tabID uint64, row, col, height, width int) (any, error) {
+ if height < 1 || width < 1 || height > 500 || width > 500 || height > 500/width || !inCellRange(row, col) || !inCellRange(row+height-1, col+width-1) {
+ return nil, access.Fail("invalid", "Choose a supported range of at most 500 cells.")
+ }
+ if err := a.tab(ctx, a.app.db, sheetID, tabID, member); err != nil {
+ return nil, sheetAgentFailure(err)
+ }
+ handle, err := store.Open(a.app.db, a.app.sealer, tabID)
+ if err != nil {
+ return nil, sheetAgentFailure(err)
+ }
+ defer handle.Release()
+ snapshot, err := handle.ReadRange(row, col, height, width)
+ if err != nil {
+ return nil, sheetAgentFailure(err)
+ }
+ cells := make([]agentRangeCell, 0, len(snapshot.Cells))
+ for _, cell := range snapshot.Cells {
+ out := agentRangeCell{Row: cell.Row, Column: cell.Col, Raw: cell.Raw, Kind: "empty", Display: display(cell.Value, nil)}
+ switch cell.Value.Kind {
+ case calc.KindNum:
+ if math.IsNaN(cell.Value.Num) || math.IsInf(cell.Value.Num, 0) {
+ return nil, access.Fail("unavailable", "A calculated value is not finite.")
+ }
+ out.Kind = "number"
+ out.Value = cell.Value.Num
+ case calc.KindStr:
+ out.Kind = "string"
+ out.Value = cell.Value.Str
+ case calc.KindBool:
+ out.Kind = "boolean"
+ out.Value = cell.Value.Bool
+ case calc.KindErr:
+ out.Kind = "error"
+ out.Value = out.Display
+ case calc.KindEmpty:
+ default:
+ return nil, access.Fail("unavailable", "A calculated value is unavailable.")
+ }
+ cells = append(cells, out)
+ }
+ a.remember(ctx, sheetID)
+ return sheetAgentBounded(agentRange{strconv.FormatUint(sheetID, 10), strconv.FormatUint(tabID, 10), strconv.FormatUint(snapshot.Version, 10), cells})
+}
diff --git a/internal/sheets/agent_response.go b/internal/sheets/agent_response.go
new file mode 100644
index 0000000..9164d82
--- /dev/null
+++ b/internal/sheets/agent_response.go
@@ -0,0 +1,28 @@
+package sheets
+
+import (
+ "amadan.net/oficina/home/roster"
+ "context"
+)
+
+// Check standing after the last permission query. An independent grant may
+// remain valid while the list's team-wide authority expires during that read.
+func (a *sheetAgent) checkVisible(ctx context.Context, state *sheetAgentContext, fresh Member) error {
+ for id := range state.sheets {
+ role, err := a.role(ctx, a.app.db, id, fresh)
+ if err != nil {
+ return err
+ }
+ need := SheetViewer
+ if state.edits[id] {
+ need = SheetEditor
+ }
+ if !role.Allows(need) {
+ return errNoAccess
+ }
+ }
+ if state.list && a.app.team != nil && fresh.team.state() == roster.Unknown {
+ return errTeamUnavailable
+ }
+ return nil
+}
diff --git a/internal/sheets/agent_response_test.go b/internal/sheets/agent_response_test.go
new file mode 100644
index 0000000..5efffc6
--- /dev/null
+++ b/internal/sheets/agent_response_test.go
@@ -0,0 +1,95 @@
+package sheets
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+type agentRevokingWriter struct {
+ http.ResponseWriter
+ revoke func()
+}
+
+func (w *agentRevokingWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+func (w *agentRevokingWriter) Write(body []byte) (int, error) {
+ n, e := w.ResponseWriter.Write(body)
+ if w.revoke != nil {
+ f := w.revoke
+ w.revoke = nil
+ f()
+ }
+ return n, e
+}
+func TestAgentSheetResponseRevocation(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ input := initialSheetAgentInput()
+ input.Cells = nil
+ for i := 0; i < 20; i++ {
+ input.Cells = append(input.Cells, sheetAgentCell{Row: i, Column: 0, Raw: strings.Repeat("z", 4000)})
+ }
+ made := decodeSheetCreated(t, f.call(t, "sheets_create", input))
+ f.checks.Store(0)
+ f.revokeAt.Store(2)
+ if rec := f.call(t, "sheets_get_range", f.rangeInput(made)); rec.Code != 401 || strings.Contains(rec.Body.String(), "zzzz") {
+ t.Fatal("response escaped final check", rec.Code)
+ }
+ f.revoked.Store(false)
+ f.revokeAt.Store(0)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ f.a.app.Router().ServeHTTP(&agentRevokingWriter{w, func() { f.revoked.Store(true) }}, r)
+ }))
+ defer server.Close()
+ args := f.rangeInput(made)
+ args["height"] = 20
+ args["width"] = 1
+ raw, _ := json.Marshal(args)
+ req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/sheets_get_range", 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("first response chunk missing", e)
+ }
+ defer res.Body.Close()
+ body, e := io.ReadAll(res.Body)
+ if !errors.Is(e, io.ErrUnexpectedEOF) || res.StatusCode != 200 || len(body) == 0 || len(body) > 64<<10 || json.Valid(body) {
+ t.Fatal("revoked stream completed", res.StatusCode, len(body), e)
+ }
+}
+func TestAgentSheetExactLargeIDsAndPagination(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ const base = int64(9007199254740992)
+ for _, table := range []string{"sheets", "tabs"} {
+ if e := f.a.app.db.Exec("INSERT INTO sqlite_sequence(name,seq) VALUES(?,?)", table, base).Error; e != nil {
+ t.Fatal(e)
+ }
+ }
+ first := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
+ if first.SheetID != strconv.FormatInt(base+1, 10) || first.TabID != strconv.FormatInt(base+1, 10) {
+ t.Fatal("large ID lost", first)
+ }
+ second := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
+ type result struct {
+ Sheets []agentSheetSummary `json:"sheets"`
+ Next string `json:"next_cursor"`
+ }
+ var page result
+ rec := f.call(t, "sheets_list", map[string]any{"team": "blue", "limit": 1})
+ if e := json.Unmarshal(rec.Body.Bytes(), &page); e != nil || rec.Code != 200 || len(page.Sheets) != 1 || page.Sheets[0].ID != second.SheetID || page.Next != second.SheetID {
+ t.Fatal("first page", rec.Body.String(), e)
+ }
+ rec = f.call(t, "sheets_list", map[string]any{"team": "blue", "limit": 1, "cursor": page.Next})
+ if e := json.Unmarshal(rec.Body.Bytes(), &page); e != nil || rec.Code != 200 || len(page.Sheets) != 1 || page.Sheets[0].ID != first.SheetID || page.Next != "" {
+ t.Fatal("second page", rec.Body.String(), e)
+ }
+ if rec = f.call(t, "sheets_get_range", f.rangeInput(first)); rec.Code != 200 {
+ t.Fatal("large-ID range", rec.Code, rec.Body.String())
+ }
+}
diff --git a/internal/sheets/agent_storage_test.go b/internal/sheets/agent_storage_test.go
new file mode 100644
index 0000000..eb04a63
--- /dev/null
+++ b/internal/sheets/agent_storage_test.go
@@ -0,0 +1,118 @@
+package sheets
+
+import (
+ "amadan.net/oficina/sheets/internal/sheets/seal"
+ "bytes"
+ "net/http/httptest"
+ "testing"
+
+ rdb "amadan.net/rastrillo/rastrillo/db"
+ "gorm.io/gorm"
+)
+
+func TestAgentSheetReceiptRestartAndAttribution(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ input := initialSheetAgentInput()
+ created := decodeSheetCreated(t, f.call(t, "sheets_create", input))
+ var attribution sheetAgentAttribution
+ if e := f.a.app.db.First(&attribution, "sheet_id=?", created.SheetID).Error; e != nil {
+ t.Fatal(e)
+ }
+ plain, e := f.a.app.sealer.Open("agent.client/"+created.SheetID, attribution.ClientSealed)
+ if e != nil || string(plain) != f.p.Client || bytes.Contains(attribution.ClientSealed, []byte(f.p.Client)) {
+ t.Fatal("client attribution is not sealed and recoverable", e)
+ }
+ member, e := f.a.member(t.Context(), f.p, false)
+ if e != nil || member.ID != attribution.MemberID {
+ t.Fatal("operator attribution", e)
+ }
+ var files []struct{ Name, File string }
+ if e = f.a.app.db.Raw("PRAGMA database_list").Scan(&files).Error; e != nil {
+ t.Fatal(e)
+ }
+ path := ""
+ for _, file := range files {
+ if file.Name == "main" {
+ path = file.File
+ }
+ }
+ d, e := f.a.app.db.DB()
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = d.Close(); e != nil {
+ t.Fatal(e)
+ }
+ reopened, e := rdb.Open(path, quietLogger())
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer reopened.Close()
+ sealer, e := seal.New(make([]byte, dekBytes))
+ if e != nil {
+ t.Fatal(e)
+ }
+ app := New(Config{DB: reopened.G, Sealer: sealer, Origin: testOrigin, Admit: Admits([]string{signedInAddress})})
+ cfg := f.credentials()
+ auth, e := NewAuth(reopened.Writer(), AuthEnv{Origin: testOrigin, InstanceKey: "test-instance-key", Owners: []string{signedInAddress}, Home: cfg, Mailer: f.home.app.testMailer(t)}, quietLogger(), app)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer CloseSigninMail(auth)
+ app.UseAuth(auth)
+ if e = app.ConfigureHome(cfg); e != nil {
+ t.Fatal(e)
+ }
+ if e = app.ConfigureAgentAccess(f.a.issuer, f.a.team, cfg); e != nil {
+ t.Fatal(e)
+ }
+ a := *f.a
+ a.app = app
+ restarted := &sheetAgentFixture{home: f.home, a: &a, p: f.p}
+ restarted.install(t)
+ if got := decodeSheetCreated(t, restarted.call(t, "sheets_create", input)); got != created {
+ t.Fatal("restart replay changed receipt", got, created)
+ }
+
+ if e = reopened.G.Transaction(func(tx *gorm.DB) error { return a.bind(tx) }); e != nil {
+ t.Fatal("unchanged restart refused", e)
+ }
+ coordinate := a.digest("coordinate", []string{a.identityIssuer, a.issuer, f.p.Subject, f.p.Client, a.team, input.ClientID})
+ var receipt sheetAgentReceipt
+ if e = reopened.G.First(&receipt, "coordinate=?", coordinate).Error; e != nil || receipt.SheetID != attribution.SheetID {
+ t.Fatal("receipt did not survive restart", e)
+ }
+ a.issuer = "https://other-connect.example"
+ if e = reopened.G.Transaction(func(tx *gorm.DB) error { return a.bind(tx) }); e == nil {
+ t.Fatal("restart changed authority")
+ }
+}
+func TestAgentSheetReservedWriterRevocationAndCookieRefusal(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ f.revokeAt.Store(2)
+ if rec := f.call(t, "sheets_create", initialSheetAgentInput()); rec.Code != 401 {
+ t.Fatal("reserved writer used revoked delegation", rec.Code)
+ }
+ assertAgentSheetEmpty(t, f)
+ req := httptest.NewRequest("GET", testOrigin+"/api/v1/operations", nil)
+ for _, cookie := range f.home.jar {
+ req.AddCookie(cookie)
+ }
+ rec := httptest.NewRecorder()
+ f.a.app.Router().ServeHTTP(rec, req)
+ if rec.Code != 401 {
+ t.Fatal("browser cookie authenticated agent API", rec.Code)
+ }
+}
+func TestAgentSheetAuthorityStorageFailure(t *testing.T) {
+ f := newSheetAgentFixture(t)
+ created := decodeSheetCreated(t, f.call(t, "sheets_create", initialSheetAgentInput()))
+ if e := f.a.app.db.Exec("ALTER TABLE grants RENAME TO unavailable_grants").Error; e != nil {
+ t.Fatal(e)
+ }
+ for name, args := range map[string]any{"sheets_list": map[string]any{"team": "blue"}, "sheets_get_range": f.rangeInput(created)} {
+ if rec := f.call(t, name, args); rec.Code != 503 {
+ t.Fatal("authority failure hidden", name, rec.Code)
+ }
+ }
+}
diff --git a/internal/sheets/agent_team_compat_test.go b/internal/sheets/agent_team_compat_test.go
new file mode 100644
index 0000000..a3c9e72
--- /dev/null
+++ b/internal/sheets/agent_team_compat_test.go
@@ -0,0 +1,219 @@
+package sheets
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "testing"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/home/teammode"
+ "gorm.io/gorm"
+)
+
+func newTeamSheetAgent(t *testing.T) (*teamFixture, *sheetAgentFixture, Member) {
+ t.Helper()
+ f := newTeamFixture(t, signedInAddress)
+ m := f.local(t, signedInAddress)
+ subject := teamSubject('a')
+ f.link(t, subject)
+ f.dir.Set(subject, "member")
+ f.refreshed(t)
+ a := &sheetAgent{app: f.app, issuer: "https://connect.oficina.works", identityIssuer: homeTestIssuer, team: teamTestTeam, key: bytes.Repeat([]byte{81}, 32)}
+ if err := f.app.db.Transaction(func(tx *gorm.DB) error { return a.bind(tx) }); err != nil {
+ t.Fatal(err)
+ }
+ af := &sheetAgentFixture{home: f.homeFixture, a: a, p: access.Principal{Subject: subject, Client: "test-client", Grant: "grant-one", Teams: []string{teamTestTeam}, Scopes: []string{"sheets:read", "sheets:write"}}}
+ af.install(t)
+ return f, af, m
+}
+func teamSheetInput() sheetAgentCreate {
+ in := initialSheetAgentInput()
+ in.Team = teamTestTeam
+ return in
+}
+func teamSheetCounts(t *testing.T, f *teamFixture) []int64 {
+ t.Helper()
+ out := []int64{}
+ for _, table := range []string{"sheets", "tabs", "grants", "sheets_agent_receipts", "sheets_agent_attribution"} {
+ var n int64
+ if e := f.app.db.Table(table).Count(&n).Error; e != nil {
+ t.Fatal(e)
+ }
+ out = append(out, n)
+ }
+ return out
+}
+func TestAgentTeamSheetsMembershipAndIndependentShares(t *testing.T) {
+ f, af, m := newTeamSheetAgent(t)
+ // Stored role and local admission cannot supply (or deny) roster standing.
+ f.app.admit = func(string) bool { return false }
+ if e := f.app.db.Model(&Member{}).Where("id=?", m.ID).Update("team_role", TeamGuest).Error; e != nil {
+ t.Fatal(e)
+ }
+ mine := decodeSheetCreated(t, af.call(t, "sheets_create", teamSheetInput()))
+ shared := teamSheet(t, f, "Independent shared sheet")
+ other, err := f.app.memberFor("colleague@example.com")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = f.app.db.Create(&Grant{SheetID: shared.ID, MemberID: m.ID, GrantedBy: other.ID, Role: string(SheetViewer)}).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err = f.app.db.Model(&Member{}).Where("id=?", m.ID).Update("team_role", TeamOwner).Error; err != nil {
+ t.Fatal(err)
+ }
+ f.app.admit = func(string) bool { return true }
+ f.dir.Set(af.p.Subject, "")
+ f.refreshed(t)
+ if w := af.call(t, "sheets_create", teamSheetInput()); w.Code != 403 {
+ t.Fatal("removed creator", w.Code, w.Body.String())
+ }
+ tabs := func(id string) *httptest.ResponseRecorder {
+ return af.call(t, "sheets_list_tabs", map[string]any{"team": teamTestTeam, "sheet_id": id})
+ }
+ if w := tabs(mine.SheetID); w.Code != 404 {
+ t.Fatal("self grant survived removal", w.Code, w.Body.String())
+ }
+ if w := tabs(strconv.FormatUint(shared.ID, 10)); w.Code != 200 {
+ t.Fatal("independent share lost", w.Code, w.Body.String())
+ }
+ w := af.call(t, "sheets_list", map[string]any{"team": teamTestTeam, "limit": 1})
+ if w.Code != 200 || !strings.Contains(w.Body.String(), "Independent shared sheet") || strings.Contains(w.Body.String(), "PRIVATE_BUDGET") {
+ t.Fatal("list visibility", w.Code, w.Body.String())
+ }
+ f.expired(t)
+ if w := tabs(strconv.FormatUint(shared.ID, 10)); w.Code != 200 {
+ t.Fatal("share under Unknown", w.Code, w.Body.String())
+ }
+ if w := af.call(t, "sheets_list", map[string]any{"team": teamTestTeam}); w.Code != 503 {
+ t.Fatal("partial list presented as complete", w.Code, w.Body.String())
+ }
+ if w := af.call(t, "sheets_create", teamSheetInput()); w.Code != 503 {
+ t.Fatal("Unknown creator", w.Code)
+ }
+}
+
+// Reviewer-selected mutation targets: remove creatorInTx's last call or its
+// leased-standing check. Expiry is injected inside the writer, never at HTTP emission.
+func TestAgentTeamSheetsWriterExpiryAndCompletedRetry(t *testing.T) {
+ for _, retry := range []bool{false, true} {
+ t.Run(strconv.FormatBool(retry), func(t *testing.T) {
+ f, af, _ := newTeamSheetAgent(t)
+ in := teamSheetInput()
+ if retry {
+ decodeSheetCreated(t, af.call(t, "sheets_create", in))
+ }
+ before, _ := json.Marshal(teamSheetCounts(t, f))
+ m, err := af.a.member(t.Context(), af.p, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ n := 0
+ state := &sheetAgentContext{member: m, sheets: map[uint64]bool{}, verify: func(context.Context) error {
+ n++
+ if n == 2 {
+ f.expired(t)
+ }
+ return nil
+ }}
+ ctx := teammode.WithAccess(context.WithValue(t.Context(), sheetAgentKey{}, state), m.team.Access)
+ if _, err = af.a.create(ctx, af.p, m, in); err == nil {
+ t.Fatal("expired writer accepted")
+ }
+ after, _ := json.Marshal(teamSheetCounts(t, f))
+ if !bytes.Equal(before, after) {
+ t.Fatal("expired write committed", string(before), string(after))
+ }
+ })
+ }
+}
+func TestAgentTeamSheetsHomeOnlyAndBindingRefused(t *testing.T) {
+ f, af, _ := newTeamSheetAgent(t)
+ subject := teamSubject('b')
+ f.dir.Set(subject, "member")
+ f.refreshed(t)
+ if w := f.signInHome(t, subject); w.Code != 303 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ before := memberCount(t, f)
+ af.p.Subject = subject
+ if w := af.call(t, "sheets_list", map[string]any{"team": teamTestTeam}); w.Code != 403 {
+ t.Fatal("HomeOnly accepted", w.Code)
+ }
+ if memberCount(t, f) != before {
+ t.Fatal("agent allocated identity")
+ }
+ fresh := newTeamFixture(t, signedInAddress)
+ if err := fresh.app.ConfigureAgentAccess("https://connect.oficina.works", "wrong-team", &fresh.creds); err == nil {
+ t.Fatal("foreign roster binding accepted")
+ }
+ var n int64
+ if err := fresh.app.db.Table("sheets_agent_state").Count(&n).Error; err != nil || n != 0 {
+ t.Fatal("bad binding wrote marker", n, err)
+ }
+}
+func TestAgentTeamSheetsLateUnknownListWithShares(t *testing.T) {
+ f, af, m := newTeamSheetAgent(t)
+ shared := teamSheet(t, f, "Independent share")
+ if err := f.app.db.Create(&Grant{SheetID: shared.ID, MemberID: m.ID, GrantedBy: m.ID + 1, Role: string(SheetViewer)}).Error; err != nil {
+ t.Fatal(err)
+ }
+ n := 0
+ handler, err := af.a.httpHandler(access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ n++
+ if n == 2 {
+ f.expired(t)
+ }
+ return af.p, nil
+ }))
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.app.agent = handler
+ if w := af.call(t, "sheets_list", map[string]any{"team": teamTestTeam}); w.Code != 503 || strings.Contains(w.Body.String(), "Independent share") {
+ t.Fatal("late partial list escaped", w.Code, w.Body.String())
+ }
+}
+
+// Exercise one response check, so a later chunk check cannot mask a missing
+// post-query list check. The independent grant itself remains valid throughout.
+func TestAgentTeamSheetsListExpiryDuringFinalGrantRead(t *testing.T) {
+ for _, list := range []bool{false, true} {
+ t.Run(strconv.FormatBool(list), func(t *testing.T) {
+ f, af, m := newTeamSheetAgent(t)
+ shared := teamSheet(t, f, "Independent share")
+ if err := f.app.db.Create(&Grant{SheetID: shared.ID, MemberID: m.ID, GrantedBy: m.ID + 1, Role: string(SheetViewer)}).Error; err != nil {
+ t.Fatal(err)
+ }
+ fresh, err := af.a.member(t.Context(), af.p, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ state := &sheetAgentContext{member: fresh, list: list, sheets: map[uint64]bool{shared.ID: true}}
+ triggered := false
+ if err = f.app.db.Callback().Query().After("gorm:query").Register("agent-test:expire-after-grant", func(tx *gorm.DB) {
+ if tx.Statement.Table == "grants" && !triggered {
+ triggered = true
+ f.expired(t)
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { f.app.db.Callback().Query().Remove("agent-test:expire-after-grant") })
+ err = af.a.checkVisible(t.Context(), state, fresh)
+ if !triggered {
+ t.Fatal("did not reach grant read")
+ }
+ if list && err == nil {
+ t.Fatal("list accepted Unknown reached during final grant lookup")
+ }
+ if !list && err != nil {
+ t.Fatal("exact independent grant refused", err)
+ }
+ })
+ }
+}
diff --git a/internal/sheets/agent_team_lease_test.go b/internal/sheets/agent_team_lease_test.go
new file mode 100644
index 0000000..9d63385
--- /dev/null
+++ b/internal/sheets/agent_team_lease_test.go
@@ -0,0 +1,80 @@
+package sheets
+
+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, _ := newTeamSheetAgent(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.app.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/sheets_list", 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/sheets/app.go b/internal/sheets/app.go
index 4595114..bbbe54c 100644
--- a/internal/sheets/app.go
+++ b/internal/sheets/app.go
@@ -58,6 +58,7 @@ type Config struct {
// App holds the wiring. One per process.
type App struct {
+ agent http.Handler
dashboard http.Handler
native *nativeauth.Auth
home *connect.Bridge
@@ -272,10 +273,7 @@ func (a *App) Router() http.Handler {
// constraint and not a preference.
r.Post("/sheets/{sheetID}/view", a.handleViewSave)
- // The grid's own API. Under /api because it answers JSON and
- // carries no chrome; behind the same session as everything
- // else, because a sheet is a sheet whichever content type you
- // ask for it in.
+ // The grid API answers JSON behind the same session as the pages.
r.Get("/api/sheets/{sheetID}/tabs/{tabID}/cells", a.handleCellsGet)
r.Post("/api/sheets/{sheetID}/tabs/{tabID}/cells", a.handleCellPost)
r.Post("/api/sheets/{sheetID}/tabs/{tabID}/cells/batch", a.handleCellBatchPost)
@@ -296,5 +294,5 @@ func (a *App) Router() http.Handler {
r.Get("/jobs/{id}/fragment", a.jobPages.Fragment)
r.Get("/jobs/{id}/events", a.jobPages.Events)
})
- return r
+ return a.agentRoutes(r)
}
diff --git a/internal/sheets/auth.go b/internal/sheets/auth.go
index b50f604..41fbef2 100644
--- a/internal/sheets/auth.go
+++ b/internal/sheets/auth.go
@@ -19,7 +19,9 @@ import (
// AuthEnv is everything sign-in needs from the environment, already
// validated. Building it is the only place these variable names appear.
type AuthEnv struct {
- Home *connect.Credentials
+ AgentIssuer string
+ AgentTeam string
+ Home *connect.Credentials
// Team is team mode's configuration (teammode.ConfigFromEnv), nil
// unless a SHEETS_TEAM_* variable is set. With it the roster is the
// team and SHEETS_OWNERS is optional: if set, it only admits local
@@ -82,6 +84,8 @@ func loopback(origin string) bool {
// any address. Both serve pages and answer /healthz.
func LoadAuthEnv(logger *slog.Logger) (AuthEnv, error) {
env := AuthEnv{
+ AgentIssuer: os.Getenv("SHEETS_AGENT_ISSUER"),
+ AgentTeam: os.Getenv("SHEETS_AGENT_TEAM"),
Home: connect.CredentialsFromEnv("SHEETS"),
Origin: strings.TrimSpace(os.Getenv("SHEETS_ORIGIN")),
InstanceKey: strings.TrimSpace(os.Getenv("SHEETS_INSTANCE_KEY")),
@@ -121,6 +125,9 @@ func LoadAuthEnv(logger *slog.Logger) (AuthEnv, error) {
if _, err := connect.DecodeCredentials(env.Home, env.Origin); err != nil {
return AuthEnv{}, errHome
}
+ if err := validateAgentConfig(env.AgentIssuer, env.AgentTeam, env.Origin, env.Home); err != nil {
+ return AuthEnv{}, err
+ }
env.Mailer = mail.FromEnv("CARLOS", logger)
return env, nil
diff --git a/internal/sheets/auth_test.go b/internal/sheets/auth_test.go
index 775a114..b71d189 100644
--- a/internal/sheets/auth_test.go
+++ b/internal/sheets/auth_test.go
@@ -19,6 +19,7 @@ func setEnv(t *testing.T, kv map[string]string) {
t.Helper()
for _, k := range []string{
"SHEETS_ORIGIN", "SHEETS_INSTANCE_KEY", "SHEETS_OWNERS",
+ "SHEETS_AGENT_ISSUER", "SHEETS_AGENT_TEAM",
"SHEETS_HOME_ISSUER", "SHEETS_HOME_CONSUMER_ID", "SHEETS_HOME_KEYS_BASE64", "SHEETS_HOME_DEK_BASE64",
"CARLOS_SMTP_HOST", "CARLOS_SMTP_FROM",
} {
diff --git a/internal/sheets/migrations.go b/internal/sheets/migrations.go
index 1d3dc18..3b8622c 100644
--- a/internal/sheets/migrations.go
+++ b/internal/sheets/migrations.go
@@ -52,6 +52,7 @@ var BootSchema = migrate.Merge(migrate.MustFromFS(dashboard.Migrations, "oficina
// structs live where they belong. See store/models.go for why they
// moved.
var Models = []any{
+ sheetAgentState{}, sheetAgentReceipt{}, sheetAgentAttribution{}, sheetAgentEdit{},
store.Sheet{}, store.Tab{}, store.Row{}, store.Col{},
store.Cell{}, store.Format{}, store.Event{}, Member{}, Grant{}, ShareLink{}, Comment{}, TabView{},
}
diff --git a/internal/sheets/migrations/0011_agent_access.sql b/internal/sheets/migrations/0011_agent_access.sql
new file mode 100644
index 0000000..3c8845a
--- /dev/null
+++ b/internal/sheets/migrations/0011_agent_access.sql
@@ -0,0 +1,14 @@
+CREATE TABLE sheets_agent_state (
+ id INTEGER PRIMARY KEY CHECK(id=1),
+ keycheck TEXT NOT NULL
+);
+CREATE TABLE sheets_agent_receipts (
+ coordinate TEXT PRIMARY KEY NOT NULL,
+ content TEXT NOT NULL,
+ sheet_id INTEGER NOT NULL
+);
+CREATE TABLE sheets_agent_attribution (
+ sheet_id INTEGER PRIMARY KEY NOT NULL,
+ member_id INTEGER NOT NULL,
+ client_sealed BLOB NOT NULL
+);
diff --git a/internal/sheets/migrations/0012_create_sheets_agent_edits.sql b/internal/sheets/migrations/0012_create_sheets_agent_edits.sql
new file mode 100644
index 0000000..455d16b
--- /dev/null
+++ b/internal/sheets/migrations/0012_create_sheets_agent_edits.sql
@@ -0,0 +1,2 @@
+CREATE TABLE `sheets_agent_edits` (`coordinate` text,`content` text NOT NULL,`sheet_id` integer NOT NULL,`tab_id` integer NOT NULL,`before` integer NOT NULL,`revision` integer NOT NULL,`member_id` integer NOT NULL,`first_event_id` integer NOT NULL,`last_event_id` integer NOT NULL,`client_sealed` blob NOT NULL,PRIMARY KEY (`coordinate`));
+
diff --git a/internal/sheets/migrations/schema.sql b/internal/sheets/migrations/schema.sql
index 6d8675c..f3952dc 100644
--- a/internal/sheets/migrations/schema.sql
+++ b/internal/sheets/migrations/schema.sql
@@ -21,6 +21,25 @@ CREATE TABLE `share_links` (`id` integer PRIMARY KEY AUTOINCREMENT,`sheet_id` in
CREATE TABLE `sheets` (`id` integer PRIMARY KEY AUTOINCREMENT,`title_sealed` blob,`created_by` integer,`created_at` datetime,`updated_at` datetime,`deleted_at` datetime, `filling_since` datetime);
+CREATE TABLE sheets_agent_attribution (
+ sheet_id INTEGER PRIMARY KEY NOT NULL,
+ member_id INTEGER NOT NULL,
+ client_sealed BLOB NOT NULL
+);
+
+CREATE TABLE `sheets_agent_edits` (`coordinate` text,`content` text NOT NULL,`sheet_id` integer NOT NULL,`tab_id` integer NOT NULL,`before` integer NOT NULL,`revision` integer NOT NULL,`member_id` integer NOT NULL,`first_event_id` integer NOT NULL,`last_event_id` integer NOT NULL,`client_sealed` blob NOT NULL,PRIMARY KEY (`coordinate`));
+
+CREATE TABLE sheets_agent_receipts (
+ coordinate TEXT PRIMARY KEY NOT NULL,
+ content TEXT NOT NULL,
+ sheet_id INTEGER NOT NULL
+);
+
+CREATE TABLE sheets_agent_state (
+ id INTEGER PRIMARY KEY CHECK(id=1),
+ keycheck TEXT NOT NULL
+);
+
CREATE TABLE `tab_views` (`id` integer PRIMARY KEY AUTOINCREMENT,`tab_id` integer,`spec_sealed` blob,`updated_by` integer,`updated_at` datetime);
CREATE TABLE `tabs` (`id` integer PRIMARY KEY AUTOINCREMENT,`sheet_id` integer,`name_sealed` blob,`position` integer,`frozen_rows` integer,`frozen_cols` integer, `content_version` integer NOT NULL DEFAULT 0);
diff --git a/internal/sheets/sheetsvc.go b/internal/sheets/sheetsvc.go
index 19a8aec..623dfbf 100644
--- a/internal/sheets/sheetsvc.go
+++ b/internal/sheets/sheetsvc.go
@@ -94,6 +94,12 @@ func (a *App) createFillingSheet(g store.Guard, title string, by Member) (SheetS
}
func (a *App) newSheet(g store.Guard, title string, by Member, filling bool) (SheetSummary, error) {
+ return a.newSheetWithTab(g, title, firstTabName, by, filling)
+}
+
+// newSheetWithTab shares the ordinary creation transaction and owner grant.
+// Agent callers validate their explicit first-tab name before entering it.
+func (a *App) newSheetWithTab(g store.Guard, title, tabName string, by Member, filling bool) (SheetSummary, error) {
if a.db == nil {
return SheetSummary{}, errNoDB
}
@@ -111,7 +117,7 @@ func (a *App) newSheet(g store.Guard, title string, by Member, filling bool) (Sh
if err != nil {
return SheetSummary{}, err
}
- sealedName, err := a.sealer.Seal("tab.name", []byte(firstTabName))
+ sealedName, err := a.sealer.Seal("tab.name", []byte(tabName))
if err != nil {
return SheetSummary{}, err
}
@@ -145,7 +151,7 @@ func (a *App) newSheet(g store.Guard, title string, by Member, filling bool) (Sh
}
return SheetSummary{
ID: sheet.ID, Title: clean, TabID: tab.ID,
- TabName: firstTabName, UpdatedAt: sheet.UpdatedAt,
+ TabName: tabName, UpdatedAt: sheet.UpdatedAt,
}, nil
}
diff --git a/internal/sheets/store/handle_blank_cap_test.go b/internal/sheets/store/handle_blank_cap_test.go
index fa46609..733f155 100644
--- a/internal/sheets/store/handle_blank_cap_test.go
+++ b/internal/sheets/store/handle_blank_cap_test.go
@@ -118,6 +118,24 @@ func TestBlankFeederOverCapDependentsAreRecoverable(t *testing.T) {
t.Fatalf("seed dependent cells: %v", err)
}
+ // A corrupt cache with equal version stamps cannot be repaired when its
+ // fanout exceeds the per-pass cap. It must not masquerade as an empty cell.
+ feeder := db.Model(&store.Cell{}).Where("tab_id=? AND row_id=? AND col_id=?", localTab, feederRow, colA)
+ if err := feeder.Update("cached_sealed", []byte("broken-cache")).Error; err != nil {
+ t.Fatal(err)
+ }
+ broken, err := store.Open(db, s, localTab)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if snapshot, err := broken.ReadRange(0, 0, 1, 1); err == nil {
+ t.Fatalf("range hid missing cache as empty: %+v", snapshot)
+ }
+ broken.Release()
+ if err := feeder.Update("cached_sealed", feederCachedSealed).Error; err != nil {
+ t.Fatal(err)
+ }
+
h, err := store.Open(db, s, localTab)
if err != nil {
t.Fatalf("store.Open: %v", err)
@@ -144,6 +162,9 @@ func TestBlankFeederOverCapDependentsAreRecoverable(t *testing.T) {
if !rep.Capped {
t.Fatal("blank unexpectedly recalculated")
}
+ if snapshot, err := h.ReadRange(1, 0, 1, 1); err == nil {
+ t.Fatalf("range served stale calculation at new revision: %+v", snapshot)
+ }
var watermark uint64
if err := db.Raw("SELECT content_version FROM tabs WHERE id = ?", localTab).Scan(&watermark).Error; err != nil {
t.Fatal(err)
diff --git a/internal/sheets/store/handle_range.go b/internal/sheets/store/handle_range.go
new file mode 100644
index 0000000..05057ad
--- /dev/null
+++ b/internal/sheets/store/handle_range.go
@@ -0,0 +1,50 @@
+package store
+
+import (
+ "errors"
+ "math"
+
+ "amadan.net/oficina/sheets/internal/sheets/calc"
+)
+
+// RangeCell is one coordinate and its raw/calculated content at one watermark.
+type RangeCell struct {
+ Row, Col int
+ Raw string
+ Value calc.Value
+}
+type RangeSnapshot struct {
+ Version uint64
+ Cells []RangeCell
+}
+
+// ReadRange takes one lock for inputs, calculated values and next-stamp version.
+// It never grows axes or evaluates a formula. App authority is checked upstream.
+func (h *Handle) ReadRange(row, col, height, width int) (RangeSnapshot, error) {
+ if row < 0 || col < 0 || height < 1 || width < 1 || height > MaxCellBatch || width > MaxCellBatch || height > MaxCellBatch/width || row > math.MaxInt-height || col > math.MaxInt-width {
+ return RangeSnapshot{}, errors.New("store: invalid range")
+ }
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ // A capped browser edit leaves durable dirty markers and old graph caches.
+ // Refuse the tab until recovery completes; never label those values current.
+ var stale int
+ if err := h.db.Raw("SELECT 1 FROM cells WHERE tab_id=? AND cache_version < input_version LIMIT 1", h.tabID).Scan(&stale).Error; err != nil {
+ return RangeSnapshot{}, err
+ }
+ if stale != 0 {
+ return RangeSnapshot{}, errors.New("store: calculation incomplete")
+ }
+ out := RangeSnapshot{Version: h.nextVersion, Cells: make([]RangeCell, 0, height*width)}
+ for r := row; r < row+height; r++ {
+ for c := col; c < col+width; c++ {
+ key := calc.CellKey{RowID: uint64(r) + 1, ColID: uint64(c) + 1}
+ value, cached := h.graph.CachedValue(key)
+ if !cached && h.rawText[key] != "" {
+ return RangeSnapshot{}, errors.New("store: calculation cache unavailable")
+ }
+ out.Cells = append(out.Cells, RangeCell{Row: r, Col: c, Raw: h.rawText[key], Value: value})
+ }
+ }
+ return out, nil
+}
diff --git a/internal/sheets/store/handle_write_batch.go b/internal/sheets/store/handle_write_batch.go
index 489ba3a..4bbdea6 100644
--- a/internal/sheets/store/handle_write_batch.go
+++ b/internal/sheets/store/handle_write_batch.go
@@ -2,6 +2,7 @@ package store
import (
"amadan.net/oficina/sheets/internal/sheets/calc"
+ "context"
"errors"
"gorm.io/gorm"
@@ -16,89 +17,135 @@ type CellWrite struct {
var errCellBatch = errors.New("store: invalid cell batch")
-func (h *Handle) SetBatch(writes []CellWrite, actor uint64) (Report, error) {
- return h.setBatch(nil, writes, actor)
-}
+// ErrRevisionConflict means the tab changed since the caller's snapshot.
+var ErrRevisionConflict = errors.New("store: tab revision changed")
-// setBatch is SetBatch with its one transaction run under g (guard.go).
-func (h *Handle) setBatch(g Guard, writes []CellWrite, actor uint64) (Report, error) {
+// BatchTransaction runs under the canonical handle lock and one writer
+// transaction. It may call apply once, with the expected next-stamp watermark,
+// or skip it for a completed receipt. It must use tx for every database read
+// and must not call another locking method on the handle. Returning an error
+// rolls back both the batch and the caller's receipt/authority work.
+type BatchTransaction func(tx *gorm.DB, apply func(expected uint64) (uint64, error)) error
+
+// ValidateCellWrites uses the same shape and parser checks as SetBatch.
+func ValidateCellWrites(writes []CellWrite) error {
if len(writes) == 0 || len(writes) > MaxCellBatch {
- return Report{}, errCellBatch
+ return errCellBatch
}
seen := make(map[[2]int]bool, len(writes))
for _, w := range writes {
pos := [2]int{w.Row, w.Col}
if w.Row < 0 || w.Col < 0 || seen[pos] {
- return Report{}, errCellBatch
+ return errCellBatch
}
seen[pos] = true
if _, _, err := contentNode(w.Raw); err != nil {
- return Report{}, errCellBatch
+ return errCellBatch
}
}
+ return nil
+}
+
+func (h *Handle) SetBatch(writes []CellWrite, actor uint64) (Report, error) {
+ return h.setBatch(nil, writes, actor)
+}
+func (h *Handle) setBatch(g Guard, writes []CellWrite, actor uint64) (Report, error) {
+ return h.SetBatchInTransaction(context.Background(), g, writes, actor, nil)
+}
+
+// SetBatchInTransaction extends the native batch with app-owned transactional
+// checks and receipts. Only a committed fresh batch replaces the cached graph.
+func (h *Handle) SetBatchInTransaction(ctx context.Context, g Guard, writes []CellWrite, actor uint64, run BatchTransaction) (Report, error) {
+ if err := ValidateCellWrites(writes); err != nil {
+ return Report{}, err
+ }
+
h.mu.Lock()
defer h.mu.Unlock()
var staged *Handle
var result Report
- err := h.db.Transaction(func(tx *gorm.DB) error {
+ err := h.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
return g.Run(func() error {
- var err error
- staged, err = buildHandle(tx, h.sealer, h.tabID)
- if err != nil {
- return err
- }
- if staged.nextVersion < h.nextVersion {
- staged.nextVersion = h.nextVersion
- }
- changed := make(map[CellCoord]ChangedCell)
- direct := make(map[CellCoord]bool)
- for _, w := range writes {
- r, err := staged.EnsureRow(w.Row)
- if err != nil {
- return err
+ used := false
+ var applyErr error
+ apply := func(expected uint64) (revision uint64, failure error) {
+ defer func() { applyErr = failure }()
+ if used {
+ return 0, errCellBatch
}
- c, err := staged.EnsureCol(w.Col)
+ used = true
+ var err error
+ staged, err = buildHandle(tx, h.sealer, h.tabID)
if err != nil {
- return err
+ return 0, err
}
- rep, err := staged.SetReport(r, c, w.Raw, actor)
- if err != nil {
- return err
+ if staged.nextVersion < h.nextVersion {
+ staged.nextVersion = h.nextVersion
}
- if rep.Capped {
- return errCellBatch
+ if expected != 0 && expected != staged.nextVersion {
+ return 0, ErrRevisionConflict
}
- direct[CellCoord{r, c}] = true
- result.Version = rep.Version
- for _, cell := range rep.Cells {
- changed[CellCoord{cell.RowID, cell.ColID}] = cell
+ changed := make(map[CellCoord]ChangedCell)
+ direct := make(map[CellCoord]bool)
+ for _, w := range writes {
+ r, err := staged.EnsureRow(w.Row)
+ if err != nil {
+ return 0, err
+ }
+ c, err := staged.EnsureCol(w.Col)
+ if err != nil {
+ return 0, err
+ }
+ rep, err := staged.SetReport(r, c, w.Raw, actor)
+ if err != nil {
+ return 0, err
+ }
+ if rep.Capped {
+ return 0, errCellBatch
+ }
+ direct[CellCoord{r, c}] = true
+ result.Version = rep.Version
+ for _, cell := range rep.Cells {
+ changed[CellCoord{cell.RowID, cell.ColID}] = cell
+ }
+ if len(changed) > calc.MaxDirtyPerPass {
+ return 0, errCellBatch
+ }
}
- if len(changed) > calc.MaxDirtyPerPass {
- return errCellBatch
+ var count int64
+ if err := tx.Model(&Cell{}).Where("tab_id = ?", h.tabID).Count(&count).Error; err != nil {
+ return 0, err
}
+ if count > MaxCellsPerTab {
+ return 0, ErrTabTooLarge
+ }
+ for coord, cell := range changed {
+ cell.Derived = !direct[coord]
+ result.Cells = append(result.Cells, cell)
+ }
+ result.Stamps = len(writes)
+ return staged.nextVersion, nil
}
- var count int64
- if err := tx.Model(&Cell{}).Where("tab_id = ?", h.tabID).Count(&count).Error; err != nil {
- return err
- }
- if count > MaxCellsPerTab {
- return ErrTabTooLarge
- }
- for coord, cell := range changed {
- cell.Derived = !direct[coord]
- result.Cells = append(result.Cells, cell)
+ if run != nil {
+ if err := run(tx, apply); err != nil {
+ return err
+ }
+ return applyErr
}
- return nil
+ _, err := apply(0)
+ return err
})
})
if err != nil {
return Report{}, err
}
+ if staged == nil {
+ return Report{}, nil
+ }
h.graph, h.rawText, h.keyToIDs = staged.graph, staged.rawText, staged.keyToIDs
h.rowPos, h.colPos = staged.rowPos, staged.colPos
h.rowByPos, h.colByPos = staged.rowByPos, staged.colByPos
h.nextVersion = staged.nextVersion
- result.Stamps = len(writes) // one SetReport, so one stamp, per write
return result, nil
}
diff --git a/internal/sheets/store/handle_write_batch_test.go b/internal/sheets/store/handle_write_batch_test.go
index 59fec8f..8a7a50a 100644
--- a/internal/sheets/store/handle_write_batch_test.go
+++ b/internal/sheets/store/handle_write_batch_test.go
@@ -249,3 +249,22 @@ func TestCellBatchRejectsMergedReportPastCalculationCap(t *testing.T) {
t.Fatal("oversized report committed partial write")
}
}
+
+// The callback cannot accidentally turn a failed batch into a commit by
+// swallowing apply's error (nor execute it a second time).
+func TestConditionalBatchCannotSwallowApplyFailure(t *testing.T) {
+ h := openSeeded(t)
+ before := h.Version()
+ for _, twice := range []bool{false, true} {
+ _, err := h.SetBatchInTransaction(t.Context(), nil, []store.CellWrite{{Row: 0, Col: 0, Raw: "99"}}, actor, func(tx *gorm.DB, apply func(uint64) (uint64, error)) error {
+ if twice {
+ _, _ = apply(before)
+ }
+ _, _ = apply(before + 100)
+ return nil
+ })
+ if err == nil || h.Version() != before || h.Value(rowA, colA).Num != 5 {
+ t.Fatal("partial callback committed", twice, err)
+ }
+ }
+}
diff --git a/internal/sheets/store/initial_export_test.go b/internal/sheets/store/initial_export_test.go
new file mode 100644
index 0000000..0a40697
--- /dev/null
+++ b/internal/sheets/store/initial_export_test.go
@@ -0,0 +1,10 @@
+package store
+
+import "gorm.io/gorm"
+
+func InitialHandleCachedForTest(db *gorm.DB, tabID uint64) bool {
+ registryMu.Lock()
+ defer registryMu.Unlock()
+ _, ok := registry[handleKey{db: db, tabID: tabID}]
+ return ok
+}
diff --git a/internal/sheets/store/initial_tab.go b/internal/sheets/store/initial_tab.go
new file mode 100644
index 0000000..d53dcd7
--- /dev/null
+++ b/internal/sheets/store/initial_tab.go
@@ -0,0 +1,40 @@
+package store
+
+import (
+ "errors"
+
+ "amadan.net/oficina/sheets/internal/sheets/seal"
+ "gorm.io/gorm"
+)
+
+// InitializeTab writes initial cells inside the caller's creation transaction.
+// Its handle is never registered or returned: it holds tx and must be discarded
+// on either commit or rollback. The caller opens a canonical handle after commit.
+func InitializeTab(tx *gorm.DB, sealer *seal.Sealer, tabID uint64, writes []CellWrite, actor uint64) error {
+ if tx == nil || tx.Statement == nil {
+ return errors.New("store: creation transaction required")
+ }
+ if _, ok := tx.Statement.ConnPool.(gorm.TxCommitter); !ok {
+ return errors.New("store: creation transaction required")
+ }
+ var tab Tab
+ if err := tx.Select("id", "content_version").First(&tab, tabID).Error; err != nil {
+ return err
+ }
+ var count int64
+ if err := tx.Model(&Cell{}).Where("tab_id=?", tabID).Count(&count).Error; err != nil {
+ return err
+ }
+ if tab.ContentVersion != 0 || count != 0 {
+ return errors.New("store: initial tab is not empty")
+ }
+ h, err := buildHandle(tx, sealer, tabID)
+ if err != nil {
+ return err
+ }
+ if len(writes) == 0 {
+ return nil
+ }
+ _, err = h.SetBatch(writes, actor)
+ return err
+}
diff --git a/internal/sheets/store/initial_tab_test.go b/internal/sheets/store/initial_tab_test.go
new file mode 100644
index 0000000..92d8a60
--- /dev/null
+++ b/internal/sheets/store/initial_tab_test.go
@@ -0,0 +1,127 @@
+package store_test
+
+import (
+ "errors"
+ "math"
+ "strconv"
+ "sync"
+ "testing"
+
+ "amadan.net/oficina/sheets/internal/sheets/store"
+ "gorm.io/gorm"
+)
+
+func TestInitialTabSharesOuterTransactionAndNeverCachesIt(t *testing.T) {
+ db, sealer, _ := seeded(t)
+ writes := []store.CellWrite{{Row: 0, Col: 0, Raw: "21"}, {Row: 1, Col: 0, Raw: "=A1*2"}}
+ if err := store.InitializeTab(db, sealer, 99, writes, actor); err == nil {
+ t.Fatal("nontransaction initialization accepted")
+ }
+ refused := errors.New("parent rollback")
+ create := func(rollback bool) error {
+ return db.Transaction(func(tx *gorm.DB) error {
+ if err := tx.Create(&store.Tab{ID: 99, SheetID: 1}).Error; err != nil {
+ return err
+ }
+ if err := store.InitializeTab(tx, sealer, 99, writes, actor); err != nil {
+ return err
+ }
+ if store.InitialHandleCachedForTest(tx, 99) {
+ t.Fatal("transaction handle entered live cache")
+ }
+ if rollback {
+ return refused
+ }
+ if err := store.InitializeTab(tx, sealer, 99, writes, actor); err == nil {
+ t.Fatal("initial values reapplied")
+ }
+ return nil
+ })
+ }
+ if err := create(true); !errors.Is(err, refused) {
+ t.Fatal(err)
+ }
+ for _, model := range []any{&store.Tab{}, &store.Cell{}, &store.Row{}, &store.Col{}} {
+ var count int64
+ q := db.Model(model)
+ if _, ok := model.(*store.Tab); ok {
+ q = q.Where("id=99")
+ } else {
+ q = q.Where("tab_id=99")
+ }
+ if err := q.Count(&count).Error; err != nil || count != 0 {
+ t.Fatal("outer rollback retained rows", count, err)
+ }
+ }
+ if err := create(false); err != nil {
+ t.Fatal(err)
+ }
+ h, err := store.Open(db, sealer, 99)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer h.Release()
+ snapshot, err := h.ReadRange(0, 0, 2, 1)
+ if err != nil || snapshot.Cells[0].Value.Num != 21 || snapshot.Cells[1].Value.Num != 42 || snapshot.Version != h.Version() {
+ t.Fatal(snapshot, err)
+ }
+ if _, err = h.SetBatch([]store.CellWrite{{Row: 0, Col: 0, Raw: "8"}}, actor); err != nil {
+ t.Fatal("canonical handle retained committed transaction", err)
+ }
+ snapshot, err = h.ReadRange(0, 0, 2, 1)
+ if err != nil || snapshot.Cells[1].Value.Num != 16 {
+ t.Fatal(snapshot, err)
+ }
+}
+
+func TestRangeSnapshotIsBoundedAndCoherentDuringBatchWrites(t *testing.T) {
+ h := openSeeded(t)
+ if _, err := h.SetBatch([]store.CellWrite{{Row: 0, Col: 0, Raw: "0"}, {Row: 1, Col: 0, Raw: "0"}}, actor); err != nil {
+ t.Fatal(err)
+ }
+ for _, box := range [][4]int{{-1, 0, 1, 1}, {0, 0, 0, 1}, {0, 0, 501, 1}, {0, 0, 25, 25}, {math.MaxInt, 0, 1, 1}} {
+ if _, err := h.ReadRange(box[0], box[1], box[2], box[3]); err == nil {
+ t.Fatal("unbounded range accepted", box)
+ }
+ }
+ done := make(chan struct{})
+ var wg sync.WaitGroup
+ errs := make(chan error, 1)
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ defer close(done)
+ for i := 1; i <= 20; i++ {
+ value := strconv.Itoa(i)
+ if _, err := h.SetBatch([]store.CellWrite{{Row: 0, Col: 0, Raw: value}, {Row: 1, Col: 0, Raw: value}}, actor); err != nil {
+ errs <- err
+ return
+ }
+ }
+ }()
+ var last uint64
+readLoop:
+ for {
+ snapshot, err := h.ReadRange(0, 0, 2, 1)
+ if err != nil || snapshot.Cells[0].Raw != snapshot.Cells[1].Raw || snapshot.Cells[0].Value.Num != snapshot.Cells[1].Value.Num || snapshot.Version < last {
+ t.Error("mixed range snapshot", snapshot, err)
+ break
+ }
+ last = snapshot.Version
+ select {
+ case <-done:
+ break readLoop
+ default:
+ }
+ }
+ wg.Wait()
+ select {
+ case err := <-errs:
+ t.Fatal(err)
+ default:
+ }
+ snapshot, err := h.ReadRange(0, 0, 2, 1)
+ if err != nil || snapshot.Cells[0].Value.Num != 20 || snapshot.Version != h.Version() {
+ t.Fatal(snapshot, err)
+ }
+}
diff --git a/internal/sheets/store/metadata_read.go b/internal/sheets/store/metadata_read.go
new file mode 100644
index 0000000..06094bd
--- /dev/null
+++ b/internal/sheets/store/metadata_read.go
@@ -0,0 +1,16 @@
+package store
+
+import "amadan.net/oficina/sheets/internal/sheets/seal"
+
+// ReadTitle returns a decryption error instead of disguising damaged metadata
+// as an empty title. Callers must establish current access before calling it.
+func ReadTitle(sealer *seal.Sealer, sheet Sheet) (string, error) {
+ plain, err := sealer.Open("sheet.title", sheet.TitleSealed)
+ return string(plain), err
+}
+
+// ReadTabName has the same failure semantics as ReadTitle.
+func ReadTabName(sealer *seal.Sealer, tab Tab) (string, error) {
+ plain, err := sealer.Open("tab.name", tab.NameSealed)
+ return string(plain), err
+}
diff --git a/internal/sheets/team_guard_test.go b/internal/sheets/team_guard_test.go
index c312fba..33d2a61 100644
--- a/internal/sheets/team_guard_test.go
+++ b/internal/sheets/team_guard_test.go
@@ -145,6 +145,7 @@ func TestNoGuardOutsideTeamMode(t *testing.T) {
// lapse inside it with the retryable 503: the lease runs out after each
// write and before its commit, and the route must refuse.
func TestTeamEveryWriteRouteRefusesALapseBeforeCommit(t *testing.T) {
+ t.Run("delegated range edit", testAgentRangeEditGuardLapse)
f := newTeamFixture(t)
a := teamSubject('a')
f.dir.Set(a, "owner")