oficina / docs Public

Docs: the Team rung, the revision counter and the suite feed log

Paul, 2026-11-01: "New docs Team, old private" (spec §8.2.1).
documents.visibility ('private' | 'team', CHECKed) defaults to private in
migration 0009, so every existing document stays private; CreateDraft
writes team. The sample library is created private. The rung is a third
clause of permissionScope for reading only: a roster Member in team mode,
an address on the configured allowlist in lone shape, never a guest. It
needs no person row, so a member who has never signed in reads it (S2
asks for them). Ownership and every write still need a person, and links
are still never consulted.

documents.revision bumps in the same writer transaction as every applied
update, rename, visibility change and deletion, and each bump (and each
creation) appends a suite_feed row; 0009 announces every live document
once. Deletion has no route yet, so Store.deleteDocument is the one way a
document becomes deleted and TestSoftDelete goes through it.

The share page gains "Your team": one scriptless form, direction in a
hidden field, owner- and member-only like granting (POST
/d/{sqid}/share/team). The list marks a team document someone else owns
"Shared with your team". Tests whose subject is a private document's
isolation now create it private (createPrivateDoc, TestCreatePrivate,
createDocument(..., VisibilityPrivate)); a new document on the team rung
is readable by every member in development, where everyone is one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 899842495c36ce205c6bad84ea75f5946128a7cb parent 47b88d5
26 files changed, +438 −55
  • internal/docs/app.go +3 −0
  • internal/docs/dashboard_test.go +3 −3
  • internal/docs/export_test.go +1 −1
  • internal/docs/handlers.go +5 −0
  • internal/docs/home_router_integration_test.go +3 −3
  • internal/docs/identity_test.go +3 −3
  • internal/docs/migrations/0009_suite.sql +43 −0
  • internal/docs/models.go +40 −0
  • internal/docs/native_test.go +5 −0
  • internal/docs/nowebfont_test.go +1 −1
  • internal/docs/render.go +15 −0
  • internal/docs/search_test.go +1 −1
  • internal/docs/seed.go +1 −1
  • internal/docs/share.go +65 −1
  • internal/docs/share_test.go +20 −3
  • internal/docs/shared_list_test.go +5 −5
  • internal/docs/store.go +41 −7
  • internal/docs/store_test.go +1 −2
  • internal/docs/stream_test.go +1 −1
  • internal/docs/suite_feed.go +96 −0
  • internal/docs/team_access.go +41 −12
  • internal/docs/team_identity_test.go +1 −1
  • internal/docs/team_router_test.go +3 −3
  • internal/docs/testing.go +22 −6
  • internal/docs/updates_test.go +1 −1
  • internal/docs/views/share.html +17 −0
