oficina / docs Public

Docs: the agent API's writes held to the suite rules; Astra's two coverage notes

The delegated agent API from main creates and edits through CreateDraft and
ApplyUpdate, so it inherits the team default, random revisions and feed
rows; TestSuiteAgentCreateAndEditAreTeamRandomAndAnnounced proves it with
scripted draws, and TestSuiteAgentWritesRollBackWithoutTheirFeedRow shows
a create or edit rolls back (receipt and attribution included) when its
feed row cannot be written. The agent's body_revision / expected_revision
is doc_updates.seq, a separate number: spec §8.2.2 says so.

Astra's notes on 65acd67: a source that fails after the revision draw, on
the nonce, stops the change; a source that answers a byte at a time is
read to eight bytes, and one that runs out part-way is an error.

Mutations, each reverted, recorded in the comments: red for private
creation, a fixed revision, a missing announce, a missing bump, a swallowed
feed error in bumpRevision, a guessable nonce fallback, and a single Read.
Two stayed green for a reason, both recorded: create's announce swallowed
(the agent's ApplyUpdate fails on the same trigger), and a zero nonce
fallback (the column's CHECK refuses it).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 74c255ad4cb54ae550e0a92e0bca6eea8ffb3a68 parent 48e4ceb
2 files changed, +235 −6
  • docs/superpowers/specs/2026-08-30-docs-design.md +22 −6
  • internal/docs/suite_agent_test.go +213 −0

CI passed — run details

diff --git a/docs/superpowers/specs/2026-08-30-docs-design.md b/docs/superpowers/specs/2026-08-30-docs-design.md
index 434d165..86a68ca 100644
--- a/docs/superpowers/specs/2026-08-30-docs-design.md
+++ b/docs/superpowers/specs/2026-08-30-docs-design.md
@@ -623,7 +623,7 @@ its owner shares it. Suite revision 10's status block records the same
ruling.
- **The column.** `documents.visibility` is `private` or `team`
- (migration `0009_suite.sql`, a CHECK holding the two values). The
+ (migration `0011_suite.sql`, a CHECK holding the two values). The
migration's column default is `private`, which is what every existing row
gets. `Store.Create`/`CreateDraft` write `team` explicitly; nothing writes
the empty string.
@@ -668,12 +668,12 @@ transaction as the change, on creation and on every applied update
(`ApplyUpdate`), rename, visibility change and deletion. `doc_updates.seq`
alone misses renames, and a rename changes S3's bytes. A grant, a revoke or
a link changes who may read, which S2 asks live, so none of them moves it.
-Each new value — on every change, on creation, and in migration 0009 for
+Each new value — on every change, on creation, and in migration 0011 for
every document that existed before it — is **a fresh random positive
value**, never the current one. In code it is 63 random bits from Go's
`crypto/rand` (a zero, or the current value, is drawn again; a source that
cannot be read is an error and the change does not commit — nothing falls
-back to a clock or a counter). In migration 0009 it is SQLite's `random()`
+back to a clock or a counter). In migration 0011 it is SQLite's `random()`
masked to 63 bits and forced odd, so **62 random bits**; SQLite's PRNG is
ChaCha20 (verified in modernc.org/sqlite v1.55.0), seeded from the OS
(`/dev/urandom`), and falls back to the time and the process id if that
@@ -689,7 +689,7 @@ uses in `store.go` and `agent_response.go` are `==`/`!=` with 0 as the
gone, touched_at, stamp)` is append-only and written in the same
transaction as each bump, creation included; a change whose feed row cannot
be written does not commit. `stamp` is a random positive nonce, written
-once with the row (the backfill rows too). Migration `0009` writes one row per live
+once with the row (the backfill rows too). Migration `0011` writes one row per live
document that existed before it, so a consumer's first poll sees the whole
library. *Live* is `deleted_at IS NULL AND owner_id > 0`: the orphans
`0002_owners.sql` made are readable by nobody and are not fed.
@@ -754,7 +754,7 @@ taken. Three ways of breaking that were found and are closed:
- *Clock-floored revisions* (this branch's first fix) reissued it when the
restore landed on a clock set back to the confidential edit's time, which
the first fix's own allowance permitted.
-- *A backup taken before migration 0009*, restored and migrated again,
+- *A backup taken before migration 0011*, restored and migrated again,
gave its harmless, still-granted document the same revision the first
migration gave the confidential one.
@@ -775,6 +775,20 @@ signal, not something to retry past — **after a restore memoria must drop
everything it holds from Docs and its Docs cursor, and re-read from
`""`.**
+**The delegated agent API (main `5039cf6`) and this section.** Its
+`docs_create` and `docs_update` write through `CreateDraft` and
+`ApplyUpdate` inside their own writer transaction, so an agent-created
+document is on the team rung, its revisions are drawn by `newRevision`,
+every change is announced in `suite_feed` in the same transaction, and a
+change whose feed row cannot be written rolls the agent's receipt and
+attribution back with it. Its `body_revision`, `expected_revision` and
+acknowledged `revision` are a different number: `doc_updates.seq`, as a
+decimal string, compared for equality against the current sequence for
+optimistic concurrency. Nothing in the agent API reads or exposes
+`documents.revision`, and nothing here reads the sequence, so the two never
+meet; the shared word is the only overlap. The suite migration is
+`0011_suite.sql`, after the agent API's `0009` and `0010`.
+
**`DOCS_SUITE_CONSUMERS`.** `server.EnvSuffix`'s variable, strict JSON:
`[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"<64 hex>"}]}]`,
one or two tokens per consumer, each the SHA-256 of a token the operator
@@ -812,7 +826,9 @@ batch), both redraws forced through a scripted random source and a broken
one refused, the custody fixture seeded
with each item's revision − 1 in its log, a lease running out (before, between and after S2's reads)
before and after S2's reads, a change whose feed row cannot be written not
-committing, and a lone-shape guest answered 404 by every sharing route.
+committing, a lone-shape guest answered 404 by every sharing route, and
+the agent API's create and edit held to the same (team default, scripted
+random draws, a feed row each, rollback without it).
---
diff --git a/internal/docs/suite_agent_test.go b/internal/docs/suite_agent_test.go
new file mode 100644
index 0000000..9d3f55b
--- /dev/null
+++ b/internal/docs/suite_agent_test.go
@@ -0,0 +1,213 @@
+package docs
+
+import (
+ "context"
+ crand "crypto/rand"
+ "errors"
+ "io"
+ "strconv"
+ "testing"
+
+ "amadan.net/oficina/suite"
+)
+
+// feedRowsOf is a document's suite_feed rows, oldest first.
+func feedRowsOf(t *testing.T, s *Store, docID int64) []SuiteFeedRow {
+ t.Helper()
+ var rows []SuiteFeedRow
+ if err := s.db.Where("document_id = ?", docID).Order("id").Find(&rows).Error; err != nil {
+ t.Fatal(err)
+ }
+ return rows
+}
+
+// The delegated agent API that landed on main (5039cf6) creates and edits
+// documents through CreateDraft and ApplyUpdate, inside its own writer
+// transaction. So an agent-created document is on the team rung (Paul,
+// 2026-11-01), its revisions are drawn by newRevision from randomSource,
+// each change is announced in suite_feed, and S2 reads an agent edit's
+// predecessor as STALE from the log. The agent's own "body_revision" /
+// "expected_revision" is doc_updates.seq — a different number, untouched.
+//
+// MUTATION-TESTED 2026-11-02, each reverted: CreateDraft creating private →
+// "visibility"; createDocument's revision fixed at 1 instead of drawn → "the
+// scripted draws" (first row at 1); createDocument without its announce →
+// one row short; ApplyUpdate without bumpRevision → "the edit's revision"
+// unchanged, no third row, and S2 [VISIBLE VISIBLE]. (The fixed-revision
+// mutation first failed to compile — an unused variable, red for the wrong
+// reason — and was redone.)
+func TestSuiteAgentCreateAndEditAreTeamRandomAndAnnounced(t *testing.T) {
+ f := newDocAgentFixture(t)
+ t.Cleanup(func() { randomSource = crand.Reader })
+
+ // create: the document's revision, its nonce, the initial content's
+ // revision, its nonce — in that order, all from randomSource.
+ randomSource = draws(101, 102, 103, 104)
+ body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
+ randomSource = crand.Reader
+ var doc Document
+ if err := f.a.store.db.Where("sqid = ?", body.ID).First(&doc).Error; err != nil {
+ t.Fatal(err)
+ }
+ if doc.Visibility != VisibilityTeam {
+ t.Errorf("visibility: an agent-created document is %q, want team", doc.Visibility)
+ }
+ rows := feedRowsOf(t, f.a.store, doc.ID)
+ if len(rows) != 2 || rows[0].Revision != 101 || rows[0].Stamp != 102 || rows[1].Revision != 103 || rows[1].Stamp != 104 || doc.Revision != 103 {
+ t.Errorf("the scripted draws / feed rows: document at %d, rows %+v; want revisions 101 then 103 with nonces 102, 104", doc.Revision, rows)
+ }
+ if body.Revision != "1" {
+ t.Errorf("the agent's body_revision is doc_updates.seq, %q; want \"1\" (the two revisions are separate)", body.Revision)
+ }
+
+ edited := f.call(t, "docs_update", editAgentInput(body))
+ if edited.Code != 200 {
+ t.Fatal(edited.Code, edited.Body.String())
+ }
+ before := doc.Revision
+ if err := f.a.store.db.First(&doc, doc.ID).Error; err != nil {
+ t.Fatal(err)
+ }
+ if doc.Revision == before {
+ t.Errorf("the edit's revision: unchanged at %d", before)
+ }
+ rows = feedRowsOf(t, f.a.store, doc.ID)
+ if len(rows) != 3 || rows[2].Revision != doc.Revision || rows[2].Gone {
+ t.Errorf("the edit's feed row: %+v, want a third row at %d", rows, doc.Revision)
+ }
+ got, err := f.app.suite.Rule(context.Background(), suite.Subject{Kind: suite.SubjectAddress, Value: "owner@example.com"},
+ []suite.ItemRevision{{ItemID: doc.Sqid, Revision: before}, {ItemID: doc.Sqid, Revision: doc.Revision}})
+ if err != nil || got[0] != suite.STALE || got[1] != suite.VISIBLE {
+ t.Errorf("S2 around the agent's edit: %v %v, want [STALE VISIBLE]", got, err)
+ }
+ if strconv.FormatInt(doc.Revision, 10) == body.Revision {
+ t.Error("documents.revision and the agent's body_revision coincide")
+ }
+}
+
+// An agent create or edit whose feed row cannot be written commits nothing:
+// no document, receipt or attribution for a create; no update, receipt,
+// attribution or new revision for an edit.
+//
+// MUTATION-TESTED 2026-11-02, reverted: bumpRevision returning nil when
+// announce fails → the agent edit commits. createDocument ignoring
+// announce's error stayed GREEN here, correctly: the agent create's initial
+// content goes through ApplyUpdate in the same transaction, whose own feed
+// row fails on the same trigger and rolls everything back. That swallow is
+// held where creation is alone — TestSuiteAChangeWithoutItsFeedRowDoesNotCommit
+// ("create"), red under it.
+func TestSuiteAgentWritesRollBackWithoutTheirFeedRow(t *testing.T) {
+ f := newDocAgentFixture(t)
+ body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
+ var doc Document
+ if err := f.a.store.db.Where("sqid = ?", body.ID).First(&doc).Error; err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.app.db.Writer().Exec(`CREATE TRIGGER suite_feed_refuses BEFORE INSERT ON suite_feed BEGIN SELECT RAISE(ABORT, 'refused'); END`); err != nil {
+ t.Fatal(err)
+ }
+ count := func(model any) int64 {
+ var n int64
+ if err := f.a.store.db.Model(model).Count(&n).Error; err != nil {
+ t.Fatal(err)
+ }
+ return n
+ }
+ docs, receipts, attributions := count(&Document{}), count(&agentReceipt{}), count(&agentAttribution{})
+ if w := f.call(t, "docs_create", initialAgentInput()); w.Code == 200 {
+ t.Error("an agent create committed without its feed row")
+ }
+ if count(&Document{}) != docs || count(&agentReceipt{}) != receipts || count(&agentAttribution{}) != attributions {
+ t.Error("an agent create left rows behind without its feed row")
+ }
+ updates, editReceipts := count(&DocUpdate{}), count(&agentUpdateReceipt{})
+ if w := f.call(t, "docs_update", editAgentInput(body)); w.Code == 200 {
+ t.Error("an agent edit committed without its feed row")
+ }
+ var after Document
+ if err := f.a.store.db.First(&after, doc.ID).Error; err != nil {
+ t.Fatal(err)
+ }
+ if count(&DocUpdate{}) != updates || count(&agentUpdateReceipt{}) != editReceipts || after.Revision != doc.Revision {
+ t.Error("an agent edit left rows behind without its feed row")
+ }
+}
+
+// failingAfter hands out its bytes and then fails, like a source that dies
+// between two draws.
+type failingAfter struct{ r io.Reader }
+
+func (f failingAfter) Read(p []byte) (int, error) {
+ n, err := f.r.Read(p)
+ if err == io.EOF {
+ return n, errors.New("entropy gone")
+ }
+ return n, err
+}
+
+// byteAtATime returns one byte per Read, as a source may.
+type byteAtATime struct{ r io.Reader }
+
+func (b byteAtATime) Read(p []byte) (int, error) {
+ if len(p) == 0 {
+ return 0, nil
+ }
+ return b.r.Read(p[:1])
+}
+
+// Astra's two nonblocking notes on 65acd67. A source that fails after the
+// revision was drawn — when the feed row's nonce is drawn — still stops the
+// change; and a source that answers in pieces is read until eight bytes are
+// in hand, while one that runs out part-way is an error, never a value
+// built from a half-filled buffer.
+//
+// MUTATION-TESTED 2026-11-02, each reverted: announce falling back to a
+// time-based nonce when randomPositive fails → "nonce failure" commits the
+// rename and the create; randomPositive using a single Read in place of
+// io.ReadFull → "one byte at a time" gets 0x0100000000000000 and "runs out
+// part-way" gets a value. (Falling back to a ZERO nonce stayed green: the
+// column's CHECK (stamp > 0) refuses it and the change rolls back anyway — a
+// second guard, so the mutation was redone with a guessable nonzero value.)
+func TestSuiteRandomnessFailsPartWayAndArrivesInPieces(t *testing.T) {
+ t.Cleanup(func() { randomSource = crand.Reader })
+ app, err := NewForTest(t)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+ alice := app.TestPerson(t, "alice@example.com")
+ doc, err := app.store.Create(ctx, alice, "Kept")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var docs int64
+ app.store.db.Model(&Document{}).Count(&docs)
+ rows := len(feedRowsOf(t, app.store, doc.ID))
+
+ // One draw is there (the revision), the nonce's is not.
+ randomSource = failingAfter{draws(77)}
+ if err := app.store.Rename(ctx, app.TestActorForPerson(t, alice), doc, "Not renamed"); err == nil {
+ t.Error("nonce failure: a rename committed")
+ }
+ randomSource = failingAfter{draws(78)}
+ if _, err := app.store.Create(ctx, alice, "Not made"); err == nil {
+ t.Error("nonce failure: a document was created")
+ }
+ randomSource = crand.Reader
+ var after Document
+ app.store.db.First(&after, doc.ID)
+ var docsAfter int64
+ app.store.db.Model(&Document{}).Count(&docsAfter)
+ if after.Title != "Kept" || after.Revision != doc.Revision || docsAfter != docs || len(feedRowsOf(t, app.store, doc.ID)) != rows {
+ t.Errorf("nonce failure changed something: %+v, documents %d→%d", after, docs, docsAfter)
+ }
+
+ randomSource = byteAtATime{draws(0x0102030405060708)}
+ if n, err := randomPositive(); err != nil || n != 0x0102030405060708 {
+ t.Errorf("one byte at a time: %#x %v", n, err)
+ }
+ randomSource = failingAfter{io.LimitReader(draws(0x0102030405060708).r, 3)}
+ if n, err := randomPositive(); !errors.Is(err, errNoRandomness) {
+ t.Errorf("runs out part-way: %#x %v, want errNoRandomness", n, err)
+ }
+}