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