diff --git a/internal/docs/app.go b/internal/docs/app.go
index 9b65167..afc0799 100644
--- a/internal/docs/app.go
+++ b/internal/docs/app.go
@@ -449,6 +449,8 @@ func New(cfg Config) (*App, error) {
// The sample library is for members. A guest admitted by a grant is
// visiting, not moving in.
store.seedOnlyMembers = list.configured
+ // The team rung's readers in lone shape: members, never guests.
+ store.members = list.configured
// Home: connect's Bridge, then the one-time move of Docs' own links
// into connect's table (home_links_move.go). connect.New has swept
// already, nothing else is running, and the team census below reads
@@ -753,6 +755,7 @@ func New(cfg Config) (*App, error) {
r.Post("/d/{sqid}/share", h.sharePost)
r.Post("/d/{sqid}/share/revoke", h.shareRevoke)
r.Post("/d/{sqid}/share/link", h.shareLink)
+ r.Post("/d/{sqid}/share/team", h.shareTeam)
r.Get("/d/{sqid}/updates", h.updatesGet)
r.Post("/d/{sqid}/updates", h.updatesPost)
diff --git a/internal/docs/dashboard_test.go b/internal/docs/dashboard_test.go
index b462f37..b1724c1 100644
--- a/internal/docs/dashboard_test.go
+++ b/internal/docs/dashboard_test.go
@@ -23,15 +23,15 @@ func TestDashboardUsesExistingAccountAndDocumentGrants(t *testing.T) {
if e != nil {
t.Fatal(e)
}
- own, e := s.Create(ctx, alice, "Own")
+ own, e := s.createDocument(ctx, alice, "Own", "", VisibilityPrivate)
if e != nil {
t.Fatal(e)
}
- shared, e := s.Create(ctx, bob, "Shared")
+ shared, e := s.createDocument(ctx, bob, "Shared", "", VisibilityPrivate)
if e != nil {
t.Fatal(e)
}
- if _, e = s.Create(ctx, bob, "Private"); e != nil {
+ if _, e = s.createDocument(ctx, bob, "Private", "", VisibilityPrivate); e != nil {
t.Fatal(e)
}
if e = s.Grant(ctx, bob, shared.Sqid, "alice@example.com", RoleWriter); e != nil {
diff --git a/internal/docs/export_test.go b/internal/docs/export_test.go
index 7cca92f..9c41273 100644
--- a/internal/docs/export_test.go
+++ b/internal/docs/export_test.go
@@ -20,7 +20,7 @@ func exportable(t *testing.T, app *App, address, title string) *Document {
t.Helper()
ctx := context.Background()
owner := app.TestPerson(t, address)
- doc, err := app.Store().Create(ctx, owner, title)
+ doc, err := app.Store().createDocument(ctx, owner, title, "", VisibilityPrivate)
if err != nil {
t.Fatalf("Create: %v", err)
}
diff --git a/internal/docs/handlers.go b/internal/docs/handlers.go
index 57c7b11..dae406a 100644
--- a/internal/docs/handlers.go
+++ b/internal/docs/handlers.go
@@ -1045,6 +1045,11 @@ func sharedNote(r *http.Request, d *Document, mine int64) string {
if d.OwnerID == mine {
return ""
}
+ // A team document reads as the team's, whether or not the reader also
+ // holds a grant on it: that is the wider of the two, and the true one.
+ if d.Visibility == VisibilityTeam {
+ return rastrillo.T(r, "docs.list.team")
+ }
return rastrillo.T(r, "docs.list.shared")
}
diff --git a/internal/docs/home_router_integration_test.go b/internal/docs/home_router_integration_test.go
index b737b96..278b4c1 100644
--- a/internal/docs/home_router_integration_test.go
+++ b/internal/docs/home_router_integration_test.go
@@ -218,15 +218,15 @@ func TestHomeRouterExistingAccountRoundTripPreservesOwnedAndSharedContent(t *tes
if err != nil {
t.Fatal(err)
}
- own, err := s.Create(ctx, alice, "Alice original")
+ own, err := s.createDocument(ctx, alice, "Alice original", "", VisibilityPrivate)
if err != nil {
t.Fatal(err)
}
- shared, err := s.Create(ctx, bob, "Bob shared")
+ shared, err := s.createDocument(ctx, bob, "Bob shared", "", VisibilityPrivate)
if err != nil {
t.Fatal(err)
}
- hidden, err := s.Create(ctx, bob, "Bob private")
+ hidden, err := s.createDocument(ctx, bob, "Bob private", "", VisibilityPrivate)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/docs/identity_test.go b/internal/docs/identity_test.go
index 19fc08a..41ffafe 100644
--- a/internal/docs/identity_test.go
+++ b/internal/docs/identity_test.go
@@ -87,15 +87,15 @@ func TestLinkedHomeIdentityPreservesOwnersAndAddressGrants(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- own, err := store.Create(ctx, alice, "Alice private")
+ own, err := store.createDocument(ctx, alice, "Alice private", "", VisibilityPrivate)
if err != nil {
t.Fatal(err)
}
- shared, err := store.Create(ctx, bob, "Bob shared")
+ shared, err := store.createDocument(ctx, bob, "Bob shared", "", VisibilityPrivate)
if err != nil {
t.Fatal(err)
}
- hidden, err := store.Create(ctx, bob, "Bob private")
+ hidden, err := store.createDocument(ctx, bob, "Bob private", "", VisibilityPrivate)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/docs/migrations/0009_suite.sql b/internal/docs/migrations/0009_suite.sql
new file mode 100644
index 0000000..0e3f8e0
--- /dev/null
+++ b/internal/docs/migrations/0009_suite.sql
@@ -0,0 +1,43 @@
+-- The team rung, and the revision counter and feed log the suite contract's
+-- producer half reads (spec §8.2.1 and §8.2.2; suite revision 10, commit
+-- 12848f8).
+--
+-- visibility: Paul's ruling, 2026-11-01, "New docs Team, old private". The
+-- column DEFAULT is 'private', and that default is the half of the ruling
+-- this migration carries: every document that exists when it runs stays
+-- private until its owner shares it. New documents are written 'team'
+-- explicitly by Store.CreateDraft; nothing relies on this default for them.
+-- The CHECK keeps the vocabulary closed, so a typo is a loud write failure
+-- rather than a third value every reader treats as private.
+ALTER TABLE documents ADD COLUMN visibility TEXT NOT NULL DEFAULT 'private'
+ CHECK (visibility IN ('private', 'team'));
+
+-- revision: one counter per document, bumped in the same writer transaction
+-- as every applied update, rename, visibility change and deletion. Not
+-- doc_updates.seq, which a rename never touches although a rename changes
+-- what S3 serves. Existing documents start at 1, which is also what a new
+-- document is created at.
+ALTER TABLE documents ADD COLUMN revision INTEGER NOT NULL DEFAULT 1
+ CHECK (revision >= 1);
+
+-- suite_feed: append-only, one row per bump (creation included), written in
+-- the bump's own transaction, so S1 can page by id and a consumer's cursor is
+-- a position in this table. No title, no content, no visibility: the four
+-- fields suite S1 carries and nothing else, so the table holds nothing the
+-- plaintext gate (spec §12) would have to look at.
+CREATE TABLE IF NOT EXISTS suite_feed (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ document_id INTEGER NOT NULL,
+ revision INTEGER NOT NULL,
+ gone INTEGER NOT NULL CHECK (gone IN (0, 1)),
+ touched_at DATETIME NOT NULL
+);
+
+-- Every live document that already exists is announced once, at revision 1,
+-- so a consumer's first poll sees the whole library rather than only what
+-- changes after this deploy. Live is the producer's definition: not deleted,
+-- and not one of 0002_owners.sql's orphans, which nobody can read.
+INSERT INTO suite_feed (document_id, revision, gone, touched_at)
+ SELECT id, revision, 0, updated_at FROM documents
+ WHERE deleted_at IS NULL AND owner_id > 0
+ ORDER BY updated_at, id;
diff --git a/internal/docs/models.go b/internal/docs/models.go
index 0522305..b3b336d 100644
--- a/internal/docs/models.go
+++ b/internal/docs/models.go
@@ -55,11 +55,51 @@ type Document struct {
GUID string `gorm:"column:guid;not null"`
ClientID uint64 `gorm:"column:client_id;not null"`
+ // Visibility is the document's rung beside grants and links:
+ // VisibilityPrivate or VisibilityTeam (spec §8.2.1). createDocument
+ // always writes it; the default tag only means a row built some other way
+ // (a test inserting a Document directly) is private, as 0009 makes every
+ // existing row, rather than an empty string the CHECK refuses.
+ Visibility Visibility `gorm:"column:visibility;not null;default:private"`
+ // Revision counts the changes a suite consumer must re-read: every
+ // applied update, rename, visibility change and deletion, bumped in the
+ // same transaction (bumpRevision, suite.go). Starts at 1.
+ Revision int64 `gorm:"column:revision;not null;default:1"`
+
CreatedAt time.Time `gorm:"column:created_at;not null"`
UpdatedAt time.Time `gorm:"column:updated_at;not null"`
DeletedAt *time.Time `gorm:"column:deleted_at"`
}
+// Visibility is the team rung's switch (spec §8.2.1, Paul 2026-11-01: "New
+// docs Team, old private"). A link is not a rung and a grant is its own
+// table; this says only whether every admitted member may read it.
+type Visibility string
+
+const (
+ // VisibilityPrivate: the owner and the people it is granted to.
+ VisibilityPrivate Visibility = "private"
+ // VisibilityTeam: also every admitted member, for reading only.
+ VisibilityTeam Visibility = "team"
+)
+
+func (v Visibility) valid() bool { return v == VisibilityPrivate || v == VisibilityTeam }
+
+// SuiteFeedRow is one row of the append-only log suite S1 pages through
+// (0009_suite.sql): which document, at which revision, whether that bump
+// deleted it, and when. Written only by bumpRevision and CreateDraft, inside
+// the transaction that made the change.
+type SuiteFeedRow struct {
+ ID int64 `gorm:"column:id;primaryKey"`
+ DocumentID int64 `gorm:"column:document_id;not null"`
+ Revision int64 `gorm:"column:revision;not null"`
+ Gone bool `gorm:"column:gone;not null"`
+ TouchedAt time.Time `gorm:"column:touched_at;not null"`
+}
+
+// TableName pins the table rather than leaving it to GORM's pluralising.
+func (SuiteFeedRow) TableName() string { return "suite_feed" }
+
// Person is this app's own record of someone who has signed in —
// deliberately separate from rastrillo/auth's session Subject, which
// under the magic-link plugin is the verified email address itself,
diff --git a/internal/docs/native_test.go b/internal/docs/native_test.go
index d0cbf19..9e6b271 100644
--- a/internal/docs/native_test.go
+++ b/internal/docs/native_test.go
@@ -90,6 +90,11 @@ func TestNativeMetadataPreservesPermissions(t *testing.T) {
t.Fatalf("missing native identity: %s", created.Body.String())
}
path := "/d/" + document.Sqid
+ // New documents are on the team rung (spec §8.2.1); this test is about
+ // what a grant carries, so the document goes private first.
+ if got := nativeRequest(app, alice, "POST", path+"/share/team", "visibility=private"); got.Code != 200 {
+ t.Fatalf("make private: %d", got.Code)
+ }
if got := nativeRequest(app, bob, "GET", path, ""); got.Code != 404 {
t.Fatalf("foreign document: %d", got.Code)
}
diff --git a/internal/docs/nowebfont_test.go b/internal/docs/nowebfont_test.go
index 44ba79d..a7cac4d 100644
--- a/internal/docs/nowebfont_test.go
+++ b/internal/docs/nowebfont_test.go
@@ -69,7 +69,7 @@ func TestNoPageLinksOrPreloadsAChromeWebfont(t *testing.T) {
t.Fatal(err)
}
alice := signInCookies(t, app, "alice@example.com")
- sqid := createDoc(t, app, alice, "Minutes")
+ sqid := createPrivateDoc(t, app, alice, "Minutes")
public := linkFor(t, app, alice, sqid)
// Someone it is not shared with meets the error page, not a 404 line.
bob := signInCookies(t, app, "bob@example.com")
diff --git a/internal/docs/render.go b/internal/docs/render.go
index bf04b19..087d3e8 100644
--- a/internal/docs/render.go
+++ b/internal/docs/render.go
@@ -80,6 +80,18 @@ var Catalog = rastrillo.Catalog{
"docs.share.back": "Back to the document",
"docs.share.empty": "Only you can open this document.",
"docs.share.error.address": "Type the email address of the person you want to share with.",
+ // docs.share.empty.team replaces docs.share.empty on a team document,
+ // where "Only you can open this document" would be false.
+ "docs.share.empty.team": "Nobody has been added by name.",
+ // docs.share.team.* is the team rung (spec §8.2.1, Paul 2026-11-01:
+ // "New docs Team, old private"). The body says which side the switch is
+ // on in words, so the state never rests on a button's label alone, and
+ // says that the team reads and does not edit.
+ "docs.share.team.heading": "Your team",
+ "docs.share.team.body.team": "Everyone on your team can read this document. Only you and the people you add above can change it.",
+ "docs.share.team.body.private": "Only you and the people you add above can open this document.",
+ "docs.share.team.make_private": "Make private",
+ "docs.share.team.make_team": "Share with your team",
// docs.share.public.* is the third rung — a read-only link anyone
// can follow, signed in or not (suite doctrine ruling 15).
@@ -350,6 +362,9 @@ var Catalog = rastrillo.Catalog{
// day sharing landed, and a row that looks like yours and is not is
// how a person opens a document expecting to be able to edit it.
"docs.list.shared": "Shared with you",
+ // docs.list.team marks a row somebody else owns that the reader reaches
+ // through the team rung rather than a grant of their own.
+ "docs.list.team": "Shared with your team",
"docs.signout.label": "Sign out",
diff --git a/internal/docs/search_test.go b/internal/docs/search_test.go
index 8eca7f2..5983db2 100644
--- a/internal/docs/search_test.go
+++ b/internal/docs/search_test.go
@@ -16,7 +16,7 @@ func seedTitles(t *testing.T, app *App, address string, titles ...string) int64
ctx := context.Background()
owner := app.TestPerson(t, address)
for _, title := range titles {
- if _, err := app.Store().Create(ctx, owner, title); err != nil {
+ if _, err := app.Store().createDocument(ctx, owner, title, "", VisibilityPrivate); err != nil {
t.Fatalf("Create(%q): %v", title, err)
}
}
diff --git a/internal/docs/seed.go b/internal/docs/seed.go
index fb59e89..dde7dc0 100644
--- a/internal/docs/seed.go
+++ b/internal/docs/seed.go
@@ -86,7 +86,7 @@ func Seed(ctx context.Context, store *Store, actor Actor) error {
base := time.Now().UTC()
for _, sd := range seedDocs {
- doc, err := store.Create(ctx, owner, sd.Title)
+ doc, err := store.createDocument(ctx, owner, sd.Title, "", VisibilityPrivate)
if err != nil {
return fmt.Errorf("docs: seed: create %q: %w", sd.Title, err)
}
diff --git a/internal/docs/share.go b/internal/docs/share.go
index 70201a2..46ef893 100644
--- a/internal/docs/share.go
+++ b/internal/docs/share.go
@@ -5,6 +5,7 @@ import (
"net/http"
"amadan.net/rastrillo/rastrillo"
+ "gorm.io/gorm"
)
// sharePage is the share screen's view data, resolved in the handler rather
@@ -59,6 +60,14 @@ type sharePage struct {
CopyButton string
CopiedLabel string
ShareScript string
+
+ // The team rung (spec §8.2.1). Team is the switch's state, and TeamBody
+ // says it in words; the one form posts the other direction.
+ Team bool
+ TeamHeading string
+ TeamBody string
+ TeamButton string
+ TeamDestination Visibility
}
// roleChoice is one option card: rastrillo's choice-field reads Value,
@@ -138,7 +147,7 @@ func (h *handlers) renderShare(w http.ResponseWriter, r *http.Request, doc *Docu
for _, g := range grants {
rows = append(rows, grant{g.Subject, g.Role})
}
- nativeJSON(w, r, status, map[string]any{"sqid": doc.Sqid, "title": doc.Title, "grants": rows, "published": published, "public_url": publicURL, "error": errKey})
+ nativeJSON(w, r, status, map[string]any{"sqid": doc.Sqid, "title": doc.Title, "grants": rows, "published": published, "public_url": publicURL, "visibility": doc.Visibility, "error": errKey})
return
}
rows := make([]shareRow, 0, len(grants))
@@ -186,6 +195,18 @@ func (h *handlers) renderShare(w http.ResponseWriter, r *http.Request, doc *Docu
CopiedLabel: rastrillo.T(r, "docs.share.public.copied"),
ShareScript: shareScriptPath(),
}
+ page.Team = doc.Visibility == VisibilityTeam
+ page.TeamHeading = rastrillo.T(r, "docs.share.team.heading")
+ if page.Team {
+ page.EmptyBody = rastrillo.T(r, "docs.share.empty.team")
+ page.TeamBody = rastrillo.T(r, "docs.share.team.body.team")
+ page.TeamButton = rastrillo.T(r, "docs.share.team.make_private")
+ page.TeamDestination = VisibilityPrivate
+ } else {
+ page.TeamBody = rastrillo.T(r, "docs.share.team.body.private")
+ page.TeamButton = rastrillo.T(r, "docs.share.team.make_team")
+ page.TeamDestination = VisibilityTeam
+ }
if errKey != "" {
page.Error = rastrillo.T(r, errKey)
}
@@ -301,3 +322,46 @@ func (h *handlers) ownerLookupFailure(w http.ResponseWriter, r *http.Request, er
}
h.fail(w, r, http.StatusNotFound, failDocument)
}
+
+// shareTeam serves POST /d/{sqid}/share/team: move a document between the
+// private and team rungs (spec §8.2.1). Owner- and member-only, exactly as
+// granting is, and answering 404 to anybody else. Scriptless: the direction
+// rides a hidden field, so a page left open cannot flip the switch the
+// wrong way from a stale label, and a 303 comes back here.
+func (h *handlers) shareTeam(w http.ResponseWriter, r *http.Request) {
+ if !h.requireMemberRequest(w, r, true) {
+ return
+ }
+ owner, err := h.owner(r)
+ if err != nil {
+ h.logger.Error("docs: resolve owner for visibility", "err", err)
+ h.fail(w, r, h.internalFailureStatus(), failStatus)
+ return
+ }
+ sqid := r.PathValue("sqid")
+ err = h.store.SetVisibility(r.Context(), owner, sqid, Visibility(r.PostFormValue("visibility")))
+ switch {
+ case err == nil:
+ if wantsNative(r) {
+ nativeJSON(w, r, 200, map[string]bool{"ok": true})
+ return
+ }
+ http.Redirect(w, r, "/d/"+sqid+"/share", http.StatusSeeOther)
+ case errors.Is(err, errUnknownVisibility):
+ h.fail(w, r, http.StatusBadRequest, failStatus)
+ default:
+ h.ownerLookupFailureOrStatus(w, r, err)
+ }
+}
+
+// ownerLookupFailureOrStatus is ownerLookupFailure for an error that may also
+// be a storage failure: not-found and team-unavailable answer as a lookup
+// does, and anything else is logged and is the internal failure status.
+func (h *handlers) ownerLookupFailureOrStatus(w http.ResponseWriter, r *http.Request, err error) {
+ if errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, errTeamUnavailable) {
+ h.ownerLookupFailure(w, r, err)
+ return
+ }
+ h.logger.Error("docs: set visibility", "sqid", r.PathValue("sqid"), "err", err)
+ h.fail(w, r, h.internalFailureStatus(), failStatus)
+}
diff --git a/internal/docs/share_test.go b/internal/docs/share_test.go
index b861990..2a8375f 100644
--- a/internal/docs/share_test.go
+++ b/internal/docs/share_test.go
@@ -48,12 +48,29 @@ func createDoc(t *testing.T, app *docs.App, cookies []*http.Cookie, title string
return strings.TrimPrefix(rec.Header().Get("Location"), "/d/")
}
+// createPrivateDoc makes a document and moves it off the team rung, for the
+// tests whose subject is who reaches a PRIVATE document — grants, revokes,
+// 404s for strangers. A new document is on the team rung (spec §8.2.1, Paul
+// 2026-11-01: "New docs Team, old private"), and in NewForTest's development
+// mode every signed-in address is a member, so createDoc alone would hand
+// every one of them the document by team standing and those tests would be
+// testing the rung instead of the grant. Moved through the share page's own
+// form, so it is the path an owner takes.
+func createPrivateDoc(t *testing.T, app *docs.App, cookies []*http.Cookie, title string) string {
+ t.Helper()
+ sqid := createDoc(t, app, cookies, title)
+ if rec := post(t, app, cookies, "/d/"+sqid+"/share/team", "visibility=private"); rec.Code != http.StatusSeeOther {
+ t.Fatalf("POST /d/%s/share/team: status %d, want 303", sqid, rec.Code)
+ }
+ return sqid
+}
+
// The whole point of the feature, end to end and scriptless: Alice shares a
// document with Bob by typing his address into a form, and Bob can read it.
func TestShareThenTheGranteeCanRead(t *testing.T) {
app, _ := docs.NewForTest(t)
alice := signInCookies(t, app, "alice@example.com")
- sqid := createDoc(t, app, alice, "Minutes")
+ sqid := createPrivateDoc(t, app, alice, "Minutes")
// Bob cannot see it yet.
bob := signInCookies(t, app, "bob@example.com")
@@ -99,7 +116,7 @@ func TestSharePageListsGrantees(t *testing.T) {
func TestOnlyTheOwnerReachesTheSharePage(t *testing.T) {
app, _ := docs.NewForTest(t)
alice := signInCookies(t, app, "alice@example.com")
- sqid := createDoc(t, app, alice, "Minutes")
+ sqid := createPrivateDoc(t, app, alice, "Minutes")
if rec := post(t, app, alice, "/d/"+sqid+"/share", "address=bob@example.com&role=writer"); rec.Code != http.StatusSeeOther {
t.Fatalf("POST share: status %d", rec.Code)
@@ -124,7 +141,7 @@ func TestOnlyTheOwnerReachesTheSharePage(t *testing.T) {
func TestRevokeRemovesAccess(t *testing.T) {
app, _ := docs.NewForTest(t)
alice := signInCookies(t, app, "alice@example.com")
- sqid := createDoc(t, app, alice, "Minutes")
+ sqid := createPrivateDoc(t, app, alice, "Minutes")
bob := signInCookies(t, app, "bob@example.com")
if rec := post(t, app, alice, "/d/"+sqid+"/share", "address=bob@example.com&role=reader"); rec.Code != http.StatusSeeOther {
diff --git a/internal/docs/shared_list_test.go b/internal/docs/shared_list_test.go
index 7ad59c4..532e48a 100644
--- a/internal/docs/shared_list_test.go
+++ b/internal/docs/shared_list_test.go
@@ -18,7 +18,7 @@ import (
func TestASharedDocumentAppearsInTheGranteesList(t *testing.T) {
app, _ := docs.NewForTest(t)
alice := signInCookies(t, app, "alice@example.com")
- sqid := createDoc(t, app, alice, "Minutes")
+ sqid := createPrivateDoc(t, app, alice, "Minutes")
// Before the grant, Bob's list does not mention it. Without this the
// test would pass on a list that shows everybody everything.
@@ -60,9 +60,9 @@ func TestASharedDocumentAppearsInTheGranteesList(t *testing.T) {
func TestASharedRowSaysSo(t *testing.T) {
app, _ := docs.NewForTest(t)
alice := signInCookies(t, app, "alice@example.com")
- sqid := createDoc(t, app, alice, "Alices")
+ sqid := createPrivateDoc(t, app, alice, "Alices")
bob := signInCookies(t, app, "bob@example.com")
- createDoc(t, app, bob, "Bobs")
+ createPrivateDoc(t, app, bob, "Bobs")
post(t, app, alice, "/d/"+sqid+"/share", "address=bob@example.com&role=reader")
// The catalog KEY, not the English. NewForTest's app never wires
@@ -96,7 +96,7 @@ func TestASharedRowSaysSo(t *testing.T) {
func TestRevokingRemovesItFromTheGranteesList(t *testing.T) {
app, _ := docs.NewForTest(t)
alice := signInCookies(t, app, "alice@example.com")
- sqid := createDoc(t, app, alice, "Minutes")
+ sqid := createPrivateDoc(t, app, alice, "Minutes")
bob := signInCookies(t, app, "bob@example.com")
post(t, app, alice, "/d/"+sqid+"/share", "address=bob@example.com&role=reader")
@@ -119,7 +119,7 @@ func TestRevokingRemovesItFromTheGranteesList(t *testing.T) {
func TestAGranteeCanSearchForASharedDocument(t *testing.T) {
app, _ := docs.NewForTest(t)
alice := signInCookies(t, app, "alice@example.com")
- sqid := createDoc(t, app, alice, "Quarterly plan")
+ sqid := createPrivateDoc(t, app, alice, "Quarterly plan")
bob := signInCookies(t, app, "bob@example.com")
post(t, app, alice, "/d/"+sqid+"/share", "address=bob@example.com&role=reader")
diff --git a/internal/docs/store.go b/internal/docs/store.go
index 320b6c7..8d9c6e3 100644
--- a/internal/docs/store.go
+++ b/internal/docs/store.go
@@ -45,6 +45,12 @@ type Store struct {
// an allowlist gets, and matches sampleDocuments' own default shape.
seedOnlyMembers func(address string) bool
+ // members answers "is this address a member of this instance" in lone
+ // shape — allowlist.configured, the same predicate seedOnlyMembers and
+ // handlers.isMember hold — for the team rung (permissionScope). nil
+ // means nobody reads the team rung in lone shape: it fails closed.
+ members func(address string) bool
+
// logger is where a sample-seeding failure goes — see
// seedIfEnabled's own doc comment for why that failure is logged
// and swallowed here rather than ever returned to EnsurePerson's
@@ -284,7 +290,22 @@ func (s *Store) Create(ctx context.Context, owner int64, title string) (*Documen
// CreateDraft makes retries after a lost acknowledgement return the same document.
// The token is scoped to the authenticated owner, never a document capability.
+//
+// A new document is on the team rung (spec §8.2.1, Paul 2026-11-01: "New docs
+// Team, old private"); its owner makes it private from the share page.
func (s *Store) CreateDraft(ctx context.Context, owner int64, title, token string) (*Document, error) {
+ return s.createDocument(ctx, owner, title, token, VisibilityTeam)
+}
+
+// createDocument is CreateDraft with the rung chosen by the caller: team for
+// every document a person makes, private for the sample library (seed.go),
+// which is one person's welcome content and would otherwise sit in every
+// member's list. Creation writes revision 1 and its suite_feed row in the
+// same transaction as the document.
+func (s *Store) createDocument(ctx context.Context, owner int64, title, token string, visibility Visibility) (*Document, error) {
+ if !visibility.valid() {
+ return nil, fmt.Errorf("docs: create document: unknown visibility %q", visibility)
+ }
actor := s.ownerActor(ctx, owner)
if err := s.requireMember(ctx, actor); err != nil {
return nil, err
@@ -303,13 +324,15 @@ func (s *Store) CreateDraft(ctx context.Context, owner int64, title, token strin
return nil, err
}
doc := &Document{
- Sqid: sqid,
- Title: title,
- OwnerID: owner,
- GUID: guid,
- ClientID: clientID,
- CreatedAt: now,
- UpdatedAt: now,
+ Sqid: sqid,
+ Title: title,
+ OwnerID: owner,
+ GUID: guid,
+ ClientID: clientID,
+ Visibility: visibility,
+ Revision: 1,
+ CreatedAt: now,
+ UpdatedAt: now,
}
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := s.requireMember(ctx, actor); err != nil {
@@ -333,6 +356,9 @@ func (s *Store) CreateDraft(ctx context.Context, owner int64, title, token strin
if err := tx.Create(doc).Error; err != nil {
return err
}
+ if err := announce(tx, doc.ID, doc.Revision, false, now); err != nil {
+ return err
+ }
return s.requireMember(ctx, actor)
})
if err == nil {
@@ -926,6 +952,10 @@ func (s *Store) ApplyUpdate(ctx context.Context, doc *Document, actor Actor, upd
if err := s.permissionScope(ctx, tx, actor, permissionWrite).Model(&Document{}).Where("documents.id = ?", doc.ID).Update("updated_at", time.Now().UTC()).Error; err != nil {
return s.permissionError(ctx, actor, err)
}
+ // The content changed, so a suite consumer must read it again.
+ if err := bumpRevision(tx, doc.ID, false); err != nil {
+ return err
+ }
assignedSeq = row.Seq
return s.checkPermission(ctx, tx, actor, doc.ID, permissionWrite)
}); err != nil {
@@ -947,6 +977,10 @@ func (s *Store) Rename(ctx context.Context, actor Actor, doc *Document, title st
if err := s.permissionScope(ctx, tx.Model(&Document{}), actor, permissionWrite).Where("documents.id = ? AND documents.deleted_at IS NULL", doc.ID).Updates(map[string]any{"title": title, "updated_at": time.Now().UTC()}).Error; err != nil {
return err
}
+ // The title is the first line of what S3 serves.
+ if err := bumpRevision(tx, doc.ID, false); err != nil {
+ return err
+ }
return s.checkPermission(ctx, tx, actor, doc.ID, permissionWrite)
})
}
diff --git a/internal/docs/store_test.go b/internal/docs/store_test.go
index 679c789..b32d74b 100644
--- a/internal/docs/store_test.go
+++ b/internal/docs/store_test.go
@@ -179,9 +179,8 @@ func TestADocumentYouDoNotOwnIsNotThere(t *testing.T) {
// stranger cannot learn a sqid exists by probing it.
func TestUnownedDocumentOverHTTPIs404Not403(t *testing.T) {
app, _ := docs.NewForTest(t)
- ctx := context.Background()
alice := app.TestPerson(t, "alice@example.com")
- doc, _ := app.Store().Create(ctx, alice, "Alice's private notes")
+ doc := app.TestCreatePrivate(t, alice, "Alice's private notes")
req := app.TestRequest(t, "bob@example.com", http.MethodGet, "/d/"+doc.Sqid, nil)
rec := httptest.NewRecorder()
diff --git a/internal/docs/stream_test.go b/internal/docs/stream_test.go
index 8943972..2b35469 100644
--- a/internal/docs/stream_test.go
+++ b/internal/docs/stream_test.go
@@ -111,7 +111,7 @@ func TestStreamIsOwnerScoped(t *testing.T) {
ctx := context.Background()
owner := app.TestPerson(t, "owner@example.com")
app.TestPerson(t, "stranger@example.com")
- doc, err := app.Store().Create(ctx, owner, "Private")
+ doc, err := app.Store().createDocument(ctx, owner, "Private", "", VisibilityPrivate)
if err != nil {
t.Fatalf("Create: %v", err)
}
diff --git a/internal/docs/suite_feed.go b/internal/docs/suite_feed.go
new file mode 100644
index 0000000..04aa5df
--- /dev/null
+++ b/internal/docs/suite_feed.go
@@ -0,0 +1,96 @@
+package docs
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "gorm.io/gorm"
+)
+
+// errUnknownVisibility is a visibility form posting something other than
+// the two rungs this column holds.
+var errUnknownVisibility = errors.New("docs: unknown visibility")
+
+// announce appends one row to suite_feed. Called only inside the transaction
+// that made the change it records, so the log and the documents table can
+// never disagree about a committed revision (spec §8.2.2).
+func announce(tx *gorm.DB, docID, revision int64, gone bool, at time.Time) error {
+ row := &SuiteFeedRow{DocumentID: docID, Revision: revision, Gone: gone, TouchedAt: at}
+ if err := tx.Create(row).Error; err != nil {
+ return fmt.Errorf("docs: announce document %d: %w", docID, err)
+ }
+ return nil
+}
+
+// bumpRevision moves a document to its next revision and announces it, in
+// the caller's transaction. Every change a suite consumer must re-read goes
+// through here: an applied update, a rename, a visibility change and a
+// deletion (gone). A row that is not there is an error rather than a silent
+// no-op, because a bump that touched nothing would announce a revision no
+// document has.
+func bumpRevision(tx *gorm.DB, docID int64, gone bool) error {
+ // UpdateColumn, not Update: GORM's Update also stamps updated_at, and a
+ // bump is not an edit — the list's recency must not move on a rename of
+ // the rung or a deletion's bookkeeping.
+ res := tx.Model(&Document{}).Where("id = ?", docID).UpdateColumn("revision", gorm.Expr("revision + 1"))
+ if res.Error != nil {
+ return fmt.Errorf("docs: bump revision of document %d: %w", docID, res.Error)
+ }
+ if res.RowsAffected != 1 {
+ return fmt.Errorf("docs: bump revision of document %d: %d rows", docID, res.RowsAffected)
+ }
+ var revision int64
+ if err := tx.Model(&Document{}).Where("id = ?", docID).Select("revision").Scan(&revision).Error; err != nil {
+ return fmt.Errorf("docs: read revision of document %d: %w", docID, err)
+ }
+ return announce(tx, docID, revision, gone, time.Now().UTC())
+}
+
+// SetVisibility moves a document between the private and team rungs (spec
+// §8.2.1). The owner's alone, through the owner-scoped Get and ownerMutation,
+// exactly as granting is: a writer may edit a document and still may not
+// decide who else reads it. Setting the rung it is already on changes
+// nothing and announces nothing.
+func (s *Store) SetVisibility(ctx context.Context, owner int64, sqid string, v Visibility) error {
+ if !v.valid() {
+ return errUnknownVisibility
+ }
+ doc, err := s.Get(ctx, owner, sqid)
+ if err != nil {
+ return err
+ }
+ return s.ownerMutation(ctx, owner, doc.ID, func(tx *gorm.DB) error {
+ res := tx.Model(&Document{}).
+ Where("id = ? AND deleted_at IS NULL AND visibility <> ?", doc.ID, v).
+ UpdateColumn("visibility", v)
+ if res.Error != nil {
+ return res.Error
+ }
+ if res.RowsAffected == 0 {
+ return nil
+ }
+ return bumpRevision(tx, doc.ID, false)
+ })
+}
+
+// deleteDocument soft-deletes a document and announces it gone, in one
+// transaction. There is no delete route yet; this is the one way a
+// document becomes deleted (TestSoftDelete reaches it), so the delete verb
+// that arrives later inherits the feed row rather than forgetting it. A
+// document already deleted is left alone and announced nothing.
+func (s *Store) deleteDocument(ctx context.Context, docID int64) error {
+ return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ res := tx.Model(&Document{}).
+ Where("id = ? AND deleted_at IS NULL", docID).
+ Update("deleted_at", time.Now().UTC())
+ if res.Error != nil {
+ return res.Error
+ }
+ if res.RowsAffected == 0 {
+ return nil
+ }
+ return bumpRevision(tx, docID, true)
+ })
+}
diff --git a/internal/docs/team_access.go b/internal/docs/team_access.go
index d1cf512..d5ef804 100644
--- a/internal/docs/team_access.go
+++ b/internal/docs/team_access.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"net/http"
+ "strings"
"amadan.net/oficina/home/roster"
"amadan.net/oficina/home/teammode"
@@ -80,18 +81,32 @@ func (t *teamRuntime) admission(next http.Handler) http.Handler {
// permissionScope is also usable under the SQLite writer. It never refreshes
// the roster, and checks a lease without waiting for a cache publisher.
+//
+// It is the one read predicate (spec §8.2.1, §8.2.2): ownership, an
+// individual grant, and for reading only the team rung. A link is never one
+// of its clauses — links are a separate table this never reads — so a
+// link-shared document reaches nobody here by being link-shared.
+//
+// The team rung is read by an admitted member: in team mode a roster Member
+// under the request's own lease (the same standing ownership needs), and in
+// lone shape an address on the configured allowlist (Store.members). A guest
+// admitted only by a grant is not a member. The rung needs no person row:
+// S2 asks for members who have never opened Docs, and their first sign-in
+// would show them the team's documents, so the answer is the same now.
+// Ownership and every write still need a person.
func (s *Store) permissionScope(ctx context.Context, g *gorm.DB, actor Actor, p permission) *gorm.DB {
- owner := s.team == nil
+ member := s.team == nil
if s.team != nil {
a, ok := s.access(ctx, actor)
if !ok {
return g.Where("1 = 0")
}
- owner = a.state() == roster.Member
+ member = a.state() == roster.Member
}
- if actor.PersonID <= 0 {
+ if actor.PersonID <= 0 && p != permissionRead {
return g.Where("1 = 0")
}
+ owner := member && actor.PersonID > 0
if p == permissionOwner {
if !owner {
return g.Where("1 = 0")
@@ -99,28 +114,42 @@ func (s *Store) permissionScope(ctx context.Context, g *gorm.DB, actor Actor, p
return owned(g, actor.PersonID)
}
grant := actor.VerifiedAddress != nil && *actor.VerifiedAddress != ""
- if !owner && !grant {
+ team := p == permissionRead && s.teamReader(actor, member)
+ if !owner && !grant && !team {
return g.Where("1 = 0")
}
- clause := "documents.owner_id > 0 AND ("
+ var clauses []string
args := []any{}
if owner {
- clause += "documents.owner_id = ?"
+ clauses = append(clauses, "documents.owner_id = ?")
args = append(args, actor.PersonID)
}
if grant {
- if owner {
- clause += " OR "
- }
- clause += "EXISTS (SELECT 1 FROM grants WHERE grants.doc_id = documents.id AND grants.subject = ?"
+ clause := "EXISTS (SELECT 1 FROM grants WHERE grants.doc_id = documents.id AND grants.subject = ?"
args = append(args, subjectOf(*actor.VerifiedAddress))
if p == permissionWrite {
clause += " AND grants.role = ?"
args = append(args, RoleWriter)
}
- clause += ")"
+ clauses = append(clauses, clause+")")
+ }
+ if team {
+ clauses = append(clauses, "documents.visibility = ?")
+ args = append(args, VisibilityTeam)
+ }
+ return g.Where("documents.owner_id > 0 AND ("+strings.Join(clauses, " OR ")+")", args...)
+}
+
+// teamReader is whether actor reads the team rung: member is the team-mode
+// standing permissionScope already read (a Member under a current lease);
+// in lone shape it is an address on the configured allowlist. A Store with
+// no members predicate (one built without an allowlist) has no team readers
+// in lone shape: the rung fails closed.
+func (s *Store) teamReader(actor Actor, member bool) bool {
+ if s.team != nil {
+ return member
}
- return g.Where(clause+")", args...)
+ return actor.VerifiedAddress != nil && *actor.VerifiedAddress != "" && s.members != nil && s.members(*actor.VerifiedAddress)
}
func (s *Store) permissionError(ctx context.Context, actor Actor, err error) error {
if s.team == nil || err == nil {
diff --git a/internal/docs/team_identity_test.go b/internal/docs/team_identity_test.go
index 89b6321..32e5647 100644
--- a/internal/docs/team_identity_test.go
+++ b/internal/docs/team_identity_test.go
@@ -79,7 +79,7 @@ func TestTeamIdentityAddressAbsenceNeverRedeemsEmptyGrant(t *testing.T) {
if e != nil {
t.Fatal(e)
}
- doc, e := s.Create(ctx, local, "private")
+ doc, e := s.createDocument(ctx, local, "private", "", VisibilityPrivate)
if e != nil {
t.Fatal(e)
}
diff --git a/internal/docs/team_router_test.go b/internal/docs/team_router_test.go
index d87278f..4157677 100644
--- a/internal/docs/team_router_test.go
+++ b/internal/docs/team_router_test.go
@@ -100,15 +100,15 @@ func newTeamRouterFixtureWithDashboard(t *testing.T, dashboard bool) *teamRouter
if e != nil {
t.Fatal(e)
}
- f.own, e = app.store.Create(ctx, f.alice, "Alice original")
+ f.own, e = app.store.createDocument(ctx, f.alice, "Alice original", "", VisibilityPrivate)
if e != nil {
t.Fatal(e)
}
- f.shared, e = app.store.Create(ctx, f.bob, "Bob shared")
+ f.shared, e = app.store.createDocument(ctx, f.bob, "Bob shared", "", VisibilityPrivate)
if e != nil {
t.Fatal(e)
}
- f.hidden, e = app.store.Create(ctx, f.bob, "Bob private")
+ f.hidden, e = app.store.createDocument(ctx, f.bob, "Bob private", "", VisibilityPrivate)
if e != nil {
t.Fatal(e)
}
diff --git a/internal/docs/testing.go b/internal/docs/testing.go
index 29a22a7..2437157 100644
--- a/internal/docs/testing.go
+++ b/internal/docs/testing.go
@@ -13,7 +13,6 @@ import (
"path/filepath"
"strings"
"testing"
- "time"
)
// NewForTest builds an App against a temporary SQLite database. It is
@@ -325,17 +324,34 @@ func TestEditorScriptPath() string { return editorScriptPath() }
// TestSoftDelete marks a document deleted the way a delete verb would, for
// tests that need a live link pointing at a document that is no longer
// there. There is no delete route yet; this is the state the schema
-// already models (documents.deleted_at) and that ByToken filters on.
+// already models (documents.deleted_at) and that ByToken filters on. It
+// goes through Store.deleteDocument, so the suite feed announces it gone
+// exactly as a real deletion will.
func (a *App) TestSoftDelete(t *testing.T, sqid string) {
t.Helper()
- err := a.store.db.Model(&Document{}).
- Where("sqid = ?", sqid).
- Update("deleted_at", time.Now().UTC()).Error
- if err != nil {
+ var doc Document
+ if err := a.store.db.Where("sqid = ?", sqid).First(&doc).Error; err != nil {
+ t.Fatalf("docs: TestSoftDelete(%q): %v", sqid, err)
+ }
+ if err := a.store.deleteDocument(context.Background(), doc.ID); err != nil {
t.Fatalf("docs: TestSoftDelete(%q): %v", sqid, err)
}
}
+// TestCreatePrivate makes a document on the private rung, for a test outside
+// the package whose subject is who reaches a private document. Store.Create
+// puts a new document on the team rung (spec §8.2.1), and in development every
+// signed-in address is a member, so a test of grants or of a stranger's 404
+// needs the private rung said out loud.
+func (a *App) TestCreatePrivate(t *testing.T, owner int64, title string) *Document {
+ t.Helper()
+ doc, err := a.store.createDocument(context.Background(), owner, title, "", VisibilityPrivate)
+ if err != nil {
+ t.Fatalf("docs: TestCreatePrivate(%q): %v", title, err)
+ }
+ return doc
+}
+
// TestWrite applies one update to a document as the signed-in owner,
// through the same store path a real edit takes, so a test can publish a
// document that actually has text in it.
diff --git a/internal/docs/updates_test.go b/internal/docs/updates_test.go
index 13b3b38..cd3024b 100644
--- a/internal/docs/updates_test.go
+++ b/internal/docs/updates_test.go
@@ -58,7 +58,7 @@ func TestUpdatesEndpointsAreOwnerScoped(t *testing.T) {
ctx := context.Background()
owner := app.TestPerson(t, "owner@example.com")
app.TestPerson(t, "stranger@example.com")
- doc, err := app.Store().Create(ctx, owner, "Private")
+ doc, err := app.Store().createDocument(ctx, owner, "Private", "", VisibilityPrivate)
if err != nil {
t.Fatalf("Create: %v", err)
}
diff --git a/internal/docs/views/share.html b/internal/docs/views/share.html
index 5dee3c4..153cf23 100644
--- a/internal/docs/views/share.html
+++ b/internal/docs/views/share.html
@@ -140,6 +140,23 @@
<div rst-form-foot><button rst-btn="primary" type="submit">{{.ShareButton}}</button></div>
</form>
+ {{/* The team rung (spec §8.2.1; Paul, 2026-11-01: "New docs Team, old
+ private"). The body names the state in words, so it never rests on
+ the button's label alone, and says the team reads and does not edit.
+ One <form> whichever way the switch points, the direction in a hidden
+ field, like the public link below: a page left open in a tab cannot
+ flip it the wrong way from a stale label. Scriptless; a 303 back. */}}
+ <section docs-share-public docs-share-team>
+ <h2>{{.TeamHeading}}</h2>
+ <p rst-muted docs-share-team-state>{{.TeamBody}}</p>
+ <div docs-share-actions>
+ <form method="post" action="/d/{{.Sqid}}/share/team">
+ <input type="hidden" name="visibility" value="{{.TeamDestination}}">
+ {{if .Team}}<button rst-btn type="submit">{{.TeamButton}}</button>{{else}}<button rst-btn="primary" type="submit">{{.TeamButton}}</button>{{end}}
+ </form>
+ </div>
+ </section>
+
{{/* The third rung: a read-only link anyone can follow, signed in or
not. One <form> whichever way the switch currently points, with the
direction in a hidden field — so a page left open in a tab cannot