Add revision-checked delegated range editing
Apply existing SetBatch semantics atomically with sealed retry attribution, immutable acknowledgements, and current editor authority. Preserve native input event attribution and cache state across rollback. Independent specification/source review: GPT-6 Astra. Full pinned make test, focused race, and seven effective adversarial mutants passed.
17 files changed,
+1,078
−53
docs/agent-access.md+16 −3docs/superpowers/specs/2026-11-01-agent-range-editing.md+206 −0internal/sheets/agent_access.go+7 −1internal/sheets/agent_authority.go+11 −7internal/sheets/agent_create.go+3 −0internal/sheets/agent_edit.go+183 −0internal/sheets/agent_edit_boundary_test.go+205 −0internal/sheets/agent_edit_test.go+294 −0internal/sheets/agent_integration_test.go+19 −0internal/sheets/agent_operations.go+7 −0internal/sheets/agent_response.go+5 −1internal/sheets/migrations.go+1 −1internal/sheets/migrations/0012_create_sheets_agent_edits.sql+2 −0internal/sheets/migrations/schema.sql+19 −0internal/sheets/store/handle_write_batch.go+80 −40internal/sheets/store/handle_write_batch_test.go+19 −0internal/sheets/team_guard_test.go+1 −0
CI passed — run details
diff --git a/docs/agent-access.md b/docs/agent-access.md| index 5d7305d..c897c9c 100644 |
| --- a/docs/agent-access.md |
| +++ b/docs/agent-access.md |
| @@ -1,7 +1,7 @@ |
| # Delegated Sheets access |
| The Oficina connection exposes `sheets_list`, `sheets_list_tabs`, |
| -`sheets_get_range` and `sheets_create`. CLI, Paseo, ChatGPT and Claude use the |
| +`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 |
| @@ -43,8 +43,21 @@ 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. |
| -Editing existing cells, formatting, additional tabs, comments, sharing and |
| -import/export remain separate capability slices. |
| +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-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/internal/sheets/agent_access.go b/internal/sheets/agent_access.go| index f54fe91..a694814 100644 |
| --- a/internal/sheets/agent_access.go |
| +++ b/internal/sheets/agent_access.go |
| @@ -98,12 +98,15 @@ func (a *sheetAgent) httpHandler(verifier access.Verifier) (http.Handler, error) |
| return |
| } |
| name := strings.TrimPrefix(r.URL.Path, "/api/v1/operations/") |
| - write := name == "sheets_create" |
| + 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 |
| @@ -186,6 +189,9 @@ func (a *sheetAgent) httpHandler(verifier access.Verifier) (http.Handler, error) |
| return e |
| } |
| fresh, e := a.member(checkCtx, p, write) |
| + if e == nil && name == "sheets_create" { |
| + e = a.requireCreator(fresh) |
| + } |
| if e != nil { |
| return e |
| } |
diff --git a/internal/sheets/agent_authority.go b/internal/sheets/agent_authority.go| index a5db405..af6a5be 100644 |
| --- a/internal/sheets/agent_authority.go |
| +++ b/internal/sheets/agent_authority.go |
| @@ -51,6 +51,7 @@ type sheetAgentContext struct { |
| member Member |
| verify func(context.Context) error |
| sheets map[uint64]bool |
| + edits map[uint64]bool |
| } |
| type sheetAgentKey struct{} |
| @@ -86,7 +87,7 @@ func (a *sheetAgent) digest(domain string, value any) string { |
| } |
| 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) ON CONFLICT(id) DO NOTHING", want).Error; e != nil { |
| + 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 |
| @@ -129,15 +130,18 @@ func (a *sheetAgent) member(ctx context.Context, p access.Principal, write bool) |
| } else { |
| member.team = &teamAccess{member: member, Access: a.app.team.Access(ctx, p.Subject)} |
| } |
| - if write && member.team.state() == roster.Unknown { |
| - return Member{}, sheetAgentFailure(errTeamUnavailable) |
| - } |
| - } |
| - if write && !a.creator(member) { |
| - return Member{}, access.Fail("forbidden", "Creating a sheet requires current team membership.") |
| } |
| 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 |
diff --git a/internal/sheets/agent_create.go b/internal/sheets/agent_create.go| index c56f5fe..f6d099b 100644 |
| --- a/internal/sheets/agent_create.go |
| +++ b/internal/sheets/agent_create.go |
| @@ -34,6 +34,9 @@ type sheetAgentCreated struct { |
| } |
| 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) |
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(¤t, 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_integration_test.go b/internal/sheets/agent_integration_test.go| index 5cdc1e5..d2853dd 100644 |
| --- a/internal/sheets/agent_integration_test.go |
| +++ b/internal/sheets/agent_integration_test.go |
| @@ -136,6 +136,25 @@ func TestAgentGatewayToRealSheets(t *testing.T) { |
| 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) |
diff --git a/internal/sheets/agent_operations.go b/internal/sheets/agent_operations.go| index a9990c1..5d2808d 100644 |
| --- a/internal/sheets/agent_operations.go |
| +++ b/internal/sheets/agent_operations.go |
| @@ -34,6 +34,13 @@ func (a *sheetAgent) registry() (*access.Registry, error) { |
| 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"` |
diff --git a/internal/sheets/agent_response.go b/internal/sheets/agent_response.go| index 2dbfdb8..9164d82 100644 |
| --- a/internal/sheets/agent_response.go |
| +++ b/internal/sheets/agent_response.go |
| @@ -13,7 +13,11 @@ func (a *sheetAgent) checkVisible(ctx context.Context, state *sheetAgentContext, |
| if err != nil { |
| return err |
| } |
| - if !role.Allows(SheetViewer) { |
| + need := SheetViewer |
| + if state.edits[id] { |
| + need = SheetEditor |
| + } |
| + if !role.Allows(need) { |
| return errNoAccess |
| } |
| } |
diff --git a/internal/sheets/migrations.go b/internal/sheets/migrations.go| index a9d9131..3b8622c 100644 |
| --- a/internal/sheets/migrations.go |
| +++ b/internal/sheets/migrations.go |
| @@ -52,7 +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{}, |
| + 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/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/store/handle_write_batch.go b/internal/sheets/store/handle_write_batch.go| index 744ba0d..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,6 +17,16 @@ type CellWrite struct { |
| var errCellBatch = errors.New("store: invalid cell batch") |
| +// ErrRevisionConflict means the tab changed since the caller's snapshot. |
| +var ErrRevisionConflict = errors.New("store: tab revision changed") |
| + |
| +// 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 { |
| @@ -39,6 +50,12 @@ 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 |
| } |
| @@ -48,64 +65,87 @@ func (h *Handle) setBatch(g Guard, writes []CellWrite, actor uint64) (Report, er |
| 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/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") |