oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

home/teammode, connect's Unlinked hook, and the roster lease fix

Status: built on branch teammode by Claude Opus 5.5, 2026-10-28. Reviewed by Claude Fable 5.1 (claude-fable-5-1), 2026-10-28, discussion 98, APPROVED at 0791dfd; the two record corrections it required are applied here (§3 invariant 6, §6). Landed with a merge commit, not a squash (§6). Not deployed. Implements Fable's sequencing ruling and roster note on oficina/sheets #52 (round 1) and oficina/home #97. Design context: team-members.md Part B §7.

Two apps carry roster team mode today, each by hand: Docs (e58a22f, on a private homeBridge fork of connect) and Sheets (ca78cc1, on connect plus a private completion in team_home.go). This branch extracts what is the same, so Slides, Memoria, Calendar and Calls do not write a third and fourth copy. It re-points neither app: those are follow-up branches in their repos.

1. What is in the branch

| Piece | Where | One line | |---|---|---| | Roster lease fix (#97) | roster/cache.go | A publication keeps a lease whose subject and role it still lists. | | roster.ValidSubject | roster/protocol.go | The person-ref shape Check answers about. | | Unlinked / HomeOnly hooks | connect/api.go, bridge.go | Optional; a Home-only person in team mode, nothing changes otherwise. | | home/teammode | teammode/ (own module) | Config, verification, marker, runtime, access, guard, probe. | | home/teammode/teammodetest | teammode/teammodetest/ | Directory, provisioning and clock fixture for app tests. |

2. The teammode API

// Configuration (all or none, Home required)
func EnvNames(prefix string) [5]string
func ConfigFromEnv(prefix string) *Config           // nil only when all five are empty
func ConfigFromLookup(prefix string, getenv func(string) string) *Config
type Home struct{ Issuer, ConsumerID string }
func Verify(cfg *Config, home *Home, app, origin string) (*Settings, error) // nil cfg: off
func (*Settings) Bindings() roster.Bindings
func (*Settings) Fingerprint() string
func Fingerprint(roster.Bindings) string

// Marker and evidence, per app namespace
func NewState(namespace string) (State, error); func MustState(string) State
func (State) Schema() *migrate.Set                  // set "<ns>_team", migration 0001_team
func (State) SQL() string
func (State) BootSchema(ctx, db, settings, base, team *migrate.Set) (*migrate.Set, error)
func (State) Required(ctx, db) (fingerprint string, activated bool, err error)
func (State) Activate(ctx, db, fingerprint string) error
func (State) Evidence(db) roster.Durable

// Runtime
func Open(ctx, RuntimeConfig{Settings, State, DB, Sealer, IssuerTables, Transport, Clock}) (*Runtime, error)
func (*Runtime) Check(ctx, subject) roster.Decision  // the only way to ask the cache
func (*Runtime) Access(ctx, subject) *Access          // "" is NotMember, unasked
func (*Runtime) AdmitUnlinked(ctx, issuer, subject) error // nil | ErrNotMember | ErrUnavailable
func (*Runtime) RosterState(ctx) string               // "ok" | "stale" | "unknown"
func (*Runtime) Refresh(ctx) error
func (*Runtime) Bindings() roster.Bindings

// One request's standing
func (*Access) State() roster.State   // lease re-checked, TryLock, latches Unknown
func (*Access) Role() string          // roster role while Member, else ""
func (*Access) Remaining() time.Duration // stream timer; latches like State
func (*Access) Partial() bool         // Unknown: render the list as partial
func (*Access) Subject() string
func WithAccess(ctx, *Access) context.Context; func FromContext(ctx) (*Access, bool)
func Standing(ctx) roster.State
func Guard(ctx, authorize func(roster.State) error, write func() error) error
func RequireMember(roster.State) error

// Probe
const ProbePath = "/api/team"
func Probe(*Runtime) http.Handler     // nil Runtime: {"team_mode":false}

var ErrConfig, ErrUnavailable, ErrNotMember

Connect gains two optional Config fields and a sentinel:

Unlinked func(ctx context.Context, issuer, subject string) (Person, error)
HomeOnly func(ctx context.Context, issuer, subject string) (Person, error)
var ErrNoPerson

3. Invariants

Configuration.

  1. Team mode is the five <PREFIX>_TEAM_* variables, all or none. One present is a configuration and an invalid one; Verify refuses it. There is no fall back to the allowlist.
  2. Team mode requires Home: Verify refuses a nil or empty Home.
  3. The provisioning record is verified against bindings built only from configuration: Home's issuer and consumer ID, the app, the team, the directory and the instance's origin. Values arrive as canonical standard base64 only (no padding games, no embedded newlines); operator keys are strict JSON. Errors carry no supplied value.
  4. The fingerprint is base64url SHA-256 of the bindings' JSON, the bindings alone, pinned by a test vector so an encoding change cannot strand every activated database. It is Docs' and Sheets' digest exactly.

Marker.

  1. BootSchema reads the marker before any migration (via sqlite_master first, so a never-migrated database is safe). An activated database refuses to boot without team configuration, or with a different binding. This is Docs' rule; Sheets compared the binding only at Activate, so adopting this refuses the same deployments one step earlier.
  2. Open activates before the runtime exists: it refuses a census that finds any Home identity from another issuer (the app names its issuer-bearing tables), writes the marker or refuses a different one, and only then builds the roster cache. A refused census or binding writes no marker; a cache that cannot open (unreadable or malformed evidence) leaves the verified marker in place and refuses boot until it can. That is Docs' order too, and harmless: the marker names the binding just verified, and the next boot with the same configuration re-activates as a no-op.
  3. The marker's triggers refuse UPDATE and DELETE. With namespace docs, the schema is Docs' applied migration byte for byte; with sheets, it is the marker half of Sheets' (testdata), so neither app's ledger checksum moves.

Standing.

  1. Runtime.Check is the only path to the cache that yields a decision, so every definite answer (a request's, an allocation's, the probe's) records that a roster has been held; the probe's "stale" depends on it. (Runtime.Refresh also reaches the cache, but yields no decision and so does not touch the held flag.)
  2. An app's stored roles are never consulted for standing. Access.Role is the roster's role, and only while State is Member.
  3. Access.State re-checks the Member lease every time it is asked, with roster.Lease.Valid's TryLock: it never waits on the cache, so it is safe inside the SQLite writer transaction, where a refresh's publication may be queued behind the caller. Contention reads as Unknown.
  4. The first Unknown latches for the life of the Access. One request never sees Member after Unknown, even when the lease would read valid again (contention ending, or #97's surviving lease).
  5. A held decision ends within roster.MaximumAge (60 s) under a failing refresh, and at the next publication that removes the subject or changes their role.

Writes.

  1. Guard runs the app's authorize against the carried standing, the write, and the authorize again, all inside the caller's transaction. It never asks the roster. A lease that lapses mid-write fails the commit. It decides nothing itself: the app's rule says what Unknown may still reach (a share).

Home-only people.

  1. A person is created from a Home subject alone only in connect's ordinary completion, after the assertion is verified and consumed, only when no app session is present, only for a subject with no link and no Home-only person, and only when AdmitUnlinked returns nil: the roster says Member now and the decision's lease is still valid when checked again.
  2. Connect's same-person rules hold for Home-only people: HomeOnly is consulted by ordinary resolution (Resolve, ResolveSession, and browser completion), so a known Home-only member arriving over somebody else's live session is 403, and that session survives. An unknown arrival over any live session allocates nothing ("unknown", 403). The transaction-aware ResolveOn API is a deliberate exception: it resolves existing account links only and never invokes HomeOnly or Unlinked, whose signatures cannot carry the caller's query/transaction. It refuses addressless people rather than consulting a second connection during an authorization transaction.
  3. A Home-only person has no address. Connect refuses one whose Label is not empty. Every cookie shape check stays connect's (Sheets' copy goes).
  4. With both hooks nil, connect behaves exactly as before for every existing consumer (Slides, Calendar, Calls, Memoria, Sheets today): the full pre-existing connect suite passes unchanged.

Probe.

  1. GET /api/team is unauthenticated and no-store, answers only {team_mode, consumer, roster}, the same body whoever asks, and {"team_mode":false} with team mode off.

Roster (#97).

  1. A Lease names its subject and role. Valid and Remaining accept a newer cache version when the cache is usable, the subject still holds that role, and every publication since the lease has listed them so (a per-member "since" version). A removal or role change ends the lease for good; re-adding the subject does not revive it. The deadline is the original one, so the 60 s contract is untouched. A fence (record update, generation block, clock discrepancy) ends every earlier lease even after a later publication, because the deadline was measured on a clock the fence distrusts. Apps still do not re-ask on an invalid lease: under the writer that would wait on the publisher.

4. Unknown on list pages — RULED 2026-10-28 by Paul

Partial list with a notice (Docs' behaviour), not a 503. Under Unknown a person's own list page shows what they reach without standing (their shares), with a "partial" notice; it does not answer 503 for the whole page. Fable recommended it on #52 (deviation 3) and #98: the list is where every sign-in lands, and a 503 there during a Home blip over 60 s reads as "the app is down" and gives the person nothing, where a shares-only list reads as "Home is slow" and gives them what is theirs by grant. Nothing is over-shown: Unknown never adds an item, it withholds the team rung. Rejected: Sheets' 503 for the whole list.

Conditions (Fable, #98), each part of the ruling:

  1. Ask Access.Partial() after building the list, from the same Access: State latches, so a lease that lapsed while listing marks the page partial.
  2. NotMember is never partial. A guest's shares are their complete list.
  3. A feed consumed by another origin (the dashboard pull) stays unavailable under Unknown, not short: a reader who cannot see the notice would take a short list for the truth. As required of Sheets' dashboard on #52.
  4. Item pages that need standing stay a retryable 503, never a 404. Create and import stay member-only (403 guest, 503 Unknown).

Sheets switches from its 503 to the partial list when it re-points.

5. What stays per app

  • The mapping onto the app's access queries: which rows the team rung reaches (Docs: own documents; Sheets: every sheet, self-grants counting only while Member, roster owners on orphaned sheets), and the authorize passed to Guard.
  • Home-only allocation: the app's people table and its Home-only identity table with its triggers (addressless, undeletable, disjoint from links), and the two connect hooks that read and fill it.
  • The reverse lookup (person to Home subject) for asking the roster about someone other than the viewer (a share list's "still on the team").
  • The stream hook: re-decide before each delivery, re-arm at Access.Remaining(), close on anything but a renewed answer.
  • Copy: the partial notice, the Unknown message, the Home-only label.
  • The IssuerTables list and the evidence Sealer namespace.

6. Migration plan

Each is its own branch in its own repo, after this lands on Home main, each with its own review and canary.

Module pins — ruled by Fable on #98. Branch-only pseudo-versions are acceptable on a branch (a multi-module repo has no other way to test one) and not on main: a pseudo-version is fetched by commit, so once the branch that reaches it is deleted every cold module cache fails go mod download, and MVS does not save a consumer whose go.sum needs that go.mod hash. Therefore:

  1. teammode lands on main with a merge commit, not a squash, so 17db191, 15833f7 and 6b23c73 stay reachable from main.
  2. Mandatory, immediately after: one commit on main re-pins teammode/go.mod (roster, connect) and the root go.mod (roster, until now pinned on feat-roster-lease) to the main merge commit, go mod tidy in each, CI green — before any branch is deleted and before Docs or Sheets re-point.
  3. Only then may teammode and feat-roster-lease be deleted.
  4. Docs, Sheets and every later port pin all three modules (teammode, roster, connect) at a main commit at or after that re-pin, never at 6b23c73.

Sheets (first: it is on connect already)

| Sheets at ca78cc1 | Becomes | |---|---| | TeamConfigFromEnv | teammode.ConfigFromEnv("SHEETS") | | validatedTeamConfig | teammode.Verify(cfg, &teammode.Home{creds.Issuer, creds.ConsumerID}, "sheets", origin) | | BootSchemaFor | teammode.MustState("sheets").BootSchema(ctx, w, settings, BootSchema, TeamBootSchema) | | 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(). | | ConfigureTeam's census, Activate, roster.New | teammode.Open(ctx, RuntimeConfig{…, IssuerTables: {"home_identity_links", "sheets_team_home_members"}}) | | teamRuntime.check, rosterHeld | Runtime.Check | | 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. | | homeMemberID | bridge.Resolve, which now finds Home-only members | | teamAccess{member, subject, decision, uncertain} | teamAccess{member, *teammode.Access}; state() is Access.State, role() maps Access.Role | | resolveTeamAccess, withStanding | rt.Access(ctx, subject) | | streamAccess's timer | Access.Remaining() | | list under Unknown: 503 | Access.Partial() and the notice (§4) | | mayWrite in the handler | teammode.Guard inside the store's write transactions (Fable's deviation 7) | | team_probe.go | teammode.Probe(rt) at teammode.ProbePath | | team_fixture_test.go's directory and clock | teammodetest.Provision, Directory, Clock |

Stays: team_owner.go, ownGrantIgnored, teamstate.HomeSubject, homeOnlyRefs, labels, teamMemberOnly's copy. TestFitsSheets in this branch runs this shape end to end through a real exchange.

Docs

| Docs at e58a22f | Becomes | |---|---| | validatedTeamConfig | teammode.Verify(cfg.Team, &teammode.Home{home.issuer, home.consumerID}, "docs", origin); ConfigFromEnv("DOCS") in cmd/docs | | TeamConfig.transport/clock | RuntimeConfig.Transport/Clock | | app.go's teamstate.Required check before migrate.Apply | MustState("docs").BootSchema(...) | | 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. | | newTeamRuntime's census, Activate, roster.New | teammode.Open(…, IssuerTables: {"docs_identity_links", "docs_home_identities"}) | | principalstore's RequireMembership | AdmitUnlinked, mapping ErrNotMember to principalstore.ErrRefused, else ErrUnavailable | | requestAccess.state(), resolveAccess | embedded *teammode.Access, rt.Access(ctx, id.HomeSubject) | | permissionScope, ownerMutation | unchanged in shape: they already authorize inside the writer transaction before and after; ownerMutation can be teammode.Guard | | partialCatalog | Access.Partial() | | team_probe.go, check, rosterHeld | teammode.Probe, Runtime.Check |

Docs' homeBridge stays in the first Docs branch. Moving Docs onto home/connect (its completeTeamPrincipal mapping onto HomeOnly = principals.Resolve for Home principals and Unlinked = EnsureHome) also moves its link table (docs_identity_links to connect's home_identity_links) and its local reauthentication, which is a data migration with its own review. It is a second Docs branch, after the first has a canary. TestFitsDocs in this branch runs Docs' store-side shape (allocation gate, in-transaction authorize, partial catalog).

7. The other four, in Paul's order

Each port: ConfigFromEnv("<APP>"), MustState("<app>") with State.Schema() merged after the app's schema, a Home-only people table with Sheets' triggers, the two connect hooks, Access mapped onto the app's access query, Guard in its write transactions, Partial on its lists, Probe mounted, teammodetest in its tests; Alta's recipe gets Roster: true and the five keys. Then §7's acceptance list, full app CI, top-model review, verified canary.

  1. Slides. As Sheets. Team instances ship without uploads; when storage arrives, presigned GETs are capped at Access.Remaining() (never beyond 60 s). The edit channel uses the stream hook.
  2. Memoria. Partial applies to search results and to the AI answer's sources (sources drawn only from what the person reaches; a partial answer says so). AI stays off for teams unless the owner asks and Paul agrees. Sibling calls already bind to MEMORIA_TEAM hosts.
  3. Calendar. Published .ics feed tokens stay capability links with an owner revoke. Home-only members have no address, so reminders need an in-app "email for reminders" the instance stores (ruling 5) before a Home-only member can get one.
  4. Calls. Standing checked at room join and on every signaling reconnect, and the signaling socket closed at Access.Remaining() unless renewed. Native clients need a team-host picker and Home sign-in first, which is why Calls is last.

8. Tests and hand mutations

make test runs the new module in vet, build, test and race. Package tests mirror the strongest of Docs' and Sheets' team tests: all-or-none configuration per variable; every binding pinned; malformed values; the pinned fingerprint; marker lock-in, rebinding and triggers; boot before migrations (fresh, applied-not-activated, activated with none, other and same binding); census per table with no marker written; roles; the 59 s / 61 s lease under failing refresh with the latch; #97 across a refresh (unchanged kept on the old deadline, removal and role change ended); AdmitUnlinked for Member, stranger, Unknown, impossible subjects (no fetch) and a lease that lapses between decision and check; Guard before and after the write, a lapse mid-write, and inside a real one-connection SQLite writer with a publication queued behind it (no wait, contention latched, an uncontended request's lease surviving the publication); the probe's three states, team off, no account data, same body whoever asks, and "stale" from a request's check alone. Connect: the hooks as a pair, Home-only sign-in and re-sign-in, refusal as connect's unknown with the marker, undecided 503, an address refused, never asked over a live session, the known arrival over another session refused with that session intact, links and the link flow untouched, malformed cookies never reaching the hook. Roster: unchanged publication kept on its own deadline, role change both ways, removal then re-add, another member's change, fence then publication.

Hand mutations, killed: in teammode, every binding unpinned (six), operator keys' unknown members, non-canonical base64, all-or-none, boot ignoring the marker, boot ignoring the binding, Activate accepting a rebind or a malformed fingerprint, sqlite_master skipped, census dropped, table validation dropped, census list optional, Activate skipped in Open, the held flag, AdmitUnlinked without the lease re-check / issuer / subject shape, the empty subject asking the roster, "stale" dropped, the probe bypassing Check, the probe leaking the team, no-store dropped, State without the lease check, State without the latch, Guard without the before or after check, Partial always false, Role ignoring standing, RequireMember admitting a guest. In connect: the hook pair, Unlinked over a live session, the same-person check, the label check, the Resolve fallback, storage read as refusal, the resume marker. In roster: the since check, the fence check, the role and since checks together, any member accepted, since always reset, the deadline.

Equivalent, recorded: Verify's explicit empty-field and Home-field checks (roster's binding validation refuses the same values; kept as the stated rule); Remaining's own latch (State, called first, latches on contention, so it is reachable only if contention begins between the two calls); in roster, the role check and the since check each alone (a role change also resets since; the pair together is killed).