oficina / home Public

Clone
git clone https://amadan.net/oficina/home

Plain git — no account needed to clone.

Download

Download this file

1# home/teammode, connect's Unlinked hook, and the roster lease fix
2
3**Status:** built on branch `teammode` by Claude Opus 5.5, 2026-10-28.
4**Reviewed by Claude Fable 5.1 (claude-fable-5-1), 2026-10-28, discussion 98,
5APPROVED at `0791dfd`**; the two record corrections it required are applied
6here (§3 invariant 6, §6). Landed with a merge commit, not a squash (§6). Not
7deployed. Implements
8Fable's sequencing ruling and roster note on oficina/sheets #52 (round 1) and
9oficina/home #97. Design context: `team-members.md` Part B §7.
10
11Two apps carry roster team mode today, each by hand: Docs (`e58a22f`, on a
12private `homeBridge` fork of connect) and Sheets (`ca78cc1`, on connect plus a
13private completion in `team_home.go`). This branch extracts what is the same,
14so Slides, Memoria, Calendar and Calls do not write a third and fourth copy.
15It re-points neither app: those are follow-up branches in their repos.
16
17## 1. What is in the branch
18
19| Piece | Where | One line |
20|---|---|---|
21| Roster lease fix (#97) | `roster/cache.go` | A publication keeps a lease whose subject and role it still lists. |
22| `roster.ValidSubject` | `roster/protocol.go` | The person-ref shape `Check` answers about. |
23| Unlinked / HomeOnly hooks | `connect/api.go`, `bridge.go` | Optional; a Home-only person in team mode, nothing changes otherwise. |
24| `home/teammode` | `teammode/` (own module) | Config, verification, marker, runtime, access, guard, probe. |
25| `home/teammode/teammodetest` | `teammode/teammodetest/` | Directory, provisioning and clock fixture for app tests. |
26
27## 2. The teammode API
28
29```go
30// Configuration (all or none, Home required)
31func EnvNames(prefix string) [5]string
32func ConfigFromEnv(prefix string) *Config // nil only when all five are empty
33func ConfigFromLookup(prefix string, getenv func(string) string) *Config
34type Home struct{ Issuer, ConsumerID string }
35func Verify(cfg *Config, home *Home, app, origin string) (*Settings, error) // nil cfg: off
36func (*Settings) Bindings() roster.Bindings
37func (*Settings) Fingerprint() string
38func Fingerprint(roster.Bindings) string
39
40// Marker and evidence, per app namespace
41func NewState(namespace string) (State, error); func MustState(string) State
42func (State) Schema() *migrate.Set // set "<ns>_team", migration 0001_team
43func (State) SQL() string
44func (State) BootSchema(ctx, db, settings, base, team *migrate.Set) (*migrate.Set, error)
45func (State) Required(ctx, db) (fingerprint string, activated bool, err error)
46func (State) Activate(ctx, db, fingerprint string) error
47func (State) Evidence(db) roster.Durable
48
49// Runtime
50func Open(ctx, RuntimeConfig{Settings, State, DB, Sealer, IssuerTables, Transport, Clock}) (*Runtime, error)
51func (*Runtime) Check(ctx, subject) roster.Decision // the only way to ask the cache
52func (*Runtime) Access(ctx, subject) *Access // "" is NotMember, unasked
53func (*Runtime) AdmitUnlinked(ctx, issuer, subject) error // nil | ErrNotMember | ErrUnavailable
54func (*Runtime) RosterState(ctx) string // "ok" | "stale" | "unknown"
55func (*Runtime) Refresh(ctx) error
56func (*Runtime) Bindings() roster.Bindings
57
58// One request's standing
59func (*Access) State() roster.State // lease re-checked, TryLock, latches Unknown
60func (*Access) Role() string // roster role while Member, else ""
61func (*Access) Remaining() time.Duration // stream timer; latches like State
62func (*Access) Partial() bool // Unknown: render the list as partial
63func (*Access) Subject() string
64func WithAccess(ctx, *Access) context.Context; func FromContext(ctx) (*Access, bool)
65func Standing(ctx) roster.State
66func Guard(ctx, authorize func(roster.State) error, write func() error) error
67func RequireMember(roster.State) error
68
69// Probe
70const ProbePath = "/api/team"
71func Probe(*Runtime) http.Handler // nil Runtime: {"team_mode":false}
72
73var ErrConfig, ErrUnavailable, ErrNotMember
74```
75
76Connect gains two optional `Config` fields and a sentinel:
77
78```go
79Unlinked func(ctx context.Context, issuer, subject string) (Person, error)
80HomeOnly func(ctx context.Context, issuer, subject string) (Person, error)
81var ErrNoPerson
82```
83
84## 3. Invariants
85
86**Configuration.**
871. Team mode is the five `<PREFIX>_TEAM_*` variables, all or none. One
88 present is a configuration and an invalid one; `Verify` refuses it. There
89 is no fall back to the allowlist.
902. Team mode requires Home: `Verify` refuses a nil or empty `Home`.
913. The provisioning record is verified against bindings built only from
92 configuration: Home's issuer and consumer ID, the app, the team, the
93 directory and the instance's origin. Values arrive as canonical standard
94 base64 only (no padding games, no embedded newlines); operator keys are
95 strict JSON. Errors carry no supplied value.
964. The fingerprint is base64url SHA-256 of the bindings' JSON, the bindings
97 alone, pinned by a test vector so an encoding change cannot strand every
98 activated database. It is Docs' and Sheets' digest exactly.
99
100**Marker.**
1015. `BootSchema` reads the marker before any migration (via `sqlite_master`
102 first, so a never-migrated database is safe). An activated database
103 refuses to boot without team configuration, or with a different binding.
104 This is Docs' rule; Sheets compared the binding only at `Activate`, so
105 adopting this refuses the same deployments one step earlier.
1066. `Open` activates before the runtime exists: it refuses a census that finds
107 any Home identity from another issuer (the app names its issuer-bearing
108 tables), writes the marker or refuses a different one, and only then
109 builds the roster cache. A refused census or binding writes no marker; a
110 cache that cannot open (unreadable or malformed evidence) leaves the
111 verified marker in place and refuses boot until it can. That is Docs'
112 order too, and harmless: the marker names the binding just verified, and
113 the next boot with the same configuration re-activates as a no-op.
1147. The marker's triggers refuse UPDATE and DELETE. With namespace `docs`, the
115 schema is Docs' applied migration byte for byte; with `sheets`, it is the
116 marker half of Sheets' (testdata), so neither app's ledger checksum moves.
117
118**Standing.**
1198. `Runtime.Check` is the only path to the cache that yields a decision, so
120 every definite answer (a request's, an allocation's, the probe's) records
121 that a roster has been held; the probe's "stale" depends on it.
122 (`Runtime.Refresh` also reaches the cache, but yields no decision and so
123 does not touch the held flag.)
1249. An app's stored roles are never consulted for standing. `Access.Role` is
125 the roster's role, and only while `State` is Member.
12610. `Access.State` re-checks the Member lease every time it is asked, with
127 `roster.Lease.Valid`'s TryLock: it never waits on the cache, so it is safe
128 inside the SQLite writer transaction, where a refresh's publication may be
129 queued behind the caller. Contention reads as Unknown.
13011. The first Unknown latches for the life of the `Access`. One request never
131 sees Member after Unknown, even when the lease would read valid again
132 (contention ending, or #97's surviving lease).
13312. A held decision ends within `roster.MaximumAge` (60 s) under a failing
134 refresh, and at the next publication that removes the subject or changes
135 their role.
136
137**Writes.**
13813. `Guard` runs the app's authorize against the carried standing, the write,
139 and the authorize again, all inside the caller's transaction. It never
140 asks the roster. A lease that lapses mid-write fails the commit. It
141 decides nothing itself: the app's rule says what Unknown may still reach
142 (a share).
143
144**Home-only people.**
14514. A person is created from a Home subject alone only in connect's ordinary
146 completion, after the assertion is verified and consumed, only when no
147 app session is present, only for a subject with no link and no Home-only
148 person, and only when `AdmitUnlinked` returns nil: the roster says Member
149 now and the decision's lease is still valid when checked again.
15015. Connect's same-person rules hold for Home-only people: `HomeOnly` is
151 consulted by ordinary resolution (`Resolve`, `ResolveSession`, and browser
152 completion), so a known Home-only
153 member arriving over somebody else's live session is 403, and that
154 session survives. An unknown arrival over any live session allocates
155 nothing ("unknown", 403). The transaction-aware `ResolveOn` API is a
156 deliberate exception: it resolves existing account links only and never
157 invokes `HomeOnly` or `Unlinked`, whose signatures cannot carry the caller's
158 query/transaction. It refuses addressless people rather than consulting a
159 second connection during an authorization transaction.
16016. A Home-only person has no address. Connect refuses one whose `Label` is
161 not empty. Every cookie shape check stays connect's (Sheets' copy goes).
16217. With both hooks nil, connect behaves exactly as before for every existing
163 consumer (Slides, Calendar, Calls, Memoria, Sheets today): the full
164 pre-existing connect suite passes unchanged.
165
166**Probe.**
16718. `GET /api/team` is unauthenticated and `no-store`, answers only
168 `{team_mode, consumer, roster}`, the same body whoever asks, and
169 `{"team_mode":false}` with team mode off.
170
171**Roster (#97).**
17219. A `Lease` names its subject and role. `Valid` and `Remaining` accept a
173 newer cache version when the cache is usable, the subject still holds
174 that role, and every publication since the lease has listed them so (a
175 per-member "since" version). A removal or role change ends the lease for
176 good; re-adding the subject does not revive it. The deadline is the
177 original one, so the 60 s contract is untouched. A fence (record update,
178 generation block, clock discrepancy) ends every earlier lease even after
179 a later publication, because the deadline was measured on a clock the
180 fence distrusts. Apps still do not re-ask on an invalid lease: under the
181 writer that would wait on the publisher.
182
183## 4. Unknown on list pages — RULED 2026-10-28 by Paul
184
185**Partial list with a notice (Docs' behaviour), not a 503.** Under Unknown a
186person's own list page shows what they reach without standing (their shares),
187with a "partial" notice; it does not answer 503 for the whole page. Fable
188recommended it on #52 (deviation 3) and #98: the list is where every sign-in
189lands, and a 503 there during a Home blip over 60 s reads as "the app is
190down" and gives the person nothing, where a shares-only list reads as "Home
191is slow" and gives them what is theirs by grant. Nothing is over-shown:
192Unknown never adds an item, it withholds the team rung. Rejected: Sheets'
193503 for the whole list.
194
195Conditions (Fable, #98), each part of the ruling:
196
1971. Ask `Access.Partial()` **after** building the list, from the **same**
198 `Access`: `State` latches, so a lease that lapsed while listing marks the
199 page partial.
2002. **NotMember is never partial.** A guest's shares are their complete list.
2013. **A feed consumed by another origin** (the dashboard pull) stays
202 **unavailable** under Unknown, not short: a reader who cannot see the
203 notice would take a short list for the truth. As required of Sheets'
204 dashboard on #52.
2054. **Item pages that need standing stay a retryable 503**, never a 404.
206 Create and import stay member-only (403 guest, 503 Unknown).
207
208Sheets switches from its 503 to the partial list when it re-points.
209
210## 5. What stays per app
211
212- **The mapping onto the app's access queries:** which rows the team rung
213 reaches (Docs: own documents; Sheets: every sheet, self-grants counting
214 only while Member, roster owners on orphaned sheets), and the `authorize`
215 passed to `Guard`.
216- **Home-only allocation:** the app's people table and its Home-only identity
217 table with its triggers (addressless, undeletable, disjoint from links),
218 and the two connect hooks that read and fill it.
219- **The reverse lookup** (person to Home subject) for asking the roster about
220 someone other than the viewer (a share list's "still on the team").
221- **The stream hook:** re-decide before each delivery, re-arm at
222 `Access.Remaining()`, close on anything but a renewed answer.
223- **Copy:** the partial notice, the Unknown message, the Home-only label.
224- **The `IssuerTables` list** and the evidence `Sealer` namespace.
225
226## 6. Migration plan
227
228Each is its own branch in its own repo, after this lands on Home main, each
229with its own review and canary.
230
231**Module pins — ruled by Fable on #98.** Branch-only pseudo-versions are
232acceptable on a branch (a multi-module repo has no other way to test one)
233and not on main: a pseudo-version is fetched by commit, so once the branch
234that reaches it is deleted every cold module cache fails `go mod download`,
235and MVS does not save a consumer whose `go.sum` needs that `go.mod` hash.
236Therefore:
237
2381. `teammode` lands on main with a **merge commit, not a squash**, so
239 `17db191`, `15833f7` and `6b23c73` stay reachable from main.
2402. **Mandatory, immediately after:** one commit on main re-pins
241 `teammode/go.mod` (roster, connect) and the root `go.mod` (roster, until
242 now pinned on `feat-roster-lease`) to the main merge commit, `go mod
243 tidy` in each, CI green — before any branch is deleted and before Docs or
244 Sheets re-point.
2453. Only then may `teammode` and `feat-roster-lease` be deleted.
2464. Docs, Sheets and every later port pin all three modules (`teammode`,
247 `roster`, `connect`) at a main commit at or after that re-pin, never at
248 `6b23c73`.
249
250### Sheets (first: it is on connect already)
251
252| Sheets at ca78cc1 | Becomes |
253|---|---|
254| `TeamConfigFromEnv` | `teammode.ConfigFromEnv("SHEETS")` |
255| `validatedTeamConfig` | `teammode.Verify(cfg, &teammode.Home{creds.Issuer, creds.ConsumerID}, "sheets", origin)` |
256| `BootSchemaFor` | `teammode.MustState("sheets").BootSchema(ctx, w, settings, BootSchema, TeamBootSchema)` |
257| `teamstate.Required/Activate/Evidence` | `State` methods over the same tables. Sheets keeps its own `sheets_team` set (its `0001_team.sql` also holds the Home-only tables, and the ledger checksums the whole file); it does not apply `State.Schema()`. |
258| `ConfigureTeam`'s census, `Activate`, `roster.New` | `teammode.Open(ctx, RuntimeConfig{…, IssuerTables: {"home_identity_links", "sheets_team_home_members"}})` |
259| `teamRuntime.check`, `rosterHeld` | `Runtime.Check` |
260| `team_home.go` (whole file: `homeFinish`, `teamComplete`, cookie copies, `t.finish`) | deleted. `connect.Config.HomeOnly` = `teamstate.HomeMember`; `Unlinked` = `AdmitUnlinked` then `teamstate.EnsureHomeMember`. `/auth/finish` is connect's `Finish`. |
261| `homeMemberID` | `bridge.Resolve`, which now finds Home-only members |
262| `teamAccess{member, subject, decision, uncertain}` | `teamAccess{member, *teammode.Access}`; `state()` is `Access.State`, `role()` maps `Access.Role` |
263| `resolveTeamAccess`, `withStanding` | `rt.Access(ctx, subject)` |
264| `streamAccess`'s timer | `Access.Remaining()` |
265| list under Unknown: 503 | `Access.Partial()` and the notice (§4) |
266| `mayWrite` in the handler | `teammode.Guard` inside the store's write transactions (Fable's deviation 7) |
267| `team_probe.go` | `teammode.Probe(rt)` at `teammode.ProbePath` |
268| `team_fixture_test.go`'s directory and clock | `teammodetest.Provision`, `Directory`, `Clock` |
269
270Stays: `team_owner.go`, `ownGrantIgnored`, `teamstate.HomeSubject`,
271`homeOnlyRefs`, labels, `teamMemberOnly`'s copy. `TestFitsSheets` in this
272branch runs this shape end to end through a real exchange.
273
274### Docs
275
276| Docs at e58a22f | Becomes |
277|---|---|
278| `validatedTeamConfig` | `teammode.Verify(cfg.Team, &teammode.Home{home.issuer, home.consumerID}, "docs", origin)`; `ConfigFromEnv("DOCS")` in `cmd/docs` |
279| `TeamConfig.transport/clock` | `RuntimeConfig.Transport/Clock` |
280| `app.go`'s `teamstate.Required` check before `migrate.Apply` | `MustState("docs").BootSchema(...)` |
281| `TeamBootSchema = Merge(BootSchema, principalstore.Schema, teamstate.Schema)` | `teamstate.Schema` becomes `MustState("docs").Schema()`: same set name, same migration ID, byte-identical SQL, so the applied ledger row matches (tested). `Merge` qualifies IDs identically (`<set>/<id>`) whether a set was built by `FromFS` or `Add`, which is the fact the ledger identity rests on. |
282| `newTeamRuntime`'s census, `Activate`, `roster.New` | `teammode.Open(…, IssuerTables: {"docs_identity_links", "docs_home_identities"})` |
283| `principalstore`'s `RequireMembership` | `AdmitUnlinked`, mapping `ErrNotMember` to `principalstore.ErrRefused`, else `ErrUnavailable` |
284| `requestAccess.state()`, `resolveAccess` | embedded `*teammode.Access`, `rt.Access(ctx, id.HomeSubject)` |
285| `permissionScope`, `ownerMutation` | unchanged in shape: they already authorize inside the writer transaction before and after; `ownerMutation` can be `teammode.Guard` |
286| `partialCatalog` | `Access.Partial()` |
287| `team_probe.go`, `check`, `rosterHeld` | `teammode.Probe`, `Runtime.Check` |
288
289**Docs' `homeBridge` stays in the first Docs branch.** Moving Docs onto
290`home/connect` (its `completeTeamPrincipal` mapping onto `HomeOnly` =
291`principals.Resolve` for Home principals and `Unlinked` = `EnsureHome`) also
292moves its link table (`docs_identity_links` to connect's
293`home_identity_links`) and its local reauthentication, which is a data
294migration with its own review. It is a second Docs branch, after the first
295has a canary. `TestFitsDocs` in this branch runs Docs' store-side shape
296(allocation gate, in-transaction authorize, partial catalog).
297
298## 7. The other four, in Paul's order
299
300Each port: `ConfigFromEnv("<APP>")`, `MustState("<app>")` with
301`State.Schema()` merged after the app's schema, a Home-only people table with
302Sheets' triggers, the two connect hooks, `Access` mapped onto the app's
303access query, `Guard` in its write transactions, `Partial` on its lists,
304`Probe` mounted, `teammodetest` in its tests; Alta's recipe gets
305`Roster: true` and the five keys. Then §7's acceptance list, full app CI,
306top-model review, verified canary.
307
3081. **Slides.** As Sheets. Team instances ship without uploads; when storage
309 arrives, presigned GETs are capped at `Access.Remaining()` (never beyond
310 60 s). The edit channel uses the stream hook.
3112. **Memoria.** `Partial` applies to search results and to the AI answer's
312 sources (sources drawn only from what the person reaches; a partial
313 answer says so). AI stays off for teams unless the owner asks and Paul
314 agrees. Sibling calls already bind to `MEMORIA_TEAM` hosts.
3153. **Calendar.** Published `.ics` feed tokens stay capability links with an
316 owner revoke. Home-only members have no address, so reminders need an
317 in-app "email for reminders" the instance stores (ruling 5) before a
318 Home-only member can get one.
3194. **Calls.** Standing checked at room join and on every signaling reconnect,
320 and the signaling socket closed at `Access.Remaining()` unless renewed.
321 Native clients need a team-host picker and Home sign-in first, which is
322 why Calls is last.
323
324## 8. Tests and hand mutations
325
326`make test` runs the new module in vet, build, test and race. Package tests
327mirror the strongest of Docs' and Sheets' team tests: all-or-none
328configuration per variable; every binding pinned; malformed values; the
329pinned fingerprint; marker lock-in, rebinding and triggers; boot before
330migrations (fresh, applied-not-activated, activated with none, other and same
331binding); census per table with no marker written; roles; the 59 s / 61 s
332lease under failing refresh with the latch; #97 across a refresh (unchanged
333kept on the old deadline, removal and role change ended); `AdmitUnlinked` for
334Member, stranger, Unknown, impossible subjects (no fetch) and a lease that
335lapses between decision and check; `Guard` before and after the write, a
336lapse mid-write, and inside a real one-connection SQLite writer with a
337publication queued behind it (no wait, contention latched, an uncontended
338request's lease surviving the publication); the probe's three states, team
339off, no account data, same body whoever asks, and "stale" from a request's
340check alone. Connect: the hooks as a pair, Home-only sign-in and re-sign-in,
341refusal as connect's unknown with the marker, undecided 503, an address
342refused, never asked over a live session, the known arrival over another
343session refused with that session intact, links and the link flow untouched,
344malformed cookies never reaching the hook. Roster: unchanged publication
345kept on its own deadline, role change both ways, removal then re-add, another
346member's change, fence then publication.
347
348Hand mutations, killed: in teammode, every binding unpinned (six), operator
349keys' unknown members, non-canonical base64, all-or-none, boot ignoring the
350marker, boot ignoring the binding, `Activate` accepting a rebind or a
351malformed fingerprint, `sqlite_master` skipped, census dropped, table
352validation dropped, census list optional, `Activate` skipped in `Open`, the
353held flag, `AdmitUnlinked` without the lease re-check / issuer / subject
354shape, the empty subject asking the roster, "stale" dropped, the probe
355bypassing `Check`, the probe leaking the team, `no-store` dropped, `State`
356without the lease check, `State` without the latch, `Guard` without the
357before or after check, `Partial` always false, `Role` ignoring standing,
358`RequireMember` admitting a guest. In connect: the hook pair, Unlinked over a
359live session, the same-person check, the label check, the Resolve fallback,
360storage read as refusal, the resume marker. In roster: the since check, the
361fence check, the role and since checks together, any member accepted, since
362always reset, the deadline.
363
364Equivalent, recorded: `Verify`'s explicit empty-field and Home-field checks
365(roster's binding validation refuses the same values; kept as the stated
366rule); `Remaining`'s own latch (`State`, called first, latches on contention,
367so it is reachable only if contention begins between the two calls); in
368roster, the role check and the since check each alone (a role change also
369resets since; the pair together is killed).
370