oficina / fichas Public

Fichas serves the suite contract's producer half (S1, S2, S3) for memoria

Suite revision 10 (Paul, 2026-11-01: "Hold private too, check per
person"), through amadan.net/oficina/suite/server at c38e3ad. S1 pages
the card events of the append-only events table; S2 is lone-shape:
address askers admitted by Admit see every live card (VISIBLE / STALE /
UNKNOWN by revision), person_ref is UNKNOWN; S3 is the card's title,
fields and entries at its current revision. Item ids and cursors carry a
created_at stamp so a restore from backup cannot let a new card pass for
an old one. Mounted at /suite/ outside the session group and CSRF only
when FICHAS_SUITE_CONSUMERS is set. Conformance runs CheckAs(address)
and asserts exactly the twelve cases Fichas cannot represent. Spec §6,
§10, §12. Reviewed by GPT-6 (Codex, Astra): REQUEST CHANGES twice
(restore identity; test coverage), all addressed; the final round's
findings were coverage only and are fixed with their mutants red.

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

Squashed from feat/suite-producer into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 7bfd4c466b1cab2785673790e75c4fe6d3fa3ddf parent 6cac4a0
11 files changed, +1,622 −5
  • Makefile +3 −1
  • docs/superpowers/specs/2026-09-19-fichas-design.md +250 −4
  • go.mod +1 −0
  • go.sum +4 −0
  • internal/fichas/app.go +18 −0
  • internal/fichas/config.go +10 −0
  • internal/fichas/config_test.go +30 −0
  • internal/fichas/suite.go +287 −0
  • internal/fichas/suite_conformance_test.go +169 −0
  • internal/fichas/suite_test.go +609 −0
  • internal/fichastest/suite_test.go +241 −0

CI passed — run details

diff --git a/Makefile b/Makefile
index 4273383..c61dad7 100644
--- a/Makefile
+++ b/Makefile
@@ -1,8 +1,10 @@
APP := fichas
# estilo, the suite's design module, is private: fetch it with Git auth.
+# So is the suite contract module (spec §6): never ask the public proxy or
+# checksum database about it.
private_comma := ,
-export GOPRIVATE := $(if $(GOPRIVATE),$(GOPRIVATE)$(private_comma))amadan.net/oficina/estilo.git
+export GOPRIVATE := $(if $(GOPRIVATE),$(GOPRIVATE)$(private_comma))amadan.net/oficina/estilo.git,amadan.net/oficina/suite
# What `carlos ship -target` defaults to, and therefore what a release
# must be built for. Building for your own machine and shipping that is a
diff --git a/docs/superpowers/specs/2026-09-19-fichas-design.md b/docs/superpowers/specs/2026-09-19-fichas-design.md
index b67204e..f7ef8e8 100644
--- a/docs/superpowers/specs/2026-09-19-fichas-design.md
+++ b/docs/superpowers/specs/2026-09-19-fichas-design.md
@@ -333,9 +333,233 @@ only importer today and is a pure consumer. **Fichas would be the first
server**, with memoria as the waiting consumer — a real end-to-end exercise
of the contract, and the first-server design tax, both.
-S1 is §5's table. S2 answers per asker, intersected with custody. S3 is
-person-less and custody-scoped. **S9 (reach) depends on an unresolved
-ruling — see §10.**
+**Amended 2026-11-01 (this session, implementing the ruling below).** The
+contract this section builds against is suite doctrine **revision 10** —
+introduced at `amadan.net/oficina/suite` commit `12848f8` and pinned at
+`c38e3ad` — suite main, where revision 10 landed after three review
+passes by GPT-6 (Codex), APPROVE on the branch tip 983114a: its status block, the revision-10
+notes at §4.2 and §4.3, and §6.5, the producer half
+`amadan.net/oficina/suite/server`. What they
+say is cited, not restated (suite AGENTS.md: "cite, never restate"). What
+follows is only what is particular to Fichas. Built on branch
+`feat/suite-producer`, which sits on `feat/contract-demo` — the build that
+is live — and not on `main`, which has no code.
+
+**S9 (reach) depends on an unresolved ruling — see §10.**
+
+### 6.1 Paul's ruling, and why it costs Fichas nothing new
+
+Paul, 2026-11-01, suite revision 10: **"Hold private too, check per
+person"** — a consumer (memoria) holds every live item, and S2 rules on each
+one per person, per request, never cached.
+
+Fichas has no sharing ladder. Every admitted person already sees every card
+that is not gone: `Card.OwnerID` is provenance, not authority (models.go,
+and §9 — one instance per team, and the team shares its cards). So the
+ruling reads, for Fichas:
+
+- **S1** lists every card. `gone` means deleted, because deletion is the
+ only way a card leaves anybody's view.
+- **S3** serves the text of any card that is not gone, at its current
+ revision.
+- **S2** is "is this asker admitted to this Fichas instance", for a card
+ that is not gone.
+
+The revision-9 sentence this replaces — "S2 answers per asker, intersected
+with custody. S3 is person-less and custody-scoped" — is withdrawn with the
+intersection (doctrine §4.3's revision-10 note).
+
+### 6.2 S1 is §5's events table
+
+§5 says the events table *is* S1, and the producer reads it and nothing
+else:
+
+- **Rows** are the `events` rows with `object_kind = card`, in id order
+ after the cursor: `created`, `updated`, `deleted`, `entry_added`, and the
+ catalogue's field-kind upgrade. An entry landing consumes a card revision
+ and is logged on the card (`entry_added`, store.go `AddEntry`), so the
+ entry's own `created` row (`object_kind = entry`, no revision) is skipped
+ — the card row beside it already carries the bump. Type and field events
+ are not items.
+- **A row is** `(item id, events.revision, events.kind = deleted,
+ events.created_at)`: the card's revision *after* that event, whether it
+ made the card gone, and when. All four are plaintext already under §4.1
+ case 1 and §4.2; serving S1 unseals nothing, and no row carries a title,
+ a value, an owner or an actor.
+- **History is replayed, not collapsed.** A card edited three times since
+ the cursor yields three rows; the consumer keeps the last.
+- **The cursor** is `"<event id>.<that event's created_at, unix
+ nanoseconds>"` for the last row returned. `""` and `"0"` are the
+ beginning. At the tip the page is `rows: []` and the same cursor —
+ except that `""` answers `"0"`, because the contract refuses an empty
+ cursor, and the next poll gets `"0"` back. Within one database history,
+ `events.id` is `AUTOINCREMENT` and SQLite has one writer, so ids are
+ committed in order: a cursor can never step past a row that commits
+ later with a lower id.
+- **Every request checks the cursor's stamp.** The event at the cursor's
+ id must still exist, be a card event, and carry that `created_at`.
+ Otherwise the feed fails, which §6.5 turns into a 503 — loud, never a
+ page. A cursor that is not in the canonical form fails the same way.
+
+**item_id is `"<card id>.<card created_at, unix nanoseconds>"`** — e.g.
+`"42.1793571162737001000"` — both parts canonical positive decimals, so one
+card has exactly one id on the wire (`"042.…"`, `"+42.…"` and a bare
+`"42"` are not it). Both parts are structural and already plaintext (§4.1
+case 2, §4.2), never content. `created_at` is written once, by the insert,
+and never updated (`bumpRevision` moves only `revision`, `updated_at` and
+`gone`); stored as text, it round-trips to the nanosecond the clock
+supplied. It tells the consumer when each card was made, which the feed's
+first row for it already says.
+
+**Why the stamps (Astra review, 2026-11-01).** "An id is never reused" is
+true only within one database history. Restore an older backup and
+`AUTOINCREMENT` starts again from the backup's counters: a card created
+afterwards can get exactly the id, revision 1 and event position of a card
+memoria already holds, with different text. With bare ids, S1 would then
+answer an unchanged empty page, S2 would answer `VISIBLE` for memoria's old
+copy, and S3 would serve the new card's text under the old identity. The
+stamps make that impossible: the new card's `created_at` differs, so the
+old item id is `NOT_VISIBLE` in S2 and refused in S3, and the event at the
+old cursor carries a different stamp (or is gone), so S1 is a 503.
+
+**What the stamps do not protect, and the reset.** A card that predates the
+restore point keeps its id and stamp — correctly, it is the same card. If
+memoria held a revision of it written *after* the restore point, and the
+card is edited again after the restore up to that same revision number,
+the same `(item id, revision)` names different text. S2 cannot tell them
+apart, so until memoria is reset it answers `VISIBLE` for the abandoned
+copy. S1 does go loud in exactly that case: memoria's cursor is at or past
+the event that wrote the abandoned revision, and the restore dropped it.
+So **a Fichas 503 on S1 after a restore means: reset the consumer** —
+discard every item it holds from this instance and its cursor, and
+re-read from `""`. Resetting the cursor alone is not enough. Closing the
+gap in S2 itself would need revisions that a restore cannot reproduce
+(e.g. event timestamps rather than a per-card counter), which the custody
+fixture's fixed revision numbers cannot express; §10.
+
+### 6.3 S2 — admission, keyed on the address
+
+Fichas boots only in the lone shape (`FICHAS_SHAPE=suite` refuses to boot,
+config.go `ErrSuiteNotBuilt`), so it keys its members on a lowercased
+address, and an asker is a subject of kind `address` (doctrine §3). Per
+pair, in order:
+
+| Asker / item | Answer |
+|---|---|
+| kind `person_ref` — a kind Fichas does not key on | `UNKNOWN`, every pair |
+| `address`, not admitted (`Admit`: the `FICHAS_OWNERS` list, the one predicate sign-in and every session already run) | `NOT_VISIBLE`, every pair |
+| admitted; card gone, unknown, an id not in the canonical `<card id>.<stamp>` form, or a stamp that is not this card's `created_at` (a different card under a reused id) | `NOT_VISIBLE` |
+| admitted; asked revision = current | `VISIBLE` |
+| admitted; 1 ≤ asked revision < current | `STALE` |
+| admitted; asked revision > current, or < 1 — zero or negative (a revision the log never issued) | `UNKNOWN` |
+
+Nothing is cached: admission and every card's revision are read per call.
+
+### 6.4 S3 — the card as plain text
+
+Current revision only; anything else — gone, unknown id, a stamp that is
+not this card's (§6.2), a revision that is not current — is
+`suite.ErrNotAvailable`, which §6.5's package answers with its one empty
+404. The revision is checked before the card is read and again after, so
+an edit that lands mid-read is refused rather than served under the old
+number. A database failure on that second read is an error, answered 503
+and retried by the consumer — never the 404, which tells it the card is
+gone.
+
+The body, lines joined by `\n` with no trailing newline:
+
+```
+<the card's title>
+<Label>: <value> each other field with a value, in field order
+ (blank line)
+<entry type label> each entry, newest first
+<Label>: <value> each of its fields with a value
+```
+
+Values are as stored (a date is `2026-10-02`); labels and values are
+unsealed in memory for the response and nowhere else. A card with only a
+title is exactly its title.
+
+**A field rename does not move a card's revision** (§3: field definitions
+version on their own), so a consumer's copy keeps the old label until that
+card next changes. §10.
+
+### 6.5 Configuration and mounting
+
+`FICHAS_SUITE_CONSUMERS`, in the format doctrine §6.5 fixes, read by
+`server.ConsumersFromEnv(os.Getenv, "fichas")` inside `LoadConfig`:
+
+```
+FICHAS_SUITE_CONSUMERS=[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"<64 hex>"}]}]
+```
+
+Unset or empty: no consumers, and **the routes do not exist** — `/suite/`
+falls through to the app like any unknown path. Malformed: boot is refused.
+
+`server.Handler` is mounted on the outer `ServeMux` at `/suite/`: outside
+the session group, and outside the chi router whose app-wide
+`csrf.Protect(cfg.Origin)` would refuse memoria's `POST /suite/s2`, which
+carries only `Authorization` — no `Origin`, no `Sec-Fetch-Site`. The CSRF
+check has nothing to protect there: the credential is a bearer header,
+which a cross-site form cannot attach. **Exactly `/suite/` is exempt**;
+every other route keeps the check.
+
+### 6.6 Gates
+
+- **Conformance.** `conformance.CheckAs(h, suite.SubjectAddress)` — the
+ harness's entry point for an address-keyed app — runs in `make ci`
+ against `server.Routes` over the real producer and a real database,
+ through a test-only naming adapter: the fixture's item ids map to the
+ card ids seeded for them (and feed rows map back) (one Customer card per case, its name the case's
+ `s3_body`, edited up to the case's revision; the deleted case deleted).
+ `CheckAs` sends the fixture's asker and stranger as addresses with their
+ values unchanged; `pers_ana` is put on the owners list and `pers_bo` is
+ not. The harness also asks under `person_ref`, which Fichas must answer
+ `UNKNOWN`, follows S1 to its tip, and asks S3 one revision either side.
+ The adapter renames ids; it decides nothing.
+ The test asserts the failures are **exactly** the twelve listed in §6.7
+ — no more, no fewer — so a fixture change on the suite branch fails
+ loudly here rather than being absorbed.
+- **Fichas-native tests** (`suite_test.go`, `fichastest/suite_test.go`):
+ S1 paging, tip, `gone` on delete, the revision bump on update and on an
+ entry, malformed and future cursors; every S2 branch above; S3
+ current-only and the text shape; the CSRF exemption is exactly
+ `/suite/`; no consumers, no routes; a configured consumer and no token is
+ a 401; a malformed `FICHAS_SUITE_CONSUMERS` refuses boot. Every guard
+ mutation-tested, recorded in the test's comment.
+
+### 6.7 What Fichas cannot represent from the custody fixture
+
+Evidence for the suite, where its AGENTS.md says fixtures are corrected by
+the second implementation. Not changed there from here.
+
+The fixture (`fixtures/custody.json` at `c38e3ad` (suite main; the reviewed branch tip 983114a plus polish)) describes a world with
+a sharing ladder. Fichas has none:
+
+| Case | Fixture state | Fichas | Result |
+|---|---|---|---|
+| `doc-team`, `doc-team-link` | team rung (± a link) | every card | passes |
+| `doc-deleted` | deleted | a gone card | passes |
+| `doc-private` | private, the asker owns it | no private state; every member sees it | passes, **by coincidence**: VISIBLE because every member sees every card, not because of ownership |
+| `doc-granted` | granted to the asker | no grants | passes, **by coincidence**, as above |
+| `doc-guest` | granted to a guest only | no guests, no grants | **fails** S2 for the asker at the current revision (VISIBLE), one behind (STALE) and one ahead (UNKNOWN); the fixture wants NOT_VISIBLE at all three |
+| `doc-link` | private to someone else, link-shared | no private state, no links | **fails**, as above |
+| `doc-was-team` | moved from team to private | no private state | **fails**, as above |
+| `doc-link-added-late` | private, link added later | no private state, no links | **fails**, as above |
+
+One more gap, not a failure because the test's adapter bridges it (a
+second, the fixture's suite-shape-only askers, was closed upstream at
+`c38e3ad` (suite main; the reviewed branch tip 983114a plus polish) by `CheckAs`):
+
+- **Item ids are names, not an app's ids.** `doc-team` is not a card id;
+ an app whose ids it allocates itself cannot seed them as given.
+
+S3 (current and superseded revisions) and S1 (every live item at its
+current revision, the deleted one gone, paged to the tip) pass in full, as
+do every stranger question and every `person_ref` question. The twelve failures — four cases, three revisions each
+— are not bugs to fix in Fichas:
+bending the producer to refuse cards that every member can open in the app
+would make memoria hide what Fichas shows.
## 7. The derived summary
@@ -466,6 +690,23 @@ sealed or sealed+print only.
retention one, and TensorX's zero-retention posture does not answer it
(`memoria/ZDR-TREAT-AS-LOCAL.md` §6). Not a blocker at one user; a
blocker at the second team.
+- **S1 after a restore from backup** (§6.2; revised after Astra's review,
+ 2026-11-01). What is protected: a card recreated after a restore cannot
+ pass as one memoria holds (the item id's stamp), and a feed position
+ rewritten by a restore is a 503 rather than a silent continuation (the
+ cursor's stamp). What is not: a card that predates the restore point and
+ is edited back up to a revision memoria already holds names different
+ text under the same `(item id, revision)`, and S2 says `VISIBLE` for
+ the abandoned copy until memoria is reset. The reset is manual today:
+ on a Fichas S1 503 after a restore, discard everything memoria holds
+ from this instance plus its cursor, and re-read from `""`. Open for
+ Paul: whether memoria should do that by itself on a persistent S1 503,
+ and whether Fichas revisions should become restore-proof (event
+ timestamps), at the cost of the fixture's fixed revision numbers.
+- **A field rename and memoria's copy** (§6.4). Renaming a field moves no
+ card's revision, so memoria keeps the old label in its copy of each card
+ until that card next changes. Bumping every card of the type on a rename
+ would fix it at the cost of a log row per card. Open; added 2026-11-01.
- **Whether fichas embeds at all**, or is keyword-only in memoria. Paul,
2026-09-19: no preference. Decide when there is content; keyword-only is
the cheaper default and §10's egress ruling points that way.
@@ -489,7 +730,12 @@ In order, and small:
Call Log. No type designer.
3. Capture from Calls (§8).
4. The S1/S2/S3 server half and the conformance harness in CI (§6), so
- memoria indexes fichas like a Doc.
+ memoria indexes fichas like a Doc. **Built 2026-11-01** on
+ `feat/suite-producer` (over `feat/contract-demo`) against suite
+ revision 10 at `c38e3ad` (suite main; the reviewed branch tip 983114a plus polish), under Paul's ruling of that day (§6.1): S1
+ from the events table, S2 as admission, S3 as the card's text, mounted
+ only when `FICHAS_SUITE_CONSUMERS` is set. Conformance runs in CI with
+ the inexpressible cases asserted (§6.7). Not deployed, not merged.
5. The derived summary, with citations (§7).
References and reach (§9) wait on §10's ruling. **Reshaping by sentence is
diff --git a/go.mod b/go.mod
index e49ebea..78785be 100644
--- a/go.mod
+++ b/go.mod
@@ -6,6 +6,7 @@ toolchain go1.26.5
require (
amadan.net/oficina/estilo.git v0.0.0-20261001113457-a264aa5b9540
+ amadan.net/oficina/suite v0.0.0-20261101215835-c38e3ad85990
amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327
github.com/chromedp/chromedp v0.14.2
diff --git a/go.sum b/go.sum
index cf6c1dc..da38446 100644
--- a/go.sum
+++ b/go.sum
@@ -1,5 +1,9 @@
amadan.net/oficina/estilo.git v0.0.0-20261001113457-a264aa5b9540 h1:lG6hyBqz13XGisiyhKMHzPoBK6QP8weHQ02je/2gquk=
amadan.net/oficina/estilo.git v0.0.0-20261001113457-a264aa5b9540/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
+amadan.net/oficina/suite v0.0.0-20261101215312-983114acce54 h1:h2/Pv6hQ/F6CvEqv5wgrxhlYn7/fqoDrNAR0Tqnv6VQ=
+amadan.net/oficina/suite v0.0.0-20261101215312-983114acce54/go.mod h1:Xgw0N+DBiDzkhQHm/nIhgumfaiMElDg/KIFD1OxTm5w=
+amadan.net/oficina/suite v0.0.0-20261101215835-c38e3ad85990 h1:LXUZq/L5aJ700z9A//W5G04O/lxsUSRZrBK1mrBEIP4=
+amadan.net/oficina/suite v0.0.0-20261101215835-c38e3ad85990/go.mod h1:Xgw0N+DBiDzkhQHm/nIhgumfaiMElDg/KIFD1OxTm5w=
amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd h1:jlFSt95M1ontOg+VePU+kIJpChtWqDQAbnmlxqCnbgc=
amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd/go.mod h1:RpyHVPD0udcSfHJroY0KZE/FUjgw6Tvfo8SJm2qeZGE=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
diff --git a/internal/fichas/app.go b/internal/fichas/app.go
index a8068d2..634eb1c 100644
--- a/internal/fichas/app.go
+++ b/internal/fichas/app.go
@@ -14,6 +14,8 @@ import (
"amadan.net/rastrillo/rastrillo/db"
"amadan.net/rastrillo/rastrillo/mail"
"amadan.net/rastrillo/rastrillo/migrate"
+
+ "amadan.net/oficina/suite/server"
)
// App wires the whole app: schema, router, static files. It returns a
@@ -138,10 +140,26 @@ func App(d *db.DB, cfg Config, logger *slog.Logger) (*http.ServeMux, *app, error
// versioned prefix. Sessionless like the rest of static, and more
// specific than GET /static/, so it wins over the app's assets.
mux.Handle("GET "+sky.Prefix, sky.Handler())
+ // The suite contract (spec §6.5), only when a consumer is configured:
+ // with none, Handler is nil and /suite/ is an unknown path like any
+ // other. Mounted HERE, on the outer mux, and not on r: outside the
+ // session group, because memoria is not a person and has no session,
+ // and outside r's app-wide csrf.Protect, which would refuse its POST
+ // /suite/s2 — it sends a bearer token and no Origin or Sec-Fetch-Site.
+ // A bearer header is not something a cross-site form can attach, so
+ // the CSRF check has nothing to protect here. Exactly /suite/ is
+ // exempt; every other path still reaches r and its check.
+ if h := server.Handler(&suiteProducer{g: d.G, sealer: cfg.Sealer, admit: a.Admit}, cfg.SuiteConsumers, logger); h != nil {
+ mux.Handle(suitePrefix, h)
+ }
mux.Handle("/", r)
return mux, a, nil
}
+// suitePrefix is where the suite routes live (suite.RouteS1 and its
+// siblings all sit under it), and the one path exempt from the CSRF check.
+const suitePrefix = "/suite/"
+
// AppForTest builds the app already signed in as one address.
//
// Named for what it does, and the naming is the point. memoria's earlier
diff --git a/internal/fichas/config.go b/internal/fichas/config.go
index a2c1717..df39fbe 100644
--- a/internal/fichas/config.go
+++ b/internal/fichas/config.go
@@ -10,6 +10,7 @@ import (
"strings"
"amadan.net/oficina/fichas/internal/fichas/seal"
+ "amadan.net/oficina/suite/server"
)
// Config is everything fichas needs from platform config.
@@ -51,6 +52,10 @@ type Config struct {
// name Home and the other apps use), the account menu's "All apps".
// Empty — a standalone instance — and there is no "All apps".
Directory string
+ // SuiteConsumers are the siblings allowed to call the suite routes
+ // (spec §6.5), from FICHAS_SUITE_CONSUMERS. None, and the routes do
+ // not exist.
+ SuiteConsumers []server.Consumer
}
// ErrMissing is returned when required platform config is absent.
@@ -148,6 +153,11 @@ func LoadConfig(getenv func(string) string) (Config, error) {
default:
return Config{}, fmt.Errorf("fichas: FICHAS_SHAPE is %q; it is %q or %q", c.Shape, ShapeLone, ShapeSuite)
}
+ // Parsed at boot: a malformed list refuses to start rather than
+ // silently serving nobody, or serving somebody it should not.
+ if c.SuiteConsumers, err = server.ConsumersFromEnv(getenv, "fichas"); err != nil {
+ return Config{}, fmt.Errorf("fichas: FICHAS_SUITE_CONSUMERS: %w", err)
+ }
c.ContractRelease, err = loadContractRelease(getenv, c.Origin)
if err != nil {
return Config{}, err
diff --git a/internal/fichas/config_test.go b/internal/fichas/config_test.go
index 2f2e1ec..b97ee3c 100644
--- a/internal/fichas/config_test.go
+++ b/internal/fichas/config_test.go
@@ -4,6 +4,8 @@ import (
"encoding/base64"
"errors"
"testing"
+
+ "amadan.net/oficina/suite/server"
)
func env(m map[string]string) func(string) string {
@@ -233,3 +235,31 @@ func TestLoadConfigTakesTheDirectoryOrigin(t *testing.T) {
}
}
}
+
+// FICHAS_SUITE_CONSUMERS (spec §6.5): unset is no consumers; a good list is
+// read; anything malformed refuses boot rather than silently serving
+// nobody.
+//
+// MUTATION-TESTED 2026-11-01, reverted: the ConsumersFromEnv error
+// discarded (boot continues with no consumers) → "malformed".
+func TestSuiteConsumersAreReadAtBoot(t *testing.T) {
+ c, err := LoadConfig(env(map[string]string{}))
+ if err != nil || c.SuiteConsumers != nil {
+ t.Fatalf("unset: %+v, %v", c.SuiteConsumers, err)
+ }
+ good := `[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"` + server.TokenHash("t") + `"}]}]`
+ c, err = LoadConfig(env(map[string]string{"FICHAS_SUITE_CONSUMERS": good}))
+ if err != nil || len(c.SuiteConsumers) != 1 || c.SuiteConsumers[0].ID != "memoria" {
+ t.Fatalf("good: %+v, %v", c.SuiteConsumers, err)
+ }
+ for name, bad := range map[string]string{
+ "not JSON": "memoria:abc",
+ "a plaintext token": `[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"the-token"}]}]`,
+ "no tokens": `[{"consumer_id":"memoria","tokens":[]}]`,
+ "an unknown field": `[{"consumer_id":"memoria","origin":"x","tokens":[{"epoch":1,"sha256":"` + server.TokenHash("t") + `"}]}]`,
+ } {
+ if _, err := LoadConfig(env(map[string]string{"FICHAS_SUITE_CONSUMERS": bad})); err == nil {
+ t.Errorf("malformed (%s) was accepted", name)
+ }
+ }
+}
diff --git a/internal/fichas/suite.go b/internal/fichas/suite.go
new file mode 100644
index 0000000..4f5a625
--- /dev/null
+++ b/internal/fichas/suite.go
@@ -0,0 +1,287 @@
+package fichas
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
+
+ "gorm.io/gorm"
+
+ "amadan.net/oficina/fichas/internal/fichas/seal"
+ "amadan.net/oficina/suite"
+ "amadan.net/oficina/suite/server"
+)
+
+// suiteProducer is Fichas' half of the suite contract (spec §6; suite
+// doctrine revision 10, pinned at 983114a, §6.5). server.Handler owns the wire —
+// the bearer check, the decoding, the one S3 refusal — and this owns only
+// what Fichas knows: its log, its admission list, and a card's text.
+//
+// Paul, 2026-11-01: "Hold private too, check per person." Fichas has no
+// sharing ladder — every admitted person sees every card that is not gone
+// (Card.OwnerID is provenance, not authority) — so the feed carries every
+// card, S3 serves any live card, and S2 is admission.
+type suiteProducer struct {
+ g *gorm.DB
+ sealer *seal.Sealer
+ // admit is app.Admit: the one admission predicate sign-in and every
+ // session already run. Passed in rather than re-derived, so S2 cannot
+ // drift from who may open the app.
+ admit func(address string) bool
+}
+
+var _ server.Producer = (*suiteProducer)(nil)
+
+// Feed pages the events table (spec §6.2): card events after the cursor,
+// in id order, one row each.
+//
+// The cursor is "<event id>.<that event's created_at, unix nanoseconds>",
+// and the stamp is checked on every request. After a restore from an older
+// backup, AUTOINCREMENT hands the same event ids out again to different
+// events; a bare id would then continue silently from a position that now
+// means something else. A stamp that no longer matches is an error — a 503,
+// loud — never a page.
+func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) {
+ after, stamp, err := parseCursor(cursor)
+ if err != nil {
+ return suite.Feed{}, err
+ }
+ g := p.g.WithContext(ctx)
+ if after > 0 {
+ var at []Event
+ if err := g.Model(&Event{}).Select("id", "created_at").
+ Where("id = ? AND object_kind = ?", after, ObjectCard).Find(&at).Error; err != nil {
+ return suite.Feed{}, fmt.Errorf("fichas: reading the feed cursor's event: %w", err)
+ }
+ if len(at) != 1 || at[0].CreatedAt.UnixNano() != stamp {
+ return suite.Feed{}, fmt.Errorf("fichas: feed cursor %q names an event this log does not hold; it was rewritten by a restore, so the consumer must be reset", cursor)
+ }
+ }
+ var evs []Event
+ // Only plaintext columns: nothing sealed is read, so nothing sealed can
+ // reach a row.
+ if err := g.Model(&Event{}).
+ Select("id", "kind", "object_id", "revision", "created_at").
+ Where("id > ? AND object_kind = ?", after, ObjectCard).
+ Order("id").Limit(limit).Find(&evs).Error; err != nil {
+ return suite.Feed{}, fmt.Errorf("fichas: reading the feed: %w", err)
+ }
+ if len(evs) == 0 {
+ // At the tip: the same cursor, and no rows. "" becomes "0", the
+ // beginning, because the contract refuses an empty cursor.
+ if cursor == "" {
+ cursor = "0"
+ }
+ return suite.Feed{Cursor: cursor, Rows: []suite.FeedRow{}}, nil
+ }
+ stamps, err := p.cardStamps(ctx, evs)
+ if err != nil {
+ return suite.Feed{}, err
+ }
+ rows := make([]suite.FeedRow, len(evs))
+ for i, e := range evs {
+ created, ok := stamps[e.ObjectID]
+ if !ok {
+ // Card rows are never deleted, so an event for a card with no
+ // row is a log this code did not write. Loud, not skipped.
+ return suite.Feed{}, fmt.Errorf("fichas: event %d names card %d, which has no row", e.ID, e.ObjectID)
+ }
+ rows[i] = suite.FeedRow{
+ ItemID: itemID(e.ObjectID, created),
+ Revision: e.Revision,
+ Gone: e.Kind == EventDeleted,
+ TouchedAt: e.CreatedAt,
+ }
+ }
+ last := evs[len(evs)-1]
+ return suite.Feed{Cursor: stampedID(last.ID, last.CreatedAt.UnixNano()), Rows: rows}, nil
+}
+
+// cardStamps is each card's creation stamp, for the cards a page names.
+func (p *suiteProducer) cardStamps(ctx context.Context, evs []Event) (map[int64]int64, error) {
+ ids := make([]int64, 0, len(evs))
+ for _, e := range evs {
+ ids = append(ids, e.ObjectID)
+ }
+ var cards []Card
+ if err := p.g.WithContext(ctx).Model(&Card{}).Select("id", "created_at").
+ Where("id IN ?", ids).Find(&cards).Error; err != nil {
+ return nil, fmt.Errorf("fichas: reading card stamps: %w", err)
+ }
+ out := make(map[int64]int64, len(cards))
+ for _, c := range cards {
+ out[c.ID] = c.CreatedAt.UnixNano()
+ }
+ return out, nil
+}
+
+// itemID is a card's id on the wire: "<card id>.<card created_at, unix
+// nanoseconds>". The id alone is not enough: after a restore from an older
+// backup, a card created afterwards can be given the id, revision and event
+// position of one the consumer already holds. created_at is written once,
+// at insert, and never updated, so the pair names one card in one history.
+func itemID(cardID, created int64) string { return stampedID(cardID, created) }
+
+func stampedID(id, stamp int64) string {
+ return strconv.FormatInt(id, 10) + "." + strconv.FormatInt(stamp, 10)
+}
+
+// parseStamped reads "<id>.<stamp>", both canonical positive decimals, so a
+// value has exactly one spelling ("042.7", "+42.7", "42" are not 42.7).
+func parseStamped(s string) (id, stamp int64, ok bool) {
+ head, tail, found := strings.Cut(s, ".")
+ if !found {
+ return 0, 0, false
+ }
+ id, ok1 := canonicalPositive(head)
+ stamp, ok2 := canonicalPositive(tail)
+ return id, stamp, ok1 && ok2
+}
+
+func canonicalPositive(s string) (int64, bool) {
+ n, err := strconv.ParseInt(s, 10, 64)
+ if err != nil || n < 1 || strconv.FormatInt(n, 10) != s {
+ return 0, false
+ }
+ return n, true
+}
+
+// parseCursor reads a cursor Fichas issued: "" or "0" is the beginning,
+// anything else "<event id>.<stamp>". Anything else was not issued here and
+// is an error, never a guess.
+func parseCursor(c string) (after, stamp int64, err error) {
+ if c == "" || c == "0" {
+ return 0, 0, nil
+ }
+ after, stamp, ok := parseStamped(c)
+ if !ok {
+ return 0, 0, fmt.Errorf("fichas: feed cursor %q was not issued by fichas", c)
+ }
+ return after, stamp, nil
+}
+
+// Rule is S2 (spec §6.3). Fichas is lone-shape only, so it keys on an
+// address; a person_ref is a kind it cannot read and answers UNKNOWN,
+// loudly, rather than NOT_VISIBLE, which a consumer may act on silently.
+// Nothing here is cached: admission and every revision are read per call.
+func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) {
+ out := make([]suite.Authorization, len(pairs))
+ if asker.Kind != suite.SubjectAddress {
+ for i := range out {
+ out[i] = suite.UNKNOWN
+ }
+ return out, nil
+ }
+ if !p.admit(asker.Value) {
+ for i := range out {
+ out[i] = suite.NOT_VISIBLE
+ }
+ return out, nil
+ }
+
+ ids := make([]int64, 0, len(pairs))
+ for _, pr := range pairs {
+ if id, _, ok := parseStamped(pr.ItemID); ok {
+ ids = append(ids, id)
+ }
+ }
+ live := map[int64]Card{} // live cards only
+ if len(ids) > 0 {
+ var cards []Card
+ if err := p.g.WithContext(ctx).Model(&Card{}).Select("id", "revision", "created_at").
+ Where("id IN ? AND gone = ?", ids, false).Find(&cards).Error; err != nil {
+ return nil, fmt.Errorf("fichas: reading revisions: %w", err)
+ }
+ for _, c := range cards {
+ live[c.ID] = c
+ }
+ }
+
+ for i, pr := range pairs {
+ id, stamp, ok := parseStamped(pr.ItemID)
+ c, found := live[id]
+ switch {
+ case !ok || !found || c.CreatedAt.UnixNano() != stamp:
+ // Gone, unknown, or a different card under a reused id.
+ out[i] = suite.NOT_VISIBLE
+ case pr.Revision == c.Revision:
+ out[i] = suite.VISIBLE
+ case pr.Revision >= 1 && pr.Revision < c.Revision:
+ out[i] = suite.STALE
+ default:
+ // Ahead of the log (a restore), or below 1, which it never
+ // issued: a revision Fichas cannot vouch for.
+ out[i] = suite.UNKNOWN
+ }
+ }
+ return out, nil
+}
+
+// Content is S3 (spec §6.4): the card's text at its current revision, and
+// suite.ErrNotAvailable for anything else.
+func (p *suiteProducer) Content(ctx context.Context, itemID string, revision int64) ([]byte, error) {
+ id, stamp, ok := parseStamped(itemID)
+ if !ok {
+ return nil, suite.ErrNotAvailable
+ }
+ cv, err := LoadCard(ctx, p.g, p.sealer, id)
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, suite.ErrNotAvailable // unknown, or gone
+ }
+ if err != nil {
+ return nil, err
+ }
+ // Checked twice, and each check catches what the other cannot.
+ // LoadCard reads the card row, then its values and entries, in
+ // separate statements, so an edit can commit between them. This first
+ // check pins where the read STARTED: without it, an edit landing
+ // mid-read that produces the asked revision passes the second check
+ // with the old row's values under the new number.
+ if cv.Card.CreatedAt.UnixNano() != stamp || cv.Card.Revision != revision {
+ // A different card under a reused id (a restore), or another
+ // revision.
+ return nil, suite.ErrNotAvailable
+ }
+ body := cardText(cv)
+ // The second pins that nothing committed since. A revision moves only
+ // in the same transaction as the values and entries — a delete too,
+ // which is why "gone" needs no check of its own here — so if it is
+ // unchanged now, everything above was read at that revision.
+ var now Card
+ if err := p.g.WithContext(ctx).Select("id", "revision").First(&now, id).Error; err != nil {
+ // Not ErrNotAvailable: a failed read is not a refusal, and the
+ // card was there a moment ago. An error is a 503, which the
+ // consumer retries.
+ return nil, fmt.Errorf("fichas: re-reading card %d's revision: %w", id, err)
+ }
+ if now.Revision != revision {
+ return nil, suite.ErrNotAvailable
+ }
+ return []byte(body), nil
+}
+
+// cardText is the plain text a consumer indexes: the title, each other
+// field with a value as "Label: value", then each entry, newest first, as
+// its type label and its fields. Lines are joined with "\n" and there is no
+// trailing newline, so a card with only a title is exactly its title.
+func cardText(cv CardView) string {
+ lines := []string{cv.Title()}
+ for _, f := range cv.Fields {
+ if cv.IsTitle(f.Def.Key) || f.Value == "" {
+ continue
+ }
+ lines = append(lines, f.Label+": "+f.Value)
+ }
+ for _, e := range cv.Entries {
+ lines = append(lines, "", e.TypeLabel)
+ for _, f := range e.Fields {
+ if f.Value == "" {
+ continue
+ }
+ lines = append(lines, f.Label+": "+f.Value)
+ }
+ }
+ return strings.Join(lines, "\n")
+}
diff --git a/internal/fichas/suite_conformance_test.go b/internal/fichas/suite_conformance_test.go
new file mode 100644
index 0000000..0d00331
--- /dev/null
+++ b/internal/fichas/suite_conformance_test.go
@@ -0,0 +1,169 @@
+package fichas
+
+import (
+ "context"
+ "fmt"
+ "slices"
+ "testing"
+
+ "amadan.net/oficina/suite"
+ "amadan.net/oficina/suite/conformance"
+ "amadan.net/oficina/suite/server"
+)
+
+// fixtureNames lets the suite's custody fixture address a real Fichas
+// world. It RENAMES and decides nothing: the fixture's item ids become the
+// card ids seeded for them, and back again in feed rows (spec §6.7 — a
+// fixture id is a name, not an id Fichas could allocate). The askers need
+// no renaming: conformance.CheckAs sends them as addresses. Every answer is
+// the real producer's, over a real database.
+type fixtureNames struct {
+ inner server.Producer
+ ids map[string]string
+}
+
+// Feed renames each row's card id back to the fixture id it was seeded
+// for, so the harness can find its items in the feed. Rows for cards the
+// fixture did not seed pass through as themselves.
+func (n fixtureNames) Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) {
+ f, err := n.inner.Feed(ctx, cursor, limit)
+ for i, row := range f.Rows {
+ for fixtureID, cardID := range n.ids {
+ if row.ItemID == cardID {
+ f.Rows[i].ItemID = fixtureID
+ }
+ }
+ }
+ return f, err
+}
+
+func (n fixtureNames) Rule(ctx context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) {
+ renamed := make([]suite.ItemRevision, len(pairs))
+ for i, pr := range pairs {
+ renamed[i] = suite.ItemRevision{ItemID: n.name(pr.ItemID), Revision: pr.Revision}
+ }
+ return n.inner.Rule(ctx, asker, renamed)
+}
+
+func (n fixtureNames) Content(ctx context.Context, itemID string, revision int64) ([]byte, error) {
+ return n.inner.Content(ctx, n.name(itemID), revision)
+}
+
+// name maps a fixture id to its card, and passes anything else through
+// untouched — so the harness's never-existed id reaches Fichas as itself.
+func (n fixtureNames) name(id string) string {
+ if c, ok := n.ids[id]; ok {
+ return c
+ }
+ return id
+}
+
+// The suite's own conformance harness, run as an address-keyed app
+// (conformance.CheckAs, suite.SubjectAddress) against Fichas' real producer
+// over a world seeded from the custody fixture: one Customer card per case,
+// named with the case's s3_body (so S3's exact-body check is a real check
+// of the text shape: a card with only a title is exactly its title), edited
+// up to the case's revision, and the deleted case deleted. The harness also
+// asks under person_ref, a kind Fichas does not key on, and requires
+// UNKNOWN; follows S1 to its tip; and refuses S3 one revision either side.
+//
+// The fixture describes a sharing ladder Fichas does not have (spec §6.7):
+// every admitted person sees every card. So four cases — guest-only,
+// link-shared private, moved to private, link added late — expect
+// NOT_VISIBLE for the fixture's asker where Fichas, correctly for Fichas,
+// answers VISIBLE at the current revision, STALE one behind and UNKNOWN one
+// ahead (a member may open the card, so a revision the log never issued is
+// UNKNOWN for them, §4.3). This test asserts the failures are EXACTLY those
+// twelve: any other failure, or one of these passing, is red, so a change
+// to the fixture on the suite branch (983114a, review round 2) is noticed
+// here rather than absorbed.
+//
+// MUTATION-TESTED 2026-11-01 against 983114a, each reverted, by how many
+// failures the harness then reports (12 expected): both of Content's
+// revision checks removed → 28 (S3 served at revision ±1); a trailing
+// newline on the text → 20; admission skipped → 36; the person_ref branch
+// removed → 21 (wrong kind answered NOT_VISIBLE); gone cards answered in
+// Rule → 15; the title repeated as a "Name:" line → 20; feed rows never
+// gone → 13; feed rows at revision 1 → 20; one-row pages under a cursor
+// that never settles → red (re-run after the stamped cursor: the junk
+// cursor is now refused outright); a revision ahead answered STALE → 16.
+// Counts re-measured after item ids and cursors gained their stamps.
+// One survivor here: the next cursor taken from a page's FIRST row repeats
+// rows but still ends on the right state, which is all the harness reads;
+// TestSuiteFeedIsTheEventLog catches it.
+func TestSuiteConformanceFailsOnlyWhereFichasCannotExpress(t *testing.T) {
+ f, err := suite.LoadCustodyFixture()
+ if err != nil {
+ t.Fatal(err)
+ }
+ g, a, p := suiteWorld(t)
+
+ ids := map[string]string{}
+ for _, c := range f.Cases {
+ gone := c.Rung == suite.RungDeleted
+ // A deleted card's last live revision is one below the fixture's,
+ // because the delete itself is a revision.
+ lastLive := c.Revision
+ if gone {
+ lastLive--
+ }
+ name := c.S3Body
+ if gone {
+ name = "a card about to be deleted"
+ }
+ first := name
+ if lastLive > 1 {
+ first = "draft 1"
+ }
+ card := mustCard(t, g, a, map[string]string{FieldName: first})
+ for r := int64(2); r <= lastLive; r++ {
+ v := fmt.Sprintf("draft %d", r)
+ if r == lastLive {
+ v = name
+ }
+ if err := UpdateCard(ctx(), g, a.sealer, card.ID, Person(1), map[string]string{FieldName: v}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if gone {
+ if err := DeleteCard(ctx(), g, a.sealer, card.ID, Person(1)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var now Card
+ if err := g.First(&now, card.ID).Error; err != nil || now.Revision != c.Revision || now.Gone != gone {
+ t.Fatalf("seeding %s: card is %+v (%v), want revision %d gone %v", c.ItemID, now, err, c.Revision, gone)
+ }
+ ids[c.ItemID] = id(now)
+ }
+
+ // CheckAs sends the fixture's asker and stranger as addresses with
+ // their values unchanged: pers_ana is put on the owners list, as
+ // FICHAS_OWNERS would, and pers_bo is not.
+ a.owners = ParseOwners(f.Asker.Value)
+ report := conformance.CheckAs(server.Routes(fixtureNames{inner: p, ids: ids}, nil), suite.SubjectAddress)
+ if report.Checked == 0 {
+ t.Fatal("conformance checked nothing")
+ }
+
+ var want []string
+ for _, item := range []string{"doc-guest", "doc-link", "doc-was-team", "doc-link-added-late"} {
+ want = append(want,
+ fmt.Sprintf("S2 %s asked for the fixture's asker, at the current revision: got VISIBLE, want NOT_VISIBLE", item),
+ fmt.Sprintf("S2 %s asked for the fixture's asker, one revision behind: got STALE, want NOT_VISIBLE", item),
+ fmt.Sprintf("S2 %s asked for the fixture's asker, one revision ahead: got UNKNOWN, want NOT_VISIBLE", item))
+ }
+ got := slices.Clone(report.Failures)
+ slices.Sort(got)
+ slices.Sort(want)
+ if !slices.Equal(got, want) {
+ t.Errorf("conformance failures are not exactly the inexpressible cases (spec §6.7).\n got (%d):", len(got))
+ for _, s := range got {
+ t.Errorf(" %s", s)
+ }
+ t.Errorf("want (%d):", len(want))
+ for _, s := range want {
+ t.Errorf(" %s", s)
+ }
+ }
+}
diff --git a/internal/fichas/suite_test.go b/internal/fichas/suite_test.go
new file mode 100644
index 0000000..08b0a72
--- /dev/null
+++ b/internal/fichas/suite_test.go
@@ -0,0 +1,609 @@
+package fichas
+
+import (
+ "errors"
+ "net/http/httptest"
+ "slices"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "gorm.io/gorm"
+
+ "amadan.net/oficina/suite"
+ "amadan.net/oficina/suite/server"
+)
+
+// The producer half of the suite contract (spec §6). These drive the
+// producer directly; fichastest/suite_test.go drives it through the real
+// router, and suite_conformance_test.go through the suite's own harness.
+
+const admittedAsker = "ana@example.com"
+
+// producerFor builds the producer over the real admission predicate,
+// app.Admit, with one admitted address — what LoadConfig gives a lone
+// instance whose FICHAS_OWNERS is that address.
+func producerFor(g *gorm.DB, a *app) *suiteProducer {
+ return &suiteProducer{g: g, sealer: a.sealer, admit: a.Admit}
+}
+
+func suiteWorld(t *testing.T) (*gorm.DB, *app, *suiteProducer) {
+ t.Helper()
+ g, s := seeded(t)
+ a := &app{sealer: s, owners: ParseOwners(admittedAsker)}
+ return g, a, producerFor(g, a)
+}
+
+func mustCard(t *testing.T, g *gorm.DB, a *app, values map[string]string) Card {
+ t.Helper()
+ return mustCardBy(t, g, a, Person(1), values)
+}
+
+// mustCardBy creates a card as actor and returns it as the database holds
+// it, so its created_at — half of its item id — is the stored value.
+func mustCardBy(t *testing.T, g *gorm.DB, a *app, actor Actor, values map[string]string) Card {
+ t.Helper()
+ c, err := CreateCard(ctx(), g, a.sealer, TypeCustomer, actor, values)
+ if err != nil {
+ t.Fatalf("CreateCard: %v", err)
+ }
+ var stored Card
+ if err := g.First(&stored, c.ID).Error; err != nil {
+ t.Fatal(err)
+ }
+ return stored
+}
+
+// id is a card's item id: "<card id>.<created_at unix nanos>".
+func id(c Card) string { return itemID(c.ID, c.CreatedAt.UnixNano()) }
+
+// bare is the card id alone, which is not an item id.
+func bare(c Card) string { return strconv.FormatInt(c.ID, 10) }
+
+func address(v string) suite.Subject { return suite.Subject{Kind: suite.SubjectAddress, Value: v} }
+
+// readFeed pages from cursor to the tip, limit rows a page, and returns
+// every row and the tip's cursor.
+func readFeed(t *testing.T, p *suiteProducer, cursor string, limit int) ([]suite.FeedRow, string) {
+ t.Helper()
+ var all []suite.FeedRow
+ for pages := 0; ; pages++ {
+ if pages > 100 {
+ t.Fatal("the feed never reached its tip")
+ }
+ f, err := p.Feed(ctx(), cursor, limit)
+ if err != nil {
+ t.Fatalf("Feed(%q): %v", cursor, err)
+ }
+ if f.Cursor == "" || len(f.Rows) > limit {
+ t.Fatalf("Feed(%q) broke the contract: %+v", cursor, f)
+ }
+ if len(f.Rows) == 0 {
+ if f.Cursor != cursor && cursor != "" {
+ t.Fatalf("at the tip the cursor moved: %q → %q", cursor, f.Cursor)
+ }
+ if f.Rows == nil {
+ t.Fatal("the tip's rows are nil, not empty")
+ }
+ return all, f.Cursor
+ }
+ all = append(all, f.Rows...)
+ cursor = f.Cursor
+ }
+}
+
+type row struct {
+ item string
+ rev int64
+ gone bool
+}
+
+func rowsOf(rs []suite.FeedRow) []row {
+ out := make([]row, len(rs))
+ for i, r := range rs {
+ out[i] = row{r.ItemID, r.Revision, r.Gone}
+ }
+ return out
+}
+
+// S1 is the events table: one row per card event, in log order, carrying
+// the card's revision after that event; an entry bumps its card; a delete
+// is gone; the catalogue's type and field events and an entry's own
+// creation row are not items. Paged two at a time so every page boundary
+// is crossed, and the tip answers the same cursor and no rows.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: the object_kind filter
+// dropped (seed and entry events become rows) → "rows"; Gone hard-coded
+// false → "rows"; Revision taken as 1 → "rows"; the next cursor taken from
+// the FIRST row of a page (pages repeat) → "rows"; the tip answering a
+// fresh cursor ("0") → "at the tip the cursor moved"; the tip's Rows left
+// nil → "nil, not empty"; created_at not selected (zero touched_at) →
+// "touched_at".
+func TestSuiteFeedIsTheEventLog(t *testing.T) {
+ g, a, p := suiteWorld(t)
+ c1 := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
+ c2 := mustCard(t, g, a, map[string]string{FieldName: "Harbour Timber"})
+ if err := UpdateCard(ctx(), g, a.sealer, c1.ID, Person(1), map[string]string{FieldStage: "Lead"}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := AddEntry(ctx(), g, a.sealer, c1.ID, Person(2), TypeCallLog, "manual", map[string]string{FieldBody: "rang them"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := DeleteCard(ctx(), g, a.sealer, c2.ID, Person(1)); err != nil {
+ t.Fatal(err)
+ }
+
+ rows, tip := readFeed(t, p, "", 2)
+ want := []row{
+ {id(c1), 1, false},
+ {id(c2), 1, false},
+ {id(c1), 2, false}, // an update
+ {id(c1), 3, false}, // an entry landing bumps its card
+ {id(c2), 2, true}, // a delete is gone
+ }
+ if got := rowsOf(rows); !slices.Equal(got, want) {
+ t.Fatalf("rows:\n got %+v\nwant %+v", got, want)
+ }
+ for _, r := range rows {
+ if r.TouchedAt.IsZero() {
+ t.Errorf("touched_at is zero on %+v", r)
+ }
+ }
+
+ // The tip, asked again, is the same cursor and no rows; a change after
+ // it is exactly one more row.
+ if more, again := readFeed(t, p, tip, 2); len(more) != 0 || again != tip {
+ t.Fatalf("at the tip: %d rows, cursor %q (was %q)", len(more), again, tip)
+ }
+ if err := UpdateCard(ctx(), g, a.sealer, c1.ID, Person(1), map[string]string{FieldStage: "Won"}); err != nil {
+ t.Fatal(err)
+ }
+ if more, _ := readFeed(t, p, tip, 2); !slices.Equal(rowsOf(more), []row{{id(c1), 4, false}}) {
+ t.Fatalf("after the tip: %+v", rowsOf(more))
+ }
+}
+
+// A row is the four plaintext columns and nothing else: no value, label or
+// actor can reach it because the query never reads one.
+func TestSuiteFeedRowsCarryNoContent(t *testing.T) {
+ g, a, p := suiteWorld(t)
+ mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta", FieldNotes: "owes us money"})
+ f, err := p.Feed(ctx(), "", 10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, r := range f.Rows {
+ for _, s := range []string{r.ItemID, f.Cursor} {
+ if strings.Contains(s, "Cnoc") || strings.Contains(s, "money") {
+ t.Fatalf("content in a feed row: %+v", r)
+ }
+ }
+ }
+}
+
+// An empty log starts at "0" (the contract refuses an empty cursor) and
+// stays there.
+func TestSuiteFeedOnAnEmptyLog(t *testing.T) {
+ g := testDB(t)
+ p := &suiteProducer{g: g, sealer: testSealer(t), admit: func(string) bool { return true }}
+ f, err := p.Feed(ctx(), "", 10)
+ if err != nil || f.Cursor != "0" || f.Rows == nil || len(f.Rows) != 0 {
+ t.Fatalf("empty log: %+v, %v", f, err)
+ }
+ if f, err := p.Feed(ctx(), "0", 10); err != nil || f.Cursor != "0" || len(f.Rows) != 0 {
+ t.Fatalf("empty log again: %+v, %v", f, err)
+ }
+}
+
+// A cursor Fichas could not have issued is an error (the server makes it a
+// 503), never a page: not "<event id>.<stamp>" in canonical form, ahead of
+// the log, or naming an event whose stamp the log does not hold — a
+// restore from an older backup, where a page would continue silently from
+// a position that now means something else.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: the canonical check removed
+// from canonicalPositive → "leading zero"/"plus"; a bare event id accepted
+// as a cursor AND the lookup skipped for it → "no stamp"; the cursor's
+// event lookup skipped → "ahead"/"wrong stamp"; the stamp comparison
+// removed → "wrong stamp"; canonicalPositive's n < 1 bound removed →
+// "zero id"/"negative id" (Astra, 2026-11-01: not equivalent — an id of 0
+// or below skips the lookup and pages from the beginning); the lookup's
+// object_kind = card restriction removed → "a catalogue event" (a correctly
+// stamped event that is not a card's would have been accepted). One mutant
+// survives and is equivalent: a bare id parsed as stamp 0, which the lookup
+// then refuses.
+func TestSuiteFeedRefusesACursorItNeverIssued(t *testing.T) {
+ g, a, p := suiteWorld(t)
+ mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
+ _, tip := readFeed(t, p, "", 10)
+ n, stamp, ok := parseStamped(tip)
+ if !ok {
+ t.Fatalf("the tip %q is not <event id>.<stamp>", tip)
+ }
+ for name, c := range map[string]string{
+ "letters": "abc",
+ "-1": "-1",
+ "no stamp": strconv.FormatInt(n, 10),
+ "leading zero": "0" + tip,
+ "plus": "+" + tip,
+ "stamp zero": stampedID(n, 0),
+ "three parts": tip + ".1",
+ "spaces": " " + tip,
+ "ahead": stampedID(n+1000, stamp),
+ "wrong stamp": stampedID(n, stamp+1),
+ "zero id": "0.1",
+ "negative id": "-1.1",
+ } {
+ if f, err := p.Feed(ctx(), c, 10); err == nil {
+ t.Errorf("%s: cursor %q answered %+v, want an error", name, c, f)
+ }
+ }
+
+ // A catalogue event, correctly stamped, is still not a feed position:
+ // the feed is card events only, so its ids are not positions in it.
+ other := Event{Kind: EventUpdated, ObjectKind: ObjectType, ObjectID: 1, Revision: 1, CreatedAt: time.Now().UTC()}
+ if err := g.Create(&other).Error; err != nil {
+ t.Fatalf("seeding a catalogue event: %v", err)
+ }
+ var stored Event
+ if err := g.First(&stored, other.ID).Error; err != nil {
+ t.Fatal(err)
+ }
+ c := stampedID(stored.ID, stored.CreatedAt.UnixNano())
+ if f, err := p.Feed(ctx(), c, 10); err == nil {
+ t.Errorf("a catalogue event: cursor %q answered %+v, want an error", c, f)
+ }
+}
+
+// S2, every branch of spec §6.3's table.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: the person_ref branch removed
+// (a person_ref falls to admission and answers NOT_VISIBLE) → "person_ref";
+// admission skipped → "not admitted"; the gone filter dropped from the
+// revision query → "gone"; STALE's lower bound removed (0 and negatives
+// are STALE) → "revision 0"/"negative revision"; the lower bound loosened
+// to >= 0 → "revision 0"; the > current case answering STALE → "ahead";
+// == current answering STALE → "current"; the canonical check removed →
+// "not canonical"; the stamp comparison removed → "wrong stamp"; the
+// query restricted to owner_id = 1 → "owned by another member".
+func TestSuiteRuleEveryBranch(t *testing.T) {
+ g, a, p := suiteWorld(t)
+ live := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
+ for _, stage := range []string{"Lead", "Won"} {
+ if err := UpdateCard(ctx(), g, a.sealer, live.ID, Person(1), map[string]string{FieldStage: stage}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // live is at revision 3.
+ gone := mustCard(t, g, a, map[string]string{FieldName: "Harbour Timber"})
+ if err := DeleteCard(ctx(), g, a.sealer, gone.ID, Person(1)); err != nil {
+ t.Fatal(err)
+ }
+ // Owner is provenance, not authority: a card another member made is
+ // every admitted person's.
+ theirs := mustCardBy(t, g, a, Person(2), map[string]string{FieldName: "Their card"})
+ wrongStamp := itemID(live.ID, live.CreatedAt.UnixNano()+1)
+
+ pairs := []suite.ItemRevision{
+ {ItemID: id(live), Revision: 3}, // current
+ {ItemID: id(live), Revision: 2}, // behind
+ {ItemID: id(live), Revision: 4}, // ahead
+ {ItemID: id(live), Revision: 0}, // revision 0
+ {ItemID: id(live), Revision: -1}, // negative revision
+ {ItemID: id(gone), Revision: 2}, // gone, at its last revision
+ {ItemID: "999999.1", Revision: 1}, // unknown
+ {ItemID: "doc-team", Revision: 1}, // not a card id
+ {ItemID: "0" + id(live), Revision: 3}, // not canonical
+ {ItemID: bare(live), Revision: 3}, // no stamp
+ {ItemID: wrongStamp, Revision: 3}, // wrong stamp
+ {ItemID: id(theirs), Revision: 1}, // owned by another member
+ }
+ names := []string{"current", "behind", "ahead", "revision 0", "negative revision", "gone", "unknown",
+ "not a card id", "not canonical", "no stamp", "wrong stamp", "owned by another member"}
+
+ check := func(what string, asker suite.Subject, want []suite.Authorization) {
+ t.Helper()
+ got, err := p.Rule(ctx(), asker, pairs)
+ if err != nil {
+ t.Fatalf("%s: %v", what, err)
+ }
+ if len(got) != len(pairs) {
+ t.Fatalf("%s: %d answers for %d pairs", what, len(got), len(pairs))
+ }
+ for i := range pairs {
+ if got[i] != want[i] {
+ t.Errorf("%s, %s: got %s, want %s", what, names[i], got[i], want[i])
+ }
+ }
+ }
+ all := func(v suite.Authorization) []suite.Authorization {
+ out := make([]suite.Authorization, len(pairs))
+ for i := range out {
+ out[i] = v
+ }
+ return out
+ }
+
+ check("admitted", address(admittedAsker), []suite.Authorization{
+ suite.VISIBLE, suite.STALE, suite.UNKNOWN, suite.UNKNOWN, suite.UNKNOWN,
+ suite.NOT_VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE,
+ suite.NOT_VISIBLE, suite.NOT_VISIBLE, suite.VISIBLE,
+ })
+ // A kind Fichas does not key on is UNKNOWN — loud — even when its value
+ // happens to be an admitted address.
+ check("person_ref", suite.Subject{Kind: suite.SubjectPersonRef, Value: admittedAsker}, all(suite.UNKNOWN))
+ check("not admitted", address("bo@example.com"), all(suite.NOT_VISIBLE))
+}
+
+// Never cached: the same question asked twice is answered from the world as
+// it is at each call — a revision that moved, and an admission list that
+// changed.
+//
+// MUTATION-TESTED 2026-11-01, reverted: Rule memoising its first answer per
+// (asker, pair) in a map on the producer → "after an edit" and "after
+// removal".
+func TestSuiteRuleIsNeverCached(t *testing.T) {
+ g, a, p := suiteWorld(t)
+ c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
+ pair := []suite.ItemRevision{{ItemID: id(c), Revision: 1}}
+ ask := func() suite.Authorization {
+ t.Helper()
+ got, err := p.Rule(ctx(), address(admittedAsker), pair)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return got[0]
+ }
+ if got := ask(); got != suite.VISIBLE {
+ t.Fatalf("first: %s", got)
+ }
+ if err := UpdateCard(ctx(), g, a.sealer, c.ID, Person(1), map[string]string{FieldStage: "Lead"}); err != nil {
+ t.Fatal(err)
+ }
+ if got := ask(); got != suite.STALE {
+ t.Errorf("after an edit: %s, want STALE", got)
+ }
+ a.owners = ParseOwners("someone-else@example.com")
+ if got := ask(); got != suite.NOT_VISIBLE {
+ t.Errorf("after removal from the owners list: %s, want NOT_VISIBLE", got)
+ }
+}
+
+// S3 serves the current revision's text, in spec §6.4's shape, and refuses
+// everything else with suite.ErrNotAvailable.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: both revision checks removed
+// (any revision served) → "an older revision"/"a newer revision"; the
+// title field repeated as a "Name:" line → "text"; empty fields emitted as
+// "Label: " → "text"; entries left out → "text"; a trailing newline →
+// "text"/"title only"; the canonical check removed → "not canonical"; the
+// stamp comparison removed → "wrong stamp".
+func TestSuiteContent(t *testing.T) {
+ g, a, p := suiteWorld(t)
+ c := mustCard(t, g, a, map[string]string{
+ FieldName: "Cnoc Teoranta",
+ FieldEmail: "orders@cnoc.example",
+ FieldNotes: "met at the trade show",
+ })
+ if _, err := AddEntry(ctx(), g, a.sealer, c.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "first call"}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := AddEntry(ctx(), g, a.sealer, c.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "second call", FieldDuration: "15"}); err != nil {
+ t.Fatal(err)
+ }
+ // c is at revision 3.
+ got, err := p.Content(ctx(), id(c), 3)
+ if err != nil {
+ t.Fatalf("current revision: %v", err)
+ }
+ want := strings.Join([]string{
+ "Cnoc Teoranta",
+ "Email: orders@cnoc.example",
+ "Notes: met at the trade show",
+ "",
+ "Call log",
+ "What was said: second call",
+ "Duration: 15",
+ "",
+ "Call log",
+ "What was said: first call",
+ }, "\n")
+ if string(got) != want {
+ t.Errorf("text:\n got %q\nwant %q", got, want)
+ }
+
+ title := mustCard(t, g, a, map[string]string{FieldName: "Harbour Timber"})
+ if got, err := p.Content(ctx(), id(title), 1); err != nil || string(got) != "Harbour Timber" {
+ t.Errorf("title only: %q, %v", got, err)
+ }
+
+ gone := mustCard(t, g, a, map[string]string{FieldName: "Gone Ltd"})
+ if err := DeleteCard(ctx(), g, a.sealer, gone.ID, Person(1)); err != nil {
+ t.Fatal(err)
+ }
+ for name, q := range map[string]struct {
+ item string
+ rev int64
+ }{
+ "an older revision": {id(c), 2},
+ "a newer revision": {id(c), 4},
+ "gone": {id(gone), 2},
+ "gone, its old revision": {id(gone), 1},
+ "unknown": {"999999.1", 1},
+ "not a card id": {"doc-team", 1},
+ "not canonical": {"0" + id(c), 3},
+ "no stamp": {bare(c), 3},
+ "wrong stamp": {itemID(c.ID, c.CreatedAt.UnixNano()+1), 3},
+ } {
+ if body, err := p.Content(ctx(), q.item, q.rev); !errors.Is(err, suite.ErrNotAvailable) || body != nil {
+ t.Errorf("%s: %q, %v; want ErrNotAvailable and no body", name, body, err)
+ }
+ }
+}
+
+// An edit that commits while S3 is reading the card is refused, not served
+// under a revision it does not match. The edit is made to land after
+// LoadCard has read the card row and its values, before its entries; the
+// card goes from revision 1 to 2. Asked for 1, the read finished on a
+// card that is no longer at 1; asked for 2, it started on a card that was
+// not yet at 2. Both are refused.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: the second revision check
+// removed → "asked for the revision it started at"; the first removed →
+// "asked for the revision the edit produced".
+func TestSuiteContentRefusesAnEditMidRead(t *testing.T) {
+ for name, asked := range map[string]int64{
+ "asked for the revision it started at": 1,
+ "asked for the revision the edit produced": 2,
+ } {
+ t.Run(name, func(t *testing.T) {
+ g, a, p := suiteWorld(t)
+ c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
+ fired := false
+ if err := g.Callback().Query().After("gorm:query").Register("test:edit_mid_read", func(tx *gorm.DB) {
+ if fired || tx.Statement.Table != "card_values" {
+ return
+ }
+ fired = true
+ if err := UpdateCard(ctx(), g, a.sealer, c.ID, Person(1), map[string]string{FieldName: "Renamed"}); err != nil {
+ t.Errorf("the mid-read edit: %v", err)
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ body, err := p.Content(ctx(), id(c), asked)
+ if !fired {
+ t.Fatal("the mid-read edit never ran; the test proves nothing")
+ }
+ if !errors.Is(err, suite.ErrNotAvailable) {
+ t.Errorf("served %q, %v; want ErrNotAvailable", body, err)
+ }
+ })
+ }
+}
+
+// A restore from an older backup, and a different card created after it,
+// reproduce the old card's id, revision and event position exactly (Astra,
+// 2026-11-01). memoria still holds the old card's item id, its text and its
+// feed cursor. None of the three may carry on as if nothing happened: S2
+// does not vouch for the old item, S3 does not serve the new card's text
+// under it, and S1 refuses the old cursor loudly.
+//
+// Modelled with two databases seeded alike: "before" is the backup, taken
+// before the original card existed; "after" is the live database that went
+// on to hold it. The test first proves the collision is real.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: Rule's stamp comparison
+// removed → "S2"; Content's stamp comparison removed → "S3"; the cursor's
+// stamp comparison removed → "S1"; the cursor's event lookup skipped
+// entirely → "S1".
+func TestSuiteRestoreCannotPassOffANewCardAsAnOldOne(t *testing.T) {
+ gBefore, aBefore, pBefore := suiteWorld(t)
+ gAfter, aAfter, pAfter := suiteWorld(t)
+
+ original := mustCard(t, gAfter, aAfter, map[string]string{FieldName: "The original, which memoria holds"})
+ held := id(original)
+ _, heldCursor := readFeed(t, pAfter, "", 10)
+ if got, _ := pAfter.Rule(ctx(), address(admittedAsker), []suite.ItemRevision{{ItemID: held, Revision: 1}}); got[0] != suite.VISIBLE {
+ t.Fatalf("before the restore, the held item: %s", got[0])
+ }
+
+ // The restore: the live database is now "before", and a different card
+ // is made in it.
+ recreated := mustCardBy(t, gBefore, aBefore, Person(2), map[string]string{FieldName: "A different card"})
+ var origEv, newEv []Event
+ gAfter.Where("object_kind = ?", ObjectCard).Find(&origEv)
+ gBefore.Where("object_kind = ?", ObjectCard).Find(&newEv)
+ if recreated.ID != original.ID || recreated.Revision != original.Revision ||
+ len(origEv) != 1 || len(newEv) != 1 || origEv[0].ID != newEv[0].ID {
+ t.Fatalf("the collision did not happen, so this proves nothing: card %d/%d rev %d/%d, events %+v %+v",
+ original.ID, recreated.ID, original.Revision, recreated.Revision, origEv, newEv)
+ }
+ if id(recreated) == held {
+ t.Fatal("the recreated card has the held item id: the clock did not move")
+ }
+
+ got, err := pBefore.Rule(ctx(), address(admittedAsker), []suite.ItemRevision{{ItemID: held, Revision: 1}})
+ if err != nil || got[0] != suite.NOT_VISIBLE {
+ t.Errorf("S2 for the held item after the restore: %v, %v; want NOT_VISIBLE", got, err)
+ }
+ if body, err := pBefore.Content(ctx(), held, 1); !errors.Is(err, suite.ErrNotAvailable) {
+ t.Errorf("S3 for the held item after the restore: served %q, %v; want ErrNotAvailable", body, err)
+ }
+ if f, err := pBefore.Feed(ctx(), heldCursor, 10); err == nil {
+ t.Errorf("S1 from the held cursor %q after the restore: %+v; want an error (a 503), not a page", heldCursor, f)
+ }
+ // The new card is served under its own id.
+ if body, err := pBefore.Content(ctx(), id(recreated), 1); err != nil || string(body) != "A different card" {
+ t.Errorf("S3 for the new card under its own id: %q, %v", body, err)
+ }
+}
+
+// A database failure on S3's final revision re-read is an error, which the
+// server answers 503 and the consumer retries — never ErrNotAvailable, the
+// refusal that tells memoria the card is gone.
+//
+// MUTATION-TESTED 2026-11-01, reverted: the re-read's error mapped to
+// suite.ErrNotAvailable → "a refusal" and "404".
+func TestSuiteContentReReadFailureIsAnError(t *testing.T) {
+ g, a, p := suiteWorld(t)
+ c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
+ cardsQueries := 0
+ if err := g.Callback().Query().Before("gorm:query").Register("test:fail_reread", func(tx *gorm.DB) {
+ if tx.Statement.Table != "cards" {
+ return
+ }
+ // LoadCard reads the card first; the re-read is the second.
+ if cardsQueries++; cardsQueries == 2 {
+ tx.AddError(errors.New("the disk went away"))
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ _, err := p.Content(ctx(), id(c), 1)
+ if cardsQueries < 2 {
+ t.Fatal("the re-read never ran; the test proves nothing")
+ }
+ if err == nil || errors.Is(err, suite.ErrNotAvailable) {
+ t.Errorf("a failed re-read: %v; want an error that is not a refusal", err)
+ }
+
+ cardsQueries = 0
+ rec := httptest.NewRecorder()
+ server.Routes(p, nil).ServeHTTP(rec, httptest.NewRequest("GET", suite.RouteS3+"/"+id(c)+"?revision=1", nil))
+ if rec.Code != 503 {
+ t.Errorf("through the server: %d, want 503 (404 is a refusal)", rec.Code)
+ }
+}
+
+// An event naming a card with no row is a database this code did not
+// write: the cards_are_not_hard_deleted trigger (migration 0002) refuses
+// the delete, so the test drops it on its own temporary database to build
+// one. The feed fails loudly rather than skip the row, which would move
+// the consumer's cursor past a change it never saw.
+//
+// MUTATION-TESTED 2026-11-01, reverted: the missing-row check skipped →
+// "a card with no row".
+func TestSuiteFeedRefusesAnEventWithNoCard(t *testing.T) {
+ g, a, p := suiteWorld(t)
+ c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
+ if err := g.Exec("DROP TRIGGER cards_are_not_hard_deleted").Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := g.Exec("DELETE FROM cards WHERE id = ?", c.ID).Error; err != nil {
+ t.Fatal(err)
+ }
+ if f, err := p.Feed(ctx(), "", 10); err == nil {
+ t.Errorf("a card with no row: %+v, want an error", f)
+ }
+}
+
+// Every suite route sits under the one prefix the app mounts and exempts.
+func TestSuiteRoutesSitUnderThePrefix(t *testing.T) {
+ for _, r := range []string{suite.RouteS1, suite.RouteS2, suite.RouteS3} {
+ if !strings.HasPrefix(r, suitePrefix) {
+ t.Errorf("%s is not under %s", r, suitePrefix)
+ }
+ }
+}
diff --git a/internal/fichastest/suite_test.go b/internal/fichastest/suite_test.go
new file mode 100644
index 0000000..727e841
--- /dev/null
+++ b/internal/fichastest/suite_test.go
@@ -0,0 +1,241 @@
+package fichastest
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "testing"
+
+ "amadan.net/rastrillo/rastrillo/db"
+
+ fichas "amadan.net/oficina/fichas/internal/fichas"
+ "amadan.net/oficina/suite"
+ "amadan.net/oficina/suite/server"
+)
+
+// The suite routes through the real router (spec §6.5): mounted only when a
+// consumer is configured, behind the bearer check, and outside the app's
+// CSRF check at exactly /suite/.
+
+const suiteToken = "a-test-token-for-memoria"
+
+func suiteConsumers() string {
+ return `[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"` + server.TokenHash(suiteToken) + `"}]}]`
+}
+
+// suiteConfig is testConfig with FICHAS_SUITE_CONSUMERS, read through
+// LoadConfig as main reads it.
+func suiteConfig(t *testing.T, consumers string) fichas.Config {
+ t.Helper()
+ c, err := fichas.LoadConfig(func(k string) string {
+ switch k {
+ case "FICHAS_DEK":
+ return base64.StdEncoding.EncodeToString(testKey())
+ case "FICHAS_ORIGIN":
+ return testOrigin
+ case "FICHAS_INSTANCE_KEY":
+ return "test-instance-key"
+ case "FICHAS_OWNERS":
+ return TestOwner
+ case "FICHAS_ALLOW_LOGGED_MAIL":
+ return "1"
+ case "FICHAS_SUITE_CONSUMERS":
+ return consumers
+ }
+ return ""
+ })
+ if err != nil {
+ t.Fatalf("LoadConfig: %v", err)
+ }
+ return c
+}
+
+// suiteApp is fichas.App exactly as main builds it — not AppForTest,
+// so nothing here leans on the test identity.
+func suiteApp(t *testing.T, consumers string) http.Handler {
+ t.Helper()
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger)
+ if err != nil {
+ t.Fatalf("db.Open: %v", err)
+ }
+ t.Cleanup(func() { d.Close() })
+ mux, _, err := fichas.App(d, suiteConfig(t, consumers), logger)
+ if err != nil {
+ t.Fatalf("App: %v", err)
+ }
+ return mux
+}
+
+// call is a sibling's request: a bearer token when tok is set, and no
+// Origin, Referer or Sec-Fetch-Site — memoria sends none.
+func call(h http.Handler, method, target, tok string, body []byte) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(method, target, bytes.NewReader(body))
+ if tok != "" {
+ req.Header.Set("Authorization", "Bearer "+tok)
+ }
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ return rec
+}
+
+func s2Body(t *testing.T, asker string, pairs ...suite.ItemRevision) []byte {
+ t.Helper()
+ if pairs == nil {
+ pairs = []suite.ItemRevision{}
+ }
+ b, err := json.Marshal(suite.S2Request{Asker: suite.Subject{Kind: suite.SubjectAddress, Value: asker}, Pairs: pairs})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+// With a consumer configured, every suite route answers the same empty 401
+// to a request without its token, and serves one with it.
+//
+// MUTATION-TESTED 2026-11-01, reverted: server.Routes mounted in place of
+// server.Handler (no bearer check) → every "no token" and "a wrong token"
+// case.
+func TestSuiteRoutesNeedTheConsumerToken(t *testing.T) {
+ h := suiteApp(t, suiteConsumers())
+ for _, r := range []struct{ method, target string }{
+ {"GET", suite.RouteS1},
+ {"POST", suite.RouteS2},
+ {"GET", suite.RouteS3 + "/1?revision=1"},
+ } {
+ for name, tok := range map[string]string{"no token": "", "a wrong token": "not-the-token"} {
+ rec := call(h, r.method, r.target, tok, s2Body(t, TestOwner))
+ if rec.Code != http.StatusUnauthorized || rec.Body.Len() != 0 {
+ t.Errorf("%s %s, %s: %d %q, want an empty 401", r.method, r.target, name, rec.Code, rec.Body.String())
+ }
+ }
+ }
+ rec := call(h, "GET", suite.RouteS1, suiteToken, nil)
+ if _, err := suite.DecodeS1(rec.Code, rec.Body.Bytes()); err != nil {
+ t.Errorf("S1 with the token: %v (%d %s)", err, rec.Code, rec.Body.String())
+ }
+}
+
+// memoria's S2 is a POST with a bearer token and no Origin, Referer or
+// Sec-Fetch-Site. The app-wide CSRF check would refuse it; /suite/ is
+// outside that check.
+//
+// MUTATION-TESTED 2026-11-01, reverted: the suite handler mounted on the
+// chi router (r.Mount("/suite", h)) instead of the outer mux → 403 here.
+func TestSuiteS2NeedsNoOrigin(t *testing.T) {
+ h := suiteApp(t, suiteConsumers())
+ rec := call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, TestOwner, suite.ItemRevision{ItemID: "1", Revision: 1}))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("POST /suite/s2 with only a bearer: %d %s", rec.Code, rec.Body.String())
+ }
+ got := suite.DecodeS2([]suite.ItemRevision{{ItemID: "1", Revision: 1}}, rec.Code, rec.Body.Bytes())
+ if got[0] != suite.NOT_VISIBLE { // no card 1 yet
+ t.Errorf("S2 for a card that does not exist: %s", got[0])
+ }
+}
+
+// The exemption is exactly /suite/: every other state-changing request
+// without same-origin evidence is still refused, a bearer token makes no
+// difference to that, and a path that only looks like /suite/ is not
+// exempt.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: csrf.Protect replaced by a
+// wrapper skipping any request carrying an Authorization header → "POST
+// /cards with a bearer"; csrf.Protect skipped for any path starting with
+// the string "/suite" → "/suites/s2" and "/suite-s2".
+func TestOnlySuiteIsExemptFromTheCSRFCheck(t *testing.T) {
+ h := suiteApp(t, suiteConsumers())
+ for name, target := range map[string]string{
+ "POST /cards with a bearer": "/cards",
+ "/suites/s2": "/suites/s2",
+ "/suite-s2": "/suite-s2",
+ "a delete with a bearer": "/cards/1/delete",
+ "/suite/../cards, before cleaning": "/suite/../cards",
+ } {
+ rec := call(h, "POST", target, suiteToken, []byte("f_name=x"))
+ if rec.Code/100 == 2 || rec.Code == http.StatusUnauthorized {
+ t.Errorf("%s: %d — reached a handler without same-origin evidence", name, rec.Code)
+ }
+ if target != "/suite/../cards" && rec.Code != http.StatusForbidden {
+ t.Errorf("%s: %d, want the CSRF check's 403", name, rec.Code)
+ }
+ }
+}
+
+// No consumers, no routes (doctrine §3): /suite/ is an unknown path like
+// any other, token or not.
+//
+// MUTATION-TESTED 2026-11-01, reverted: the suite mounted with
+// server.Routes whenever Handler returned nil → "GET" serves a feed.
+func TestNoConsumersNoSuiteRoutes(t *testing.T) {
+ h := suiteApp(t, "")
+ unknown := call(h, "GET", "/no-such-path", "", nil)
+ for _, target := range []string{suite.RouteS1, suite.RouteS3 + "/1?revision=1"} {
+ rec := call(h, "GET", target, suiteToken, nil)
+ if rec.Code != unknown.Code || rec.Body.String() != unknown.Body.String() {
+ t.Errorf("GET %s: %d %q, want what an unknown path gets (%d %q)", target, rec.Code, rec.Body.String(), unknown.Code, unknown.Body.String())
+ }
+ }
+ if rec := call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, TestOwner)); rec.Code != http.StatusForbidden {
+ t.Errorf("POST %s: %d, want the CSRF check's 403 (no exemption without consumers)", suite.RouteS2, rec.Code)
+ }
+}
+
+// End to end through the whole app: a card made through the form appears
+// in the feed, its text is served at its revision, and its admitted owner
+// may see it. This is the wiring — the producer built over the app's own
+// database and its own admission predicate.
+func TestSuiteServesACardMadeThroughTheApp(t *testing.T) {
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { d.Close() })
+ h, err := fichas.AppForTest(d, suiteConfig(t, suiteConsumers()), logger, TestOwner)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rec := post(t, h, "/cards", url.Values{"f_name": {"Cnoc Teoranta"}, "f_email": {"orders@cnoc.example"}}); rec.Code != http.StatusSeeOther {
+ t.Fatalf("creating a card: %d", rec.Code)
+ }
+
+ rec := call(h, "GET", suite.RouteS1, suiteToken, nil)
+ feed, err := suite.DecodeS1(rec.Code, rec.Body.Bytes())
+ if err != nil || len(feed.Rows) != 1 || feed.Rows[0].Revision != 1 || feed.Rows[0].Gone {
+ t.Fatalf("S1: %+v, %v", feed, err)
+ }
+ item := feed.Rows[0].ItemID
+ // "<card id>.<created_at unix nanos>" (spec §6.2).
+ if !regexp.MustCompile(`^[1-9][0-9]*\.[1-9][0-9]*$`).MatchString(item) {
+ t.Errorf("item_id %q is not <card id>.<stamp>", item)
+ }
+
+ rec = call(h, "GET", suite.RouteS3+"/"+item+"?revision=1", suiteToken, nil)
+ if rec.Code != http.StatusOK || rec.Body.String() != "Cnoc Teoranta\nEmail: orders@cnoc.example" ||
+ !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/plain") {
+ t.Errorf("S3: %d %q %q", rec.Code, rec.Body.String(), rec.Header().Get("Content-Type"))
+ }
+
+ pairs := []suite.ItemRevision{{ItemID: item, Revision: 1}}
+ rec = call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, strings.ToUpper(TestOwner), pairs...))
+ if got := suite.DecodeS2(pairs, rec.Code, rec.Body.Bytes()); got[0] != suite.VISIBLE {
+ t.Errorf("S2 for the admitted owner (sent in upper case): %s", got[0])
+ }
+ rec = call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, "bo@example.com", pairs...))
+ if got := suite.DecodeS2(pairs, rec.Code, rec.Body.Bytes()); got[0] != suite.NOT_VISIBLE {
+ t.Errorf("S2 for an address not admitted: %s", got[0])
+ }
+}