oficina / suite Public

Revision 10: custody widened to every live item (Paul, 2026-11-01); the producer half (suite/server)

Paul: "Hold private too, check per person" — a consumer holds every live
item and S2 is the app's own per-person read check, with no custody
intersection; and Docs: "New docs Team, old private". The doctrine's
operative sections follow it (contract table, provenance, leak list,
gates 3/3c/6b, S6, §13, §14, A.2–A.4), with revision 9's text kept as
history. custody.json is rewritten (owner, asker_grant, s2_result_ahead),
the harness follows paged feeds, checks asker kinds (RunAs/CheckAs for
address-keyed apps), superseded and future revisions and refusal headers.
server/ is the producer half: Producer, bearer check over
<APP>_SUITE_CONSUMERS hashes, strict decoding, one identical S3 refusal,
fixed-string logs. Reviewed by GPT-6 (Codex, Astra): REQUEST CHANGES
twice, APPROVE on 983114a; polish applied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from feat/server-half into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev c38e3ad85990a6b08e1804d8ad4cff8748b577cf parent 1d8e22e
11 files changed, +1,486 −110
  • README.md +3 −0
  • conformance/conformance.go +170 −20
  • conformance/conformance_test.go +190 −17
  • docs/superpowers/specs/2026-09-05-suite-sharing-doctrine.md +193 −24
  • fixtures.go +17 −5
  • fixtures/custody.json +76 −35
  • s1.go +3 −2
  • s3.go +9 −7
  • server/consumers.go +119 −0
  • server/server.go +256 −0
  • server/server_test.go +450 −0

CI passed — run details

