diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md
index 37bd523009..7dc85b7ea5 100644
--- a/docs/architecture/rolling-upgrades.md
+++ b/docs/architecture/rolling-upgrades.md
@@ -1214,6 +1214,22 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline
`tests/unit/test_ledger_invariants.py` check N's side, and the mixed-version gate
does not check this rule.
+79. **Namespace invitations** (`loom.namespace_invites`, migration
+ `123_namespace_invites.sql`): N-1 serves none of `grants.invite`, `grants.list_invites`,
+ `grants.cancel_invite` and `grants.accept_invite`, and answers one routed to it as an
+ unknown operation. N's dashboard sends a person's add to `grants.invite`, so while N-1
+ serves, an add or an acceptance can fail on an N-1 replica and succeed on a retry that
+ reaches N. N-1's in-use check of a new name does not count an open invitation: a name
+ retired with one outstanding can be registered as new on an N-1 replica, and the link
+ would then grant on the new owner's namespace; cancel open invitations before retiring
+ a name during the rollout. N-1's user erasure does not take the user off the
+ invitations they made: one an N-1 replica runs leaves their `user:` as an
+ invitation's `created_by` until the TTL drops the row, a week after the link expires.
+ Those links admit nobody, since the erasure revoked the user's grants, and the
+ erasure's residue check does not count the table. After a rollback the table stays,
+ its rows dropped by TTL a week after they expire. No gate holds the rollout, and the
+ mixed-version gate does not check this rule.
+
## What checks them
`scripts/gates/mixed_version.py` (`make test-mixed-version`, the `mixed-version` CI job,
diff --git a/docs/architecture/security.md b/docs/architecture/security.md
index 05a1cb43ea..6fb3104145 100644
--- a/docs/architecture/security.md
+++ b/docs/architecture/security.md
@@ -918,8 +918,8 @@ made while another change to that account runs answers 409 `SIGNUP_IN_PROGRESS`,
says only that a change is running. In use means a `loom.namespaces` row, a configured
code-plane repository or tracker namespace, any row in a table the erasure census counts
by namespace (`census.namespace_tables`), tombstoned or not, a live row in a table whose
-rows a later owner would inherit (`namespace_census.STATE_TABLES`: grants, webhooks, task
-inboxes, sources and the like), or, on the Postgres authority, a memory there
+rows a later owner would inherit (`namespace_census.STATE_TABLES`: grants, open invitations,
+webhooks, task inboxes, sources and the like), or, on the Postgres authority, a memory there
(`steps_pg.pg_holds_namespace`). Every other table keyed by namespace is exempt with a
reason (`tests/unit/test_in_use_coverage.py`), which a new table cannot skip. A namespace
can hold such rows without a registry row when auto-registration failed or was off, for
diff --git a/docs/architecture/sharing.md b/docs/architecture/sharing.md
index 9dd427d934..5cfbbac798 100644
--- a/docs/architecture/sharing.md
+++ b/docs/architecture/sharing.md
@@ -194,6 +194,78 @@ admin. The group lands in that org; a member is a user id, held as `user:`.
Membership is read by Loom on every request, never claimed by a token, so removing a
member takes effect within the consistency window below.
+## Invitations
+
+`grants.invite` gives a person a role by what an admin knows of them. An email verified
+for an account (an SSO account or an `sso_links` row) is granted at once through
+`grants.create`, under that account's handle. So is a login handle an account's row is
+owned under, or a live grant in the org is stored under (a person whose tokens Loom did
+not mint at sign-in has no account row), under the spelling stored for it. Only a
+verified tie counts for an email: a row's `owner_email` and a grant's subject are
+whatever their writer typed, and `namespace.register` takes any owner. A request with no
+token, which only a server with auth off serves, grants every person as typed: no one
+signs in there to accept a link. Any other email, one plain address as sign-up checks
+it (a dot-atom local part and a domain IDNA encodes, so no list, display name or
+comment), gets an invitation: a `loom.namespace_invites` row and the link
+`/spaces#invite=&org=…&namespace=…`. The link is the credential. Only the secret's
+SHA-256 is stored, as the row's `invite_id`, and the link works once, for seven days by
+default (`invite_ttl_seconds`). The server emails it when `smtp_url`, `mail_from` and
+`public_base_url` are set; otherwise, or when the send fails, the answer carries the link
+for the admin to pass on. An invitation is made only on an active namespace, where its
+link can be accepted. A handle no account holds is refused with 404, so a typo is never
+kept as a grant for whoever signs up under that handle later.
+
+Where sign-in is single sign-on only (`oauth_login_provider = "oidc"`), the identity
+provider verifies every account's email, so an email no account holds is granted as typed
+through `grants.create` instead, and reaches that person at their first sign-in. There is
+no link to pass on.
+
+For a person whose tokens Loom does not mint at sign-in (an upstream gateway's,
+`loom mint-token`'s, or a trusted caller's on their behalf), an email gets a link too,
+accepted by whoever opens it signed in, and a handle Loom has not seen yet is refused.
+`grants.create` grants either as typed, for a subject the token's minter names. The
+`gateway` identity provider does not mark such a server: a password server with sign-up
+off infers it too, and there a grant by email would reach nobody.
+
+The server's mail is no relay for a namespace admin, whom any sign-up can make: it emails
+at most 20 invitations an hour per inviter and 3 a day per address, counted in
+`loom.auth_attempts` across the deployment (`server.auth.attempts`). Past either limit
+the invitation is still made, and its link is the inviter's to pass on.
+
+`grants.accept_invite` gives the invitation's role to the signed-in caller, under the
+handle they sign in with, stamped `granted_by` the invitation's maker. Only a person's
+token accepts: a service account, a grant principal or a token of another org is refused.
+Under a lease per invitation (`grant_claims.invite_change`) it checks that the link is
+open, the namespace active and the maker still an admin, and marks the invitation
+accepted. It grants after leaving the lease, so the grant's own claims, and an admin
+grant's fan-out to a repository's branches, are never taken under it. One link never
+admits two people: after a failed grant the link opens again only when no grant at or
+above its role stands, so a failure after the grant row landed (a lost reply, a step after
+the write) leaves it used. A higher role the caller holds already stands.
+
+An invitation never outlasts its maker's admin. Its maker is the account the admin
+rests on: the caller, or a delegated token's creator, whose live grant holds the token to
+it. `grants.invite` and `grants.accept_invite` both read that account's grants as the gate
+reads them (`authz.subject_grant_role`): on a collection its own, its groups' and
+everyone's, there or on a collection above; elsewhere its grant, or an inheriting service
+account's creator's. The maker's account must also be active and their subject not
+revoked, as for a token they delegated (`delegation.creator_account_active`,
+`revocation.is_revoked` at the time the link was made). Short of any of these, the link is
+not made, or admits nobody; a failed read answers 503, so the dashboard keeps the link. An
+admin whose token alone makes them one (a platform admin, an operator's token) holds no
+grant that a later read could tell from a revoked one, so they cannot make a link: an
+admin through a grant invites the person. The open invitations name each maker.
+
+Self sign-up makes accounts in `self_signup_org` only. On a password server, a link to a
+namespace of another org is accepted by an account an operator made there.
+
+A password account's email is never verified, which is why an email reaches one only
+through an invitation: the link went to that address, and opening it proves the reader
+got it. The whole link is a fragment, which a browser never sends to a server or puts in a
+Referer. Namespaces in your org moves it out of the address into the tab's session
+storage, where it waits until the person accepts it or closes the card, or the server
+refuses it; where the browser refuses that storage, the card holds it until the page goes.
+
## Consistency
Every change to a grant, a group or the tree writes a row to `loom.acl_versions` for its
@@ -282,22 +354,25 @@ replaced, so none reads as live again. It deletes their uploaded originals that
writer's live document shares (each upload by an end user is recorded in
`loom.blob_uploads`, because the document version that named it may have been replaced and
merged away since), revokes and then deletes every grant naming `user:`, blanks their
-id as the issuer of the grants they gave others (those grants stay), removes them from
-every group, blanks their id as the creator of the collections they made (the collections
-stay), and retires their personal collection's directory row (`namespace.delete` and
-`collection.delete` refuse a personal collection: it goes only with its user's erasure).
-The request ledger keeps the user's calls for cost with their `user:` subject
-scrubbed, and the user's newest-call row is deleted. Deleting a SCIM group revokes the
-grants that named it, so a group made later under the same id starts with none.
-Collections that hold other writers' documents stay: Loom deletes only what its writer
-asked to delete. `collection.delete` purges what its collection held (a namespace erasure
-that takes the rows off disk) before the collection leaves the tree. A user-scope
-`erasure.export` returns the chunks and the conversation rows (transcript turns, saved
-messages and threads) that user owns in the collections its caller may read, and in the
-user's own personal collection. An org admin may erase a collection's rows without
-reading them; a platform admin sees every collection. Each section's read leaves out what
-the caller may not see before its limit, so a hidden row never takes a visible row's place
-on the page.
+id as the issuer of the grants they gave others (those grants stay) and as the maker of
+their invitations, closing the open ones, removes them from every group, blanks their id
+as the creator of the collections they made (the collections stay), and retires their
+personal collection's directory row (`namespace.delete` and `collection.delete` refuse a
+personal collection: it goes only with its user's erasure). An accept or an invitation
+already past its maker check as that step runs can still write their id, as a grant's
+issuer or an invitation's maker, as a `grants.create` in flight can; such a link admits
+nobody, since the step revokes the user's grants first. The request ledger keeps the
+user's calls for cost with their `user:` subject scrubbed, and the user's newest-call
+row is deleted. Deleting a SCIM group revokes the grants that named it, so a group made
+later under the same id starts with none. Collections that hold other writers' documents
+stay: Loom deletes only what its writer asked to delete. `collection.delete` purges what
+its collection held (a namespace erasure that takes the rows off disk) before the
+collection leaves the tree. A user-scope `erasure.export` returns the chunks and the
+conversation rows (transcript turns, saved messages and threads) that user owns in the
+collections its caller may read, and in the user's own personal collection. An org admin
+may erase a collection's rows without reading them; a platform admin sees every
+collection. Each section's read leaves out what the caller may not see before its limit,
+so a hidden row never takes a visible row's place on the page.
## Namespace guides
@@ -370,6 +445,18 @@ One text serves agents and people, so there is no second copy to drift.
principals and differs per user; no one sort order clusters every user's union.
- **Group membership in a token claim.** A claim is fixed until the token expires, so a
removed member keeps access for the token's life.
+- **A confirmation email for every password account.** Verified emails would let a grant
+ by email bind at sign-in, but every server would need mail to sign anyone up; an
+ invitation works with or without mail.
+- **A pending grant by email, bound at the first sign-in under that email.** A password
+ sign-up names any email it likes, so whoever registered the address first would take
+ the grant.
+- **The invitation's secret in the query string.** It would reach access logs and Referer
+ headers.
+- **Binding acceptance to the invited address.** A password account has no verified email
+ to compare, so only the link can prove the address was reached.
+- **Cancelling a maker's invitations when their grant is revoked.** A best-effort cascade
+ would leave a link open when it fails; reading the grant at acceptance fails closed.
- **Inheritance resolved at write time.** Moving a collection would rewrite the grants of
every descendant; resolving at check time from a cached tree costs a walk of at most
eight parents.
diff --git a/docs/architecture/storage-layout.md b/docs/architecture/storage-layout.md
index bbbccbed42..fda7713848 100644
--- a/docs/architecture/storage-layout.md
+++ b/docs/architecture/storage-layout.md
@@ -934,6 +934,7 @@ copies of tables listed here, owned and removed by that run, and erasure reaches
| `oauth_signin_state` | KeeperMap `claim_key` | Postgres `oauth_signin_state` | SoR | no content | 1 | strict compare-and-set per key with an expiry and optional verified sign-in email metadata: an `UPDATE … WHERE value = $old`; the KeeperMap expiry becomes `expires_at`, read by a sweep; named in `server/auth/claims.py`, `server/cli/secrets.py` |
| `grant_claims` | KeeperMap `claim_key` | delete | Coord | no content | 1 | no code path writes it (its census entry says so); no module outside the census names the table (`server/auth/grant_claims.py` is the claim module, whose keys are in `_migration_lock`) |
| `namespace_grants` | RMT(version) `(org, namespace, subject)`, by `org` | Postgres `namespace_grants` | SoR | step `grants.revoke` | 1 | every request's role check; a revoke takes effect within the grant cache's invalidation bound; named in `server/identity/store/grants.py`, `server/auth/self_signup.py` |
+| `namespace_invites` | RMT(version) `(org, namespace, invite_id)`, TTL | Postgres `namespace_invites` | SoR | step `grants.revoke` | 1 | an invitation read by `(org, namespace, invite_id)` when its link is accepted or cancelled, the open ones when a namespace's members are shown, the open, unexpired ones by a new name's in-use check, and the ones a user made by that user's erasure; named in `server/identity/store/invites.py` |
| `namespaces` | RMT(updated_at) `(org, namespace)`, by `org` | Postgres `namespaces` + ClickHouse mirror | SoR (head) | step `personal.retire`; step `collections.forget_owner` | 1 | the registry with its per-namespace settings, read by grants, sign-in and request paths through a cache; the mirror serves ClickHouse worker scans and the SQL surface views; named in `server/auth/self_signup.py`, `server/cli/hygiene.py` |
| `collections` | RMT(version) `(org, namespace)` | Postgres `collections` | SoR | step `collections.forget_owner` | 1 | the collection tree grants inherit through; named in `server/identity/store/collections.py`, `server/identity/store/namespace_census.py` |
| `acl_versions` | SMT(changes) `(org, kind)` | merge into Postgres `cache_generations` (kinds `grants`, `groups`, `collections`) | Coord | no content | 1 | a change counter caches poll; a generation row plus `NOTIFY` replaces it; named in `server/core/grant_cache.py` |
@@ -1194,61 +1195,61 @@ a row names a step today's ClickHouse census owns, the `pg:` census row is owned
Postgres step the flip splits off it, which joins `PG_ONLY_STEPS`
([restores](#restores)).
-| Table | Key | Kind | Erasure |
-| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| `authority` | [storage authority](storage-authority.md#the-tables); paired with ClickHouse's `storage_authority` | SoR | no content |
-| `pg_migrations` | the migration file | SoR | no content |
-| `scope_generations` | [storage authority](storage-authority.md#the-tables) | SoR (a namespace's row allocates its revision `seq`) | no content |
-| `cache_generations` | `(org, kind)` | Coord | no content |
-| `memory_current` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.memory_current` |
-| `memory_revisions` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.memory_revisions` |
-| `memory_refusals` | `(org, scope_kind, scope_value, user_id, kind, units, digest)` | SoR, hash-only consent policy committed beside memory; no TTL | no content; retained across erasure |
-| `memory_deliveries` | [storage authority](storage-authority.md#the-tables) | SoR | cascades with its revision |
-| `idempotency`, `idempotency_fences` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.idempotency`; `idempotency_fences` holds no content (the census's bound) |
-| `erased_memories`, `erased_documents` | [storage authority](storage-authority.md#the-tables) | SoR | evidence, no content |
-| `audit_outbox` | [storage authority](storage-authority.md#the-tables) | SoR | keys and ids, no values |
-| `document_catalog`, `document_uploaders` | `(org, namespace, sha256)`, `(org, user_id, namespace, sha256)` | SoR | a `pg:` census row each, owned by the Postgres step the flip splits off the steps that own the census rows of `document_blobs` and `blob_uploads` today, which joins `PG_ONLY_STEPS` (`documents.tombstone`, and the user step through `document_uploaders`) |
-| `knowledge_datasets` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.knowledge_datasets`, step `pg_knowledge.delete` |
-| `knowledge_jobs` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.knowledge_jobs`, step `pg_knowledge.delete` |
-| `mcp_worker_enrollment_challenges` | `(org, nonce)` | SoR | one-time account enrollment challenges of a canonical sign-in owner (`subject`; `user_id` is `-`), erased with the collection or by the owner's deletion (`pg_mcp_worker_enrollment.erase_subject`), never by a user erasure; census `pg:loom.mcp_worker_enrollment_challenges`, namespace step `pg_knowledge.delete` |
-| `mcp_worker_accounts` | `(org, connection_id)` | SoR | opaque connection bindings and revocation generations of a canonical sign-in owner (`subject`; `user_id` is `-`), one collection per connection, erased with the collection or by the owner's deletion (`pg_mcp_worker_enrollment.erase_subject`), never by a user erasure; census `pg:loom.mcp_worker_accounts`, namespace step `pg_knowledge.delete` |
-| `mcp_worker_approvals` | `(org, namespace, worker_id, profile_digest)` | SoR | a collection's allowed modes and approval generations, naming no subject (`user_id` is `-`), erased with the collection; census `pg:loom.mcp_worker_approvals`, namespace step `pg_knowledge.delete` |
-| `mcp_worker_source_readers` | `(org, namespace, source_id, subject)` | SoR | explicit team reader bindings of a canonical sign-in reader (`subject`; `user_id` is `-`), erased with the collection or by the reader's deletion (`pg_mcp_worker_enrollment.erase_subject`), never by a user erasure; census `pg:loom.mcp_worker_source_readers`, namespace step `pg_knowledge.delete` |
-| `knowledge_heads`, `knowledge_deliveries` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.knowledge_heads`, `pg:loom.knowledge_deliveries` |
-| `jobs`, `job_users`, `job_memories` | `(org, id)`, `(org, user_id, job_id)`, `(org, namespace, memory_id, job_id)` | SoR | a census row, a step by namespace and user, a redaction step |
-| `leases`, `write_marks`, `graph_inflight` | `(org, name)`, `(org, namespace, surface)`, `(org, namespace, token)` | Coord | no content |
-| `cursors` | `(org, consumer, scope)` | SoR | no content |
-| `carry_acks` | `process` | Coord | no content |
-| `analysis_secrets` | `id` | SoR | no content |
-| `sql_access` | `(org, namespace, user_name)` | SoR | no content |
-| `cell_self` | singleton | SoR until attach writes its fingerprint to the directory row, then Derived (rewritten from the directory on a restore, [cells](cells.md)) | no content |
-| `tenancy` | `org` | SoR until attach places its org (the first cell's `recording` rows), then Derived (written back from the directory's placements on a restore, never deleted, [cells](cells.md)) | no content; an erasure leaves the org's row |
-| `tenancy_mode` | singleton | Derived (the mode raised only upward from the directory's recorded mode on a restore, [cells](cells.md)) | no content |
-| `cell_first` | singleton | Derived (written when absent and refused when it differs on a restore; written once, its update, delete and truncate refused by triggers, [cells](cells.md)) | no content |
-| `cell_probe` (the probe nonce the `loom cell` commands write, [cells](cells.md)) | `name` | Coord | no content; deleted once the probe has read it |
-| `job_parts` | `(org, job_id, seq)` | SoR | cascades with its job; `code_index.purge` reaches it through the job |
-| `idempotency_revisions` | `(org, key_hash, namespace, seq)` | SoR | cascades with its record; redaction reaches replay answers through it |
-| `revision_relations` | `(org, namespace, seq, ord)` | SoR | census `pg:loom.revision_relations`, step `pg_memory.delete`; cascades with its revision; redaction reaches it through its revision |
-| `revision_sources` | `(org, user_id, namespace, seq)` | SoR | cascades with its revision; the user step deletes the user's rows; the user step and the census reach shared revisions through it |
-| `table_moves`, `move_acks` | `move`, `(move, process)` | SoR, Coord | no content; `table_moves` also holds the registry of kept tables (each kept table's name and scope predicates) |
-| `backfill_steps` | the column, index or check it sets | SoR | no content; the backfill step's completion record, which boots read ([schema rules](#postgres)) |
-| `working_memory`, `records`, `operator_edges`, `context_offloads`, `session_briefs`, `session_brief_revisions`, `namespace_guides`, `learning_candidates`, `learning_supporters`, `conflict_allowlist` | led by `(org, namespace, …)`, the ClickHouse sort key today | SoR | a census row and a saga step each |
-| `conversation_states` | `(org, namespace, agent, thread_id, msg_id)` | SoR | a census row and the `conversations.tombstone` step, by namespace and by the saver's `user_id` |
-| `offload_bytes` | `(org, namespace, offload_id, part)`, its head's id and a part number | SoR | deleted with its head by the `context_offloads` step, and counted by its census row |
-| `shared_current` | `(org, namespace, memory_key)` | SoR | a `pg:` census row and the provenance step `shared` has today, through `revision_sources` |
-| `tasks`, `agent_runs` | `(org, inbox, task_id)`, `(org, namespace, run_id)` | SoR | a `pg:` census row each, owned by the Postgres step the flip splits off the step that owns its ClickHouse table's census row today, which joins `PG_ONLY_STEPS` (`tasks` in the namespace scope, `agent_runs` in both) |
-| `task_inboxes`, `task_poster_policies` | `(org, inbox)`, `(org, inbox, poster, kind)` | SoR | no content |
-| `erased_messages` | `(org, erasure_id, namespace, agent, thread_id, msg_id)` | SoR | evidence, no content; the messages a conversation erasure matched by their saver, which its ClickHouse replay reads, swept with its `erasure_ledger` row |
-| `erasure_ledger` | [storage authority](storage-authority.md#the-tables) | SoR | evidence, no content; Postgres's erasure record, which `loom reconcile` runs again after a ClickHouse restore, swept after `erasure_ledger_days` |
-| `record_schemas`, `namespace_visits`, `extraction_policies`, `namespace_policies`, `namespace_types`, `namespace_ontology`, `profile_schemas`, `user_state`, `webhooks`, `knowledge_sources`, `knowledge_mirrors`, `code_repos`, `qa_sources` | led by `org`, as the ClickHouse key | SoR | no memory content |
-| `knowledge_uploads` | led by `org`, as the ClickHouse key | SoR | a `pg:` census row owned by the Postgres step split off `documents.tombstone` ([restores](#restores)) |
-| `code_coverage_watches` | led by `org`, as the ClickHouse key | SoR | no memory content; reached by the Postgres part of `code_index.purge` ([restores](#restores)) |
-| `revoked_tokens` | `(kind, key)`, kind `subject_or_jti` (the bare key, which holds both today), `cutoff` or `scim` | SoR | no content |
-| `signing_keys`, `service_accounts`, `machine_identities`, `scim_users`, `sso_links`, `principal_groups`, `oauth_state`, `oauth_signin_state`, `namespace_grants`, `namespaces`, `collections`, `blacklist`, `org_model_calls` | as the ClickHouse key, `org` first where the table is per org, except the tables of the cell that [keys lead with `org`](#postgres) names | SoR | no memory content; the identity steps (`grants.revoke`, `groups.remove_member`, `personal.retire`, `collections.forget_owner`) rewrite `namespace_grants`, `principal_groups`, `namespaces` and `collections` |
-| `auth_attempts` | kind, hashed key and window | Coord | no content |
-| `deployment_config`, `runtime_overrides`, `provider_configuration`, `assistant_service` | as the ClickHouse key | SoR | no content |
-| `instances` | process | Coord | no content |
-| `embedder_calibration`, `namespace_calibration` | as the ClickHouse key, `org` first for `namespace_calibration` | Derived (rebuilt by a recalibration, at embedding cost) | no content |
+| Table | Key | Kind | Erasure |
+| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `authority` | [storage authority](storage-authority.md#the-tables); paired with ClickHouse's `storage_authority` | SoR | no content |
+| `pg_migrations` | the migration file | SoR | no content |
+| `scope_generations` | [storage authority](storage-authority.md#the-tables) | SoR (a namespace's row allocates its revision `seq`) | no content |
+| `cache_generations` | `(org, kind)` | Coord | no content |
+| `memory_current` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.memory_current` |
+| `memory_revisions` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.memory_revisions` |
+| `memory_refusals` | `(org, scope_kind, scope_value, user_id, kind, units, digest)` | SoR, hash-only consent policy committed beside memory; no TTL | no content; retained across erasure |
+| `memory_deliveries` | [storage authority](storage-authority.md#the-tables) | SoR | cascades with its revision |
+| `idempotency`, `idempotency_fences` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.idempotency`; `idempotency_fences` holds no content (the census's bound) |
+| `erased_memories`, `erased_documents` | [storage authority](storage-authority.md#the-tables) | SoR | evidence, no content |
+| `audit_outbox` | [storage authority](storage-authority.md#the-tables) | SoR | keys and ids, no values |
+| `document_catalog`, `document_uploaders` | `(org, namespace, sha256)`, `(org, user_id, namespace, sha256)` | SoR | a `pg:` census row each, owned by the Postgres step the flip splits off the steps that own the census rows of `document_blobs` and `blob_uploads` today, which joins `PG_ONLY_STEPS` (`documents.tombstone`, and the user step through `document_uploaders`) |
+| `knowledge_datasets` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.knowledge_datasets`, step `pg_knowledge.delete` |
+| `knowledge_jobs` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.knowledge_jobs`, step `pg_knowledge.delete` |
+| `mcp_worker_enrollment_challenges` | `(org, nonce)` | SoR | one-time account enrollment challenges of a canonical sign-in owner (`subject`; `user_id` is `-`), erased with the collection or by the owner's deletion (`pg_mcp_worker_enrollment.erase_subject`), never by a user erasure; census `pg:loom.mcp_worker_enrollment_challenges`, namespace step `pg_knowledge.delete` |
+| `mcp_worker_accounts` | `(org, connection_id)` | SoR | opaque connection bindings and revocation generations of a canonical sign-in owner (`subject`; `user_id` is `-`), one collection per connection, erased with the collection or by the owner's deletion (`pg_mcp_worker_enrollment.erase_subject`), never by a user erasure; census `pg:loom.mcp_worker_accounts`, namespace step `pg_knowledge.delete` |
+| `mcp_worker_approvals` | `(org, namespace, worker_id, profile_digest)` | SoR | a collection's allowed modes and approval generations, naming no subject (`user_id` is `-`), erased with the collection; census `pg:loom.mcp_worker_approvals`, namespace step `pg_knowledge.delete` |
+| `mcp_worker_source_readers` | `(org, namespace, source_id, subject)` | SoR | explicit team reader bindings of a canonical sign-in reader (`subject`; `user_id` is `-`), erased with the collection or by the reader's deletion (`pg_mcp_worker_enrollment.erase_subject`), never by a user erasure; census `pg:loom.mcp_worker_source_readers`, namespace step `pg_knowledge.delete` |
+| `knowledge_heads`, `knowledge_deliveries` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.knowledge_heads`, `pg:loom.knowledge_deliveries` |
+| `jobs`, `job_users`, `job_memories` | `(org, id)`, `(org, user_id, job_id)`, `(org, namespace, memory_id, job_id)` | SoR | a census row, a step by namespace and user, a redaction step |
+| `leases`, `write_marks`, `graph_inflight` | `(org, name)`, `(org, namespace, surface)`, `(org, namespace, token)` | Coord | no content |
+| `cursors` | `(org, consumer, scope)` | SoR | no content |
+| `carry_acks` | `process` | Coord | no content |
+| `analysis_secrets` | `id` | SoR | no content |
+| `sql_access` | `(org, namespace, user_name)` | SoR | no content |
+| `cell_self` | singleton | SoR until attach writes its fingerprint to the directory row, then Derived (rewritten from the directory on a restore, [cells](cells.md)) | no content |
+| `tenancy` | `org` | SoR until attach places its org (the first cell's `recording` rows), then Derived (written back from the directory's placements on a restore, never deleted, [cells](cells.md)) | no content; an erasure leaves the org's row |
+| `tenancy_mode` | singleton | Derived (the mode raised only upward from the directory's recorded mode on a restore, [cells](cells.md)) | no content |
+| `cell_first` | singleton | Derived (written when absent and refused when it differs on a restore; written once, its update, delete and truncate refused by triggers, [cells](cells.md)) | no content |
+| `cell_probe` (the probe nonce the `loom cell` commands write, [cells](cells.md)) | `name` | Coord | no content; deleted once the probe has read it |
+| `job_parts` | `(org, job_id, seq)` | SoR | cascades with its job; `code_index.purge` reaches it through the job |
+| `idempotency_revisions` | `(org, key_hash, namespace, seq)` | SoR | cascades with its record; redaction reaches replay answers through it |
+| `revision_relations` | `(org, namespace, seq, ord)` | SoR | census `pg:loom.revision_relations`, step `pg_memory.delete`; cascades with its revision; redaction reaches it through its revision |
+| `revision_sources` | `(org, user_id, namespace, seq)` | SoR | cascades with its revision; the user step deletes the user's rows; the user step and the census reach shared revisions through it |
+| `table_moves`, `move_acks` | `move`, `(move, process)` | SoR, Coord | no content; `table_moves` also holds the registry of kept tables (each kept table's name and scope predicates) |
+| `backfill_steps` | the column, index or check it sets | SoR | no content; the backfill step's completion record, which boots read ([schema rules](#postgres)) |
+| `working_memory`, `records`, `operator_edges`, `context_offloads`, `session_briefs`, `session_brief_revisions`, `namespace_guides`, `learning_candidates`, `learning_supporters`, `conflict_allowlist` | led by `(org, namespace, …)`, the ClickHouse sort key today | SoR | a census row and a saga step each |
+| `conversation_states` | `(org, namespace, agent, thread_id, msg_id)` | SoR | a census row and the `conversations.tombstone` step, by namespace and by the saver's `user_id` |
+| `offload_bytes` | `(org, namespace, offload_id, part)`, its head's id and a part number | SoR | deleted with its head by the `context_offloads` step, and counted by its census row |
+| `shared_current` | `(org, namespace, memory_key)` | SoR | a `pg:` census row and the provenance step `shared` has today, through `revision_sources` |
+| `tasks`, `agent_runs` | `(org, inbox, task_id)`, `(org, namespace, run_id)` | SoR | a `pg:` census row each, owned by the Postgres step the flip splits off the step that owns its ClickHouse table's census row today, which joins `PG_ONLY_STEPS` (`tasks` in the namespace scope, `agent_runs` in both) |
+| `task_inboxes`, `task_poster_policies` | `(org, inbox)`, `(org, inbox, poster, kind)` | SoR | no content |
+| `erased_messages` | `(org, erasure_id, namespace, agent, thread_id, msg_id)` | SoR | evidence, no content; the messages a conversation erasure matched by their saver, which its ClickHouse replay reads, swept with its `erasure_ledger` row |
+| `erasure_ledger` | [storage authority](storage-authority.md#the-tables) | SoR | evidence, no content; Postgres's erasure record, which `loom reconcile` runs again after a ClickHouse restore, swept after `erasure_ledger_days` |
+| `record_schemas`, `namespace_visits`, `extraction_policies`, `namespace_policies`, `namespace_types`, `namespace_ontology`, `profile_schemas`, `user_state`, `webhooks`, `knowledge_sources`, `knowledge_mirrors`, `code_repos`, `qa_sources` | led by `org`, as the ClickHouse key | SoR | no memory content |
+| `knowledge_uploads` | led by `org`, as the ClickHouse key | SoR | a `pg:` census row owned by the Postgres step split off `documents.tombstone` ([restores](#restores)) |
+| `code_coverage_watches` | led by `org`, as the ClickHouse key | SoR | no memory content; reached by the Postgres part of `code_index.purge` ([restores](#restores)) |
+| `revoked_tokens` | `(kind, key)`, kind `subject_or_jti` (the bare key, which holds both today), `cutoff` or `scim` | SoR | no content |
+| `signing_keys`, `service_accounts`, `machine_identities`, `scim_users`, `sso_links`, `principal_groups`, `oauth_state`, `oauth_signin_state`, `namespace_grants`, `namespace_invites`, `namespaces`, `collections`, `blacklist`, `org_model_calls` | as the ClickHouse key, `org` first where the table is per org, except the tables of the cell that [keys lead with `org`](#postgres) names | SoR | no memory content; the identity steps (`grants.revoke`, `groups.remove_member`, `personal.retire`, `collections.forget_owner`) rewrite `namespace_grants`, `namespace_invites`, `principal_groups`, `namespaces` and `collections` |
+| `auth_attempts` | kind, hashed key and window | Coord | no content |
+| `deployment_config`, `runtime_overrides`, `provider_configuration`, `assistant_service` | as the ClickHouse key | SoR | no content |
+| `instances` | process | Coord | no content |
+| `embedder_calibration`, `namespace_calibration` | as the ClickHouse key, `org` first for `namespace_calibration` | Derived (rebuilt by a recalibration, at embedding cost) | no content |
A sweep deletes a `revoked_tokens` row ten days past its stored `expires_at`, as the
ClickHouse TTL does today; a token without `exp`, an operator cutoff and every SCIM
diff --git a/docs/features/dashboard.md b/docs/features/dashboard.md
index b8f7caec7b..06ef9f628b 100644
--- a/docs/features/dashboard.md
+++ b/docs/features/dashboard.md
@@ -125,13 +125,19 @@ On Namespaces in your org, a search for the exact name of a namespace the list d
show offers **Request access**, which is how a private namespace is asked for by name; a
repository's or collection's name points to Repositories or the Library instead. **Invite**
on a namespace you manage opens its members on the add field. The field takes a person's
-login handle, which their account menu shows under **Signed in as** and which may be an
-email, or a service account `sa:`. A collection's **Share** also takes a group
-`group:`, an agent `agent:` or `everyone`. An email that is not a login handle reaches its owner only
-once they sign in with it through single sign-on, or an operator links it to their account.
-Until then the grant is kept as typed and reaches nobody. With sign-in on, **Settings** ›
-**Tokens** links to Namespaces in your org for giving a person access: a token is for a tool,
-agent or script.
+login handle, which their account menu shows under **Signed in as**, an email, or a
+service account `sa:`. A collection's **Share** also takes a group `group:`, an
+agent `agent:` or `everyone`. A login handle no account or live grant holds is
+refused. An email is granted at once only when it is verified for an account; any other
+email gets an [invitation](namespaces-and-sharing.md#membership-and-grants). The add
+shows its link to copy, and the server emails it when it sends mail. The members dialog
+and a repository's Access tab list it under **Invited**, with who made it and **Cancel**,
+while it still admits someone: until it is accepted, cancelled or expired, or its maker no
+longer administers the namespace. Where sign-in is single sign-on only, the email is
+granted instead and reaches that person at their first sign-in. Whoever opens the link
+signed in accepts it on Namespaces in your org, which then switches to the namespace; a
+collection opens in the Library. With sign-in on, **Settings** › **Tokens** links to
+Namespaces in your org for giving a person access: a token is for a tool, agent or script.
The dashboard's text follows the
[copy rules](../development/dashboard-design.md#rules-a-change-is-checked-against): its
diff --git a/docs/features/namespaces-and-sharing.md b/docs/features/namespaces-and-sharing.md
index 1c6df8c43e..d16f865257 100644
--- a/docs/features/namespaces-and-sharing.md
+++ b/docs/features/namespaces-and-sharing.md
@@ -71,18 +71,30 @@ account, or a service account `sa:`) a role on one namespace: `viewer` rea
`writer` writes, `admin` manages grants and settings. The token carries the org and the
namespaces it may reach; the grant table decides the role.
-| Operation | Role | Does |
-| -------------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| `grants.create` | admin | Grant a role. A create below the subject's current role is refused with 409 `GRANT_WOULD_DOWNGRADE` unless `replace=true`. |
-| `grants.list` | viewer | Who has access, at which role, and any `pending_role`. |
-| `grants.revoke` | admin | Remove a grant. |
-| `grants.approve` | admin | Approve or reject a pending request, optionally with a different role. |
-| `grants.pending_for_me` | viewer | Every pending request in the namespaces the caller administers, org-wide. |
-| `namespace.browse` | viewer | Public namespaces in the org, never a collection (`closed` ones only with `include_closed`). |
-| `namespace.join` | viewer | Self-join a public namespace. `viewer` is granted at once; a `writer` or `admin` request always lands pending, with no access until an admin approves. |
-| `namespace.leave`, `namespace.cancel_request`, `namespace.mark_seen` | viewer | Drop one's own grant, withdraw a pending request, acknowledge an invitation. |
-| `namespace.list_mine` | viewer | The namespaces the caller belongs to, each with its `kind` (`collection` for a collection) and `title`. |
-| `namespace.list` | org admin | Every namespace in the org. |
+| Operation | Role | Does |
+| -------------------------------------------------------------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `grants.create` | admin | Grant a role. A create below the subject's current role is refused with 409 `GRANT_WOULD_DOWNGRADE` unless `replace=true`. |
+| `grants.invite` | admin | Give a person a role by login handle or email. An account's handle, or an email verified for one, is granted at once; any other email gets a single-use invitation link, emailed when the server has mail settings, or, where sign-in is single sign-on only, a grant that reaches that person at their first sign-in. A handle no account or live grant holds is refused. |
+| `grants.list_invites`, `grants.cancel_invite` | admin | The open invitations, and withdraw one. |
+| `grants.accept_invite` | a signed-in person | Accept an invitation link: its role goes to the account the caller signs in as. |
+| `grants.list` | viewer | Who has access, at which role, and any `pending_role`. |
+| `grants.revoke` | admin | Remove a grant. |
+| `grants.approve` | admin | Approve or reject a pending request, optionally with a different role. |
+| `grants.pending_for_me` | viewer | Every pending request in the namespaces the caller administers, org-wide. |
+| `namespace.browse` | viewer | Public namespaces in the org, never a collection (`closed` ones only with `include_closed`). |
+| `namespace.join` | viewer | Self-join a public namespace. `viewer` is granted at once; a `writer` or `admin` request always lands pending, with no access until an admin approves. |
+| `namespace.leave`, `namespace.cancel_request`, `namespace.mark_seen` | viewer | Drop one's own grant, withdraw a pending request, record a visit (clears the namespace's new mark). |
+| `namespace.list_mine` | viewer | The namespaces the caller belongs to, each with its `kind` (`collection` for a collection) and `title`. |
+| `namespace.list` | org admin | Every namespace in the org. |
+
+A password account's email is never verified, so a grant by email reaches such an
+account only through an invitation. The link is `/spaces#invite=…` on the dashboard, works
+once, within seven days by default (`LOOM_INVITE_TTL_SECONDS`), and gives its role to
+whoever opens it signed in, under their own login handle, as granted by the admin who made
+it, while that admin still administers the namespace. To have the server email it, set
+`LOOM_SMTP_URL` (`smtps://user:password@host:465`, or `smtp://…:587` with STARTTLS),
+`LOOM_MAIL_FROM` and `LOOM_PUBLIC_BASE_URL`; without them, or when a send fails, the
+dashboard shows the link to copy. The design is in [sharing](../architecture/sharing.md#invitations).
Minting tokens, service accounts, read scopes and restricted namespaces are covered in
the [tokens and grants guide](../guides/tokens-and-grants.md).
diff --git a/docs/getting-started/connect-a-coding-agent.md b/docs/getting-started/connect-a-coding-agent.md
index fe3312e543..b21eb91036 100644
--- a/docs/getting-started/connect-a-coding-agent.md
+++ b/docs/getting-started/connect-a-coding-agent.md
@@ -9,8 +9,11 @@ Loom gives Claude Code, Codex and Cursor shared long-term memory through plugins
tools connected to the same self-hosted server. Invite each teammate to the team's
namespace: **Invite people to this namespace** in the namespace picker, with that namespace
picked, or **Invite** on Namespaces in your org. Each teammate makes their own token, and
-their agents find the facts others save. A teammate without a dashboard account gets a token
-from an operator (`loom mint-token`). Install the plugin or MCP entry below; the next
+their agents find the facts others save. A teammate without an account is invited by email
+and accepts once signed up; where sign-in is single sign-on only, the email is granted and
+reaches them at their first sign-in. Self sign-up makes accounts in `LOOM_SELF_SIGNUP_ORG`
+only, so for a namespace of another org, or where nobody can sign up, an operator makes
+their token (`loom mint-token`). Install the plugin or MCP entry below; the next
session can recall what an agent saved. What the Claude Code and Codex plugins send to
Loom is in [data handling](../features/integrations/claude-code.md#data-handling). Conversation recording
is off by default; the namespace owner turns it on with the **Record conversations**
diff --git a/docs/guides/tokens-and-grants.md b/docs/guides/tokens-and-grants.md
index 3c9f34e25e..d0b0cfec18 100644
--- a/docs/guides/tokens-and-grants.md
+++ b/docs/guides/tokens-and-grants.md
@@ -225,13 +225,17 @@ answer to the user (the entity graph, conversation reads, exports, admin ops) is
namespace above what the token carries. Grants add; where the subject holds one, a
token's claim goes no further than it.
-| Op | Role | Does |
-| ----------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------ |
-| `grants.create` | admin | Give `subject` a `role`. Below the subject's current role it answers 409 `GRANT_WOULD_DOWNGRADE` unless `replace: true`. |
-| `grants.revoke` | admin | Remove it; on a restricted namespace the grants of tokens the subject minted there go too. |
-| `grants.list` | viewer | The namespace's grants. |
-| `grants.approve` | admin | Activate a pending join request. Below the subject's current grant it answers 409: an approval never asks to lower one. |
-| `grants.pending_for_me` | viewer | Requests waiting on the caller's approval. |
+| Op | Role | Does |
+| ----------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `grants.create` | admin | Give `subject` a `role`. Below the subject's current role it answers 409 `GRANT_WOULD_DOWNGRADE` unless `replace: true`. |
+| `grants.invite` | admin | Give a person a `role` by login handle or email: an account's handle or verified email is granted at once, any other email gets a single-use invitation link, or, where sign-in is single sign-on only, a grant as typed. A handle no account or live grant holds is refused (404). |
+| `grants.accept_invite` | a signed-in person | Accept an invitation link; its role goes to the account the caller signs in as. |
+| `grants.list_invites` | admin | The open invitations: each link that still admits someone. |
+| `grants.cancel_invite` | admin | Withdraw an open invitation. |
+| `grants.revoke` | admin | Remove it; on a restricted namespace the grants of tokens the subject minted there go too. |
+| `grants.list` | viewer | The namespace's grants. |
+| `grants.approve` | admin | Activate a pending join request. Below the subject's current grant it answers 409: an approval never asks to lower one. |
+| `grants.pending_for_me` | viewer | Requests waiting on the caller's approval. |
```bash
curl -s "$LOOM_BASE_URL/v1/grants.create" -H "Authorization: Bearer $ADMIN_TOKEN" \
@@ -253,11 +257,14 @@ curl -s "$LOOM_BASE_URL/v1/grants.create" -H "Authorization: Bearer $ADMIN_TOKEN
owner proving the password from an SSO sign-in). A self-signup email is not: whoever
typed the address first does not hold the grants written under it, which still cap
that account's claims. Grant a self-signup account under its login handle, the namespace
- it signed up with. A `grants.revoke` of an address no verified account holds, and that
- never held a row of its own on the namespace, takes the rows stored under each
- unverified account naming it, and the grants there of the tokens those accounts made.
- When the address held a row of its own there, its revoke also takes the grants of the
- tokens those accounts made there, unless one still holds an active grant of its own.
+ it signed up with, or invite its email with `grants.invite`, whose link the person
+ accepts signed in
+ ([invitations](../features/namespaces-and-sharing.md#membership-and-grants)). A
+ `grants.revoke` of an address no verified account holds, and that never held a row of
+ its own on the namespace, takes the rows stored under each unverified account naming it,
+ and the grants there of the tokens those accounts made. When the address held a row of
+ its own there, its revoke also takes the grants of the tokens those accounts made there,
+ unless one still holds an active grant of its own.
- **Registering is owning.** `namespace.register` makes the caller the namespace's `admin`.
With self-signup (`LOOM_IDENTITY_PROVIDER=trust-network`) the first principal to claim a
name owns it; `loom claim-release --org --namespace ` revokes its grants,
diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md
index cf8c6abdbf..1cec61f353 100644
--- a/docs/reference/configuration.md
+++ b/docs/reference/configuration.md
@@ -137,6 +137,10 @@ Authentication, tokens and identity providers.
| `LOOM_WORKLOAD_EXCHANGES_PER_AGENT` | `int` | `300` | | Workload-token exchanges one agent of a trust (a token with an agent claim) may make in 10 minutes, so one agent's loop cannot spend the trust's. A trust without agents has only `workload_exchanges_per_trust`. |
| `LOOM_SELF_SIGNUP` | `'off' \| 'open'` | `'off'` | | Browser self-signup: "off" (endpoint 404s) or "open" (/v1/auth/self-signup mints JWTs scoped to the requested namespace). A non-loopback bind refuses "open" unless identity_provider is "trust-network", allow_insecure is set, or oauth_login_provider is "oidc" (which closes sign-up). |
| `LOOM_SELF_SIGNUP_ORG` | `str` | `'dev'` | | Default org for self-signed tokens. |
+| `LOOM_SMTP_URL` | `str` | *(unset)* | | The mail server invitations go through: `smtps://user:password@host:465`, or `smtp://` on 587, which must offer STARTTLS. Empty: no email, and the inviter passes the link on. |
+| `LOOM_MAIL_FROM` | `str` | `''` | | The From address of an invitation email, e.g. `Loom `. Empty sends none, as does an empty smtp_url or public_base_url (the link needs it). |
+| `LOOM_SMTP_TIMEOUT_SECONDS` | `float` | `10.0` | | Seconds each step of an invitation email may wait on the mail server; past it the email is reported not sent and the link is shown to pass on. |
+| `LOOM_INVITE_TTL_SECONDS` | `int` | `604800` | | Seconds an invitation link stays valid, at most 30 days: it admits whoever opens it. |
| `LOOM_IDENTITY_PROVIDER` | `'' \| 'single-user' \| 'trust-network' \| 'gateway'` | `''` | | How callers authenticate: "single-user" (no auth, one anonymous identity), "trust-network" (self-signup, first claim wins) or "gateway" (an upstream proxy mints short-lived Loom JWTs with the shared HS256 secret; Loom only validates). Empty = inferred from auth_required and self_signup at boot. |
| `LOOM_DASHBOARD_REDIRECT_URL` | `str` | `''` | | When set, a dashboard page load redirects (302) here instead of serving the SPA (Loom behind an aggregator). Deployment-specific; never hardcode. |
| `LOOM_TRUSTED_CALLERS` | `str` | `''` | | Comma-separated subjects allowed to send `X-Loom-On-Behalf-Of` (a trusted aggregator passing each end-user's identity under one service token). Empty disables the header. |
diff --git a/docs/reference/operations.md b/docs/reference/operations.md
index bb796e5306..450b9eff73 100644
--- a/docs/reference/operations.md
+++ b/docs/reference/operations.md
@@ -124,7 +124,7 @@ python scripts/codegen/docs_reference.py --check # exit 1 when a region is stal
-389 operations in 43 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores).
+393 operations in 43 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores).
Columns: **Role** is the minimum role (`viewer` < `writer` < `admin` < `org_admin` < `platform_admin`); **Kind** is `read` (idempotent, viewer, unaudited, writes nothing — MCP `readOnlyHint`), `idempotent` (safe to retry) or `write`; **Listed under `all`** says whether an MCP connection on the `all` toolset lists the op in `tools/list` (`code.*` ops only with `LOOM_MCP_CODE_TOOLS=true`); an op marked `no` is still callable by name or through `loom_op`, unless it is hidden from MCP; **Audit** marks ops that leave an `audit_log` row.
@@ -376,9 +376,13 @@ Fields for every `grants` op: [operations/grants.md](operations/grants.md).
| Operation | Summary | Role | Kind | Listed under `all` | Audit |
| --- | --- | --- | --- | --- | --- |
+| [`grants.accept_invite`](operations/grants.md#grantsaccept_invite) | Accept an invitation link as the signed-in person. | viewer | write | no | yes |
| [`grants.approve`](operations/grants.md#grantsapprove) | Approve (or reject) a pending grant request. | admin | idempotent | no | yes |
+| [`grants.cancel_invite`](operations/grants.md#grantscancel_invite) | Cancel an open invitation, so its link admits nobody. | admin | idempotent | no | yes |
| [`grants.create`](operations/grants.md#grantscreate) | Grant another subject (user or service-account) viewer / writer / admin role on a namespace. | admin | idempotent | yes | yes |
+| [`grants.invite`](operations/grants.md#grantsinvite) | Give a person a role on a namespace by login handle or email. | admin | write | no | yes |
| [`grants.list`](operations/grants.md#grantslist) | List active grants on a namespace — who has access, at which role. | viewer | read | yes | |
+| [`grants.list_invites`](operations/grants.md#grantslist_invites) | List a namespace's open invitations. | admin | idempotent | no | |
| [`grants.pending_for_me`](operations/grants.md#grantspending_for_me) | Every pending request in the namespaces the caller administers, in one statement. | viewer | read | no | |
| [`grants.revoke`](operations/grants.md#grantsrevoke) | Remove a subject's grant on a namespace. | admin | idempotent | no | yes |
| [`grants.share_agent`](operations/grants.md#grantsshare_agent) | Let another agent of the caller's trust read, or write, the caller's own namespace. | writer | idempotent | no | yes |
@@ -607,7 +611,7 @@ Fields for every `namespace` op: [operations/namespace.md](operations/namespace.
| [`namespace.list_categories`](operations/namespace.md#namespacelist_categories) | Enumerate registered categories with item counts. | viewer | read | no | |
| [`namespace.list_mine`](operations/namespace.md#namespacelist_mine) | List namespaces the caller is a member of (own + granted). | viewer | read | yes | |
| [`namespace.list_ontology`](operations/namespace.md#namespacelist_ontology) | List the ontology terms (entity and relation kinds) registered for a namespace. | viewer | read | no | |
-| [`namespace.mark_seen`](operations/namespace.md#namespacemark_seen) | Acknowledge a new-invitation indicator on a namespace. | viewer | idempotent | no | |
+| [`namespace.mark_seen`](operations/namespace.md#namespacemark_seen) | Record a visit to a namespace, clearing its new mark. | viewer | idempotent | no | |
| [`namespace.register`](operations/namespace.md#namespaceregister) | Create a shared memory workspace within an org; caller becomes admin. | viewer | idempotent | yes | yes |
| [`namespace.register_category`](operations/namespace.md#namespaceregister_category) | Register a category in a namespace. | writer | write | no | yes |
| [`namespace.register_ontology`](operations/namespace.md#namespaceregister_ontology) | Register an entity type or relation verb for a namespace. | admin | idempotent | yes | yes |
diff --git a/docs/reference/operations/grants.md b/docs/reference/operations/grants.md
index 52365d7121..9bb2c4b5cf 100644
--- a/docs/reference/operations/grants.md
+++ b/docs/reference/operations/grants.md
@@ -8,6 +8,23 @@ Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity
+## `grants.accept_invite`
+
+Accept an invitation link as the signed-in person.
+
+`POST /v1/grants.accept_invite` · MCP `loom_grants_accept_invite` · role `viewer` · write · audited · not listed under the MCP `all` toolset
+
+| Input field | Type | Default | Meaning |
+| --- | --- | --- | --- |
+| `org` | `str` | required | The tenant (first element of the identity tuple). |
+| `namespace` | `str` | required | The namespace the link names. |
+| `secret` | `str` | required | The secret from the link's fragment. |
+
+| Output field | Type | Meaning |
+| --- | --- | --- |
+| `namespace` | `str` | The namespace the op reads or writes. |
+| `role` | `Literal['viewer', 'writer', 'admin']` | The caller's role on the namespace now: the invitation's, or a higher one they held. |
+
## `grants.approve`
Approve (or reject) a pending grant request.
@@ -30,6 +47,22 @@ Approve (or reject) a pending grant request.
| `role` | `Literal['viewer', 'writer', 'admin'] \| None` | The role approved (for `reject`, the role the request would have had); None when no grant row existed for the subject. |
| `decided_at` | `datetime` | When the decision was written (UTC). |
+## `grants.cancel_invite`
+
+Cancel an open invitation, so its link admits nobody.
+
+`POST /v1/grants.cancel_invite` · MCP `loom_grants_cancel_invite` · role `admin` · idempotent · audited · not listed under the MCP `all` toolset
+
+| Input field | Type | Default | Meaning |
+| --- | --- | --- | --- |
+| `org` | `str` | required | The tenant (first element of the identity tuple). |
+| `namespace` | `str` | required | The namespace the op reads or writes. |
+| `invite_id` | `str` | required | The invitation, as grants.invite and grants.list_invites return it. |
+
+| Output field | Type | Meaning |
+| --- | --- | --- |
+| `cancelled` | `bool` | True when an open invitation was cancelled; false when none was open under the id. |
+
## `grants.create`
Grant another subject (user or service-account) viewer / writer / admin role on a namespace.
@@ -53,6 +86,30 @@ Grant another subject (user or service-account) viewer / writer / admin role on
| `role` | `Literal['viewer', 'writer', 'admin']` | The role now active for the subject. |
| `granted_at` | `datetime` | When the grant row was written (UTC). |
+## `grants.invite`
+
+Give a person a role on a namespace by login handle or email.
+
+`POST /v1/grants.invite` · MCP `loom_grants_invite` · role `admin` · write · audited · not listed under the MCP `all` toolset
+
+| Input field | Type | Default | Meaning |
+| --- | --- | --- | --- |
+| `org` | `str` | required | The tenant (first element of the identity tuple). |
+| `namespace` | `str` | required | The namespace the op reads or writes. |
+| `to` | `str` | required | The person to give `role`: a login handle an account or live grant holds (any other is refused), or an email, granted at once when verified for an account or under single sign-on only, and otherwise sent an invitation link. |
+| `role` | `Literal['viewer', 'writer', 'admin']` | required | `viewer`, `writer` or `admin`; a code namespace takes only `viewer` and `admin`. |
+
+| Output field | Type | Meaning |
+| --- | --- | --- |
+| `outcome` | `Literal['granted', 'invited']` | "granted": the grant is written under `subject`; "invited": no account holds the email, and `link_path` opens the invitation. |
+| `role` | `Literal['viewer', 'writer', 'admin']` | The role given, as asked. |
+| `subject` | `str` | On "granted", the subject the grant is written under: the person's handle as stored (an account's, or a grant's), or, where sign-in is single sign-on only or the request has no token, `to` as typed. |
+| `invite_id` | `str` | On "invited": the invitation, for grants.cancel_invite. |
+| `link_path` | `str` | On "invited": the dashboard path that accepts it, its secret in the fragment. |
+| `url` | `str` | `link_path` on the server's public_base_url; "" when that is unset. |
+| `expires_at` | `datetime \| None` | On "invited": when the link stops working (UTC), `invite_ttl_seconds` after it was made. |
+| `emailed` | `bool` | On "invited": the link was emailed to `to` (the server has mail settings). |
+
## `grants.list`
List active grants on a namespace — who has access, at which role.
@@ -73,6 +130,21 @@ List active grants on a namespace — who has access, at which role.
| `next_cursor` | `str \| None` | Pass as `cursor` for the next page; None when this page is the last. |
| `truncated` | `bool` | True when more people follow this page (`next_cursor` is set). |
+## `grants.list_invites`
+
+List a namespace's open invitations.
+
+`POST /v1/grants.list_invites` · MCP `loom_grants_list_invites` · role `admin` · idempotent · not listed under the MCP `all` toolset
+
+| Input field | Type | Default | Meaning |
+| --- | --- | --- | --- |
+| `org` | `str` | required | The tenant (first element of the identity tuple). |
+| `namespace` | `str` | required | The namespace the op reads or writes. |
+
+| Output field | Type | Meaning |
+| --- | --- | --- |
+| `rows` | `list[_InviteEntry]` | The namespace's open links that still admit someone (not accepted, cancelled or expired, and with a maker who still stands), newest first; at most 200. |
+
## `grants.pending_for_me`
Every pending request in the namespaces the caller administers, in one statement.
diff --git a/docs/reference/operations/namespace.md b/docs/reference/operations/namespace.md
index 83a2ee29ec..f0e112310b 100644
--- a/docs/reference/operations/namespace.md
+++ b/docs/reference/operations/namespace.md
@@ -330,7 +330,7 @@ List the ontology terms (entity and relation kinds) registered for a namespace.
## `namespace.mark_seen`
-Acknowledge a new-invitation indicator on a namespace.
+Record a visit to a namespace, clearing its new mark.
`POST /v1/namespace.mark_seen` · MCP `loom_namespace_mark_seen` · role `viewer` · idempotent · not listed under the MCP `all` toolset
diff --git a/docs/reference/schema.md b/docs/reference/schema.md
index 60356c1f34..d8eddf35dc 100644
--- a/docs/reference/schema.md
+++ b/docs/reference/schema.md
@@ -142,7 +142,7 @@ the `loom` tables each view reads, and, for each materialized view, its target,
-198 tables, 5 views and 19 materialized views in the `loom` and `loom_telemetry` databases; a `loom_telemetry` object keeps its database prefix.
+199 tables, 5 views and 19 materialized views in the `loom` and `loom_telemetry` databases; a `loom_telemetry` object keeps its database prefix.
#### Tables
@@ -291,6 +291,7 @@ the `loom` tables each view reads, and, for each materialized view, its target,
| `namespace_calibration_result` | `ReplacingMergeTree(version)` | `(org, namespace)` | | | |
| `namespace_grants` | `ReplacingMergeTree(version)` | `(org, namespace, subject)` | `org` | | |
| `namespace_guides` | `MergeTree` | `(org, namespace, revision)` | | | |
+| `namespace_invites` | `ReplacingMergeTree(version)` | `(org, namespace, invite_id)` | | `toDateTime(expires_at) + toIntervalDay(7)` | |
| `namespace_ontology` | `ReplacingMergeTree(version)` | `(org, namespace, kind, name)` | `org` | | |
| `namespace_policies` | `ReplacingMergeTree(version)` | `(org, namespace, policy_id)` | | | |
| `namespace_snapshots` | `MergeTree` | `(org, source_namespace, created_at)` | `org` | | |
diff --git a/docs/reference/status.md b/docs/reference/status.md
index 21be16d80c..2036c8d72e 100644
--- a/docs/reference/status.md
+++ b/docs/reference/status.md
@@ -25,7 +25,7 @@ serves is in the [MCP reference](./mcp.md#toolsets).
-389 operations, 275 of them experimental.
+393 operations, 279 of them experimental.
| Group | Stable | Experimental |
| --- | --- | --- |
@@ -47,7 +47,7 @@ serves is in the [MCP reference](./mcp.md#toolsets).
| `erasure` | 2 | [`erasure.list`](operations/erasure.md#erasurelist), [`erasure.status`](operations/erasure.md#erasurestatus) |
| `extraction_policy` | 0 | [`extraction_policy.clear`](operations/extraction_policy.md#extraction_policyclear), [`extraction_policy.get`](operations/extraction_policy.md#extraction_policyget), [`extraction_policy.set`](operations/extraction_policy.md#extraction_policyset) |
| `facts` | 2 | [`facts.expire_by_adapter`](operations/facts.md#factsexpire_by_adapter), [`facts.path`](operations/facts.md#factspath), [`facts.related`](operations/facts.md#factsrelated) |
-| `grants` | 2 | [`grants.approve`](operations/grants.md#grantsapprove), [`grants.pending_for_me`](operations/grants.md#grantspending_for_me), [`grants.revoke`](operations/grants.md#grantsrevoke), [`grants.share_agent`](operations/grants.md#grantsshare_agent), [`grants.unshare_agent`](operations/grants.md#grantsunshare_agent) |
+| `grants` | 2 | [`grants.accept_invite`](operations/grants.md#grantsaccept_invite), [`grants.approve`](operations/grants.md#grantsapprove), [`grants.cancel_invite`](operations/grants.md#grantscancel_invite), [`grants.invite`](operations/grants.md#grantsinvite), [`grants.list_invites`](operations/grants.md#grantslist_invites), [`grants.pending_for_me`](operations/grants.md#grantspending_for_me), [`grants.revoke`](operations/grants.md#grantsrevoke), [`grants.share_agent`](operations/grants.md#grantsshare_agent), [`grants.unshare_agent`](operations/grants.md#grantsunshare_agent) |
| `help` | 0 | [`help.get`](operations/help.md#helpget), [`help.search`](operations/help.md#helpsearch) |
| `inbox` | 0 | [`inbox.list`](operations/inbox.md#inboxlist), [`inbox.policy_list`](operations/inbox.md#inboxpolicy_list), [`inbox.policy_set`](operations/inbox.md#inboxpolicy_set), [`inbox.principals`](operations/inbox.md#inboxprincipals), [`inbox.register`](operations/inbox.md#inboxregister) |
| `insights` | 0 | [`insights.catalog`](operations/insights.md#insightscatalog), [`insights.query`](operations/insights.md#insightsquery) |
diff --git a/frontend/src/api/invites.ts b/frontend/src/api/invites.ts
new file mode 100644
index 0000000000..07cecd6091
--- /dev/null
+++ b/frontend/src/api/invites.ts
@@ -0,0 +1,58 @@
+// Inviting a person to a namespace: by a login handle or verified email they are granted at
+// once; by any other email they get a single-use link, emailed when the server can send mail.
+// Wire shapes mirror server/identity/api/models_grants.py.
+import { post } from "../api";
+import type { GrantRole, Identity } from "../api";
+
+type Scope = Pick;
+
+export interface InviteResult {
+ outcome: "granted" | "invited";
+ role: GrantRole;
+ /** The subject granted, for `granted`. */
+ subject: string;
+ invite_id: string;
+ /** `/spaces#invite=&org=…&namespace=…`, for `invited`: the link without the server's address. */
+ link_path: string;
+ /** The whole link, when the server knows its public address. */
+ url: string;
+ expires_at: string | null;
+ emailed: boolean;
+}
+
+export interface OpenInvite {
+ invite_id: string;
+ email: string;
+ role: GrantRole;
+ created_by: string;
+ created_at: string;
+ expires_at: string;
+}
+
+export function invite(id: Scope, to: string, role: GrantRole): Promise {
+ return post("/v1/grants.invite", { org: id.org, namespace: id.namespace, to, role });
+}
+
+export function listInvites(id: Scope): Promise<{ rows: OpenInvite[] }> {
+ return post("/v1/grants.list_invites", { org: id.org, namespace: id.namespace });
+}
+
+export function cancelInvite(id: Scope, inviteId: string): Promise<{ cancelled: boolean }> {
+ return post("/v1/grants.cancel_invite", { org: id.org, namespace: id.namespace, invite_id: inviteId });
+}
+
+export function acceptInvite(id: Scope, secret: string): Promise<{ namespace: string; role: GrantRole }> {
+ return post("/v1/grants.accept_invite", { org: id.org, namespace: id.namespace, secret });
+}
+
+/** The link to hand over: the server's own address when it knows it, else this page's. */
+export function inviteLink(r: Pick): string {
+ return r.url || `${window.location.origin}${r.link_path}`;
+}
+
+/** A person's spelling, which `grants.invite` takes; a service account, a grant principal or
+ * everyone goes to `grants.create`, as the server's `has_aliases` and `is_reserved_subject` say. */
+export function isPersonSpelling(subject: string): boolean {
+ const last = subject.toLowerCase().split("/").pop() ?? "";
+ return subject !== "*" && last !== "everyone" && !/^(sa|user|group|agent):/.test(last);
+}
diff --git a/frontend/src/components/Invitations.test.tsx b/frontend/src/components/Invitations.test.tsx
new file mode 100644
index 0000000000..659d6899f1
--- /dev/null
+++ b/frontend/src/components/Invitations.test.tsx
@@ -0,0 +1,83 @@
+import { cleanup, render, screen, waitFor } from "../test/rtl";
+import userEvent from "@testing-library/user-event";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cancelInvite, isPersonSpelling, listInvites } from "../api/invites";
+import { ApiError } from "../lib/errors";
+import { InviteSent, OpenInvitations } from "./Invitations";
+
+vi.mock("../api/invites", async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, listInvites: vi.fn(), cancelInvite: vi.fn(async () => ({ cancelled: true })) };
+});
+afterEach(() => cleanup());
+
+const sent = {
+ outcome: "invited" as const,
+ role: "writer" as const,
+ subject: "",
+ invite_id: "abc",
+ link_path: "/spaces#invite=s3cret&org=dev&namespace=team",
+ url: "",
+ expires_at: "2026-12-11T12:00:00Z",
+ emailed: false,
+};
+
+describe("InviteSent", () => {
+ it("hands over the link on this page's address when the server knows none", () => {
+ render();
+ expect(screen.getByRole("status")).toHaveTextContent("No account in this org has verified pat@example.com.");
+ expect(
+ screen.getByText(`${window.location.origin}/spaces#invite=s3cret&org=dev&namespace=team`),
+ ).toBeInTheDocument();
+ });
+
+ it("says it was emailed, and still shows the server's link", () => {
+ render(
+ ,
+ );
+ expect(screen.getByRole("status")).toHaveTextContent("Emailed an invitation to pat@example.com.");
+ expect(screen.getByText("https://loom.example.com/spaces#x")).toBeInTheDocument();
+ });
+});
+
+const open = {
+ invite_id: "abc",
+ email: "pat@example.com",
+ role: "writer" as const,
+ created_by: "ann",
+ created_at: "2026-12-04T12:00:00Z",
+ expires_at: "2026-12-11T12:00:00Z",
+};
+
+describe("OpenInvitations", () => {
+ it("lists the open invitations and cancels one", async () => {
+ vi.mocked(listInvites).mockResolvedValue({ rows: [open] });
+ const user = userEvent.setup();
+ render();
+ await user.click(await screen.findByRole("button", { name: "Cancel the invitation to pat@example.com" }));
+ expect(cancelInvite).toHaveBeenCalledWith({ org: "dev", namespace: "team" }, "abc");
+ await waitFor(() => expect(screen.queryByRole("region", { name: "Open invitations" })).toBeNull());
+ });
+
+ it("says a failed read failed, not that there are none, and reads again on Retry", async () => {
+ vi.mocked(listInvites)
+ .mockRejectedValueOnce(new ApiError({ status: 503, code: "BACKEND_UNAVAILABLE", message: "grants unreadable" }))
+ .mockResolvedValueOnce({ rows: [{ ...open, email: "lee@example.com" }] });
+ const user = userEvent.setup();
+ render();
+ expect(await screen.findByRole("alert")).toHaveTextContent("Couldn't load the invitations: grants unreadable");
+ await user.click(screen.getByRole("button", { name: "Retry loading the invitations" }));
+ expect(await screen.findByText("lee@example.com")).toBeInTheDocument();
+ });
+});
+
+describe("isPersonSpelling", () => {
+ it("tells a person from a principal", () => {
+ for (const s of ["robin", "pat@example.com", "Pat"]) expect(isPersonSpelling(s)).toBe(true);
+ for (const s of ["sa:bot", "group:eng", "user:42", "agent:x", "everyone", "Everyone", "*", "acme/user:1"])
+ expect(isPersonSpelling(s)).toBe(false);
+ });
+});
diff --git a/frontend/src/components/Invitations.tsx b/frontend/src/components/Invitations.tsx
new file mode 100644
index 0000000000..42bdf7b2ea
--- /dev/null
+++ b/frontend/src/components/Invitations.tsx
@@ -0,0 +1,105 @@
+import { useEffect, useState } from "react";
+import { Button } from "@clickhouse/click-ui/Button";
+import { cancelInvite, inviteLink, listInvites, type InviteResult, type OpenInvite } from "../api/invites";
+import { errorLine } from "../lib/errorWords";
+import { absoluteTime, fmtInt } from "../lib/format";
+import { CopyButton } from "./CopyButton";
+import { toastError } from "./Toast";
+
+type Scope = { org: string; namespace: string };
+
+/** What an invitation by email did: the link, and whether the server emailed it. */
+export function InviteSent({ email, result }: { email: string; result: InviteResult }) {
+ const link = inviteLink(result);
+ return (
+
+
+ {result.emailed
+ ? `Emailed an invitation to ${email}. You can also send them this link:`
+ : `No account in this org has verified ${email}. Send them this link:`}
+
+
+ {link}
+
+
+
+ It works once, until {absoluteTime(result.expires_at)}: whoever opens it signed in gets the role, under the
+ account they sign in with.
+
+
+ );
+}
+
+/** The namespace's open invitations, each with Cancel; nothing while there are none, and a
+ * failed read with Retry. `version` changes to read them again after an invitation is made. */
+export function OpenInvitations({ scope, version }: { scope: Scope; version: number }) {
+ const [rows, setRows] = useState([]);
+ const [error, setError] = useState(null);
+ const [reads, setReads] = useState(0);
+ const [busy, setBusy] = useState(null);
+ useEffect(() => {
+ let live = true;
+ listInvites(scope)
+ .then((r) => {
+ if (!live) return;
+ setRows(r.rows);
+ setError(null);
+ })
+ .catch((e: unknown) => live && setError(errorLine(e, { read: true })));
+ return () => {
+ live = false;
+ };
+ }, [scope.org, scope.namespace, version, reads]);
+ // A line, not a second error state: the dialog's own list says it failed too in an outage.
+ if (error !== null && rows.length === 0) {
+ return (
+
+ {r.email}
+ {`${r.role}, by ${r.created_by}, until ${absoluteTime(r.expires_at)}`}
+
+
+ ))}
+
+
+ );
+}
diff --git a/frontend/src/components/SubjectHelp.tsx b/frontend/src/components/SubjectHelp.tsx
index ba0e03d98a..9cb14525bc 100644
--- a/frontend/src/components/SubjectHelp.tsx
+++ b/frontend/src/components/SubjectHelp.tsx
@@ -1,12 +1,12 @@
-/** What a spelling in an add field reaches: a namespace's members and a repository's readers
- * take the same subjects through `grants.create`, and a collection also takes a group, an agent
- * and everyone. */
+/** What a spelling in an add field reaches: a person through `grants.invite`, the others
+ * through `grants.create`; a collection also takes a group, an agent and everyone. */
export function SubjectHelp({ id, collection = false }: { id: string; collection?: boolean }) {
return (
- A login handle is the name a person signs in with, shown in their account menu under Signed in as; it may be an
- email. Any other email reaches them only once they sign in with it through single sign-on, or an operator links it
- to their account. A service account is sa:<name>
+ A login handle is the name a person signs in with, shown in their account menu under Signed in as. An email is
+ granted at once only when it is verified for an account; any other email gets an invitation link, emailed too when
+ this server sends mail, and whoever opens it signed in joins. Where sign-in is single sign-on only, the email is
+ granted instead. A service account is sa:<name>
{collection ? (
<>
, a group group:<id>, an agent{" "}
diff --git a/frontend/src/flows/MembersDialog.fanout.test.tsx b/frontend/src/flows/MembersDialog.fanout.test.tsx
index ddee88f32b..c31172f0e9 100644
--- a/frontend/src/flows/MembersDialog.fanout.test.tsx
+++ b/frontend/src/flows/MembersDialog.fanout.test.tsx
@@ -6,9 +6,23 @@ import { render, screen, fireEvent, waitFor } from "../test/rtl";
import { MembersDialog } from "./MembersDialog";
import { useStore } from "../lib/state";
import * as api from "../api";
+import * as invites from "../api/invites";
import { ApiError } from "../lib/errors";
import { ToastViewport } from "../components/Toast";
+vi.mock("../api/invites", async (importOriginal) => ({
+ ...(await importOriginal()),
+ invite: vi.fn(async (_id: unknown, subject: string, role: string) => ({
+ outcome: "granted" as const,
+ role,
+ subject,
+ invite_id: "",
+ link_path: "",
+ url: "",
+ expires_at: null,
+ emailed: false,
+ })),
+}));
vi.mock("../api", async (importOriginal) => {
const actual = await importOriginal();
return {
@@ -41,6 +55,7 @@ const elsewhere = {
beforeEach(() => {
vi.mocked(api.approveGrant).mockClear();
vi.mocked(api.createGrant).mockClear();
+ vi.mocked(invites.invite).mockClear();
useStore.setState({
whoami: { authenticated: true, subject: "alice", org: "clickhouse", roles: ["ADMIN"] },
});
@@ -113,9 +128,9 @@ describe("MembersDialog approves a requester on every waiting branch at once", (
expect(screen.getByRole("button", { name: "Role for the new reader" })).toHaveTextContent("Reader");
fireEvent.change(screen.getByRole("textbox", { name: /reader to add/ }), { target: { value: subject } });
fireEvent.click(screen.getByRole("button", { name: /^Add$/ }));
- await waitFor(() => expect(api.createGrant).toHaveBeenCalledTimes(n));
+ await waitFor(() => expect(invites.invite).toHaveBeenCalledTimes(n));
}
- expect(vi.mocked(api.createGrant).mock.calls.map((c) => [c[1], c[2]])).toEqual([
+ expect(vi.mocked(invites.invite).mock.calls.map((c) => [c[1], c[2]])).toEqual([
["reader-a", "viewer"],
["reader-b", "viewer"],
]);
diff --git a/frontend/src/flows/MembersDialog.invite.test.tsx b/frontend/src/flows/MembersDialog.invite.test.tsx
new file mode 100644
index 0000000000..b7fca49c84
--- /dev/null
+++ b/frontend/src/flows/MembersDialog.invite.test.tsx
@@ -0,0 +1,97 @@
+import { cleanup, render, screen, waitFor, within } from "../test/rtl";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import * as api from "../api";
+import * as invites from "../api/invites";
+import { toast } from "../components/Toast";
+import { useStore } from "../lib/state";
+import { MembersDialog } from "./MembersDialog";
+
+// A person is added through grants.invite: an account is granted at once; any other email
+// gets a link the dialog shows to copy and lists as open. A service account goes through
+// grants.create as typed.
+
+vi.mock("../api", async (importOriginal) => ({
+ ...(await importOriginal()),
+ listGrants: vi.fn(async () => ({ rows: [] })),
+ createGrant: vi.fn(async () => ({})),
+}));
+vi.mock("../components/Toast", async (importOriginal) => ({
+ ...(await importOriginal()),
+ toast: vi.fn(),
+}));
+vi.mock("../api/invites", async (importOriginal) => ({
+ ...(await importOriginal()),
+ invite: vi.fn(),
+ listInvites: vi.fn(async () => ({ rows: [] })),
+}));
+
+const invited = {
+ outcome: "invited" as const,
+ role: "writer" as const,
+ subject: "",
+ invite_id: "abc",
+ link_path: "/spaces#invite=s3cret&org=dev&namespace=team",
+ url: "https://loom.example.com/spaces#invite=s3cret&org=dev&namespace=team",
+ expires_at: "2026-12-11T12:00:00Z",
+ emailed: true,
+};
+
+beforeEach(() => {
+ vi.mocked(api.createGrant).mockClear();
+ vi.mocked(invites.invite).mockReset();
+ useStore.setState({ whoami: { authenticated: true, subject: "ann", org: "dev", roles: ["ADMIN"] } });
+});
+afterEach(() => cleanup());
+
+async function add(subject: string) {
+ const user = userEvent.setup();
+ render( {}} org="dev" namespace="team" kind="memory" />);
+ await user.click((await screen.findAllByRole("button", { name: /Add member/ }))[0]);
+ await user.type(await screen.findByRole("textbox", { name: /member to add/ }), `${subject}{Enter}`);
+}
+
+describe("MembersDialog invites a person", () => {
+ it("shows an email's invitation link and lists it as open", async () => {
+ vi.mocked(invites.invite).mockResolvedValue(invited);
+ vi.mocked(invites.listInvites)
+ .mockResolvedValueOnce({ rows: [] })
+ .mockResolvedValue({
+ rows: [
+ {
+ invite_id: "abc",
+ email: "pat@example.com",
+ role: "writer",
+ created_by: "ann",
+ created_at: "2026-12-04T12:00:00Z",
+ expires_at: "2026-12-11T12:00:00Z",
+ },
+ ],
+ });
+ await add("pat@example.com");
+ expect(invites.invite).toHaveBeenCalledWith({ org: "dev", namespace: "team" }, "pat@example.com", "writer");
+ const status = await screen.findByRole("status");
+ expect(status).toHaveTextContent("Emailed an invitation to pat@example.com.");
+ expect(within(status).getByText(invited.url)).toBeInTheDocument();
+ const open = await screen.findByRole("region", { name: "Open invitations" });
+ expect(open).toHaveTextContent("pat@example.com");
+ expect(api.createGrant).not.toHaveBeenCalled();
+ });
+
+ it("grants an account's handle at once, under the subject the server names", async () => {
+ vi.mocked(invites.invite).mockResolvedValue({ ...invited, outcome: "granted", subject: "robin", invite_id: "" });
+ await add("Robin");
+ await waitFor(() => expect(toast).toHaveBeenCalledWith("Added robin as writer", "ok"));
+ expect(invites.invite).toHaveBeenCalledTimes(1);
+ expect(screen.queryByRole("status")).toBeNull();
+ expect(screen.queryByRole("textbox", { name: /member to add/ })).toBeNull();
+ });
+
+ it("grants a service account through grants.create, as typed", async () => {
+ await add("sa:triage");
+ await waitFor(() =>
+ expect(api.createGrant).toHaveBeenCalledWith({ org: "dev", namespace: "team" }, "sa:triage", "writer"),
+ );
+ expect(invites.invite).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/flows/MembersDialog.loading.test.tsx b/frontend/src/flows/MembersDialog.loading.test.tsx
index 2d910b0245..1f306f1df5 100644
--- a/frontend/src/flows/MembersDialog.loading.test.tsx
+++ b/frontend/src/flows/MembersDialog.loading.test.tsx
@@ -6,11 +6,16 @@ import { act, render, screen, fireEvent, waitFor } from "../test/rtl";
import { MembersDialog } from "./MembersDialog";
import { useStore } from "../lib/state";
import * as api from "../api";
+import { invite } from "../api/invites";
vi.mock("../api", async (importOriginal) => {
const actual = await importOriginal();
- return { ...actual, listGrants: vi.fn(), approveGrant: vi.fn(async () => ({})), createGrant: vi.fn() };
+ return { ...actual, listGrants: vi.fn(), approveGrant: vi.fn(async () => ({})) };
});
+vi.mock("../api/invites", async (importOriginal) => ({
+ ...(await importOriginal()),
+ invite: vi.fn(),
+}));
const PENDING = {
subject: "reporter-private",
@@ -91,13 +96,15 @@ describe("MembersDialog opened on the add field", () => {
it("describes the field by a refused add's error, then the help", async () => {
vi.mocked(api.listGrants).mockResolvedValue({ rows: [] } as never);
- vi.mocked(api.createGrant).mockRejectedValueOnce(new Error("That subject is not allowed here"));
+ vi.mocked(invite).mockRejectedValueOnce(new Error("No account in clickhouse signs in as pat"));
render( {}} org="clickhouse" namespace="team" startAdding />);
const field = await screen.findByRole("textbox", { name: /member to add/ });
fireEvent.change(field, { target: { value: "pat" } });
fireEvent.keyDown(field, { key: "Enter" });
await waitFor(() =>
- expect(field).toHaveAccessibleDescription(/^That subject is not allowed here.*A login handle is the name/),
+ expect(field).toHaveAccessibleDescription(
+ /^No account in clickhouse signs in as pat.*A login handle is the name/,
+ ),
);
});
diff --git a/frontend/src/flows/MembersDialog.tsx b/frontend/src/flows/MembersDialog.tsx
index fd12ac6095..d144c2888c 100644
--- a/frontend/src/flows/MembersDialog.tsx
+++ b/frontend/src/flows/MembersDialog.tsx
@@ -33,6 +33,8 @@ import { andList, fmtInt } from "../lib/format";
import { MORE_SHOWN, type ShowMoreRows, useShowMore } from "../lib/useShowMore";
import { grantSpellings, mySpellings, namesMe, subjectLabel } from "../lib/grantSubject";
import { PlaceLink } from "../components/ui/PlaceLink";
+import { invite, isPersonSpelling, type InviteResult } from "../api/invites";
+import { InviteSent, OpenInvitations } from "../components/Invitations";
/** What Remove's confirm says: who still gets in once the grant here goes. Sign-in off serves
* every request, so it says only that the grant is revoked. */
@@ -236,6 +238,10 @@ export function MembersDialog({
const [cut, setCut] = useState(false);
const [adding, setAdding] = useState(startAdding);
const [newSubject, setNewSubject] = useState("");
+ // The invitation an add just made, with its link to copy; and how many it has made, which
+ // reads the open invitations again.
+ const [sent, setSent] = useState<{ email: string; result: InviteResult } | null>(null);
+ const [invited, setInvited] = useState(0);
// A code index has no writer role, so its default must be one the select offers.
const defaultRole: GrantRole = isCode ? "viewer" : "writer";
const [newRole, setNewRole] = useState(defaultRole);
@@ -316,8 +322,23 @@ export function MembersDialog({
setBusy("__add__");
setErr(null);
try {
- await createGrant({ org, namespace }, subj, newRole);
- toast(`Added ${subjectLabel(subj, org)} as ${newRole}`, "ok");
+ // A person by handle or email is invited: an account is granted at once, any other
+ // email gets a link. A service account, a group or everyone is granted as typed.
+ if (isPersonSpelling(subj)) {
+ const out = await invite({ org, namespace }, subj, newRole);
+ if (out.outcome === "invited") {
+ // The link stays on screen to copy, and the add field open for the next person.
+ setSent({ email: subj, result: out });
+ setInvited((n) => n + 1);
+ setNewSubject("");
+ return;
+ }
+ toast(`Added ${subjectLabel(out.subject, org)} as ${newRole}`, "ok");
+ } else {
+ await createGrant({ org, namespace }, subj, newRole);
+ toast(`Added ${subjectLabel(subj, org)} as ${newRole}`, "ok");
+ }
+ setSent(null);
setNewSubject("");
setNewRole(defaultRole);
setAdding(false);
@@ -454,6 +475,7 @@ export function MembersDialog({
// The next open, if the caller keeps the dialog mounted, starts where this one did.
setAdding(startAdding);
setErr(null);
+ setSent(null);
}
onOpenChange(v);
}}
@@ -492,6 +514,7 @@ export function MembersDialog({
{cut && (
{`Only the first ${fmtInt(GRANTS_READ)} grants were read.`}
@@ -701,9 +724,8 @@ export function MembersDialog({
{roles.find((r) => r.value === newRole)?.desc}
- {/* An email no verified account holds is stored as typed and reaches nobody: say so
- before the add, not after. */}
+ {sent && }
)}
diff --git a/frontend/src/flows/fieldErrors.test.tsx b/frontend/src/flows/fieldErrors.test.tsx
index 9aa6f8850e..eeeda238f3 100644
--- a/frontend/src/flows/fieldErrors.test.tsx
+++ b/frontend/src/flows/fieldErrors.test.tsx
@@ -23,6 +23,13 @@ vi.mock("../api", async (importOriginal) => {
}),
};
});
+// A person's handle or email is added through grants.invite, which refuses an unknown one.
+vi.mock("../api/invites", async (importOriginal) => ({
+ ...(await importOriginal()),
+ invite: vi.fn(async () => {
+ throw new Error("No such subject");
+ }),
+}));
vi.mock("../api/tasks", async (importOriginal) => {
const actual = await importOriginal();
return {
diff --git a/frontend/src/lib/inviteLink.ts b/frontend/src/lib/inviteLink.ts
new file mode 100644
index 0000000000..5932b3f064
--- /dev/null
+++ b/frontend/src/lib/inviteLink.ts
@@ -0,0 +1,29 @@
+// An invitation link (`/spaces#invite=&org=…&namespace=…`), taken out of the address
+// into this tab's session by Namespaces in your org, which offers to accept it. A password
+// sign-in reloads the page, fragment and all; single sign-on makes no link.
+
+/** The session key for an invitation link's `{ secret, org, namespace }`. */
+export const INVITE_LINK = "loom_invite_v1";
+
+export interface InviteLink {
+ secret: string;
+ org: string;
+ namespace: string;
+}
+
+/** Take an invitation link out of the address into this tab's session, and return it. */
+export function takeInviteLink(): InviteLink | null {
+ const { hash, pathname, search } = window.location;
+ if (!hash.startsWith("#invite=")) return null;
+ history.replaceState(history.state, "", pathname + search);
+ const p = new URLSearchParams(hash.slice(1));
+ const [secret, org, namespace] = [p.get("invite"), p.get("org"), p.get("namespace")];
+ if (!secret || !org || !namespace) return null;
+ const link = { secret, org, namespace };
+ try {
+ sessionStorage.setItem(INVITE_LINK, JSON.stringify(link));
+ } catch {
+ /* no session storage: the card holds it until the page goes */
+ }
+ return link;
+}
diff --git a/frontend/src/views/Browse.tsx b/frontend/src/views/Browse.tsx
index 7db9aaa851..60fa2c3d4c 100644
--- a/frontend/src/views/Browse.tsx
+++ b/frontend/src/views/Browse.tsx
@@ -22,6 +22,7 @@ import { COLLECTION_PREFIX, NAMESPACE_NAME, isCollectionName, isPersonalCollecti
import { canEditGuide, roleOnNamespace } from "../lib/namespaceRole";
import { callReason } from "../lib/callReason";
import { CreateNamespaceDialog } from "../flows/CreateNamespaceDialog";
+import { InvitationCard } from "./InvitationCard";
import { useStore, useIdentity } from "../lib/state";
import { RowSkeleton } from "../components/Skeleton";
import { Alert, ListRow, LoadingSkeleton, PageHeader, Panel, SectionHeading, Tip } from "../components/ui";
@@ -440,6 +441,7 @@ export function Browse() {
A namespace is a project's or an agent's memory. Join public namespaces in your org, or invite people into the
ones you manage.
+
{/* The Repositories hint: under the description, or inside the folded code section when there is one. */}
{managedCode.length === 0 && repoHint &&
{repoHint}
}
diff --git a/frontend/src/views/Code.accessInvite.test.tsx b/frontend/src/views/Code.accessInvite.test.tsx
new file mode 100644
index 0000000000..94820ad328
--- /dev/null
+++ b/frontend/src/views/Code.accessInvite.test.tsx
@@ -0,0 +1,55 @@
+/**
+ * The Access tab adds a person through grants.invite, and names the subject the server
+ * granted, which may be another spelling than the one typed.
+ */
+import userEvent from "@testing-library/user-event";
+import { cleanup, render, screen, waitFor } from "../test/rtl";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { toast } from "../components/Toast";
+import * as invites from "../api/invites";
+import { useStore } from "../lib/state";
+import { AccessTab } from "./Code";
+
+vi.mock("../api", async (importOriginal) => ({
+ ...(await importOriginal()),
+ listGrants: vi.fn(async () => ({ rows: [{ subject: "alice", role: "admin", status: "active" }] })),
+ getNamespace: async () => ({ namespace: "code-app", join_policy: "approval" }),
+}));
+vi.mock("../api/invites", async (importOriginal) => ({
+ ...(await importOriginal()),
+ invite: vi.fn(),
+ listInvites: vi.fn(async () => ({ rows: [] })),
+}));
+vi.mock("../lib/sharedReads", async (importOriginal) => ({
+ ...(await importOriginal()),
+ sharedIndexStatus: async () => ({ org_readable: false }),
+}));
+vi.mock("../components/Toast", async (importOriginal) => ({
+ ...(await importOriginal()),
+ toast: vi.fn(),
+}));
+
+beforeEach(() => {
+ useStore.setState({ whoami: { authenticated: true, subject: "alice", org: "dev", roles: ["ADMIN"] } });
+});
+afterEach(() => cleanup());
+
+it("names the handle the server granted, not what was typed", async () => {
+ vi.mocked(invites.invite).mockResolvedValue({
+ outcome: "granted",
+ role: "viewer",
+ subject: "robin",
+ invite_id: "",
+ link_path: "",
+ url: "",
+ expires_at: null,
+ emailed: false,
+ });
+ const user = userEvent.setup();
+ render();
+ const field = await screen.findByRole("textbox", { name: "Login handle or email of the reader to add" });
+ await waitFor(() => expect(field).toBeEnabled());
+ await user.type(field, "Robin{Enter}");
+ await waitFor(() => expect(toast).toHaveBeenCalledWith(expect.stringMatching(/^robin is now a /), "ok"));
+ expect(invites.invite).toHaveBeenCalledWith({ org: "dev", namespace: "code-app" }, "Robin", expect.any(String));
+});
diff --git a/frontend/src/views/Code.tsx b/frontend/src/views/Code.tsx
index b79747f466..b6b09cdc96 100644
--- a/frontend/src/views/Code.tsx
+++ b/frontend/src/views/Code.tsx
@@ -34,6 +34,8 @@ import { useAbortableEffect, useVisiblePoll } from "../lib/hooks";
import { EmptyState } from "../components/EmptyState";
import { ScopeBadge } from "../components/ScopeBadge";
import { SubjectHelp } from "../components/SubjectHelp";
+import { invite, isPersonSpelling, type InviteResult } from "../api/invites";
+import { InviteSent, OpenInvitations } from "../components/Invitations";
import { IconButton } from "../components/IconButton";
import { ChoiceGroup } from "../components/ui/ChoiceGroup";
import { Modal, ModalFooter } from "../components/ui/Modal";
@@ -3043,6 +3045,10 @@ export function AccessTab({
// grants.list refused the caller (a viewer read): not a reader, so not a maintainer.
const [refused, setRefused] = useState(false);
const [subject, setSubject] = useState("");
+ // The invitation an add just made, with its link to copy; and how many, which reads the
+ // open invitations again.
+ const [sent, setSent] = useState<{ email: string; result: InviteResult } | null>(null);
+ const [invited, setInvited] = useState(0);
const [role, setRole] = useState("viewer");
const [busy, setBusy] = useState(null);
const [settingsOpen, setSettingsOpen] = useState(false);
@@ -3188,8 +3194,21 @@ export function AccessTab({
if (!s || !canManage) return;
setBusy("add");
try {
- await createGrant(id, s, role);
- toast(`${s} is now a ${roleWord(role)}`, "ok");
+ // A person by handle or email is invited: an account is granted at once, any other
+ // email gets a link to copy. Any other principal goes to grants.create as typed.
+ let granted = s;
+ if (isPersonSpelling(s)) {
+ const out = await invite(id, s, role);
+ if (out.outcome === "invited") {
+ setSent({ email: s, result: out });
+ setInvited((n) => n + 1);
+ setSubject("");
+ return;
+ }
+ granted = out.subject; // the handle the server granted, which may differ from what was typed
+ } else await createGrant(id, s, role);
+ toast(`${granted} is now a ${roleWord(role)}`, "ok");
+ setSent(null);
setSubject("");
load();
} catch (err) {
@@ -3592,8 +3611,14 @@ export function AccessTab({
Adding someone by name works under every rule. Agents read with a token that names this repository.
+ {sent && (
+
+
+
+ )}
)}
+ {canManage && }
)}
diff --git a/frontend/src/views/CollectionSharing.test.tsx b/frontend/src/views/CollectionSharing.test.tsx
index ed5ec173e8..f8e6eaec70 100644
--- a/frontend/src/views/CollectionSharing.test.tsx
+++ b/frontend/src/views/CollectionSharing.test.tsx
@@ -22,6 +22,23 @@ const api = vi.hoisted(() => ({
isAuthDisabled: vi.fn(() => false),
}));
vi.mock("../api", async (importOriginal) => ({ ...(await importOriginal()), ...api }));
+// A person is added through grants.invite; a principal through grants.create.
+const invites = vi.hoisted(() => ({
+ invite: vi.fn(async (_id: unknown, subject: string, role: string) => ({
+ outcome: "granted" as const,
+ role,
+ subject,
+ invite_id: "",
+ link_path: "",
+ url: "",
+ expires_at: null,
+ emailed: false,
+ })),
+}));
+vi.mock("../api/invites", async (importOriginal) => ({
+ ...(await importOriginal()),
+ ...invites,
+}));
vi.mock("../components/ConfirmDialog", async (importOriginal) => ({
...(await importOriginal()),
confirmAction: async () => true,
@@ -629,7 +646,7 @@ describe("the collection header", () => {
fireEvent.click(within(dialog).getByRole("button", { name: "Add member" }));
fireEvent.change(within(dialog).getByRole("textbox"), { target: { value: "bob" } });
fireEvent.click(within(dialog).getByRole("button", { name: "Add" }));
- await waitFor(() => expect(api.createGrant).toHaveBeenCalled());
+ await waitFor(() => expect(invites.invite).toHaveBeenCalled());
let answer: (v: unknown) => void = () => {};
api.listGrants.mockReturnValue(new Promise((r) => (answer = r)));
fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));
@@ -712,7 +729,7 @@ describe("the collection header", () => {
fireEvent.click(await within(dialog).findByRole("button", { name: "Add member" }));
fireEvent.change(within(dialog).getByRole("textbox"), { target: { value: "bob" } });
fireEvent.click(within(dialog).getByRole("button", { name: "Add" }));
- await waitFor(() => expect(api.createGrant).toHaveBeenCalled());
+ await waitFor(() => expect(invites.invite).toHaveBeenCalled());
const through = await within(dialog).findByRole("region", { name: "Also can see it, through Engineering" });
fireEvent.click(within(through).getByRole("link", { name: "Engineering" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
diff --git a/frontend/src/views/InvitationCard.test.tsx b/frontend/src/views/InvitationCard.test.tsx
new file mode 100644
index 0000000000..af2ff0d3a8
--- /dev/null
+++ b/frontend/src/views/InvitationCard.test.tsx
@@ -0,0 +1,255 @@
+import { act, cleanup, render, screen, waitFor } from "../test/rtl";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { listMine } from "../api";
+import { acceptInvite } from "../api/invites";
+import { INVITE_LINK, takeInviteLink } from "../lib/inviteLink";
+import { ApiError } from "../lib/errors";
+import { invalidateShared, sharedMine } from "../lib/sharedReads";
+import { useStore } from "../lib/state";
+import { InvitationCard } from "./InvitationCard";
+
+// An invitation link's secret rides in the fragment; the card moves it into the tab's session
+// and accepts it as the signed-in person.
+
+vi.mock("../api/invites", () => ({ acceptInvite: vi.fn() }));
+vi.mock("../api", async (importOriginal) => ({
+ ...(await importOriginal()),
+ listMine: vi.fn(async () => []),
+}));
+
+beforeEach(() => {
+ sessionStorage.clear();
+ vi.mocked(acceptInvite).mockReset();
+ vi.mocked(listMine).mockClear();
+ invalidateShared();
+ useStore.setState({ identity: { org: "dev", namespace: "home", agent: "loom-ui" } });
+});
+afterEach(() => cleanup());
+
+describe("takeInviteLink", () => {
+ it("moves the link out of the address into the session", () => {
+ history.replaceState(null, "", "/spaces#invite=s3cret&org=dev&namespace=team%2Falerts");
+ takeInviteLink();
+ expect(window.location.pathname + window.location.hash).toBe("/spaces");
+ expect(JSON.parse(sessionStorage.getItem(INVITE_LINK) ?? "null")).toEqual({
+ secret: "s3cret",
+ org: "dev",
+ namespace: "team/alerts",
+ });
+ });
+
+ it("leaves any other fragment alone", () => {
+ history.replaceState(null, "", "/spaces#token=x");
+ takeInviteLink();
+ expect(window.location.hash).toBe("#token=x");
+ expect(sessionStorage.getItem(INVITE_LINK)).toBeNull();
+ });
+});
+
+function opened(): void {
+ sessionStorage.setItem(INVITE_LINK, JSON.stringify({ secret: "s3cret", org: "dev", namespace: "alerts" }));
+ render();
+}
+
+describe("InvitationCard", () => {
+ it("accepts as the signed-in person and switches to the namespace", async () => {
+ vi.mocked(acceptInvite).mockResolvedValue({ namespace: "alerts", role: "writer" });
+ await sharedMine("dev");
+ const user = userEvent.setup();
+ opened();
+ expect(screen.getByRole("region", { name: "Invitation" })).toHaveTextContent("You're invited to alerts.");
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ expect(acceptInvite).toHaveBeenCalledWith(expect.objectContaining({ org: "dev", namespace: "alerts" }), "s3cret");
+ expect(useStore.getState().identity?.namespace).toBe("alerts");
+ expect(sessionStorage.getItem(INVITE_LINK)).toBeNull();
+ expect(screen.queryByRole("region", { name: "Invitation" })).toBeNull();
+ // The new grant is read at once, not after the shared list_mine read's 30 s.
+ await sharedMine("dev");
+ expect(listMine).toHaveBeenCalledTimes(2);
+ });
+
+ it("opens an accepted collection in the Library, keeping the namespace in use", async () => {
+ vi.mocked(acceptInvite).mockResolvedValue({ namespace: "col-runbooks", role: "viewer" });
+ const real = useStore.getState().navigate;
+ const navigate = vi.fn();
+ useStore.setState({ navigate });
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ expect(navigate).toHaveBeenCalledWith("knowledge", { query: { collection: "col-runbooks" } });
+ expect(useStore.getState().identity?.namespace).toBe("home");
+ useStore.setState({ navigate: real });
+ });
+
+ it.each([
+ [404, "RESOURCE_NOT_FOUND", "this invitation link is used, cancelled or expired: ask for a new one"],
+ [422, "VALIDATION_FAILED", "an invitation is accepted by a person, signed in as themselves"],
+ ])("says why a refused link is refused and offers only Close (%i %s)", async (status, code, message) => {
+ vi.mocked(acceptInvite).mockRejectedValue(new ApiError({ status, code, message }));
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ expect(await screen.findByText(message, { exact: false })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Accept invitation" })).toBeNull();
+ expect(sessionStorage.getItem(INVITE_LINK)).toBeNull();
+ expect(useStore.getState().identity?.namespace).toBe("home");
+ });
+
+ it("keeps the link when the 404 is not the server's refusal of it", async () => {
+ // A replica of the previous build answers an op it does not serve with a bare 404.
+ vi.mocked(acceptInvite).mockRejectedValueOnce(new ApiError({ status: 404, message: "Not Found" }));
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ await waitFor(() => expect(screen.getByRole("button", { name: "Accept invitation" })).toBeEnabled());
+ expect(acceptInvite).toHaveBeenCalledTimes(1);
+ expect(sessionStorage.getItem(INVITE_LINK)).not.toBeNull();
+ });
+
+ it("shows a link pasted into a tab already on the page", async () => {
+ render();
+ expect(screen.queryByRole("region", { name: "Invitation" })).toBeNull();
+ history.replaceState(null, "", "/spaces#invite=s3cret&org=dev&namespace=alerts");
+ act(() => {
+ window.dispatchEvent(new HashChangeEvent("hashchange"));
+ });
+ try {
+ expect(await screen.findByRole("button", { name: "Accept invitation" })).toBeEnabled();
+ } finally {
+ history.replaceState(null, "", "/");
+ }
+ });
+
+ it("offers Accept for a link pasted after one was accepted", async () => {
+ vi.mocked(acceptInvite).mockResolvedValue({ namespace: "alerts", role: "writer" });
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ expect(screen.queryByRole("region", { name: "Invitation" })).toBeNull();
+ history.replaceState(null, "", "/spaces#invite=other&org=dev&namespace=ops");
+ act(() => {
+ window.dispatchEvent(new HashChangeEvent("hashchange"));
+ });
+ try {
+ expect(await screen.findByRole("button", { name: "Accept invitation" })).toBeEnabled();
+ } finally {
+ history.replaceState(null, "", "/");
+ }
+ });
+
+ it.each([
+ ["accepted", () => Promise.resolve({ namespace: "alerts", role: "writer" as const })],
+ ["refused", () => Promise.reject(new ApiError({ status: 404, code: "RESOURCE_NOT_FOUND", message: "used" }))],
+ ])("keeps a link pasted while another's accept is in flight, once that one is %s", async (_, answer) => {
+ let settle: () => void = () => {};
+ vi.mocked(acceptInvite).mockReturnValueOnce(
+ new Promise((resolve, reject) => {
+ settle = () => void answer().then(resolve, reject);
+ }),
+ );
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ history.replaceState(null, "", "/spaces#invite=other&org=dev&namespace=ops");
+ act(() => {
+ window.dispatchEvent(new HashChangeEvent("hashchange"));
+ });
+ try {
+ await act(async () => settle());
+ expect(screen.getByRole("region", { name: "Invitation" })).toHaveTextContent("You're invited to ops.");
+ await waitFor(() => expect(screen.getByRole("button", { name: "Accept invitation" })).toBeEnabled());
+ expect(screen.queryByText(/used/)).toBeNull();
+ expect(JSON.parse(sessionStorage.getItem(INVITE_LINK) ?? "null")?.secret).toBe("other");
+ } finally {
+ history.replaceState(null, "", "/");
+ }
+ });
+
+ it("leaves a link set aside by Not now aside when the fragment changes", async () => {
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Not now" }));
+ history.replaceState(null, "", "/spaces#token=x");
+ act(() => {
+ window.dispatchEvent(new HashChangeEvent("hashchange"));
+ });
+ try {
+ expect(screen.queryByRole("region", { name: "Invitation" })).toBeNull();
+ } finally {
+ history.replaceState(null, "", "/");
+ }
+ });
+
+ it("holds the link itself where session storage is refused", () => {
+ const refuse = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new DOMException("blocked", "SecurityError");
+ });
+ try {
+ history.replaceState(null, "", "/spaces#invite=s3cret&org=dev&namespace=alerts");
+ render();
+ expect(screen.getByRole("button", { name: "Accept invitation" })).toBeEnabled();
+ expect(window.location.hash).toBe("");
+ } finally {
+ refuse.mockRestore();
+ history.replaceState(null, "", "/");
+ }
+ });
+
+ it("keeps the link and Accept through an outage", async () => {
+ vi.mocked(acceptInvite).mockRejectedValueOnce(
+ new ApiError({ status: 503, code: "BACKEND_UNAVAILABLE", message: "grants could not be read" }),
+ );
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ expect(await screen.findByText(/could not be read/)).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Accept invitation" })).toBeEnabled();
+ expect(sessionStorage.getItem(INVITE_LINK)).not.toBeNull();
+ });
+
+ it("keeps the link through a sign-in the session ended for", async () => {
+ vi.mocked(acceptInvite).mockRejectedValueOnce(
+ new ApiError({ status: 401, code: "AUTH_REQUIRED", message: "sign in again" }),
+ );
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Accept invitation" }));
+ expect(await screen.findByText(/sign in again/i)).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Accept invitation" })).toBeEnabled();
+ expect(sessionStorage.getItem(INVITE_LINK)).not.toBeNull();
+ });
+
+ it("keeps the link for the next visit on Not now", async () => {
+ const user = userEvent.setup();
+ opened();
+ await user.click(screen.getByRole("button", { name: "Not now" }));
+ expect(screen.queryByRole("region", { name: "Invitation" })).toBeNull();
+ expect(sessionStorage.getItem(INVITE_LINK)).not.toBeNull();
+ cleanup();
+ render();
+ expect(screen.getByRole("region", { name: "Invitation" })).toBeInTheDocument();
+ });
+
+ it("asks for a sign-in to another org's link instead of offering Accept", () => {
+ useStore.setState({ identity: { org: "acme", namespace: "home", agent: "loom-ui" } });
+ opened();
+ expect(screen.getByRole("region", { name: "Invitation" })).toHaveTextContent("Sign in to dev to accept it.");
+ expect(screen.queryByRole("button", { name: "Accept invitation" })).toBeNull();
+ expect(screen.getByRole("button", { name: "Close" })).toBeInTheDocument();
+ });
+
+ it("shows nothing without an invitation", () => {
+ render();
+ expect(screen.queryByRole("region", { name: "Invitation" })).toBeNull();
+ });
+});
+
+describe("InvitationCard on an address that still carries the link", () => {
+ it("takes the link from the address itself", () => {
+ history.replaceState(null, "", "/spaces#invite=s3cret&org=dev&namespace=alerts");
+ render();
+ expect(screen.getByRole("region", { name: "Invitation" })).toHaveTextContent("You're invited to alerts.");
+ expect(window.location.hash).toBe("");
+ });
+});
diff --git a/frontend/src/views/InvitationCard.tsx b/frontend/src/views/InvitationCard.tsx
new file mode 100644
index 0000000000..26ba0c3a66
--- /dev/null
+++ b/frontend/src/views/InvitationCard.tsx
@@ -0,0 +1,125 @@
+import { useEffect, useState } from "react";
+import { Button } from "@clickhouse/click-ui/Button";
+import { setSavedNamespace } from "../api";
+import { acceptInvite } from "../api/invites";
+import { Alert } from "../components/ui";
+import { toast } from "../components/Toast";
+import { INVITE_LINK, type InviteLink, takeInviteLink } from "../lib/inviteLink";
+import { humanizeError } from "../lib/errorWords";
+import { ApiError } from "../lib/errors";
+import { isCollectionName } from "../lib/namespace";
+import { invalidateShared } from "../lib/sharedReads";
+import { useStore } from "../lib/state";
+
+function kept(): InviteLink | null {
+ try {
+ const v = JSON.parse(sessionStorage.getItem(INVITE_LINK) ?? "null") as Partial | null;
+ if (v && typeof v.secret === "string" && typeof v.org === "string" && typeof v.namespace === "string") {
+ return { secret: v.secret, org: v.org, namespace: v.namespace };
+ }
+ } catch {
+ /* unreadable or no session storage */
+ }
+ return null;
+}
+
+function stashed(): InviteLink | null {
+ // An address opened signed in, or after a password sign-in, still carries it.
+ const taken = takeInviteLink();
+ return kept() ?? taken;
+}
+
+/** Forget `secret`'s link, and not one pasted since. */
+function drop(secret: string): void {
+ if (kept()?.secret !== secret) return;
+ try {
+ sessionStorage.removeItem(INVITE_LINK);
+ } catch {
+ /* no session storage: nothing was kept */
+ }
+}
+
+/** The invitation link this tab opened, for the signed-in person to accept. */
+export function InvitationCard() {
+ const [link, setLink] = useState(stashed);
+ const [busy, setBusy] = useState(false);
+ // Each keyed by the link's secret: an answer about one link says nothing of one pasted since.
+ const [error, setError] = useState<{ secret: string; text: string } | null>(null);
+ // The server refused the link: RESOURCE_NOT_FOUND when it is used, cancelled or expired,
+ // VALIDATION_FAILED when this account cannot accept it. Only Close is left.
+ const [refusedSecret, setRefusedSecret] = useState(null);
+ const identity = useStore((s) => s.identity);
+ const setIdentity = useStore((s) => s.setIdentity);
+ const navigate = useStore((s) => s.navigate);
+ // A link pasted into a tab already on this page changes only the fragment. Only a link
+ // the address carries now: one Not now set aside stays aside.
+ useEffect(() => {
+ const opened = () => {
+ const next = takeInviteLink();
+ if (next) setLink(next);
+ };
+ window.addEventListener("hashchange", opened);
+ return () => window.removeEventListener("hashchange", opened);
+ }, []);
+ if (!link) return null;
+
+ const refused = refusedSecret === link.secret;
+ const shownError = error?.secret === link.secret ? error.text : null;
+ // A link to another org is accepted only signed in there: the server refuses it here.
+ const elsewhere = Boolean(identity && identity.org !== link.org);
+ const close = () => {
+ drop(link.secret);
+ setLink(null);
+ };
+ const accept = async () => {
+ const current = link;
+ setBusy(true);
+ setError(null);
+ try {
+ const out = await acceptInvite(current, current.secret);
+ drop(current.secret);
+ setLink((shown) => (shown?.secret === current.secret ? null : shown));
+ toast(`Joined ${out.namespace} as ${out.role}`, "ok");
+ invalidateShared("mine:");
+ // A collection opens in the Library; a namespace becomes the one in use.
+ if (isCollectionName(out.namespace)) navigate("knowledge", { query: { collection: out.namespace } });
+ else if (identity && identity.org === current.org) {
+ setIdentity({ ...identity, namespace: out.namespace });
+ setSavedNamespace(out.namespace);
+ }
+ } catch (e) {
+ // Only the server's refusal of the link drops it: an ended session, a rate limit or a
+ // replica that does not serve the op yet keeps it for a retry.
+ if (e instanceof ApiError && (e.code === "RESOURCE_NOT_FOUND" || e.code === "VALIDATION_FAILED")) {
+ drop(current.secret);
+ setRefusedSecret(current.secret);
+ }
+ setError({ secret: current.secret, text: humanizeError(e) });
+ } finally {
+ // The card stays mounted after an accept, and the next pasted link reuses it.
+ setBusy(false);
+ }
+ };
+
+ return (
+
+
+ You're invited to {link.namespace}
+ {elsewhere ? ` in ${link.org}. Sign in to ${link.org} to accept it.` : "."}
+ {elsewhere ? "" : " Accepting gives the account you're signed in as the role the invitation names."}
+
+ {shownError && }
+
+ {/* Not now keeps the link in this tab, so the card is back on the next visit. */}
+
+ {!refused && !elsewhere && (
+
+ )}
+