CI log
=== gate ===
ok  	amadan.net/oficina/suite	0.008s
ok  	amadan.net/oficina/suite/conformance	0.017s
ok  	amadan.net/oficina/suite/server	0.008s
diff --git a/README.md b/README.md
index 1141e05..c80cff8 100644
--- a/README.md
+++ b/README.md
@@ -21,6 +21,9 @@ owns the rule that binds the others.
client must refuse. Both are shared so every app runs the same gate
rather than inventing its own.
- `conformance/`: the harness an app points at its own server half.
+- `server/`: the producer half — the bearer check, the three routes and
+ their wire shapes — that an app mounts by implementing `Producer`
+ (doctrine §6.5, revision 10).
## How an app uses it
diff --git a/conformance/conformance.go b/conformance/conformance.go
index 3fcc01e..87dadf6 100644
--- a/conformance/conformance.go
+++ b/conformance/conformance.go
@@ -14,7 +14,10 @@ import (
"fmt"
"net/http"
"net/http/httptest"
+ "net/url"
+ "sort"
"strconv"
+ "strings"
"testing"
"amadan.net/oficina/suite"
@@ -43,11 +46,33 @@ func Run(t *testing.T, h http.Handler) {
}
}
+// RunAs is Run for an app that keys its askers on kind — a lone-shape app
+// keys on addresses, a suite-shape one on person refs (§3). The fixture's
+// asker and stranger keep their values and take that kind, and the harness
+// also asks with the other kind, which must be UNKNOWN for the whole call
+// (gate 2).
+func RunAs(t *testing.T, h http.Handler, kind suite.SubjectKind) {
+ t.Helper()
+ report := CheckAs(h, kind)
+ for _, f := range report.Failures {
+ t.Error(f)
+ }
+ if report.Checked == 0 {
+ t.Error("conformance ran no checks; a gate that asserts nothing passes everything")
+ }
+}
+
// Check drives the handler and returns what it found, without touching a
// *testing.T. It exists so the harness itself can be tested: a harness that
// passes every server is worse than no harness, and the only way to know is to
-// point it at servers that should fail.
+// point it at servers that should fail. It asks as the fixture's own kind,
+// person_ref.
func Check(h http.Handler) Report {
+ return CheckAs(h, suite.SubjectPersonRef)
+}
+
+// CheckAs is Check for an app that keys on kind (see RunAs).
+func CheckAs(h http.Handler, kind suite.SubjectKind) Report {
var r Report
fixture, err := suite.LoadCustodyFixture()
@@ -55,16 +80,41 @@ func Check(h http.Handler) Report {
r.fail("loading the custody fixture: %v", err)
return r
}
+ if kind != suite.SubjectPersonRef && kind != suite.SubjectAddress {
+ r.fail("unknown asker kind %q", kind)
+ return r
+ }
+ fixture.Asker.Kind, fixture.Stranger.Kind = kind, kind
checkS3(h, fixture, &r)
checkS2(h, fixture, &r)
- checkS1(h, &r)
+ checkWrongKind(h, fixture, kind, &r)
+ checkS1(h, fixture, &r)
return r
}
-// Gate 3, the content half. Every rung but `team` answers 404, and it answers
-// the same 404 as a deleted item — a consumer that could tell "not
-// team-visible" from "does not exist" would learn that a private item exists.
+// Gate 2's kind rule: an asker of a kind the app does not key on is UNKNOWN
+// for the whole call, never NOT_VISIBLE and never an answer read off the
+// value alone (Astra, 2026-11-01: the reference server compared values only
+// and answered VISIBLE to the right string under the wrong kind).
+func checkWrongKind(h http.Handler, f suite.CustodyFixture, kind suite.SubjectKind, r *Report) {
+ other := suite.SubjectAddress
+ if kind == suite.SubjectAddress {
+ other = suite.SubjectPersonRef
+ }
+ wrong := suite.Subject{Kind: other, Value: f.Asker.Value}
+ pairs := make([]suite.ItemRevision, 0, len(f.Cases))
+ for _, c := range f.Cases {
+ pairs = append(pairs, suite.ItemRevision{ItemID: c.ItemID, Revision: c.Revision})
+ }
+ askS2(h, f, r, "the asker's value under the kind this app does not key on", wrong, pairs,
+ func(suite.CustodyCase) suite.Authorization { return suite.UNKNOWN })
+}
+
+// Gate 3, the content half. Since revision 10 (Paul, 2026-11-01) every live
+// item is served — the consumer holds private and granted items too, and S2
+// decides who sees them — and a deleted item answers the same 404 as one
+// that never existed, so a consumer cannot tell a deletion from a made-up id.
func checkS3(h http.Handler, f suite.CustodyFixture, r *Report) {
// The refusal every non-team item must be indistinguishable from. Taken
// from an id that is not in the fixture at all, so it is the server's
@@ -75,6 +125,21 @@ func checkS3(h http.Handler, f suite.CustodyFixture, r *Report) {
r.fail("S3 for an item that does not exist: got %d, want 404", baseline.Code)
}
+ // Only the current revision is ever served: a consumer asking for
+ // revision 6 or 8 of an item now at 7 gets the refusal, not today's
+ // bytes under another number (Astra, 2026-11-01: the reference server
+ // served the older one; a mutant serving the newer one passed).
+ for _, c := range f.Cases {
+ for _, rev := range []int64{c.Revision - 1, c.Revision + 1} {
+ rec := do(h, "GET", suite.RouteS3+"/"+c.ItemID+"?revision="+strconv.FormatInt(rev, 10), nil)
+ r.Checked++
+ if refusal(rec) != refusal(baseline) {
+ r.fail("S3 %s at revision %d (current %d): %s, want the refusal for an item that does not exist (%s)",
+ c.ItemID, rev, c.Revision, refusal(rec), refusal(baseline))
+ }
+ }
+ }
+
for _, c := range f.Cases {
url := suite.RouteS3 + "/" + c.ItemID + "?revision=" + strconv.FormatInt(c.Revision, 10)
rec := do(h, "GET", url, nil)
@@ -99,20 +164,22 @@ func checkS3(h http.Handler, f suite.CustodyFixture, r *Report) {
continue
}
- // A refusal must be byte-identical to the refusal for an item that
- // never existed. Anything a server adds here — a reason, a name, a
- // revision — tells the caller the item is real.
- if body != baseline.Body.String() {
- r.fail("S3 %s: refusal body %q differs from the refusal for an item that does not exist (%q), so the answer reveals that this item exists",
- c.ItemID, body, baseline.Body.String())
+ // A refusal must be identical to the refusal for an item that never
+ // existed — body AND headers. Anything a server adds here, a reason
+ // in the body or a title in a header, tells the caller the item is
+ // real (headers: Astra, 2026-11-01).
+ if refusal(rec) != refusal(baseline) {
+ r.fail("S3 %s: refusal %s differs from the refusal for an item that does not exist (%s), so the answer reveals that this item exists",
+ c.ItemID, refusal(rec), refusal(baseline))
}
}
}
-// Gate 3, the authorization half. The fixture's asker deliberately holds a
-// live grant on the private and granted items and a former grant on the
-// deleted one: the custody intersection (§4.3) has to beat the grant, or a
-// consumer holding an ingested id learns the item is still there.
+// Gate 3, the authorization half. Since revision 10, S2 is the app's own read
+// check for the named asker: the team rung, ownership, or a live individual
+// grant, and never a link. The fixture's asker owns one private item, holds a
+// grant on another and a former grant on a deleted one, and does not own the
+// link-shared and moved-to-private items, so each part of the check shows.
func checkS2(h http.Handler, f suite.CustodyFixture, r *Report) {
// Three questions, not one. A single question at the current revision for
// a single person lets a server answer from the rung alone and read
@@ -130,8 +197,23 @@ func checkS2(h http.Handler, f suite.CustodyFixture, r *Report) {
askS2(h, f, r, "the fixture's asker, one revision behind", f.Asker, behind,
func(c suite.CustodyCase) suite.Authorization { return c.S2ResultSuperseded })
+ ahead := make([]suite.ItemRevision, 0, len(f.Cases))
+ for _, c := range f.Cases {
+ ahead = append(ahead, suite.ItemRevision{ItemID: c.ItemID, Revision: c.Revision + 1})
+ }
+ askS2(h, f, r, "the fixture's asker, one revision ahead", f.Asker, ahead,
+ func(c suite.CustodyCase) suite.Authorization { return c.S2ResultAhead })
+
askS2(h, f, r, "a person with no team standing", f.Stranger, current,
func(c suite.CustodyCase) suite.Authorization { return c.S2ResultStranger })
+
+ // The stranger at the other revisions too: a server that checks the
+ // revision before the person tells a stranger STALE where it owes them
+ // NOT_VISIBLE (Astra, 2026-11-01).
+ askS2(h, f, r, "a person with no team standing, one revision behind", f.Stranger, behind,
+ func(c suite.CustodyCase) suite.Authorization { return c.S2ResultStranger })
+ askS2(h, f, r, "a person with no team standing, one revision ahead", f.Stranger, ahead,
+ func(c suite.CustodyCase) suite.Authorization { return c.S2ResultStranger })
}
func askS2(h http.Handler, f suite.CustodyFixture, r *Report, what string, asker suite.Subject, pairs []suite.ItemRevision, want func(suite.CustodyCase) suite.Authorization) {
@@ -160,13 +242,81 @@ func askS2(h http.Handler, f suite.CustodyFixture, r *Report, what string, asker
// Gate 1 for the feed, and the leak memoria's draft 1 shipped. The decoder
// refuses unknown fields, so a row carrying a title, a body or a visibility
// flag fails here rather than in a store somebody greps a year later.
-func checkS1(h http.Handler, r *Report) {
- rec := do(h, "GET", suite.RouteS1+"?cursor=", nil)
- r.Checked++
+//
+// And what the rows say (Astra, 2026-11-01). Under revision 10 the feed
+// carries every live item at its current revision, not gone, and `gone`
+// means deleted and nothing else: a server still marking private items gone
+// would keep a person's own documents out of their search. The last row for
+// an item is its state; a deleted item may be absent or gone, never live.
+func checkS1(h http.Handler, f suite.CustodyFixture, r *Report) {
+ // Every page, as a consumer reads them: follow the cursor until it
+ // comes back unchanged with no rows (Astra, 2026-11-01: the first
+ // version read one page and failed a correct server that paged). A
+ // cursor that comes back unchanged WITH rows, or a feed that will not
+ // end, is a server a consumer cannot finish reading.
+ const maxPages = 100
+ last := map[string]suite.FeedRow{}
+ cursor := ""
+ for page := 0; ; page++ {
+ if page == maxPages {
+ r.fail("S1: no tip after %d pages — a consumer polls a feed like this for ever", maxPages)
+ return
+ }
+ rec := do(h, "GET", suite.RouteS1+"?cursor="+url.QueryEscape(cursor), nil)
+ r.Checked++
+ feed, err := suite.DecodeS1(rec.Code, rec.Body.Bytes())
+ if err != nil {
+ r.fail("S1: %v", err)
+ return
+ }
+ for _, row := range feed.Rows {
+ last[row.ItemID] = row
+ }
+ if feed.Cursor == cursor {
+ if len(feed.Rows) > 0 {
+ r.fail("S1: the cursor came back unchanged with %d rows; a consumer cannot make progress", len(feed.Rows))
+ }
+ break
+ }
+ cursor = feed.Cursor
+ }
+ for _, c := range f.Cases {
+ r.Checked++
+ row, ok := last[c.ItemID]
+ if c.Rung == suite.RungDeleted {
+ if ok && !row.Gone {
+ r.fail("S1 %s: a deleted item's last row is not gone", c.ItemID)
+ }
+ continue
+ }
+ switch {
+ case !ok:
+ r.fail("S1 %s (%s): a live item is missing from the feed", c.ItemID, c.Name)
+ case row.Gone:
+ r.fail("S1 %s (%s): a live item's last row is gone; gone means deleted", c.ItemID, c.Name)
+ case row.Revision != c.Revision:
+ r.fail("S1 %s: last row at revision %d, want %d", c.ItemID, row.Revision, c.Revision)
+ }
+ }
+}
- if _, err := suite.DecodeS1(rec.Code, rec.Body.Bytes()); err != nil {
- r.fail("S1: %v", err)
+// refusal is a response as a consumer could compare it: status, body and
+// every header but Date.
+func refusal(rec *httptest.ResponseRecorder) string {
+ var keys []string
+ for k := range rec.Header() {
+ if k != "Date" {
+ keys = append(keys, k)
+ }
+ }
+ sort.Strings(keys)
+ var b strings.Builder
+ b.WriteString(strconv.Itoa(rec.Code))
+ for _, k := range keys {
+ b.WriteString("|" + k + "=" + strings.Join(rec.Header()[k], ","))
}
+ b.WriteString("|" + rec.Body.String())
+ return b.String()
}
func do(h http.Handler, method, url string, body []byte) *httptest.ResponseRecorder {
diff --git a/conformance/conformance_test.go b/conformance/conformance_test.go
index acc53b7..d3882ea 100644
--- a/conformance/conformance_test.go
+++ b/conformance/conformance_test.go
@@ -19,12 +19,26 @@ type referenceServer struct {
// The bugs each broken variant introduces.
forbidInsteadOfNotFound bool // answers 403 where the contract says 404
- honourGrantOverCustody bool // answers VISIBLE for a granted item
+ intersectWithTeamRung bool // revision 9's rule: NOT_VISIBLE for anything off the team rung
+ linkCountsAsGrant bool // answers VISIBLE for a link-shared item
leakVisibilityInFeed bool // adds a field the feed row may not carry
leakBodyInRefusal bool // right status, and the item's secrets in the body
wrongBodyForTeamItem bool // 200, carrying a different item's bytes
tellExistenceApart bool // a different refusal for "never existed"
ignoreAskerAndRevision bool // VISIBLE for any asker, at any revision
+ serveSuperseded bool // 200 with today's bytes for an older revision
+ staleWhenAhead bool // STALE for a revision ahead of the log
+ revisionBeforePerson bool // STALE for a stranger at an old revision
+ privateAsGone bool // revision 9's feed: non-team items gone
+ leakHeaderInRefusal bool // the right 404, with a title in a header
+ serveFuture bool // 200 with today's bytes for a newer revision
+ ignoreKind bool // answers by the asker's value, whatever its kind
+ deletedLive bool // a deleted item advertised live in the feed
+ staleFeedRevision bool // feed rows one revision behind
+ neverEnds bool // a new cursor every page, for ever
+ stuckWithRows bool // the same cursor back, with rows
+ reservedCursor bool // cursors that need query escaping (correct)
+ repeatEarlierRow bool // an item's last row older than its current revision
}
func (s *referenceServer) find(itemID string) (suite.CustodyCase, bool) {
@@ -62,7 +76,10 @@ func (s *referenceServer) serveS3(w http.ResponseWriter, r *http.Request) {
}
return
}
- if c.Rung == suite.RungTeam {
+ // Revision 10: every live item is held, so every live item is served —
+ // at its current revision only.
+ rev, _ := strconv.ParseInt(r.URL.Query().Get("revision"), 10, 64)
+ if c.Rung != suite.RungDeleted && (rev == c.Revision || (s.serveSuperseded && rev < c.Revision) || (s.serveFuture && rev > c.Revision)) {
w.WriteHeader(200)
if s.wrongBodyForTeamItem {
w.Write([]byte("the bytes of some other document entirely"))
@@ -75,6 +92,9 @@ func (s *referenceServer) serveS3(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(403)
return
}
+ if s.leakHeaderInRefusal {
+ w.Header().Set("X-Item-Title", c.Name)
+ }
w.WriteHeader(404)
if s.leakBodyInRefusal {
// The status the contract demands, and the secret in the body anyway.
@@ -98,8 +118,34 @@ func (s *referenceServer) serveS2(w http.ResponseWriter, r *http.Request) {
Results []result `json:"results"`
}{}
+ if req.Asker.Kind != s.fixture.Asker.Kind && !s.ignoreKind {
+ // An asker of a kind this server does not key on: UNKNOWN for the
+ // whole call (gate 2).
+ for _, p := range req.Pairs {
+ out.Results = append(out.Results, result{ItemID: p.ItemID, Revision: p.Revision, Result: suite.UNKNOWN})
+ }
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(out)
+ return
+ }
stranger := req.Asker.Value != s.fixture.Asker.Value
+ // mayOpen is the app's own read check (revision 10): the team rung for
+ // any member, the item's owner, or a live individual grant. A link is
+ // not a grant, and a deleted item opens for nobody.
+ mayOpen := func(c suite.CustodyCase) bool {
+ if c.Rung == suite.RungDeleted {
+ return false
+ }
+ if s.linkCountsAsGrant && c.Link != "" {
+ return true
+ }
+ if s.intersectWithTeamRung {
+ return c.Rung == suite.RungTeam
+ }
+ return c.Rung == suite.RungTeam || c.Owner == "asker" || c.AskerGrant
+ }
+
for _, p := range req.Pairs {
c, ok := s.find(p.ItemID)
answer := suite.NOT_VISIBLE
@@ -114,19 +160,24 @@ func (s *referenceServer) serveS2(w http.ResponseWriter, r *http.Request) {
answer = suite.VISIBLE
}
+ case stranger && s.revisionBeforePerson && p.Revision < c.Revision:
+ answer = suite.STALE
+
case stranger:
// No team standing reaches nothing, the team rung included.
answer = suite.NOT_VISIBLE
- case c.Rung == suite.RungTeam && p.Revision != c.Revision:
+ case mayOpen(c) && p.Revision < c.Revision:
answer = suite.STALE
- case c.Rung == suite.RungTeam:
- answer = suite.VISIBLE
+ case mayOpen(c) && p.Revision > c.Revision:
+ // A revision the log does not recognise (§4.3).
+ answer = suite.UNKNOWN
+ if s.staleWhenAhead {
+ answer = suite.STALE
+ }
- case s.honourGrantOverCustody && c.Rung == suite.RungGranted:
- // The bug the intersection exists to prevent: answering from the
- // grants join alone, so a grantee learns a non-team item exists.
+ case mayOpen(c):
answer = suite.VISIBLE
}
out.Results = append(out.Results, result{ItemID: p.ItemID, Revision: p.Revision, Result: answer})
@@ -139,10 +190,14 @@ func (s *referenceServer) serveS2(w http.ResponseWriter, r *http.Request) {
func (s *referenceServer) serveS1(w http.ResponseWriter, r *http.Request) {
rows := []map[string]any{}
for _, c := range s.fixture.Cases {
+ rev := c.Revision
+ if s.staleFeedRevision {
+ rev--
+ }
row := map[string]any{
"item_id": c.ItemID,
- "revision": c.Revision,
- "gone": c.Rung != suite.RungTeam,
+ "revision": rev,
+ "gone": (c.Rung == suite.RungDeleted && !s.deletedLive) || (s.privateAsGone && c.Rung != suite.RungTeam),
"touched_at": "2026-09-05T09:00:00Z",
}
if s.leakVisibilityInFeed {
@@ -150,8 +205,50 @@ func (s *referenceServer) serveS1(w http.ResponseWriter, r *http.Request) {
}
rows = append(rows, row)
}
+ // Two pages of rows, and then the tip, which answers the cursor it was
+ // given. A correct feed may page; the harness must follow it.
+ cursor := r.URL.Query().Get("cursor")
+ half := len(rows) / 2
+ var page []map[string]any
+ next := cursor
+ switch cursor {
+ case "":
+ page, next = rows[:half], "c-1"
+ case "c-1":
+ page, next = rows[half:], "c-2"
+ default:
+ page = []map[string]any{}
+ }
+ if s.reservedCursor {
+ // A cursor with characters a query string must escape. A harness
+ // that sent it unescaped would read "c 1&x=y" as "c 1".
+ switch cursor {
+ case "":
+ page, next = rows[:half], "c 1&x=y"
+ case "c 1&x=y":
+ page, next = rows[half:], "c+2#end"
+ default:
+ page = []map[string]any{}
+ }
+ }
+ if s.repeatEarlierRow && cursor == "c-1" {
+ // The second page repeats an item from the first at an older
+ // revision: the item's state is its LAST row, and it is stale.
+ stale := map[string]any{}
+ for k, v := range rows[0] {
+ stale[k] = v
+ }
+ stale["revision"] = rows[0]["revision"].(int64) - 1
+ page = append(page, stale)
+ }
+ if s.neverEnds {
+ next = cursor + "x"
+ }
+ if s.stuckWithRows && cursor == "c-1" {
+ next = cursor
+ }
w.Header().Set("Content-Type", "application/json")
- json.NewEncoder(w).Encode(map[string]any{"cursor": "c-" + strconv.Itoa(len(rows)), "rows": rows})
+ json.NewEncoder(w).Encode(map[string]any{"cursor": next, "rows": page})
}
func newReference(t *testing.T) *referenceServer {
@@ -186,17 +283,32 @@ func TestHarnessCatches403ForANonTeamItem(t *testing.T) {
}
}
-// §4.3's custody intersection. A server answering from its grants join alone
-// says VISIBLE for an individually granted item, and a consumer holding that
-// item's id learns it still exists.
-func TestHarnessCatchesGrantBeatingCustody(t *testing.T) {
+// Revision 10 (Paul, 2026-11-01) removed §4.3's custody intersection: the
+// consumer holds every live item, and S2 answers from the app's own read
+// check. A server still answering by revision 9's rule — NOT_VISIBLE for
+// anything off the team rung — hides a person's own private documents and
+// those granted to them from their own search.
+func TestHarnessCatchesTheOldTeamOnlyRule(t *testing.T) {
s := newReference(t)
- s.honourGrantOverCustody = true
+ s.intersectWithTeamRung = true
report := conformance.Check(s)
if len(report.Failures) == 0 {
- t.Error("harness passed a server whose S2 ignored the custody intersection")
+ t.Error("harness passed a server whose S2 still intersects with the team rung")
+ }
+}
+
+// A link is not a grant (§4.2), and with custody widened it is the line
+// that keeps a link-shared private document out of a teammate's search.
+func TestHarnessCatchesALinkCountedAsAGrant(t *testing.T) {
+ s := newReference(t)
+ s.linkCountsAsGrant = true
+
+ report := conformance.Check(s)
+
+ if len(report.Failures) == 0 {
+ t.Error("harness passed a server whose S2 treats a read link as a grant")
}
}
@@ -265,3 +377,64 @@ func TestHarnessCatchesAFeedRowCarryingVisibility(t *testing.T) {
t.Error("harness passed a feed row carrying a visibility flag")
}
}
+
+// Astra's surviving mutants (2026-11-01), each now a broken server the
+// harness must refuse.
+func TestHarnessCatchesWhatTheFirstRevision10HarnessMissed(t *testing.T) {
+ for name, bend := range map[string]func(*referenceServer){
+ "a superseded revision served": func(s *referenceServer) { s.serveSuperseded = true },
+ "STALE for a revision ahead": func(s *referenceServer) { s.staleWhenAhead = true },
+ "STALE for a stranger": func(s *referenceServer) { s.revisionBeforePerson = true },
+ "private items gone from the feed": func(s *referenceServer) { s.privateAsGone = true },
+ "a title in a refusal's headers": func(s *referenceServer) { s.leakHeaderInRefusal = true },
+ "a future revision served": func(s *referenceServer) { s.serveFuture = true },
+ "the asker's kind ignored": func(s *referenceServer) { s.ignoreKind = true },
+ "a deleted item advertised live": func(s *referenceServer) { s.deletedLive = true },
+ "feed rows a revision behind": func(s *referenceServer) { s.staleFeedRevision = true },
+ "a feed that never ends": func(s *referenceServer) { s.neverEnds = true },
+ "a cursor stuck with rows": func(s *referenceServer) { s.stuckWithRows = true },
+ } {
+ s := newReference(t)
+ bend(s)
+ if report := conformance.Check(s); len(report.Failures) == 0 {
+ t.Errorf("%s: the harness passed it", name)
+ }
+ }
+}
+
+// A lone-shape app keys on addresses. RunAs gives the fixture's asker and
+// stranger that kind; the reference server, keyed on addresses, passes, and
+// asks under person_ref are UNKNOWN.
+func TestHarnessRunsForAnAddressKeyedApp(t *testing.T) {
+ s := newReference(t)
+ s.fixture.Asker.Kind, s.fixture.Stranger.Kind = suite.SubjectAddress, suite.SubjectAddress
+ if report := conformance.CheckAs(s, suite.SubjectAddress); len(report.Failures) != 0 {
+ t.Errorf("an address-keyed reference server failed: %v", report.Failures)
+ }
+}
+
+// Astra's round-3 polish (2026-11-01): what its independent probes covered
+// and the repository's suite did not.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: the cursor sent unescaped →
+// "reserved characters"; the FIRST row for an item taken as its state →
+// "an item's last row"; the wrong-kind check skipped in address mode → "an
+// address-keyed server ignoring the kind".
+func TestHarnessRound3(t *testing.T) {
+ s := newReference(t)
+ s.reservedCursor = true
+ if report := conformance.Check(s); len(report.Failures) != 0 {
+ t.Errorf("reserved characters: a correct server with such cursors failed: %v", report.Failures)
+ }
+ s = newReference(t)
+ s.repeatEarlierRow = true
+ if report := conformance.Check(s); len(report.Failures) == 0 {
+ t.Error("an item's last row: a feed whose last row for an item is a revision behind passed")
+ }
+ s = newReference(t)
+ s.fixture.Asker.Kind, s.fixture.Stranger.Kind = suite.SubjectAddress, suite.SubjectAddress
+ s.ignoreKind = true
+ if report := conformance.CheckAs(s, suite.SubjectAddress); len(report.Failures) == 0 {
+ t.Error("an address-keyed server ignoring the kind passed")
+ }
+}
diff --git a/docs/superpowers/specs/2026-09-05-suite-sharing-doctrine.md b/docs/superpowers/specs/2026-09-05-suite-sharing-doctrine.md
index f5ac5c6..1935b18 100644
--- a/docs/superpowers/specs/2026-09-05-suite-sharing-doctrine.md
+++ b/docs/superpowers/specs/2026-09-05-suite-sharing-doctrine.md
@@ -3,7 +3,61 @@
How the apps of the suite share identity, membership and content with
each other, and where the line is that nothing crosses.
-**Status:** design, **revision 9**, 2026-10-26.
+**Status:** design, **revision 10**, 2026-11-01. Revision 10 carries
+Paul's ruling and was reviewed by GPT-6 (Codex, "Astra") in three passes:
+REQUEST CHANGES on 12848f8 and 53b79d5, **APPROVE** on 983114a, its polish
+items applied after.
+
+**Revision 10 widens custody to every live item, by Paul's ruling, and
+builds the producer half.** Asked *"Is it possible for everyone's Memoria to
+respect / search across the things that only they have access to?"* and
+offered three answers — keep custody to the team rung; let a consumer hold
+private and granted items too and rule each one per person on every
+request; or search each app live and copy nothing — Paul chose the second:
+**"Hold private too, check per person"** (2026-11-01). The same day he ruled
+Docs' sharing default: *"New docs Team, old private"* — a new document is on
+the `team` rung unless its owner makes it private, and an existing document
+stays where it is. What changes, each where it lives:
+
+- **§4.2 custody** is every live item. The ladder still exists and still
+ decides who may open what inside the app; it no longer bounds what a
+ consumer may hold. `gone` means deleted, and only that.
+- **§4.3**: S2 is the app's own read check for the named asker — the team
+ rung for a member, ownership, a live grant, never a link — with **no
+ intersection with custody**. The cost the intersection paid is gone with
+ it; the risk it carried moves into S2 itself (below).
+- **S3** serves every live item, and refuses with one byte-identical 404
+ only what is deleted, unknown, at a revision that is not current, or too
+ large to serve.
+- **The fixture** (`custody.json`) is rewritten to that rule, with an
+ `owner` and `asker_grant` per case so an app can seed it; the harness's
+ reference server is the new rule, and its broken variants now include
+ revision 9's team-only S2 and a link counted as a grant.
+- **§6.5** is new: the producer half, `amadan.net/oficina/suite/server`.
+
+**What Paul accepted, said plainly.** Under revision 9 a consumer held only
+what every teammate could read, so a bug in its per-person gate could at
+worst show a teammate something they could already open in the app. Under
+revision 10 a consumer holds everyone's private and individually shared
+items, sealed at rest like everything else it holds, and the same bug shows
+a teammate somebody else's private document. S2 — asked per person, per
+request, never cached, with every non-`VISIBLE` answer withholding — is now
+the only thing between those documents and a teammate's search, and every
+surface of a consumer that names an item must pass through it, not search
+alone. A consumer also learns that private items exist, which §4.2's
+indistinguishability used to hide from it; it was never a person, and the
+person-facing guarantee is S2's.
+
+**A consumer must be ready before it ingests a private item** (gate 3c,
+§11). Every surface it has that names a document asks S2 for the person in
+the same request — not search alone. memoria found its own document page
+asking nothing on the day of the ruling (memoria §8.13); A.4 makes the
+gate binding.
+
+**What is not ruled by this revision:** guests. A guest is never on a
+roster, so a consumer never names one as an asker; an item granted only to a
+guest is held, and only its owner (and any member it is also granted to)
+sees it in a consumer.
**Revision 8 records that the contract module cannot be imported**, which
makes §12 step 2 built rather than done. `amadan.net/oficina/suite` does not
@@ -121,7 +175,11 @@ The falsifiable form, in two halves:
- **Inside.** Take a team's instances of every app. Publish what any one of
them holds and the worst anyone learns is what that team could read in
- the owning app **at the moment the copy was taken**. An honest instance
+ the owning app **at the moment the copy was taken**. *(Since revision
+ 10 (Paul, 2026-11-01) an instance holds every live item, so "what that
+ team could read" becomes "every live item in the team's apps", and a copy
+ is retired when its item is deleted, not when it leaves the team rung.
+ The sentence that follows is revision 9's.)* An honest instance
retires a copy that has left team-visibility within one feed pull plus
**the retention its own spec states** — memoria §7.4 holds that number
today, and a consumer that states none is not conformant. §4.2 carries
@@ -163,7 +221,7 @@ happened to fall while every CARLOS app was one process.
|---|---|---|---|
| 1 | **The team is the boundary. An instance is a process.** A team's instances across every app are one trust domain at `<team>.<app>.oficina.works`. | One boundary per process, which left memoria holding person-initiated snapshots and made the home's activity feed a federation question | Paul, 2026-09-03 (memoria decision 1); reaffirmed suite-wide 2026-09-05 |
| 2 | **Sharing is membership across teams, unchanged.** No data crosses a team label. A guest is a scoped member of the granting team. A link share moves nothing. | Any federation story; a "copy to my team" verb | Pegamento §3, applied |
-| 3 | **Custody and authorization are two rules.** Custody bounds what a sibling may *hold*: team-visible items only. Authorization is what a *person* may read: asked of the app of record, per person, per query, **never cached**. Team standing is not authorization; it is the roster, a pulled copy refreshed by epoch (§5). A copy is never an authority. | One ACL copied between apps; "is a member" as the only question | Paul, 2026-09-03 (memoria decision 3); generalised 2026-09-05 |
+| 3 | **Custody and authorization are two rules.** *(Custody's half superseded by revision 10, Paul, 2026-11-01: a sibling holds every live item; authorization's half stands and now carries the whole weight.)* Custody bounds what a sibling may *hold*: team-visible items only. Authorization is what a *person* may read: asked of the app of record, per person, per query, **never cached**. Team standing is not authorization; it is the roster, a pulled copy refreshed by epoch (§5). A copy is never an authority. | One ACL copied between apps; "is a member" as the only question | Paul, 2026-09-03 (memoria decision 3); generalised 2026-09-05 |
| 4 | **The home owns identity and the team, including the membership roster. It never owns a per-item grant.** | Per-instance rosters as the record, reconciled by asking siblings; the home holding document-level grants | Paul, 2026-09-05 |
| 5 | **Two shapes, one switch.** A *lone* instance is its own identity authority and its own roster. A *suite* instance takes both from the home. Membership authority follows identity authority; an instance never has one without the other. | A suite instance half-trusting its local table; a lone instance dialling a home for a roster it does not need | Paul, 2026-08-31 (Docs §8.1, two shapes); extended to the roster 2026-09-05 |
| 6 | **Egress is one suite sentence.** Egress that is a property of the product is forbidden. Egress that is per-team opt-in, to one named recipient, disclosed, with a working floor when off, is admissible. | Two contradicting texts, Docs §11.2 and memoria §8.3 | Paul, 2026-09-03 (memoria decision 4); made suite-wide 2026-09-05 |
@@ -174,8 +232,8 @@ happened to fall while every CARLOS app was one process.
| 11 | **Activity is pulled at render and held nowhere at rest** — `oficina/home` ruling 18 and the `design-activity-pull` spec, adopted as suite contract call 7. | Push into the home; a contentless heat map | Paul, 2026-09-05 (home ruling 18) |
| 12 | **Membership is its own record at the home, written only by an owner.** `(team, person, role)`, written at the directory origin behind step-up, or seeded by the drain with the team's first owner. A directory row says where a person has things; it never grants or revokes team standing. Call 2 cannot write membership and call 8 reads only the membership record. | Deriving the roster from call-2 directory rows, which revision 1 chose. The row has no owner role to project (home §6: `kind` is member or guest; home §7: who counts as an owner "is the instance's business… and the home never learns the answer"); it is scoped per (team, app) where the roster is per team, so a projection can express "member of acme.docs but not acme.sheets", which ruling 1 forbids; and any instance writes it under a consumer token, so deriving from it routes around §5.4's step-up. Those three are verified against home §§6 and 7; whether they are together *unbuildable* is a stronger claim than the evidence carries, and revision 3 made it | Paul, 2026-09-05, on Fable's recommendation after the GPT-6 review (finding 1) |
| 13 | **A compromised home is three compromises and each is conceded on its own.** A leaked database reveals the graph, the roster, and who owns each team. A compromised directory origin can add a member, and a member reads everything team-visible in every instance of that team. A compromised credential origin can sign in as anyone, owners included, and no instance can tell. | One undifferentiated "compromised home" that "cannot read a document", which took home §2's careful *directory* and widened it to *home*, and counted as evidence what only honest code leaves behind | Paul, 2026-09-05, on Fable's recommendation after the GPT-6 review (finding 2) |
-| 14 | **Custody is bounded at acquisition and retired by the feed. It is not enforced by erasure.** What an instance may *acquire* is team-visible at the time; what it may *render* is live-authorized (ruling 3); what it must *retire* is stated and timed. Three rules, not one. | §0's inside test stated instantaneously; source-driven tombstone push (home §6: no channel reaches a hibernating instance); sealing pulled content under a source-held key, which buys nothing once a consumer has indexed, since an embedding is content in another costume (memoria §3.1) | Paul, 2026-09-05, on Fable's recommendation after the GPT-6 review (finding 6) |
-| 15 | **Three rungs and a read-only link.** An item is *private*, *granted* to named people, or *team*. Orthogonally it may carry a **read-only** link capability — view, or comment where the app has that role. **Only the `team` rung is team-visible**, so custody keys on the rung and never on the link. **Every write has a named actor**: a member, or a guest who signed in and took a grant. | Treating a link as team-visible because "anyone can read it", which turns a capability held by whoever has the URL into a listing every team member finds by search. **And anonymous link editing**, which Sheets ruling 12 rejected on 2026-08-30 and which revision 3 rebuilt without citing it. An "edit link" is a capability to *obtain a guest grant at sign-in* — the `granted` rung, and how Docs already builds its commenter link | Paul, 2026-09-05, confirming Sheets ruling 12 |
+| 14 | **Custody is bounded at acquisition and retired by the feed. It is not enforced by erasure.** *(Revision 10, Paul, 2026-11-01: what may be acquired is every live item, and the feed retires on deletion only; the three-rules shape stands.)* What an instance may *acquire* is team-visible at the time; what it may *render* is live-authorized (ruling 3); what it must *retire* is stated and timed. Three rules, not one. | §0's inside test stated instantaneously; source-driven tombstone push (home §6: no channel reaches a hibernating instance); sealing pulled content under a source-held key, which buys nothing once a consumer has indexed, since an embedding is content in another costume (memoria §3.1) | Paul, 2026-09-05, on Fable's recommendation after the GPT-6 review (finding 6) |
+| 15 | **Three rungs and a read-only link.** An item is *private*, *granted* to named people, or *team*. Orthogonally it may carry a **read-only** link capability — view, or comment where the app has that role. **Only the `team` rung is team-visible**, so custody keys on the rung and never on the link. *(Revision 10, Paul, 2026-11-01: custody no longer keys on the rung — a sibling holds every live item — and the ladder decides who may open what through S2; a link is still never a grant.)* **Every write has a named actor**: a member, or a guest who signed in and took a grant. | Treating a link as team-visible because "anyone can read it", which turns a capability held by whoever has the URL into a listing every team member finds by search. **And anonymous link editing**, which Sheets ruling 12 rejected on 2026-08-30 and which revision 3 rebuilt without citing it. An "edit link" is a capability to *obtain a guest grant at sign-in* — the `granted` rung, and how Docs already builds its commenter link | Paul, 2026-09-05, confirming Sheets ruling 12 |
---
@@ -275,6 +333,15 @@ they are claimed as (memoria §6.3).
### 4.2 Custody
+> **Revision 10 (Paul, 2026-11-01): custody is every live item.** The
+> predicate below — team-visible — and the ladder now decide only who may
+> open an item inside its app, through S2 (§4.3); they no longer bound what
+> a consumer holds. A consumer holds every live item, `gone` means deleted
+> and nothing else, and S3 serves every live item. The text that follows is
+> revision 9's and is kept because its reasoning — a link is not a grant,
+> the rung and not the link decides — still governs S2. Where it says a
+> private item must not reach a consumer, revision 10 overrules it.
+
What a sibling may *hold* a copy of. The predicate is **team-visible**:
readable by every roster member by virtue of team standing alone. Each app
defines it in one function, and the conformance suite (§11) proves that a
@@ -385,6 +452,13 @@ in.** A copy never becomes an authority, and a derived artefact carries the
provenance of every source it was built from, transitively, so two hops
cannot launder what one cannot (memoria §13, now a suite rule).
+> **Revision 10 (Paul, 2026-11-01) removes the intersection below.** With
+> custody widened to every live item there is nothing to intersect with: S2
+> is the app's own read check for the named asker — the team rung for a
+> member, ownership, a live individual grant, never a link. A person's own
+> private documents and those granted to them reach their own search, and
+> nobody else's. The two paragraphs that follow are revision 9's.
+
**S2's answer is intersected with custody.** The app of record runs its
grants join for the named asker, and then answers `NOT_VISIBLE` for any
item that is not team-visible, whatever the asker's individual grants say.
@@ -676,9 +750,9 @@ spec, which owns them, and are cited here for completeness of direction.
| 7 activity | home → instance | **assertion** for the person, `aud` = instance | who the front door is for | `design-activity-pull` §4–5 owns the wire shape. The home renders and holds rendered output only, under two ages (§4.3). Not in the contract module yet — §12 step 2 is S1, S2 and S3. When it arrives, the fixtures **cite** that spec's gates 10–20 rather than restate them, or this contract rebuilds §2's drift one layer down. |
| 8 roster | instance → home | consumer token | which instance asks | §5.3. Scoped to the caller's team. Paged; the copy has a TTL. |
| S1 change feed | sibling → sibling | consumer token | same-team sibling | `(item_id, revision, gone, touched_at)`. No title, no content, no visibility flag. Per-consumer TTL; past it, full re-announce. |
-| S2 authorization | sibling → sibling | consumer token **+ named asker** | same-team sibling, asking for a person | Four values, total decoder, cap 256 pairs. **Never cached**: a passage crosses no request boundary without an S2 `VISIBLE` in the request that carried it (memoria §8.4, gate 26). Asker is a typed subject (§3); the answer is intersected with custody (§4.3). |
-| S3 content | sibling → sibling | consumer token | same-team sibling | `(id, revision)`, **no person**. Team-visible only. 404, never 403. |
-| S6 aggregate | sibling → Sheets | consumer token + named asker | as S2 | Enumerated function over cell refs, never expression text. Cap 64. Typed subject and the custody intersection, as S2. |
+| S2 authorization | sibling → sibling | consumer token **+ named asker** | same-team sibling, asking for a person | Four values, total decoder, cap 256 pairs. **Never cached**: a passage crosses no request boundary without an S2 `VISIBLE` in the request that carried it (memoria §8.4, gate 26). Asker is a typed subject (§3); the answer is the app's own read check for that person — team rung, ownership, a live grant, never a link — with no custody intersection since revision 10 (§4.3). |
+| S3 content | sibling → sibling | consumer token | same-team sibling | `(id, revision)`, **no person**. Every live item at its current revision since revision 10 (team-visible only before it); one identical 404 for deleted, unknown or superseded. Never 403. |
+| S6 aggregate | sibling → Sheets | consumer token + named asker | as S2 | Enumerated function over cell refs, never expression text. Cap 64. Typed subject and the app's own read check, as S2 (no custody intersection since revision 10). |
| S8 write-as-self | sibling → sibling | consumer token | same-team sibling | §7.2. Into the caller's designated area only; only items the caller authored. |
| hand-off | browser → instance | the **person's own session** | the person | §7.1. A redirect POST, the shape of home call 6. Not a server call. |
@@ -720,6 +794,40 @@ Both are settled; they are recorded here because a table that runs S1, S2,
S3, S6, S8 leaves two holes, and a hole in a numbered contract is somewhere
a later call falls. *(Review pass, 2026-09-05.)*
+### 6.5 The producer half (revision 10)
+
+`amadan.net/oficina/suite/server` is the server half §6 names, built with
+the first two apps that serve it (Docs and Fichas). An app implements one
+interface, `Producer` — `Feed(cursor, limit)`, `Rule(asker, pairs)`,
+`Content(item, revision)` — and mounts `server.Handler` beside its router.
+The package owns everything an app could get subtly wrong and must not get
+differently from its neighbour:
+
+- **The bearer check.** `<APP>_SUITE_CONSUMERS` is strict JSON,
+ `[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"<hex>"}]}]`,
+ one or two tokens per consumer (§6.2's rotation), each held only as its
+ SHA-256. Every configured hash is compared in constant time, and every
+ failure is the same empty 401. Unset means no consumers and no routes;
+ malformed refuses boot.
+- **S1.** `rows` is never null; a producer's empty cursor is a 500, and a
+ failed read a 503, never an empty page. At the tip the producer returns
+ the cursor it was given and no rows, which is what stops memoria's poll.
+ 256 rows a page.
+- **S2.** The request is decoded strictly (no unknown fields, no trailing
+ document), the asker through `NewSubject`, the batch through
+ `CheckS2Batch`; anything else is a 400. A producer error is a 503, which
+ the consumer reads as `UNKNOWN` for the whole call; an answer count that
+ differs from the pair count is a 500. Every pair is echoed.
+- **S3.** One refusal — an empty 404 — for a deleted item, an id that
+ never existed, a revision that is not current, missing or malformed, and
+ a body over 2 MiB (memoria refuses more than 2 MiB + 64 KiB and would
+ otherwise retry the same feed page for ever). Never 403. A 200 is
+ `text/plain`.
+
+`server.Routes` is the same routes without the bearer check, for the
+conformance harness, which drives a handler with no token. An app never
+mounts it. The package keeps the module's rule: standard library only.
+
### 6.1 Why two credentials
**Only the home can mint an assertion**, and putting the home in the loop
@@ -787,7 +895,7 @@ depends on whether the path has a person**, because two of them do not:
| Path | Has an asker? | The check |
|---|---|---|
| An ordinary read, an export, an activity row | Yes | S2 to each app of record, for that person |
-| An onward S3 fetch | **No** — S3 is person-less by definition (§6) | **Custody**: every source still team-visible, or S3 answers 404 |
+| An onward S3 fetch | **No** — S3 is person-less by definition (§6) | **Custody**: every source still live (revision 10; "still team-visible" before it), or S3 answers 404. The person-facing check is the ordinary read's: S2 for every source, for the asker |
| A read through a read-only link | **No** — a link holder is no roster subject | The item carries no link while any source is not itself link-shared |
Revision 3 wrote "the sources still authorize the asker" for all of them,
@@ -972,7 +1080,15 @@ wording (Appendix A).
Each app keeps its own. These are the costs that exist only because the
apps are a suite, and every one is a consequence of ruling 1 or 4.
-1. **A compromised sibling reads everything team-visible in its team**,
+1. **Since revision 10 (Paul, 2026-11-01), a compromised sibling reads
+ every live item in its team**, private and individually granted ones
+ included, through S3 and from its own store — that is what "Hold
+ private too, check per person" costs, and Paul accepted it knowingly.
+ What follows in this item is revision 9's bound, kept for the record;
+ the claim that a compromised sibling "cannot read an item that was
+ never team-visible" no longer holds.
+
+ *Revision 9:* **A compromised sibling reads everything team-visible in its team**,
across every app, through S3, **and everything that was team-visible
when it was ingested**. This is what "one trust domain" means and there
is no version of ruling 1 without it. Custody buys two things and not a
@@ -981,11 +1097,12 @@ apps are a suite, and every one is a consequence of ruling 1 or 4.
leaves; a compromised one retires nothing, and no revocation reaches a
copy it already holds (ruling 14).
2. **A compromised sibling can name any asker on S2**, and so learn which
- team-visible items a given member may see. Bounded by item 1: it can
- already read them all. **The bound holds only because S2 is intersected
- with custody** (§4.3); without the intersection it would also learn
- which private items exist, which item 1 does not cover and §4.2
- forbids.
+ items a given member may open — private ones included, since revision
+ 10 removed the intersection (Paul, 2026-11-01). Bounded by item 1 as
+ revision 10 states it: it already holds every live item, so what S2
+ adds is who may open each, which a compromised holder of the items and
+ the roster could largely infer anyway. *Revision 9 bounded this by the
+ custody intersection; that bound no longer exists.*
3. **A compromised sibling can write into its own designated area** as
itself (S8). It cannot write as a person or touch a person-authored
item.
@@ -1088,7 +1205,21 @@ that cannot be written as stated is a spec bug.
with short, duplicate, malformed and non-2xx responses, and with an
asker subject of a kind the receiver does not key on, which is
`UNKNOWN` for the whole call and never `NOT_VISIBLE`.
-3. **Custody, one fixture per rung.** S3 answers 200 for a `team` item and
+3. **Custody, one fixture per rung — revision 10's rule** (Paul,
+ 2026-11-01; `fixtures/custody.json` is the operative statement). S3
+ answers 200 with the item's own bytes for **every live item** at its
+ current revision, whatever its rung, and one identical 404 — status,
+ headers and body — for a deleted item, an id that never existed, and a
+ superseded revision. S2 is the app's own read check for the named asker:
+ `VISIBLE` for the team rung, the owner and a live grantee; `NOT_VISIBLE`
+ for a link-only, guest-only or moved-to-private item the asker neither
+ owns nor holds a grant on, for a deleted one, and for a stranger at any
+ revision; `STALE` one revision behind and `UNKNOWN` one ahead for a
+ person who may open it. S1 carries every live item at its current
+ revision, and `gone` only for deletion. The paragraph below is revision
+ 9's gate 3, superseded.
+
+ *Revision 9:* **Custody, one fixture per rung.** S3 answers 200 for a `team` item and
404 for `private`, `granted`, guest-only, **link-shared-but-not-team**
(ruling 15) and deleted. The status and body are identical for "not
team-visible" and "does not exist". **S2 answers `NOT_VISIBLE` for the
@@ -1098,6 +1229,14 @@ that cannot be written as stated is a spec bug.
live grant against a deleted row. Add **team-plus-link** (team-visible
because of the rung) and **a link added or revoked after ingest** (no
change to custody either way).
+3c. **A consumer is ready for private items** (revision 10). Before a
+ consumer ingests a sibling's private or granted items, a test seeds one
+ document the asker may open and one they may not, from a sibling that
+ answers S2 per item, and asserts that **every** surface naming a
+ document — search, its suggestions, any generated answer and its
+ citations, the document page, every list, a delete or report path —
+ shows the first and never the second, and withholds loudly when the
+ sibling does not answer. memoria's is `TestEverySurfaceAsksTheAppOfRecord`.
4. **No cross-team dial.** Zero connections to a host whose `<team>` label
differs — `acme-evil`, `acme.docs.oficina.works.evil` — and zero
*follow-up* connections when an allowed host answers with a redirect to
@@ -1129,9 +1268,9 @@ that cannot be written as stated is a spec bug.
6b. **Provenance survives the hop** (§7), one case per path because the
paths differ. Write an item into app B derived from sources in A and C.
Revoke A's source for a person: B's **ordinary read and export** withhold
- the **whole artefact** and name A — never a partial redaction. Make A's
- source non-team-visible: B's **S3** answers 404, on custody, with no
- asker anywhere in the call. Give B's item a read-only link while A's
+ the **whole artefact** and name A — never a partial redaction. Delete A's
+ source (revision 10; "make it non-team-visible" before it): B's **S3**
+ answers 404, on custody, with no asker anywhere in the call. Give B's item a read-only link while A's
source has none: the link is refused. Assert a write is refused when a
source's app of record serves no S2 at all.
7. **The hand-off, through the real middleware.** A handler-level fixture
@@ -1201,14 +1340,15 @@ that cannot be written as stated is a spec bug.
blocked, which is the right answer.
Types and fixtures only: S1, S2, S3, the
- hostile-hostname fixture, gates 1 to 4. No server half yet. Docs moves
- its module path.
+ hostile-hostname fixture, gates 1 to 4. No server half yet *(built in
+ revision 10 as `suite/server`, §6.5)*. Docs moves its module path.
3. **memoria slice 1 against the module**, with Sheets and Docs serving
S1 to S3. The second adoption corrects the fixtures.
4. **S6, before memoria's slice 2 and not before its slice 1.** Sheets
serves it, memoria calls it, and nobody else does either: an enumerated
aggregate over cell refs, capped at 64, never expression text, carrying
- the typed asker and the custody intersection S2 carries.
+ the typed asker and the read check S2 carries (no custody intersection
+ since revision 10).
**Slice 1 does not need it** — that is S1, S2, S3 and memoria §4.1, all
of which the module already has. Slice 2 is memoria's model layer, and
@@ -1245,7 +1385,7 @@ change to where the list comes from.
| A token exchange so siblings can hold assertions | The home's latency budget can afford being in every search, which §6.1 says it cannot |
| Mail and files as suite apps | A wrapper around keymail or slopbox that serves S1 to S3 and takes a roster |
| An instance-side check on membership changes — refusing a roster addition, or a call-7 arrival, for a person with no recent session; an owner countersignature on roster writes | A designed mechanism. Ruling 13 concedes a compromised home rather than bounding it, and this is the shape a bound would take. Recorded so it reads as absent by decision, not by oversight |
-| A link share that a sibling can index | Never, under ruling 15. A link is a capability, and a capability that becomes searchable by the team is a different grant than the one made |
+| A link share that a sibling can index | Never, under ruling 15. A link is a capability, and a capability that becomes searchable by the team is a different grant than the one made. **Since revision 10** a sibling holds link-shared items like every live item, and this row survives as a rule of S2: a link never makes an item `VISIBLE` to anybody (the fixture's `doc-link` and `doc-link-added-late`) |
---
@@ -1257,7 +1397,11 @@ change to where the list comes from.
different text. Rulings 12, 13 and 14 are Paul's, taken on Fable's
recommendation. **Ruling 15 is this session's proposal from Paul's
product requirement and he has not ruled on it** — a reader should treat
- it as the one rung of §1 that is not yet settled.
+ it as the one rung of §1 that is not yet settled. **Superseded
+ 2026-11-01**: Paul ruled the custody half away (revision 10, *"Hold
+ private too, check per person"*) and kept the ladder for who may open
+ what, with Docs' default *"New docs Team, old private"*. A link is still
+ never a grant.
- **What the second review said**, kept for the record. `CODEX-FINDINGS.md`
is unedited beside this file; the map from its findings to revision 3 is
in the status block. Its six trust-boundary findings were:
@@ -1376,6 +1520,13 @@ instance boundary."* with *"'Sharing is membership' forbids data crossing
a team boundary (suite ruling 2). Same-team siblings may pull
team-visible content under the suite contract (suite §6), and Docs serves
S1 to S3 and S8 **wherever sibling consumer tokens are configured**."*
+
+> **Revision 10 (Paul, 2026-11-01)** changes "team-visible content" to
+> **every live document**: Docs' S1 lists them all, S3 serves any at its
+> current revision, and S2 is Docs' own read check per person. Docs gains
+> a `team` rung for documents, the default for new ones and not for
+> existing ones (*"New docs Team, old private"*). Docs implements the
+> producer through `suite/server` (§6.5).
The sibling switch is independent of shape (suite §3): §12 steps 2 and 3
have Docs and Sheets serving lone peers before the home exists, so "in
suite shape" would forbid the sequencing this document depends on.
@@ -1418,6 +1569,11 @@ several apps sharing one trust domain (suite ruling 1), and same-team
siblings may pull team-visible sheets under the suite contract. There is
no federation story across teams and there will not be one."*
+> **Revision 10 (Paul, 2026-11-01):** "team-visible sheets" becomes
+> **every live sheet**, with S2 Sheets' own per-person read check, when
+> Sheets adopts the producer half (§6.5). Until then Sheets serves no
+> suite routes at all.
+
§8.2: append *"Team standing comes from the roster the home holds (suite
§5) in suite shape, and from `$SHEETS_OWNERS` in lone shape. Per-sheet
roles stay here."*
@@ -1447,6 +1603,19 @@ retired."*
§1.3: correct the S3 prose to match §6.1: S3 takes no person; the fix
removed the asker rather than adding one.
+> **Revision 10 (Paul, 2026-11-01) reverses the next paragraph's first
+> instruction**: do **not** intersect S2's answer with custody — memoria
+> holds every live sibling item and S2 is the app's own per-person check.
+> Typing the asker subject stands. And add one: **before memoria ingests a
+> sibling's private items, every memoria surface that names a sibling
+> document must obtain a fresh S2 answer for the person in the same
+> request** — search, typeahead, the AI answer and its citations, a
+> document's own page, every list ("Recently updated", the documents
+> list), the delete question, report and feedback links (which reach the
+> document page, so they are ruled there). A surface that names a document
+> without asking is the leak revision 10 moved the risk into. memoria
+> §8.13 records the surfaces and their gate.
+
§4.1: intersect S2's answer with the custody predicate (suite §4.3), and
type the asker subject (suite §3). The grants join as §4.1 states it —
Sheets §4.5's *"plus rows granted to me individually"* — answers `VISIBLE`
diff --git a/fixtures.go b/fixtures.go
index 1e63ad5..82b4bca 100644
--- a/fixtures.go
+++ b/fixtures.go
@@ -39,14 +39,22 @@ const (
)
// CustodyCase is one row of the custody fixture: an item, where it sits, and
-// what both calls must answer for the fixture's asker.
+// what both calls must answer for the fixture's asker. Since revision 10
+// (Paul, 2026-11-01) a consumer holds every live item and S2 answers from
+// the app's own read check, so the rung matters only through that check.
type CustodyCase struct {
Name string `json:"name"`
ItemID string `json:"item_id"`
Revision int64 `json:"revision"`
Rung Rung `json:"rung"`
Link string `json:"link"`
- S3Status int `json:"s3_status"`
+ // Owner is "asker" when the fixture's asker owns the item and "other"
+ // when somebody else does; AskerGrant is whether the asker holds a live
+ // individual grant on it. Together with Rung they are what an app seeds
+ // so its own read check produces the S2 answers below (revision 10).
+ Owner string `json:"owner"`
+ AskerGrant bool `json:"asker_grant"`
+ S3Status int `json:"s3_status"`
// S3Body is the exact body a content fetch must return: the item's bytes
// for a 200, and empty for every refusal. Checking the status alone let a
// server return the required 404 while including the item's secrets in the
@@ -57,14 +65,18 @@ type CustodyCase struct {
// revision behind. A team item is STALE — readable, but the app of record
// has moved on — and anything custody already refuses stays refused.
S2ResultSuperseded Authorization `json:"s2_result_superseded"`
+ // S2ResultAhead is the answer one revision ahead of the app's own: a
+ // revision its log does not recognise. UNKNOWN for a person who may open
+ // the item (§4.3), NOT_VISIBLE for one who may not.
+ S2ResultAhead Authorization `json:"s2_result_ahead"`
// S2ResultStranger is the answer for a person with no team standing.
S2ResultStranger Authorization `json:"s2_result_stranger"`
}
// NonexistentItemID is never in the fixture. A refusal for an item that does
-// not exist has to be byte-for-byte the refusal for one that exists and is not
-// team-visible — that indistinguishability is the whole of §4.2, and no case
-// in the fixture can test it, because every case is an item that exists.
+// not exist has to be byte-for-byte the refusal for one that was deleted, so
+// a consumer cannot tell a deletion from an id it made up. (Before revision
+// 10 the same held for every item that was not team-visible.)
const NonexistentItemID = "doc-no-such-item-ever"
// CustodyFixture is gate 3's world: one case per rung, plus team-plus-link and
diff --git a/fixtures/custody.json b/fixtures/custody.json
index fb10c04..1ec285e 100644
--- a/fixtures/custody.json
+++ b/fixtures/custody.json
@@ -1,84 +1,113 @@
{
"comment": [
- "Gate 3. One fixture per rung of the sharing ladder (doctrine §4.2,",
- "ruling 15), plus the two cases the reviews asked for: an item on the",
- "team rung that also carries a link, and an item whose link changed",
- "after it was ingested.",
+ "Gate 3. One fixture per rung of the sharing ladder (doctrine §4.2), plus",
+ "the cases the reviews asked for: an item on the team rung that also",
+ "carries a link, and an item whose link or rung changed after it was",
+ "ingested.",
+ "",
+ "REVISION 10 (Paul, 2026-11-01): custody is every live item, not only",
+ "team-visible ones. A consumer holds private and granted items too, and",
+ "S2 decides per person, from the app's own read check, with no",
+ "intersection with custody. So every live item answers S3 200 with its",
+ "own bytes; only a deleted item, and one that never existed, answer the",
+ "identical 404.",
"",
"The asker is the same person for every case, and the item id is quoted",
"in every case, so a server cannot pass by answering differently for",
- "different ids. What must differ is the rung; what must not differ is",
- "the answer for everything that is not `team`.",
+ "different ids. `owner` says who owns the item (the asker or someone",
+ "else) and `asker_grant` whether the asker holds a live individual grant",
+ "on it, so an app can seed the world. What must differ is whether the",
+ "asker may open the item today; the rung decides that only through the",
+ "app's own read check.",
"",
- "s3_status is what a content fetch answers. s2_result is what an",
- "authorization call answers for `asker`, who deliberately holds a live",
- "grant on doc-private and doc-granted and a former grant on doc-deleted:",
- "the intersection with custody (§4.3) must beat the grant every time."
+ "s2_result_ahead is the answer one revision AHEAD of the app's own: a",
+ "revision its log does not recognise is UNKNOWN for a person who may",
+ "open the item (§4.3), and NOT_VISIBLE for one who may not — a person",
+ "with no right to the item learns nothing about its revisions."
],
-
"team": "acme",
- "asker": { "kind": "person_ref", "value": "pers_ana" },
- "stranger": { "kind": "person_ref", "value": "pers_bo" },
-
+ "asker": {
+ "kind": "person_ref",
+ "value": "pers_ana"
+ },
+ "stranger": {
+ "kind": "person_ref",
+ "value": "pers_bo"
+ },
"cases": [
{
- "name": "team rung is the only thing custody admits",
+ "name": "team rung: every member may open it",
"item_id": "doc-team",
"s3_body": "the Q3 plan, shared with the whole team",
"revision": 7,
"rung": "team",
"link": null,
+ "owner": "other",
+ "asker_grant": false,
"s3_status": 200,
"s2_result": "VISIBLE",
"s2_result_superseded": "STALE",
+ "s2_result_ahead": "UNKNOWN",
"s2_result_stranger": "NOT_VISIBLE"
},
{
"name": "private, and the asker owns it",
"item_id": "doc-private",
- "s3_body": "",
+ "s3_body": "my own notes, private to me",
"revision": 4,
"rung": "private",
"link": null,
- "s3_status": 404,
- "s2_result": "NOT_VISIBLE",
- "s2_result_superseded": "NOT_VISIBLE",
+ "owner": "asker",
+ "asker_grant": false,
+ "s3_status": 200,
+ "s2_result": "VISIBLE",
+ "s2_result_superseded": "STALE",
+ "s2_result_ahead": "UNKNOWN",
"s2_result_stranger": "NOT_VISIBLE"
},
{
- "name": "granted to the asker individually",
+ "name": "private to someone else, granted to the asker by name",
"item_id": "doc-granted",
- "s3_body": "",
+ "s3_body": "the board pack, shared with me by name",
"revision": 9,
"rung": "granted",
"link": null,
- "s3_status": 404,
- "s2_result": "NOT_VISIBLE",
- "s2_result_superseded": "NOT_VISIBLE",
+ "owner": "other",
+ "asker_grant": true,
+ "s3_status": 200,
+ "s2_result": "VISIBLE",
+ "s2_result_superseded": "STALE",
+ "s2_result_ahead": "UNKNOWN",
"s2_result_stranger": "NOT_VISIBLE"
},
{
- "name": "granted to a guest only",
+ "name": "granted to a guest only: held, and the asker may not open it",
"item_id": "doc-guest",
- "s3_body": "",
+ "s3_body": "the contractor brief, shared with a guest only",
"revision": 2,
"rung": "granted",
"link": null,
- "s3_status": 404,
+ "owner": "other",
+ "asker_grant": false,
+ "s3_status": 200,
"s2_result": "NOT_VISIBLE",
"s2_result_superseded": "NOT_VISIBLE",
+ "s2_result_ahead": "NOT_VISIBLE",
"s2_result_stranger": "NOT_VISIBLE"
},
{
- "name": "link-shared but not team-shared: a link is not a rung",
+ "name": "private to someone else and link-shared: a link is not a grant",
"item_id": "doc-link",
- "s3_body": "",
+ "s3_body": "the press draft, private with a read link",
"revision": 5,
"rung": "private",
"link": "read",
- "s3_status": 404,
+ "owner": "other",
+ "asker_grant": false,
+ "s3_status": 200,
"s2_result": "NOT_VISIBLE",
"s2_result_superseded": "NOT_VISIBLE",
+ "s2_result_ahead": "NOT_VISIBLE",
"s2_result_stranger": "NOT_VISIBLE"
},
{
@@ -88,9 +117,12 @@
"revision": 3,
"rung": "team",
"link": "read",
+ "owner": "other",
+ "asker_grant": false,
"s3_status": 200,
"s2_result": "VISIBLE",
"s2_result_superseded": "STALE",
+ "s2_result_ahead": "UNKNOWN",
"s2_result_stranger": "NOT_VISIBLE"
},
{
@@ -100,33 +132,42 @@
"revision": 6,
"rung": "deleted",
"link": null,
+ "owner": "other",
+ "asker_grant": true,
"s3_status": 404,
"s2_result": "NOT_VISIBLE",
"s2_result_superseded": "NOT_VISIBLE",
+ "s2_result_ahead": "NOT_VISIBLE",
"s2_result_stranger": "NOT_VISIBLE"
},
{
- "name": "ingested on the team rung, since moved to private",
+ "name": "ingested on the team rung, since moved to private by its owner",
"item_id": "doc-was-team",
- "s3_body": "",
+ "s3_body": "the old roadmap, moved back to private",
"revision": 8,
"rung": "private",
"link": null,
- "s3_status": 404,
+ "owner": "other",
+ "asker_grant": false,
+ "s3_status": 200,
"s2_result": "NOT_VISIBLE",
"s2_result_superseded": "NOT_VISIBLE",
+ "s2_result_ahead": "NOT_VISIBLE",
"s2_result_stranger": "NOT_VISIBLE"
},
{
"name": "a link added after ingest changes nothing either way",
"item_id": "doc-link-added-late",
- "s3_body": "",
+ "s3_body": "the hiring plan, private, link added later",
"revision": 11,
"rung": "private",
"link": "read",
- "s3_status": 404,
+ "owner": "other",
+ "asker_grant": false,
+ "s3_status": 200,
"s2_result": "NOT_VISIBLE",
"s2_result_superseded": "NOT_VISIBLE",
+ "s2_result_ahead": "NOT_VISIBLE",
"s2_result_stranger": "NOT_VISIBLE"
}
]
diff --git a/s1.go b/s1.go
index cccee5f..ba5c3d2 100644
--- a/s1.go
+++ b/s1.go
@@ -13,8 +13,9 @@ import (
// no visibility flag. memoria's draft 1 carried a visible-to-team field and it
// was a leak: `visible=false, gone=false` told a consumer that a guest-only
// item existed, at what revision and when it was touched, which is what S3's
-// "404, never 403" is there to hide. §4.2: departure from team-visibility is
-// `gone`, indistinguishable from deletion.
+// "404, never 403" is there to hide. Since revision 10 (Paul, 2026-11-01)
+// the feed carries every live item and `gone` means deleted; a row still
+// carries nothing but these four fields, and who may open an item is S2's.
type FeedRow struct {
ItemID string `json:"item_id"`
Revision int64 `json:"revision"`
diff --git a/s3.go b/s3.go
index 31dbdd2..ea47259 100644
--- a/s3.go
+++ b/s3.go
@@ -7,11 +7,11 @@ import (
// ErrNotAvailable is the whole vocabulary of an S3 refusal.
//
-// Doctrine §4.2: a content fetch for anything outside the custody predicate
-// answers 404, never 403, and the status is identical for "not team-visible"
-// and "does not exist". Deleted, never team-visible, and departed from
-// team-visibility are one answer here on purpose — a consumer that could tell
-// them apart would learn that a private item exists.
+// Doctrine §4.2: a content fetch for anything outside custody answers 404,
+// never 403, identical to "does not exist". Since revision 10 (Paul,
+// 2026-11-01) custody is every live item, so the refusal covers a deleted
+// item, an unknown id and a revision that is not current — one answer, so a
+// consumer cannot tell a deletion from an id it made up.
var ErrNotAvailable = errors.New("suite: item not available")
// ErrContractBreach marks a sibling answering in a way the contract forbids.
@@ -22,8 +22,10 @@ var ErrContractBreach = errors.New("suite: sibling broke the contract")
// DecodeS3 reads a content fetch. There is no asker anywhere in this call:
// S3 is custody-scoped and person-less, and memoria's draft 3 added a person
// to it, which both broke the ingest path — the warm-up, the rebuild and
-// derived-artefact regeneration have no asker — and pulled individually
-// granted rows into a store that may not hold them.
+// derived-artefact regeneration have no asker — and (before revision 10,
+// when a store could hold only team-visible items) pulled individually
+// granted rows into a store that might not hold them. Since revision 10 a
+// consumer holds every live item and who sees one is S2's question.
func DecodeS3(status int, body []byte) ([]byte, error) {
switch {
case status >= 200 && status <= 299:
diff --git a/server/consumers.go b/server/consumers.go
new file mode 100644
index 0000000..b4d0899
--- /dev/null
+++ b/server/consumers.go
@@ -0,0 +1,119 @@
+package server
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "strings"
+)
+
+// Consumer is one sibling allowed to call this app's suite routes: memoria,
+// today. Doctrine §6.2: one bearer token per consumer, minted by the
+// operator, delivered as platform config, and held here only as its SHA-256.
+// Up to two tokens at once, each with an epoch, so a token can be rotated in
+// three steps (accept both, switch the sender, drop the old) without a gap.
+type Consumer struct {
+ ID string `json:"consumer_id"`
+ Tokens []Token `json:"tokens"`
+}
+
+// Token is one accepted token, as the hex SHA-256 of its bytes.
+type Token struct {
+ Epoch int `json:"epoch"`
+ SHA256 string `json:"sha256"`
+}
+
+// MaxTokensPerConsumer is two: the old token and the new one, for the length
+// of a rotation, and never more.
+const MaxTokensPerConsumer = 2
+
+// EnvSuffix names the variable an app reads its consumers from:
+// <APP>_SUITE_CONSUMERS, e.g. DOCS_SUITE_CONSUMERS.
+const EnvSuffix = "_SUITE_CONSUMERS"
+
+// ConsumersFromEnv reads <app>_SUITE_CONSUMERS. Unset or empty is no
+// consumers — the routes are not served — and anything malformed is an
+// error, so a typo refuses boot rather than silently serving nobody.
+func ConsumersFromEnv(getenv func(string) string, app string) ([]Consumer, error) {
+ return ParseConsumers(getenv(strings.ToUpper(app) + EnvSuffix))
+}
+
+// ParseConsumers reads the strict JSON list:
+//
+// [{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"<64 hex>"}]}]
+func ParseConsumers(raw string) ([]Consumer, error) {
+ if strings.TrimSpace(raw) == "" {
+ return nil, nil
+ }
+ // A list and nothing but a list: "null" decodes into a nil slice
+ // without error, and would have read as "no consumers" — the routes
+ // switched off by a typo rather than boot refused (Astra, 2026-11-01).
+ if !strings.HasPrefix(strings.TrimSpace(raw), "[") {
+ return nil, errors.New("suite consumers: not the agreed JSON list")
+ }
+ dec := json.NewDecoder(bytes.NewReader([]byte(raw)))
+ dec.DisallowUnknownFields()
+ var cs []Consumer
+ if err := dec.Decode(&cs); err != nil || !atEOF(dec) || len(cs) == 0 {
+ return nil, errors.New("suite consumers: not the agreed JSON list")
+ }
+ seen := map[string]bool{}
+ for _, c := range cs {
+ if c.ID == "" || seen[c.ID] {
+ return nil, errors.New("suite consumers: a consumer_id is empty or repeated")
+ }
+ seen[c.ID] = true
+ if len(c.Tokens) == 0 || len(c.Tokens) > MaxTokensPerConsumer {
+ return nil, fmt.Errorf("suite consumers: %s must have one or two tokens", c.ID)
+ }
+ for _, t := range c.Tokens {
+ b, err := hex.DecodeString(t.SHA256)
+ if err != nil || len(b) != sha256.Size {
+ return nil, fmt.Errorf("suite consumers: %s has a token that is not a hex SHA-256", c.ID)
+ }
+ }
+ }
+ return cs, nil
+}
+
+// TokenHash is what an operator puts in the consumers list for a token.
+func TokenHash(token string) string {
+ sum := sha256.Sum256([]byte(token))
+ return hex.EncodeToString(sum[:])
+}
+
+// Authenticate admits a request carrying a configured consumer's token and
+// answers every other one with the same empty 401: no token, a malformed
+// header, an unknown token and a retired one are indistinguishable. Every
+// configured hash is compared, in constant time, whatever matched first.
+func Authenticate(consumers []Consumer, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ tok, ok := bearer(r)
+ if !ok || tok == "" {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ sum := sha256.Sum256([]byte(tok))
+ var match Consumer
+ found := 0
+ for _, c := range consumers {
+ for _, t := range c.Tokens {
+ want, _ := hex.DecodeString(t.SHA256)
+ if subtle.ConstantTimeCompare(sum[:], want) == 1 {
+ match = c
+ found = 1
+ }
+ }
+ }
+ if found == 0 {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ next.ServeHTTP(w, r.WithContext(contextWithConsumer(r.Context(), match)))
+ })
+}
diff --git a/server/server.go b/server/server.go
new file mode 100644
index 0000000..037e8b4
--- /dev/null
+++ b/server/server.go
@@ -0,0 +1,256 @@
+// Package server is the producer half of the suite contract: the three
+// routes an app of record serves so a same-team consumer (memoria) can hold
+// and rule on its items. Doctrine §6; revision 10 (Paul, 2026-11-01) for what
+// is held.
+//
+// An app implements Producer — its feed, its own per-person read check, and
+// an item's text — and mounts Handler beside its router. Everything the
+// contract fixes and an app could get subtly wrong lives here instead: the
+// bearer check, the strict S2 decode and cap, the wire shapes, and the one
+// byte-identical refusal S3 gives for anything it will not serve.
+//
+// Like the rest of the module it has no dependencies beyond the standard
+// library, so an app's pin chain stays one deep (AGENTS.md).
+package server
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "log/slog"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "amadan.net/oficina/suite"
+)
+
+// Producer is an app's half of the contract.
+type Producer interface {
+ // Feed returns the rows after cursor — "" is the beginning — at most
+ // limit of them, in the app's own log order, and the cursor to ask from
+ // next. At the tip it returns rows: [] and the SAME cursor it was given
+ // (a consumer stops polling only when the cursor comes back unchanged
+ // with no rows; a fresh cursor at the tip makes it page forever). The
+ // cursor is opaque and never empty.
+ //
+ // Since revision 10 the feed carries every live item, private and
+ // granted ones included; gone means deleted, and nothing else.
+ Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error)
+
+ // Rule answers, for each pair in order, whether asker may open that item
+ // now: the app's own read check (team rung, ownership, a live grant;
+ // never a link). VISIBLE at the current revision; STALE when the asker
+ // may open it and the asked revision is older than current; NOT_VISIBLE
+ // when the asker may not, or the item is deleted or unknown; UNKNOWN when
+ // the app cannot say (an asker of a kind it does not key on, a revision
+ // its log does not recognise, a roster it cannot reach). Never cached.
+ // It returns exactly len(pairs) answers.
+ Rule(ctx context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error)
+
+ // Content returns the item's text at revision, as the plain text a
+ // consumer indexes. suite.ErrNotAvailable for a deleted item, an unknown
+ // id, or a revision that is not the current one; this package turns it
+ // into the one refusal every such case shares.
+ Content(ctx context.Context, itemID string, revision int64) ([]byte, error)
+}
+
+// FeedPageLimit is how many rows one S1 page carries. memoria caps an S1
+// response at 4 MiB; a row is under 200 bytes on the wire, so 256 rows sit
+// two orders of magnitude inside it, and memoria pages up to 50 times a poll.
+const FeedPageLimit = 256
+
+// MaxContentBytes is the largest body S3 serves. memoria refuses a body over
+// 2 MiB + 64 KiB as an error and retries the same feed page for ever, so an
+// item over this is answered as not available instead — counted by the
+// consumer as missing, and the feed moves on. The slack keeps a body at
+// exactly this size well inside the consumer's cap.
+const MaxContentBytes = 2 << 20
+
+// maxS2Body bounds an S2 request: 256 pairs of a long id and a revision,
+// and an asker, are far under it.
+const maxS2Body = 256 << 10
+
+// Handler returns the authenticated routes, or nil when no consumer is
+// configured: an app with no consumers serves no suite routes at all
+// (doctrine §3, A.2 — the routes exist wherever consumer tokens do).
+func Handler(p Producer, consumers []Consumer, logger *slog.Logger) http.Handler {
+ if len(consumers) == 0 {
+ return nil
+ }
+ return Authenticate(consumers, Routes(p, logger))
+}
+
+// Routes is the three routes with no authentication. An app never mounts it
+// directly; it exists for Handler and for the conformance harness, which
+// drives a handler without a bearer token.
+func Routes(p Producer, logger *slog.Logger) http.Handler {
+ if logger == nil {
+ logger = slog.New(slog.NewTextHandler(io.Discard, nil))
+ }
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET "+suite.RouteS1, func(w http.ResponseWriter, r *http.Request) { serveS1(p, logger, w, r) })
+ mux.HandleFunc("POST "+suite.RouteS2, func(w http.ResponseWriter, r *http.Request) { serveS2(p, logger, w, r) })
+ mux.HandleFunc("GET "+suite.RouteS3+"/{item}", func(w http.ResponseWriter, r *http.Request) { serveS3(p, logger, w, r) })
+ return mux
+}
+
+func serveS1(p Producer, logger *slog.Logger, w http.ResponseWriter, r *http.Request) {
+ cursor := r.URL.Query().Get("cursor")
+ feed, err := p.Feed(r.Context(), cursor, FeedPageLimit)
+ if err != nil {
+ // Never an empty feed: an empty page for a failed read would move a
+ // consumer's cursor past changes it never saw.
+ // A fixed string, never the error: a producer's error can carry a
+ // title or a passage, and logs are storage nobody can grep clean.
+ logger.Error("suite S1: the producer's feed failed")
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ if err := checkFeed(feed); err != nil {
+ logger.Error("suite S1: the producer's page broke the contract", "rule", err.Error())
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ if feed.Rows == nil {
+ feed.Rows = []suite.FeedRow{}
+ }
+ writeJSON(w, feed)
+}
+
+// checkFeed holds the producer to what DecodeS1 will demand. Its errors are
+// fixed strings of this package's own, never the producer's, so they may be
+// logged., so a mistake
+// is a 500 here rather than a consumer stalling on a page it refuses.
+func checkFeed(f suite.Feed) error {
+ if f.Cursor == "" {
+ return errors.New("empty cursor")
+ }
+ if len(f.Rows) > FeedPageLimit {
+ return errors.New("page over the limit")
+ }
+ for _, row := range f.Rows {
+ if row.ItemID == "" || row.TouchedAt.IsZero() {
+ return errors.New("row without an item id or a time")
+ }
+ }
+ return nil
+}
+
+type s2Result struct {
+ ItemID string `json:"item_id"`
+ Revision int64 `json:"revision"`
+ Result suite.Authorization `json:"result"`
+}
+
+func serveS2(p Producer, logger *slog.Logger, w http.ResponseWriter, r *http.Request) {
+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxS2Body))
+ dec.DisallowUnknownFields()
+ var req suite.S2Request
+ if err := dec.Decode(&req); err != nil || !atEOF(dec) {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ asker, err := suite.NewSubject(req.Asker.Kind, req.Asker.Value)
+ if err != nil || req.Pairs == nil || suite.CheckS2Batch(req.Pairs) != nil {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ for _, pr := range req.Pairs {
+ if pr.ItemID == "" {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ }
+ answers, err := p.Rule(r.Context(), asker, req.Pairs)
+ if err != nil {
+ // A non-2xx is UNKNOWN for the whole call on the consumer's side:
+ // withheld loudly, never silently.
+ logger.Error("suite S2: the producer's rule failed")
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ if len(answers) != len(req.Pairs) {
+ logger.Error("suite S2: the producer answered a different number of pairs")
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ out := struct {
+ Results []s2Result `json:"results"`
+ }{Results: make([]s2Result, len(answers))}
+ for i, a := range answers {
+ out.Results[i] = s2Result{ItemID: req.Pairs[i].ItemID, Revision: req.Pairs[i].Revision, Result: a}
+ }
+ writeJSON(w, out)
+}
+
+func serveS3(p Producer, logger *slog.Logger, w http.ResponseWriter, r *http.Request) {
+ item := r.PathValue("item")
+ rev, err := strconv.ParseInt(r.URL.Query().Get("revision"), 10, 64)
+ if item == "" || err != nil || rev < 1 {
+ notAvailable(w)
+ return
+ }
+ body, err := p.Content(r.Context(), item, rev)
+ switch {
+ case errors.Is(err, suite.ErrNotAvailable):
+ notAvailable(w)
+ return
+ case err != nil:
+ logger.Error("suite S3: the producer's content failed")
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ case len(body) > MaxContentBytes:
+ notAvailable(w)
+ return
+ }
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ w.WriteHeader(http.StatusOK)
+ w.Write(body)
+}
+
+// notAvailable is the one refusal S3 gives: the same status, headers and
+// (empty) body for a deleted item, an id that never existed, a superseded or
+// malformed revision and an item too large to serve, so none of them can be
+// told apart. Never 403.
+func notAvailable(w http.ResponseWriter) {
+ w.WriteHeader(http.StatusNotFound)
+}
+
+func writeJSON(w http.ResponseWriter, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ json.NewEncoder(w).Encode(v)
+}
+
+// contextKey carries the authenticated consumer.
+type contextKey struct{}
+
+// ConsumerFrom returns the consumer a request authenticated as, for an app
+// that keeps per-consumer state.
+func ConsumerFrom(ctx context.Context) (Consumer, bool) {
+ c, ok := ctx.Value(contextKey{}).(Consumer)
+ return c, ok
+}
+
+func bearer(r *http.Request) (string, bool) {
+ h := r.Header.Get("Authorization")
+ const prefix = "Bearer "
+ if len(h) <= len(prefix) || !strings.EqualFold(h[:len(prefix)], prefix) {
+ return "", false
+ }
+ return strings.TrimSpace(h[len(prefix):]), true
+}
+
+func contextWithConsumer(ctx context.Context, c Consumer) context.Context {
+ return context.WithValue(ctx, contextKey{}, c)
+}
+
+// atEOF is the end-of-input check. Decoder.More is not one: it answers false
+// before a stray ']' or '}', so a valid document followed by either passed
+// as strict (Astra, 2026-11-01). Decoding once more must find nothing.
+func atEOF(dec *json.Decoder) bool {
+ var extra json.RawMessage
+ return dec.Decode(&extra) == io.EOF
+}
diff --git a/server/server_test.go b/server/server_test.go
new file mode 100644
index 0000000..81595d4
--- /dev/null
+++ b/server/server_test.go
@@ -0,0 +1,450 @@
+package server_test
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/suite"
+ "amadan.net/oficina/suite/conformance"
+ "amadan.net/oficina/suite/server"
+)
+
+// fixtureProducer is a correct Producer built from the custody fixture, the
+// same world the conformance harness checks.
+type fixtureProducer struct {
+ f suite.CustodyFixture
+ extraRows int // Feed returns this many more rows than the cases
+ contentErr error
+ feedErr error
+ ruleErr error
+ short bool // Rule answers one fewer than asked
+ cursor string // overrides the feed's cursor when set
+ content []byte // overrides S3 bytes when set
+ lastAsker suite.Subject
+}
+
+func (p *fixtureProducer) find(id string) (suite.CustodyCase, bool) {
+ for _, c := range p.f.Cases {
+ if c.ItemID == id {
+ return c, true
+ }
+ }
+ return suite.CustodyCase{}, false
+}
+
+func (p *fixtureProducer) Feed(_ context.Context, cursor string, limit int) (suite.Feed, error) {
+ if p.feedErr != nil {
+ return suite.Feed{}, p.feedErr
+ }
+ if cursor == "end" {
+ return suite.Feed{Cursor: "end"}, nil
+ }
+ var rows []suite.FeedRow
+ for _, c := range p.f.Cases {
+ rows = append(rows, suite.FeedRow{ItemID: c.ItemID, Revision: c.Revision, Gone: c.Rung == suite.RungDeleted, TouchedAt: time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)})
+ }
+ for i := 0; i < p.extraRows; i++ {
+ rows = append(rows, suite.FeedRow{ItemID: "extra-" + strconv.Itoa(i), Revision: 1, TouchedAt: time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)})
+ }
+ next := "end"
+ if p.cursor != "" {
+ next = p.cursor
+ }
+ if p.cursor == "-" {
+ next = ""
+ }
+ return suite.Feed{Cursor: next, Rows: rows}, nil
+}
+
+func (p *fixtureProducer) Rule(_ context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) {
+ p.lastAsker = asker
+ if p.ruleErr != nil {
+ return nil, p.ruleErr
+ }
+ out := make([]suite.Authorization, 0, len(pairs))
+ if asker.Kind != p.f.Asker.Kind {
+ for range pairs {
+ out = append(out, suite.UNKNOWN)
+ }
+ return out, nil
+ }
+ for _, pr := range pairs {
+ c, ok := p.find(pr.ItemID)
+ may := ok && asker == p.f.Asker && c.Rung != suite.RungDeleted && (c.Rung == suite.RungTeam || c.Owner == "asker" || c.AskerGrant)
+ switch {
+ case !may:
+ out = append(out, suite.NOT_VISIBLE)
+ case pr.Revision < c.Revision:
+ out = append(out, suite.STALE)
+ case pr.Revision > c.Revision:
+ out = append(out, suite.UNKNOWN)
+ default:
+ out = append(out, suite.VISIBLE)
+ }
+ }
+ if p.short {
+ out = out[:len(out)-1]
+ }
+ return out, nil
+}
+
+func (p *fixtureProducer) Content(_ context.Context, id string, rev int64) ([]byte, error) {
+ if p.contentErr != nil {
+ return nil, p.contentErr
+ }
+ c, ok := p.find(id)
+ if !ok || c.Rung == suite.RungDeleted || rev != c.Revision {
+ return nil, suite.ErrNotAvailable
+ }
+ if p.content != nil {
+ return p.content, nil
+ }
+ return []byte(c.S3Body), nil
+}
+
+func producer(t *testing.T) *fixtureProducer {
+ t.Helper()
+ f, err := suite.LoadCustodyFixture()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return &fixtureProducer{f: f}
+}
+
+const token = "a-test-token-for-memoria"
+
+func consumers(t *testing.T, tokens ...string) []server.Consumer {
+ t.Helper()
+ var ts []server.Token
+ for i, tok := range tokens {
+ ts = append(ts, server.Token{Epoch: i + 1, SHA256: server.TokenHash(tok)})
+ }
+ return []server.Consumer{{ID: "memoria", Tokens: ts}}
+}
+
+func do(h http.Handler, method, url, tok string, body []byte) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(method, url, bytes.NewReader(body))
+ if tok != "" {
+ req.Header.Set("Authorization", "Bearer "+tok)
+ }
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ return rec
+}
+
+// The routes this package serves pass the doctrine's own harness, driven
+// through a producer that only knows the fixture. The harness never sends a
+// malformed revision or an unauthenticated request, which is why the tests
+// below exist beside it.
+func TestRoutesPassConformance(t *testing.T) {
+ conformance.Run(t, server.Routes(producer(t), nil))
+}
+
+// No consumers, no routes (doctrine §3).
+func TestNoConsumersServesNothing(t *testing.T) {
+ if h := server.Handler(producer(t), nil, nil); h != nil {
+ t.Fatal("Handler with no consumers returned routes")
+ }
+}
+
+// Every failure to authenticate is the same empty 401, and both tokens of a
+// rotation are accepted.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: the hash comparison skipped
+// (any bearer admitted) → "an unknown token"; only the first token of a
+// consumer compared → "the second token"; a reason written in the 401 body
+// → "alike".
+func TestAuthentication(t *testing.T) {
+ h := server.Handler(producer(t), consumers(t, token, "the-next-token"), nil)
+ ok := do(h, "GET", suite.RouteS1, token, nil)
+ if ok.Code != 200 {
+ t.Fatalf("the configured token: %d", ok.Code)
+ }
+ if rec := do(h, "GET", suite.RouteS1, "the-next-token", nil); rec.Code != 200 {
+ t.Errorf("the second token of a rotation: %d", rec.Code)
+ }
+ var first string
+ for name, req := range map[string]func() *http.Request{
+ "no header": func() *http.Request { return httptest.NewRequest("GET", suite.RouteS1, nil) },
+ "an unknown token": func() *http.Request {
+ r := httptest.NewRequest("GET", suite.RouteS1, nil)
+ r.Header.Set("Authorization", "Bearer not-the-token")
+ return r
+ },
+ "not a bearer": func() *http.Request {
+ r := httptest.NewRequest("GET", suite.RouteS1, nil)
+ r.Header.Set("Authorization", "Basic "+token)
+ return r
+ },
+ "an empty bearer": func() *http.Request {
+ r := httptest.NewRequest("GET", suite.RouteS1, nil)
+ r.Header.Set("Authorization", "Bearer ")
+ return r
+ },
+ } {
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req())
+ if rec.Code != 401 {
+ t.Errorf("%s: %d, want 401", name, rec.Code)
+ }
+ got := strconv.Itoa(rec.Code) + "|" + rec.Body.String()
+ if first == "" {
+ first = got
+ } else if got != first {
+ t.Errorf("%s: refusals not alike: %q vs %q", name, got, first)
+ }
+ }
+}
+
+func TestParseConsumers(t *testing.T) {
+ good := `[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"` + server.TokenHash("x") + `"}]}]`
+ if cs, err := server.ParseConsumers(good); err != nil || len(cs) != 1 || cs[0].ID != "memoria" {
+ t.Fatalf("good: %+v, %v", cs, err)
+ }
+ if cs, err := server.ParseConsumers(" "); err != nil || cs != nil {
+ t.Errorf("empty is no consumers: %+v, %v", cs, err)
+ }
+ h := server.TokenHash("x")
+ for name, bad := range map[string]string{
+ "an unknown field": `[{"consumer_id":"m","origin":"x","tokens":[{"epoch":1,"sha256":"` + h + `"}]}]`,
+ "three tokens": `[{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"` + h + `"},{"epoch":2,"sha256":"` + h + `"},{"epoch":3,"sha256":"` + h + `"}]}]`,
+ "no tokens": `[{"consumer_id":"m","tokens":[]}]`,
+ "not hex": `[{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"plaintext-token"}]}]`,
+ "a repeated id": `[{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"` + h + `"}]},{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"` + h + `"}]}]`,
+ "trailing content": good + `[]`,
+ "not a list": `{"consumer_id":"m"}`,
+ } {
+ if _, err := server.ParseConsumers(bad); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+ if cs, err := server.ConsumersFromEnv(func(k string) string {
+ if k == "DOCS_SUITE_CONSUMERS" {
+ return good
+ }
+ return ""
+ }, "docs"); err != nil || len(cs) != 1 {
+ t.Errorf("ConsumersFromEnv: %+v, %v", cs, err)
+ }
+}
+
+// S1 holds the producer to what the consumer's decoder demands.
+func TestS1(t *testing.T) {
+ p := producer(t)
+ h := server.Routes(p, nil)
+ rec := do(h, "GET", suite.RouteS1+"?cursor=", "", nil)
+ feed, err := suite.DecodeS1(rec.Code, rec.Body.Bytes())
+ if err != nil || len(feed.Rows) != len(p.f.Cases) || feed.Cursor != "end" {
+ t.Fatalf("first page: %+v, %v", feed, err)
+ }
+ // At the tip: rows [] (never null) and the same cursor back.
+ tip := do(h, "GET", suite.RouteS1+"?cursor=end", "", nil)
+ if !strings.Contains(tip.Body.String(), `"rows":[]`) {
+ t.Errorf("rows: the tip's rows are not an empty list: %s", tip.Body.String())
+ }
+ if feed, err := suite.DecodeS1(tip.Code, tip.Body.Bytes()); err != nil || feed.Cursor != "end" || len(feed.Rows) != 0 {
+ t.Errorf("tip: %+v, %v", feed, err)
+ }
+ p.cursor = "-"
+ if rec := do(h, "GET", suite.RouteS1, "", nil); rec.Code != 500 {
+ t.Errorf("an empty cursor from the producer: %d, want 500", rec.Code)
+ }
+ p.cursor, p.feedErr = "", errors.New("db down")
+ if rec := do(h, "GET", suite.RouteS1, "", nil); rec.Code != 503 {
+ t.Errorf("a failed feed: %d, want 503 (never an empty page)", rec.Code)
+ }
+}
+
+// S2 decodes strictly, caps the batch, echoes every pair, and fails loudly.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: DisallowUnknownFields removed →
+// "an unknown field"; the cap check removed → "257 pairs"; the answer-count
+// check removed → "a short answer"; a producer error answered 200 with no
+// results → "a failed rule".
+func TestS2(t *testing.T) {
+ p := producer(t)
+ h := server.Routes(p, nil)
+ ask := func(body string) *httptest.ResponseRecorder { return do(h, "POST", suite.RouteS2, "", []byte(body)) }
+ asker := `{"kind":"person_ref","value":"pers_ana"}`
+ ok := ask(`{"asker":` + asker + `,"pairs":[{"item_id":"doc-team","revision":7},{"item_id":"doc-link","revision":5}]}`)
+ got := suite.DecodeS2([]suite.ItemRevision{{ItemID: "doc-team", Revision: 7}, {ItemID: "doc-link", Revision: 5}}, ok.Code, ok.Body.Bytes())
+ if len(got) != 2 || got[0] != suite.VISIBLE || got[1] != suite.NOT_VISIBLE {
+ t.Fatalf("answers = %v (%d %s)", got, ok.Code, ok.Body.String())
+ }
+ if p.lastAsker != (suite.Subject{Kind: suite.SubjectPersonRef, Value: "pers_ana"}) {
+ t.Errorf("the asker reached the producer as %+v", p.lastAsker)
+ }
+ var many []string
+ for i := 0; i < 257; i++ {
+ many = append(many, `{"item_id":"doc-team","revision":7}`)
+ }
+ for name, body := range map[string]string{
+ "an unknown field": `{"asker":` + asker + `,"pairs":[],"extra":1}`,
+ "257 pairs": `{"asker":` + asker + `,"pairs":[` + strings.Join(many, ",") + `]}`,
+ "a bad kind": `{"asker":{"kind":"email","value":"x"},"pairs":[]}`,
+ "an empty asker": `{"asker":{"kind":"address","value":""},"pairs":[]}`,
+ "no pairs": `{"asker":` + asker + `}`,
+ "an empty item id": `{"asker":` + asker + `,"pairs":[{"item_id":"","revision":1}]}`,
+ "not JSON": `nope`,
+ "two documents": `{"asker":` + asker + `,"pairs":[]}{}`,
+ } {
+ if rec := ask(body); rec.Code != 400 {
+ t.Errorf("%s: %d, want 400", name, rec.Code)
+ }
+ }
+ p.short = true
+ if rec := ask(`{"asker":` + asker + `,"pairs":[{"item_id":"doc-team","revision":7}]}`); rec.Code != 500 {
+ t.Errorf("a short answer: %d, want 500", rec.Code)
+ }
+ p.short, p.ruleErr = false, errors.New("roster unreachable")
+ if rec := ask(`{"asker":` + asker + `,"pairs":[{"item_id":"doc-team","revision":7}]}`); rec.Code != 503 {
+ t.Errorf("a failed rule: %d, want 503", rec.Code)
+ }
+}
+
+// Every S3 refusal is the same response: a deleted item, an id that never
+// existed, a superseded, missing or malformed revision, and an item too
+// large to serve.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: a malformed revision answered
+// 400 → "malformed"; the size check removed → "too large"; ErrNotAvailable
+// answered 503 → "deleted".
+func TestS3RefusesAlike(t *testing.T) {
+ p := producer(t)
+ h := server.Routes(p, nil)
+ base := do(h, "GET", suite.RouteS3+"/"+suite.NonexistentItemID+"?revision=1", "", nil)
+ if base.Code != 404 {
+ t.Fatalf("baseline: %d", base.Code)
+ }
+ sig := func(r *httptest.ResponseRecorder) string {
+ var hs []string
+ for k, v := range r.Header() {
+ hs = append(hs, k+"="+strings.Join(v, ","))
+ }
+ sort.Strings(hs)
+ return strconv.Itoa(r.Code) + "|" + strings.Join(hs, "|") + "|" + r.Body.String()
+ }
+ for name, url := range map[string]string{
+ "deleted": suite.RouteS3 + "/doc-deleted?revision=6",
+ "superseded": suite.RouteS3 + "/doc-team?revision=6",
+ "missing": suite.RouteS3 + "/doc-team",
+ "malformed": suite.RouteS3 + "/doc-team?revision=seven",
+ "zero": suite.RouteS3 + "/doc-team?revision=0",
+ } {
+ if rec := do(h, "GET", url, "", nil); sig(rec) != sig(base) {
+ t.Errorf("%s: %q, want the baseline %q", name, sig(rec), sig(base))
+ }
+ }
+ p.content = bytes.Repeat([]byte("x"), server.MaxContentBytes+1)
+ if rec := do(h, "GET", suite.RouteS3+"/doc-team?revision=7", "", nil); sig(rec) != sig(base) {
+ t.Errorf("too large: %d, want the baseline", rec.Code)
+ }
+ p.content = bytes.Repeat([]byte("x"), server.MaxContentBytes)
+ if rec := do(h, "GET", suite.RouteS3+"/doc-team?revision=7", "", nil); rec.Code != 200 || !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/plain") || !bytes.Equal(rec.Body.Bytes(), p.content) {
+ t.Errorf("at the limit: %d %s, %d bytes", rec.Code, rec.Header().Get("Content-Type"), rec.Body.Len())
+ }
+ // A producer that fails is not an item that is unavailable: 503, which
+ // the consumer retries, never the 404 it would count as gone.
+ p.content, p.contentErr = nil, errors.New("replay failed")
+ if rec := do(h, "GET", suite.RouteS3+"/doc-team?revision=7", "", nil); rec.Code != 503 {
+ t.Errorf("a failed producer: %d, want 503", rec.Code)
+ }
+}
+
+// Astra's survivors (2026-11-01).
+//
+// MUTATION-TESTED 2026-11-01, each reverted: only the first consumer
+// compared → "a second consumer"; the consumer left out of the context →
+// "context"; the S2 body cap removed → "an oversized body"; the page limit
+// check removed → "a page over the limit"; a producer error logged with its
+// text → "the log"; Decoder.More() back as the end check → "trailing".
+func TestTheSurvivors(t *testing.T) {
+ two := append(consumers(t, token), server.Consumer{ID: "another", Tokens: []server.Token{{Epoch: 1, SHA256: server.TokenHash("another-token")}}})
+ h := server.Handler(producer(t), two, nil)
+ if rec := do(h, "GET", suite.RouteS1, "another-token", nil); rec.Code != 200 {
+ t.Errorf("a second consumer: %d", rec.Code)
+ }
+ who := server.Authenticate(two, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ c, _ := server.ConsumerFrom(r.Context())
+ w.Write([]byte(c.ID))
+ }))
+ if rec := do(who, "GET", "/", "another-token", nil); rec.Body.String() != "another" {
+ t.Errorf("context: the consumer is %q", rec.Body.String())
+ }
+
+ p := producer(t)
+ var logs bytes.Buffer
+ routes := server.Routes(p, slog.New(slog.NewTextHandler(&logs, nil)))
+ big := `{"asker":{"kind":"person_ref","value":"pers_ana"},"pairs":[{"item_id":"` + strings.Repeat("a", 300<<10) + `","revision":1}]}`
+ if rec := do(routes, "POST", suite.RouteS2, "", []byte(big)); rec.Code != 400 {
+ t.Errorf("an oversized body: %d, want 400", rec.Code)
+ }
+ p.extraRows = server.FeedPageLimit
+ if rec := do(routes, "GET", suite.RouteS1, "", nil); rec.Code != 500 {
+ t.Errorf("a page over the limit: %d, want 500", rec.Code)
+ }
+ p.extraRows = 0
+ const secret = "Q3 board pack: acquisition of Acme"
+ p.feedErr, p.ruleErr, p.contentErr = errors.New(secret), errors.New(secret), errors.New(secret)
+ do(routes, "GET", suite.RouteS1, "", nil)
+ do(routes, "POST", suite.RouteS2, "", []byte(`{"asker":{"kind":"person_ref","value":"pers_ana"},"pairs":[{"item_id":"doc-team","revision":7}]}`))
+ do(routes, "GET", suite.RouteS3+"/doc-team?revision=7", "", nil)
+ if strings.Contains(logs.String(), "acquisition") {
+ t.Errorf("the log: a producer's error text was logged: %s", logs.String())
+ }
+ if !strings.Contains(logs.String(), "S1") || !strings.Contains(logs.String(), "S2") || !strings.Contains(logs.String(), "S3") {
+ t.Errorf("the log: failures were not logged at all: %s", logs.String())
+ }
+
+ p.feedErr, p.ruleErr, p.contentErr = nil, nil, nil
+ for _, junk := range []string{"]", "}", "[]", `{"a":1}`} {
+ body := `{"asker":{"kind":"person_ref","value":"pers_ana"},"pairs":[{"item_id":"doc-team","revision":7}]}` + junk
+ if rec := do(routes, "POST", suite.RouteS2, "", []byte(body)); rec.Code != 400 {
+ t.Errorf("trailing %q after an S2 request: %d, want 400", junk, rec.Code)
+ }
+ }
+ good := `[{"consumer_id":"m","tokens":[{"epoch":1,"sha256":"` + server.TokenHash("x") + `"}]}]`
+ for _, bad := range []string{good + "]", good + "}", "null", "[]", `{"consumer_id":"m"}`} {
+ if _, err := server.ParseConsumers(bad); err == nil {
+ t.Errorf("trailing or not a list: %q accepted", bad)
+ }
+ }
+}
+
+// S1's guards at their edges (Astra, 2026-11-01).
+//
+// MUTATION-TESTED 2026-11-01, each reverted: the page limit off by one
+// (>= for >) → "exactly the limit"; the empty item id check removed → "an
+// empty item id".
+func TestS1Edges(t *testing.T) {
+ p := producer(t)
+ h := server.Routes(p, nil)
+ p.extraRows = server.FeedPageLimit - len(p.f.Cases)
+ if rec := do(h, "GET", suite.RouteS1, "", nil); rec.Code != 200 {
+ t.Errorf("exactly the limit: %d, want 200", rec.Code)
+ }
+ p.extraRows = 0
+ bad := &emptyIDProducer{fixtureProducer: p}
+ if rec := do(server.Routes(bad, nil), "GET", suite.RouteS1, "", nil); rec.Code != 500 {
+ t.Errorf("an empty item id: %d, want 500", rec.Code)
+ }
+}
+
+type emptyIDProducer struct{ *fixtureProducer }
+
+func (p *emptyIDProducer) Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) {
+ f, err := p.fixtureProducer.Feed(ctx, cursor, limit)
+ if len(f.Rows) > 0 {
+ f.Rows[0].ItemID = ""
+ }
+ return f, err
+}