Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(access): operator-only member lookup by declared email (GST-1158 F10a)
garrytanba14d625959c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 93a9bf532c..271c0b1eed 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,8 @@ identifiers and attribution are available in the pre-removal Git revision## [Unreleased]+**The brain owner can declare an email on a member and link a trusted system's canonical id to the member by that email, instead of looking up the member id first.** `gbrain access member add <id> --email <addr>` and `gbrain access member set <id> --email <addr>|none` declare or clear it, `member list` shows it, and `gbrain access member link --email <addr> --qm <id>` makes the same link `link <id> --qm <id>` makes. Over the running server, `gbrain mcp admin member-add --email`, `member-set` and `link --email` do the same through the owner-session routes. An email is stored lower-case, is unique per brain, and is cleared when a member is removed. An email no member declares is `not_found` and creates nothing. This changes no trust: the operator still makes every link, and no OAuth token, attested call or MCP tool can set an email or make a link. Members and emails are database state (migration v287), so a repo-less brain works the same.+**The brain owner can now set a trusted system's attest right and manage members and their canonical-id links from another machine, over the running server, instead of needing a shell on the brain host.** Three owner-session routes back new `gbrain mcp admin` commands. Every refusal the local commands make still applies, and no OAuth token or MCP tool reaches them.### What changeddiff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.mdindex 9b6d84eef0..f89aa41d5a 100644--- a/docs/architecture/key-files/access.md+++ b/docs/architecture/key-files/access.md@@ -3,5 +3,5 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit; a database with no revision yet replays each committed `access.yml` since the `access.approved` baseline, so a rebuild holds a removal a plain commit made); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v283 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. Attested actor (C1, GST-359): `actor-model.ts` (dependency-free: `x-qm-actor`, `acting_user`, `EXTERNAL_ID_RE` = 1-256 visible ASCII, `attestRightFrom`: the right counts only for a member-less credential whose token is legacy or `client_credentials`, read from `oauth_tokens.grant_type`) and `actor.ts`. `resolveAttestedActor` runs in dispatch before any work: an invalid id refuses `actor_not_attested` (`invalid_actor_id`) before any lookup, then the right, the op list (`attest_ops`, default `get_write_request,memory_recall,memory_write`), `acting_user` = header (stripped), and `actorCoverage` (the one coverage test: live right plus a live link in `access_member_links` to an enabled member, compared exactly) or `actor_unlinked`. `ACTOR_DEFERRED_OPS` (`capture`, `extract_facts`, take writes, `list_write_conflicts`) are never attestable until each is keyed to the member: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v286. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`. A member id whose page slug `slugifyPath` would change (`a--b`, `zed-`) is refused (`invalid_params`). The page must name that member alone (`memberPageIsOwn`, checked at submission and again in preparation, `memberPageNotOwned`), and remote writes under `memory/members/` go only to the caller's own page (`assertMemberPageWriter`, called from `ops/context.ts` `enforceClientSlugFence`, so every remote page write passes it; trusted local callers are unaffected). Reads widen a world-only fact list only by `memberFactAdmitSql` (a private fact on the caller's own live member page whose readers and folder rules admit the caller; `factVisibilitySql` in `engine-sql/facts.ts` and `search/fact-relevance.ts`), and `privateProvenanceFilterUnderPolicy` judges a member-page fact's source page as the caller (every other fact keeps the empty identity, so a fact from a page that names readers stays hidden from every remote caller). Writers never cross pages: `facts/single-prepare.ts` (`SingleFactIntent.page_slug`) and `trust/supersede-handlers.ts` dedup, supersede and contest only within the member page, and no other write matches a fact there (`onMemberPageSql`); consolidation skips facts whose page names readers (`readersSourcedFactSql`). Per-person keys: `callerIdentityKey` joins the hot-memory cache key (`facts/meta-hook.ts`, `::xid=`), `callerSessionKey` the `delta` cursor (`ops/facts.ts`), `sameAttestedActor` gates receipts (`persistence/authority.ts` `ownRequestAccessible`) and replays (`persistence/journal.ts`), and `get_agent_job` and the owner-fenced `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_job` match the job's `grant.actor` (system, external id, member; `jobActorSql` in `minions/types.ts`), so a job with an actor reads as missing to the bare client and to other actors. Tests: `test/access-member-facts.test.ts` (both engines), `test/access-member-sweep.test.ts` (every attestable op as Bob, the bare client and an unbound credential; `test/helpers/member-sweep.ts`), `test/e2e/serve-http-member-sweep.test.ts` (two members over a real `serve --http` on a keyless repo-less brain).+- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and before and after every managed pass (`performManagedSync`: sync, drain, `sources refresh`, git conversion), read with `git show` at the synced commit; a database with no revision yet replays each committed `access.yml` since the `access.approved` baseline, so a rebuild holds a removal a plain commit made); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it, and the unrestricted short form tests `folder_rule_ids IS NULL` next to `page_readers IS NULL` (v283 triggers set `access.restrictions_present` on the first rule or pending prefix); `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`. Shared agents (B, GBRA-231): `audience.ts` parses the audience a harness asserts (`X-Gbrain-On-Behalf-Of` or request-level `_meta.on_behalf_of`, 1-50 principals, `guest` = the empty identity; the same key inside tool arguments is refused) and appends each assertion to `access-audience-YYYY-Www.jsonl`. Dispatch resolves it on every remote call through `caller.ts` (`resolveAudienceIdentities`: every entry must be in the credential's live `may_act_for`, then name an enabled member or existing group); the caller-access record then carries `audienceIdentities`, and `accessAllowedForAllSql` needs one readers conjunct per identity, folder rules the intersection of each entry's satisfied set (`folderAccessForAll`). Privacy relaxes only for a one-member audience. Writes carry the audience as `WriteAuthority.actingFor` (re-resolved at publication) and agent jobs as `grant.actingFor`. Every remote response carries `_meta.access` (`appliedAccessSummary`), which `whoami` returns as `access.applied`; doctor `access_may_act_for_wildcard` (`checks/shared-agent-access.ts`) warns on `*`. Tests: `test/access-on-behalf-of.test.ts` (both engines), `test/e2e/serve-http-on-behalf-of.test.ts`. Attested actor (C1, GST-359): `actor-model.ts` (dependency-free: `x-qm-actor`, `acting_user`, `EXTERNAL_ID_RE` = 1-256 visible ASCII, `attestRightFrom`: the right counts only for a member-less credential whose token is legacy or `client_credentials`, read from `oauth_tokens.grant_type`) and `actor.ts`. `resolveAttestedActor` runs in dispatch before any work: an invalid id refuses `actor_not_attested` (`invalid_actor_id`) before any lookup, then the right, the op list (`attest_ops`, default `get_write_request,memory_recall,memory_write`), `acting_user` = header (stripped), and `actorCoverage` (the one coverage test: live right plus a live link in `access_member_links` to an enabled member, compared exactly) or `actor_unlinked`. `ACTOR_DEFERRED_OPS` (`capture`, `extract_facts`, take writes, `list_write_conflicts`) are never attestable until each is keyed to the member: refused by `parseAttestOps`, `bindCredential`, every call and the stored re-check, which also re-checks `attest_ops` for a queued write's operation and each job tool call. Under the header serve-http lists only attested tools and refuses `resources/read`. `attestedCallerAccess` is a one-member audience with privacy never relaxed (no granted sources, no hatch), never B's `may_act_for` path. Writes store `WriteAuthority.actingFor = {system, external_id, member}` and jobs `grant.actor`; `storedActorIdentity` re-resolves both through `actorCoverage` and refuses when the member changed. `linkMember` / `unlinkMember` / `listMemberLinks` back `gbrain access member link|unlink|links`; `linkMemberByEmail` (GST-1158) finds the member by its declared email (`members.ts` `memberByEmail`: `access_members.email`, migration v287, case-folded, unique, cleared on removal; `not_found` when none, `email_ambiguous` when several) and then links exactly as `linkMember`, from the local CLI and the owner-session routes in `src/commands/serve-http-access.ts` only; `--attest-actor` / `--attest-ops` on `auth rescope` (`members.ts`) only for a member-less legacy token or confidential client-credentials client. Migration v286. Tests: `test/access-qm-actor.test.ts` (both engines), `test/e2e/serve-http-qm-actor.test.ts`. Member facts (C2, GST-359): `member-facts.ts`. A remote `remember` from an attested actor or a lone-member credential (`callerMember`, never an audience of several) writes to `memory/members/<member>` (`memberFactPage`; `persistence/memory-prepare.ts` creates the page with `readable_by: [member:<id>]`), `visibility: private`, `infer_entity` off, the entity kept as `entity_slug`. A member id whose page slug `slugifyPath` would change (`a--b`, `zed-`) is refused (`invalid_params`). The page must name that member alone (`memberPageIsOwn`, checked at submission and again in preparation, `memberPageNotOwned`), and remote writes under `memory/members/` go only to the caller's own page (`assertMemberPageWriter`, called from `ops/context.ts` `enforceClientSlugFence`, so every remote page write passes it; trusted local callers are unaffected). Reads widen a world-only fact list only by `memberFactAdmitSql` (a private fact on the caller's own live member page whose readers and folder rules admit the caller; `factVisibilitySql` in `engine-sql/facts.ts` and `search/fact-relevance.ts`), and `privateProvenanceFilterUnderPolicy` judges a member-page fact's source page as the caller (every other fact keeps the empty identity, so a fact from a page that names readers stays hidden from every remote caller). Writers never cross pages: `facts/single-prepare.ts` (`SingleFactIntent.page_slug`) and `trust/supersede-handlers.ts` dedup, supersede and contest only within the member page, and no other write matches a fact there (`onMemberPageSql`); consolidation skips facts whose page names readers (`readersSourcedFactSql`). Per-person keys: `callerIdentityKey` joins the hot-memory cache key (`facts/meta-hook.ts`, `::xid=`), `callerSessionKey` the `delta` cursor (`ops/facts.ts`), `sameAttestedActor` gates receipts (`persistence/authority.ts` `ownRequestAccessible`) and replays (`persistence/journal.ts`), and `get_agent_job` and the owner-fenced `get_job`, `wait_job`, `get_job_progress`, `list_jobs` and `cancel_job` match the job's `grant.actor` (system, external id, member; `jobActorSql` in `minions/types.ts`), so a job with an actor reads as missing to the bare client and to other actors. Tests: `test/access-member-facts.test.ts` (both engines), `test/access-member-sweep.test.ts` (every attestable op as Bob, the bare client and an unbound credential; `test/helpers/member-sweep.ts`), `test/e2e/serve-http-member-sweep.test.ts` (two members over a real `serve --http` on a keyless repo-less brain).- `src/core/ops/qm-memory.ts` (GST-359 D) — QM's memory provider pair. `memory_recall` reads the attested person's own last-24-hour facts on their member page (`listFactsSince` with `sourceMarkdownSlug`), then `rankFactsByQuestion` over the facts they may read, renders one plain line per fact (`plainFactText` strips fence and heading markers) and cuts at a line within `max_chars` (`boundFactLines`). `memory_write` validates 1-20 facts, derives each request id from uuidv5(member, idempotency_key) (`memoryWriteRequestId`) and saves through `remember`'s handler with `ctx.attestedOp = 'memory_write'`, which the stored write authority keeps (`WriteAuthority.attestedOp`) so publication and receipt reads re-check that operation's attest right. `qmMemoryToolResult` (dispatch) moves the result into `structuredContent` and leaves the model text in `content`; `unlinkedRecallResult` is the empty success dispatch's `actorRefusal` returns for an unlinked person. Contract fixture: `scripts/build-qm-memory-contract.ts` writes `docs/contracts/qm-memory-provider/v1.json` (a `regen:all` artifact). Tests: `test/qm-memory-tools.test.ts` (both engines), `test/qm-memory-contract.test.ts` (drift), `test/e2e/serve-http-qm-memory.test.ts` (keyless `serve --http`).diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 55b53c736c..d7b34118df 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -99,9 +99,9 @@ More: [docs/guides/write-refusals.md#access_member_id_retired](../../docs/guides| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| A member or group id given to an access command, a credential binding or --as is ill-formed or names no usable member, so nothing was read or changed. | Ids are matched exactly against page readers; an unknown or disabled member is refused rather than read as unbound, so a typo never previews or binds the wrong view. | Check the id with gbrain access member list --all, or add the member first. Run: gbrain access member list --all --json | agent | `gbrain access member list --all --json` | 1 | no |+| A member or group id given to an access command, a credential binding or --as is ill-formed or names no usable member, or a declared member email is invalid, taken or ambiguous, so nothing was read or changed. | Ids are matched exactly against page readers; an unknown or disabled member is refused rather than read as unbound, so a typo never previews or binds the wrong view. | Check the id with gbrain access member list --all, or add the member first. Run: gbrain access member list --all --json | agent | `gbrain access member list --all --json` | 1 | no |-Reasons: `ill_formed`, `unknown`, `disabled`, `removed`, `exists`, `unknown_group`, `invalid_external_id`, `link_exists`, `unknown_link`.+Reasons: `ill_formed`, `unknown`, `disabled`, `removed`, `exists`, `unknown_group`, `invalid_external_id`, `link_exists`, `unknown_link`, `invalid_email`, `email_taken`, `email_ambiguous`.More: [docs/guides/write-refusals.md#access_member_invalid](../../docs/guides/write-refusals.md#access_member_invalid)diff --git a/docs/guides/qm.md b/docs/guides/qm.mdindex 973ea25e17..c2ca1b7691 100644--- a/docs/guides/qm.md+++ b/docs/guides/qm.md@@ -11,12 +11,18 @@ names in the `x-qm-actor` header. The wire contract QM vendors is```bashgbrain auth register-client qm --grant-types client_credentials --scopes "read write"gbrain auth rescope --client <client_id> --attest-actor qm # attested ops default to get_write_request,memory_recall,memory_write-gbrain access member add alice-example+gbrain access member add alice-example --email [email protected] # --email is optionalgbrain access member link alice-example --qm U0ALICE # the canonical id QM sends, compared exactly+gbrain access member link --email [email protected] --qm U0ALICE # the same link, finding the member by email```+A declared email (`--email` on `member add`, or `gbrain access member set <id> --email <addr>|none`) is+stored lower-case and is unique per brain. It only helps the operator find the member: the operator+still makes every link, an unknown email is `not_found` and creates nothing, and QM can't set an email+or make a link.+From another machine, the owner runs the same steps over the running server with-`gbrain mcp admin attest`, `member-add` and `link` (owner session only; see+`gbrain mcp admin attest`, `member-add`, `member-set` and `link` (owner session only; see[ADMIN](../mcp/ADMIN.md#inspect-clients-and-edit-access)).Add `forget` with `--attest-ops forget,get_write_request,memory_recall,memory_write` if QMdiff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex a8fdfa2b76..248097cc31 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -976,7 +976,7 @@ same on a repo-less brain and on a git-backed one.| Code | What happened | What to do ||---|---|---|-| <a id="access_member_invalid"></a>`access_member_invalid` | A member or group id given to `gbrain access`, to `--member` on `gbrain auth create`, `rescope` or `register-client`, or to a local `--as <member>` is ill-formed (`ill_formed`) or names no usable member (`unknown`, `disabled`, `removed`, `unknown_group`), or `member add` named an existing member (`exists`). Nothing was read or changed: an unknown `--as` is refused before the command runs instead of reading as unbound. | Check the id with `gbrain access member list --all`; add the member with `gbrain access member add <id>` or enable it with `gbrain access member enable <id>`. Ids are 1-64 characters: lower-case letters, digits, `.`, `_` or `-`. |+| <a id="access_member_invalid"></a>`access_member_invalid` | A member or group id given to `gbrain access`, to `--member` on `gbrain auth create`, `rescope` or `register-client`, or to a local `--as <member>` is ill-formed (`ill_formed`) or names no usable member (`unknown`, `disabled`, `removed`, `unknown_group`), or `member add` named an existing member (`exists`). A member's declared email (`--email` on `member add` or `member set`) is not an address (`invalid_email`), another member already declares it (`email_taken`), or `member link --email` found several members declaring it (`email_ambiguous`; the email is unique, so this means a damaged table). Nothing was read or changed: an unknown `--as` is refused before the command runs instead of reading as unbound. | Check the id with `gbrain access member list --all`; add the member with `gbrain access member add <id>` or enable it with `gbrain access member enable <id>`. Ids are 1-64 characters: lower-case letters, digits, `.`, `_` or `-`. An email has one `@`, no spaces and at most 254 characters; clear a taken one with `gbrain access member set <id> --email none`, and link by member id when an email is ambiguous. `member link --email` naming an email no member declares is `not_found`; it never creates a member. || <a id="access_member_id_retired"></a>`access_member_id_retired` | `gbrain access member add` or `enable` named an id that `gbrain access member rm --yes` removed. Member ids are never reused, because pages and audit history may still name the removed id. Nothing was created. | Choose a new member id. `gbrain access member disable` is the reversible way to pause a member. || <a id="access_member_disabled"></a>`access_member_disabled` | The access token or OAuth client is bound to a member who is disabled, removed or missing, so it was refused at verification (HTTP 401, `invalid_token` with this code in the description). A credential bound to a member reads as that member, so it is refused rather than silently treated as unbound. | Ask the brain operator to run `gbrain access member enable <id>`, or to rebind the credential with `gbrain auth rescope --token <name> --member <id>` (`--member none` unbinds it; an unbound credential sees no page that names readers). || <a id="access_rule_invalid"></a>`access_rule_invalid` | `gbrain access rule add` was given a rule whose prefix is not a literal lower-case slug folder ending in `/` (or holds `..` or `*`), whose readers are not member ids or `group:<id>`, or whose prefix another rule already covers; nothing was written. Prefixes match slugs literally, so a pattern or typo would restrict the wrong pages. | Write the prefix as a folder such as `partners/alice-example/` and the readers as `alice-example,group:team-a`; to change who reads a folder that already has a rule, pass that rule's `--id`. |diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex 5003abfd5b..b6fadbe377 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -269,13 +269,17 @@ over the running server:```bashgbrain mcp admin attest CLIENT_ID --attest-actor qm [--attest-ops <op,...>] --dry-run \--url https://brain.example.com/mcp --admin-token-file /absolute/private/admin-token-gbrain mcp admin member-add alice-example --url … --admin-token-file …+gbrain mcp admin member-add alice-example --email [email protected] --url … --admin-token-file …gbrain mcp admin link alice-example --qm U0ALICE --dry-run --url … --admin-token-file …+gbrain mcp admin link --email [email protected] --qm U0ALICE --dry-run --url … --admin-token-file …```The other commands are `--attest-actor none` (clear the right),-`member-disable|member-enable ID`, `members [--all]`, `unlink --qm ID` and-`links [--member ID]`. They call `/admin/api/access/attest`, `/admin/api/access/members` and+`member-set ID --email ADDR|none`, `member-disable|member-enable ID`, `members [--all]`,+`unlink --qm ID` and `links [--member ID]`. A member's email is optional,+stored lower-case and unique per brain; `link --email` finds the one member that+declares it and makes the same link `link ID` makes, and an unknown email is+`not_found` and creates nothing. They call `/admin/api/access/attest`, `/admin/api/access/members` and`/admin/api/access/member-links`. These routes accept only the owner session:no OAuth token and no MCP tool reaches them. They refuse exactly what thelocal commands refuse, and each applied change is logged as `access_admin` indiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex b4c0b3a456..33e9a0d51b 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1611 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot)+src/core/behavior-change-notice.ts 1612 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot)diff --git a/src/commands/access.ts b/src/commands/access.tsindex 12db4eeeae..ac7c87e657 100644--- a/src/commands/access.ts+++ b/src/commands/access.ts@@ -1,8 +1,9 @@/*** GBRA-218: `gbrain access`, the operator surface for per-member read access.*- * gbrain access member add|disable|enable|rm|list <id> [--name N] [--groups a,b] [--bind-token <name>]- * gbrain access member link <id> --qm <canonical id> | unlink --qm <canonical id> | links [--member <id>]+ * gbrain access member add|disable|enable|rm|list <id> [--name N] [--email <addr>] [--groups a,b] [--bind-token <name>]+ * gbrain access member set <id> --email <addr>|none+ * gbrain access member link <id>|--email <addr> --qm <canonical id> | unlink --qm <canonical id> | links [--member <id>]* gbrain access group add|rm|list <group> [--members a,b]* gbrain access who-can-read <slug> [--source <id>]* gbrain access check --token <name>|--client <id> [--as a,b]@@ -22,22 +23,27 @@ import { resolveTokenGrant } from '../core/grants/legacy-token.ts';import { isPrivacyPrivatePage } from '../core/search/private-visibility.ts';import { identityFor, normalizePrincipal, normalizeReaders, readersAllow } from '../core/access/principals.ts';import { mayActForCovers, singleMemberAudience, type AudiencePrincipal } from '../core/access/audience.ts';-import { linkMember, listMemberLinks, unlinkMember } from '../core/access/actor.ts';+import { linkMember, linkMemberByEmail, listMemberLinks, unlinkMember } from '../core/access/actor.ts';import {addGroup, addMember, assertAccessId, disableMember, enableMember, getMember, legacyTokenByName, listGroups, listMembers,- parseIdList, previewRemoveGroup, previewRemoveMember, removeGroup, removeGroupMembers, removeMember, type MemberRecord,+ parseIdList, previewRemoveGroup, previewRemoveMember, removeGroup, removeGroupMembers, removeMember, setMemberEmail, type MemberRecord,} from '../core/access/members.ts';export const ACCESS_USAGE = `gbrain access: per-member read access inside one brainMembers and groups:- gbrain access member add <id> [--name <display name>] [--groups a,b] [--bind-token <token name>]+ gbrain access member add <id> [--name <display name>] [--email <addr>] [--groups a,b] [--bind-token <token name>]+ gbrain access member set <id> --email <addr>|none+ Declare or clear the email an operator finds the member by+ (case-folded, unique per brain)gbrain access member disable <id> Reversible: the member and its credentials stop readinggbrain access member enable <id>gbrain access member rm <id> [--yes] Preview first; --yes removes for good (the id is never reused)gbrain access member list [--all] --all includes removed idsgbrain access member link <id> --qm <canonical id> [--dry-run]An attested QM call naming that person reads and writes as <id>+ gbrain access member link --email <addr> --qm <canonical id> [--dry-run]+ The same link, to the member that declares <addr>gbrain access member unlink --qm <canonical id> [--dry-run]gbrain access member links [--member <id>] Canonical ids are compared exactly (no case folding)gbrain access group add <group> [--members a,b]@@ -79,7 +85,7 @@ function flagValue(args: string[], name: string): string | undefined {return v;}-const VALUE_FLAGS = new Set(['--name', '--groups', '--bind-token', '--members', '--source', '--token', '--client', '--as', '--qm', '--member']);+const VALUE_FLAGS = new Set(['--name', '--groups', '--bind-token', '--members', '--source', '--token', '--client', '--as', '--qm', '--member', '--email']);function positionals(args: string[]): string[] {const out: string[] = [];@@ -91,7 +97,7 @@ function positionals(args: string[]): string[] {}function memberLine(m: MemberRecord): string {- return ` ${m.id}${m.display_name ? ` (${m.display_name})` : ''} ${m.status}${m.groups.length ? ` groups: ${m.groups.join(', ')}` : ''}`;+ return ` ${m.id}${m.display_name ? ` (${m.display_name})` : ''} ${m.status}${m.email ? ` email: ${m.email}` : ''}${m.groups.length ? ` groups: ${m.groups.join(', ')}` : ''}`;}export interface WhoCanReadEntry {@@ -203,7 +209,7 @@ async function memberCmd(engine: BrainEngine, sub: string | undefined, args: strconst id = positionals(args)[0];switch (sub) {case 'add': {- const r = await addMember(engine, id, { name: flagValue(args, '--name'), groups: parseIdList(flagValue(args, '--groups'), 'group'), bindToken: flagValue(args, '--bind-token') });+ const r = await addMember(engine, id, { name: flagValue(args, '--name'), email: flagValue(args, '--email'), groups: parseIdList(flagValue(args, '--groups'), 'group'), bindToken: flagValue(args, '--bind-token') });return print(json, r, () => [`Member added: ${r.member.id}`, memberLine(r.member),...(r.groups_created.length ? [` Groups created: ${r.groups_created.join(', ')}`] : []),...(r.bound ? [` Bound token: ${r.bound.name} (${r.bound.id})`] : [' Bind a credential: gbrain auth rescope --token <name> --member ' + r.member.id]),@@ -215,6 +221,12 @@ async function memberCmd(engine: BrainEngine, sub: string | undefined, args: strreturn print(json, { member: m }, () => [`Member ${sub}d: ${m.id}`, memberLine(m),sub === 'disable' ? 'Its credentials are refused on their next request; gbrain access member enable undoes this.' : 'Its credentials read again on their next request.']);}+ case 'set': {+ const email = flagValue(args, '--email');+ if (email === undefined) throw usageError('access member set needs --email <addr>|none.', 'gbrain access member set <id> --email <addr>|none');+ const r = await setMemberEmail(engine, id, email === 'none' ? null : email);+ return print(json, r, () => [`${r.changed ? 'Member updated' : 'Unchanged'}: ${r.member.id}`, memberLine(r.member)]);+ }case 'rm': {const yes = args.includes('--yes');const r = yes ? await removeMember(engine, id) : await previewRemoveMember(engine, id);@@ -234,7 +246,7 @@ async function memberCmd(engine: BrainEngine, sub: string | undefined, args: strcase 'links':return memberLinksCmd(engine, sub, args, json, id);default:- throw usageError(`Unknown access member subcommand: ${sub ?? '(none)'}.`, 'Use add, disable, enable, rm, list, link, unlink or links (gbrain access --help).');+ throw usageError(`Unknown access member subcommand: ${sub ?? '(none)'}.`, 'Use add, set, disable, enable, rm, list, link, unlink or links (gbrain access --help).');}}@@ -246,9 +258,15 @@ async function memberLinksCmd(engine: BrainEngine, sub: 'link' | 'unlink' | 'linreturn print(json, { links }, () => links.length ? ['Links:', ...links.map(l => ` ${l.system}:${l.external_id} -> ${l.member_id}`)] : ['No links. Add one: gbrain access member link <id> --qm <canonical id>']);}const externalId = flagValue(args, '--qm');- if (externalId === undefined) throw usageError(`access member ${sub} needs --qm <canonical id>.`, sub === 'link' ? 'gbrain access member link <id> --qm <canonical id> [--dry-run]' : 'gbrain access member unlink --qm <canonical id> [--dry-run]');+ if (externalId === undefined) throw usageError(`access member ${sub} needs --qm <canonical id>.`, sub === 'link' ? 'gbrain access member link <id>|--email <addr> --qm <canonical id> [--dry-run]' : 'gbrain access member unlink --qm <canonical id> [--dry-run]');const dryRun = args.includes('--dry-run');- const r = sub === 'link' ? await linkMember(engine, id, 'qm', externalId, { dryRun }) : await unlinkMember(engine, 'qm', externalId, { dryRun });+ const email = flagValue(args, '--email');+ if (email !== undefined && (sub === 'unlink' || id !== undefined)) {+ throw usageError(sub === 'link' ? 'access member link takes a member id or --email, not both.' : 'access member unlink takes only --qm.',+ sub === 'link' ? 'gbrain access member link <id> --qm <canonical id>, or gbrain access member link --email <addr> --qm <canonical id>' : 'gbrain access member unlink --qm <canonical id> [--dry-run]');+ }+ const r = sub === 'unlink' ? await unlinkMember(engine, 'qm', externalId, { dryRun })+ : email !== undefined ? await linkMemberByEmail(engine, email, 'qm', externalId, { dryRun }) : await linkMember(engine, id, 'qm', externalId, { dryRun });return print(json, r, () => [`${r.applied ? (sub === 'link' ? 'Linked' : 'Unlinked') : `Would ${sub}`} ${r.link.system}:${r.link.external_id} ${sub === 'link' ? '->' : 'from'} ${r.link.member_id}`,r.applied ? 'Takes effect on the next attested call.' : `Apply without --dry-run.`]);}diff --git a/src/commands/mcp-admin.ts b/src/commands/mcp-admin.tsindex f8716806c5..531f733c47 100644--- a/src/commands/mcp-admin.ts+++ b/src/commands/mcp-admin.ts@@ -19,10 +19,12 @@ gbrain mcp admin setup ID --harness ID [--flow authorization-code|client-credentgbrain mcp admin invalidate-tokens|revoke|delete ID [--yes --if-version N]gbrain mcp admin attest CLIENT_ID --attest-actor qm|none [--attest-ops LIST] [--dry-run]gbrain mcp admin members [--all]-gbrain mcp admin member-add ID [--name NAME] [--groups G1,G2]+gbrain mcp admin member-add ID [--name NAME] [--email ADDR] [--groups G1,G2]+gbrain mcp admin member-set ID --email ADDR|nonegbrain mcp admin member-disable|member-enable IDgbrain mcp admin links [--member ID]gbrain mcp admin link MEMBER --qm CANONICAL_ID [--dry-run]+gbrain mcp admin link --email ADDR --qm CANONICAL_ID [--dry-run]gbrain mcp admin unlink --qm CANONICAL_ID [--dry-run]--url URL Running server URL or /mcp endpoint (required)@@ -40,6 +42,7 @@ gbrain mcp admin unlink --qm CANONICAL_ID [--dry-run]--attest-actor qm|none Grant or clear the right to name the person a call serves (x-qm-actor)--attest-ops LIST Operations an attested call may run (default get_write_request,memory_recall,memory_write)--qm ID A canonical person id from the trusted system+--email ADDR A member's declared email (case-folded, unique); link finds the member by it--timeout-ms N Request timeout, 100..300000 (default: 30000)--json Structured result; credentials stay in private exports@@ -63,8 +66,8 @@ const commandValues: Record<string, string[]> = {register: ['--redirect-uri', '--token-endpoint-auth-method', '--source', '--federated-read', '--scopes', '--profile', '--credentials-out', '--harness'],setup: ['--harness', '--flow', '--credentials-out'],'invalidate-tokens': ['--if-version'], revoke: ['--if-version'], delete: ['--if-version'],- attest: ['--attest-actor', '--attest-ops'], members: [], 'member-add': ['--name', '--groups'], 'member-disable': [], 'member-enable': [],- links: ['--member'], link: ['--qm'], unlink: ['--qm'],+ attest: ['--attest-actor', '--attest-ops'], members: [], 'member-add': ['--name', '--groups', '--email'], 'member-set': ['--email'], 'member-disable': [], 'member-enable': [],+ links: ['--member'], link: ['--qm', '--email'], unlink: ['--qm'],};const untargeted = ['login-link', 'clients', 'members', 'links', 'unlink'];const previewable = ['register', 'invalidate-tokens', 'revoke', 'delete', 'attest', 'link', 'unlink'];@@ -72,7 +75,7 @@ const previewable = ['register', 'invalidate-tokens', 'revoke', 'delete', 'attesexport function parseMcpAdmin(args: string[]): AdminArgs {const command = args[0];if (!command || !Object.hasOwn(commandValues, command)) throw new McpAdminError('invalid_admin_command', `Expected one of: ${Object.keys(commandValues).join(', ')}. Use mcp admin --help.`);- const targeted = !untargeted.includes(command);+ const targeted = !untargeted.includes(command) && !(command === 'link' && args[1]?.startsWith('-'));const target = targeted ? args[1] : undefined;if (targeted && (!target || target.startsWith('-'))) throw new McpAdminError('missing_target', `${command} requires ${command === 'register' ? 'a name' : command.startsWith('member') || command === 'link' ? 'a member ID' : 'a client ID'}.`);const allowedValues = new Set([...common, ...commandValues[command]]);@@ -113,7 +116,13 @@ const ACCESS_COMMANDS: Record<string, (client: AdminClient, parsed: AdminArgs, v},members: (client, parsed) => client.request(`/admin/api/access/members${parsed.flags.has('--all') ? '?all=1' : ''}`),'member-add': (client, parsed, value) => client.request('/admin/api/access/members', { method: 'POST', mutation: true, nextAction: `gbrain mcp admin members --url ${client.base}`,- body: { action: 'add', id: parsed.target, ...(value('--name') === undefined ? {} : { name: value('--name') }), ...(value('--groups') === undefined ? {} : { groups: list(value('--groups')) }) } }),+ body: { action: 'add', id: parsed.target, ...(value('--name') === undefined ? {} : { name: value('--name') }), ...(value('--email') === undefined ? {} : { email: value('--email') }),+ ...(value('--groups') === undefined ? {} : { groups: list(value('--groups')) }) } }),+ 'member-set': (client, parsed, value) => {+ const email = value('--email');+ if (email === undefined) throw new McpAdminError('invalid_arguments', 'member-set needs --email <addr>|none.');+ return client.request('/admin/api/access/members', { method: 'POST', mutation: true, nextAction: `gbrain mcp admin members --url ${client.base}`, body: { action: 'set', id: parsed.target, email: email === 'none' ? null : email } });+ },'member-disable': (client, parsed) => client.request('/admin/api/access/members', { method: 'POST', mutation: true, nextAction: `gbrain mcp admin members --url ${client.base}`, body: { action: 'disable', id: parsed.target } }),'member-enable': (client, parsed) => client.request('/admin/api/access/members', { method: 'POST', mutation: true, nextAction: `gbrain mcp admin members --url ${client.base}`, body: { action: 'enable', id: parsed.target } }),links: (client, _parsed, value) => client.request(`/admin/api/access/member-links${value('--member') ? `?member=${encodeURIComponent(value('--member')!)}` : ''}`),@@ -124,9 +133,11 @@ const ACCESS_COMMANDS: Record<string, (client: AdminClient, parsed: AdminArgs, vfunction linkRequest(client: AdminClient, parsed: AdminArgs, value: (flag: string) => string | undefined, action: 'link' | 'unlink'): Promise<unknown> {const externalId = value('--qm');if (externalId === undefined) throw new McpAdminError('invalid_arguments', `${action} needs --qm <canonical id>.`);+ const email = value('--email');+ if (action === 'link' && (email === undefined) === (parsed.target === undefined)) throw new McpAdminError('invalid_arguments', 'link needs a member ID or --email <addr>, not both.');const dryRun = parsed.flags.has('--dry-run');return client.request('/admin/api/access/member-links', { method: 'POST', mutation: !dryRun, nextAction: `gbrain mcp admin links --url ${client.base}`,- body: { action, externalId, dryRun, ...(action === 'link' ? { member: parsed.target } : {}) } });+ body: { action, externalId, dryRun, ...(action === 'link' ? (email === undefined ? { member: parsed.target } : { email }) : {}) } });}function destinationAvailable(path: string): void {diff --git a/src/commands/serve-http-access.ts b/src/commands/serve-http-access.tsindex e7d6141ce3..2f4f124c24 100644--- a/src/commands/serve-http-access.ts+++ b/src/commands/serve-http-access.ts@@ -1,8 +1,8 @@import express, { type Express, type Request, type Response, type RequestHandler } from 'express';import type { BrainEngine } from '../core/engine.ts';import { OperationError } from '../core/ops/contract.ts';-import { addMember, bindCredential, disableMember, enableMember, listMembers, type BindingPatch } from '../core/access/members.ts';-import { ATTEST_SYSTEMS, linkMember, listMemberLinks, parseAttestOps, unlinkMember } from '../core/access/actor.ts';+import { addMember, bindCredential, disableMember, enableMember, listMembers, setMemberEmail, type BindingPatch } from '../core/access/members.ts';+import { ATTEST_SYSTEMS, linkMember, linkMemberByEmail, listMemberLinks, parseAttestOps, unlinkMember } from '../core/access/actor.ts';import { operationsByName } from '../core/operations.ts';import { executeRawJsonb } from '../core/sql-query.ts';@@ -11,25 +11,33 @@ import { executeRawJsonb } from '../core/sql-query.ts';* right on a client, members, and the canonical ids linked to them. Owner session only (requireAdmin); never an MCP* operation or an OAuth scope. Every refusal is the library's, as on the local CLI (gbrain auth rescope --attest-actor,* gbrain access member add|disable|enable|link|unlink).+ *+ * GST-1158: a member's declared email is set on add or with action set, and a link may name the member by that email+ * instead of its id. Only here and on the brain host: no MCP operation or OAuth scope reads or sets it.*/export function mountAdminAccess(app: Express, requireAdmin: RequestHandler, engine: BrainEngine): void {- const json = express.json();-app.get('/admin/api/access/members', requireAdmin, async (req, res) => {await answer(res, false, async () => ({ members: await listMembers(engine, { includeRemoved: req.query.all === '1' || req.query.all === 'true' }) }));});- app.post('/admin/api/access/members', requireAdmin, json, async (req, res) => {+ app.post('/admin/api/access/members', requireAdmin, express.json(), async (req, res) => {const { action, id } = req.body ?? {};- if (action !== 'add' && action !== 'disable' && action !== 'enable') return refuse(res, 'action must be add, disable or enable.');+ if (action !== 'add' && action !== 'set' && action !== 'disable' && action !== 'enable') return refuse(res, 'action must be add, set, disable or enable.');+ if (action === 'add' && req.body.email !== undefined && typeof req.body.email !== 'string') return refuse(res, 'email must be a string.');+ if (action === 'set' && !(typeof req.body.email === 'string' || req.body.email === null)) return refuse(res, 'set needs email: an address, or null to clear it.');if (action === 'add' && req.body.name !== undefined && typeof req.body.name !== 'string') return refuse(res, 'name must be a string.');if (action === 'add' && req.body.groups !== undefined && !(Array.isArray(req.body.groups) && req.body.groups.every((g: unknown) => typeof g === 'string'))) return refuse(res, 'groups must be an array of group ids.');await answer(res, true, async () => {if (action === 'add') {- const result = await addMember(engine, id, { name: req.body.name, groups: req.body.groups });+ const result = await addMember(engine, id, { name: req.body.name, email: req.body.email, groups: req.body.groups });await audit(engine, 'member_add', { member: result.member.id, groups_created: result.groups_created });return { applied: true, ...result };}+ if (action === 'set') {+ const result = await setMemberEmail(engine, id, req.body.email);+ if (result.changed) await audit(engine, 'member_set', { member: result.member.id, email: result.member.email === null ? 'cleared' : 'declared' });+ return { applied: result.changed, ...result };+ }const member = await (action === 'disable' ? disableMember : enableMember)(engine, id);await audit(engine, `member_${action}`, { member: member.id });return { applied: true, member };@@ -41,20 +49,22 @@ export function mountAdminAccess(app: Express, requireAdmin: RequestHandler, engawait answer(res, false, async () => ({ links: await listMemberLinks(engine, { member }) }));});- app.post('/admin/api/access/member-links', requireAdmin, json, async (req, res) => {- const { action, member, externalId, dryRun } = req.body ?? {};+ app.post('/admin/api/access/member-links', requireAdmin, express.json(), async (req, res) => {+ const { action, member, email, externalId, dryRun } = req.body ?? {};const system = req.body?.system ?? 'qm';if (action !== 'link' && action !== 'unlink') return refuse(res, 'action must be link or unlink.');+ if (email !== undefined && (action !== 'link' || member !== undefined || typeof email !== 'string')) return refuse(res, 'email names the member of a link, instead of member; it is a string and only link takes it.');if (!ATTEST_SYSTEMS.includes(system)) return refuse(res, `system must be ${ATTEST_SYSTEMS.join(' or ')}.`);if (dryRun !== undefined && typeof dryRun !== 'boolean') return refuse(res, 'dryRun must be a boolean.');await answer(res, dryRun !== true, async () => {- const result = action === 'link' ? await linkMember(engine, member, system, externalId, { dryRun }) : await unlinkMember(engine, system, externalId, { dryRun });+ const result = action === 'unlink' ? await unlinkMember(engine, system, externalId, { dryRun })+ : email !== undefined ? await linkMemberByEmail(engine, email, system, externalId, { dryRun }) : await linkMember(engine, member, system, externalId, { dryRun });if (result.applied) await audit(engine, `member_${action}`, { system, external_id: result.link.external_id, member: result.link.member_id });return result;});});- app.post('/admin/api/access/attest', requireAdmin, json, async (req, res) => {+ app.post('/admin/api/access/attest', requireAdmin, express.json(), async (req, res) => {const { clientId, attestActor, attestOps, dryRun } = req.body ?? {};if (typeof clientId !== 'string' || !clientId) return refuse(res, 'clientId required.');if (attestActor === undefined && attestOps === undefined) return refuse(res, 'Pass attestActor (qm or null) and/or attestOps.');diff --git a/src/core/access/actor.ts b/src/core/access/actor.tsindex ebb2fe6ec9..d23b47aacc 100644--- a/src/core/access/actor.ts+++ b/src/core/access/actor.ts@@ -19,7 +19,7 @@ import { catalogueError, ERROR_CATALOGUE } from '../error-catalogue.ts';import type { CallerAccess } from '../search/private-visibility.ts';import { identityFor } from './principals.ts';import { isMissingSchemaObject } from '../utils.ts';-import { memberIdentity } from './members.ts';+import { memberByEmail, memberIdentity } from './members.ts';import { folderAccessFor } from './caller.ts';import { ACTOR_ARGUMENT, ACTOR_DEFERRED_OPS, ACTOR_HEADER, attestRightFrom, DEFAULT_ATTEST_OPS, EXTERNAL_ID_RE, QM_AUDIENCE_HEADER, type AttestedActor, type AttestRight } from './actor-model.ts';@@ -291,6 +291,11 @@ export async function linkMember(engine: BrainEngine, rawMember: unknown, systemreturn { link: (await linkRow(engine, system, externalId))!, applied: true };}+/** GST-1158: the operator names the member by its declared email (memberByEmail); the link is then exactly linkMember's. */+export async function linkMemberByEmail(engine: BrainEngine, rawEmail: unknown, system: string, rawId: unknown, opts: { dryRun?: boolean } = {}): Promise<{ link: MemberLink; applied: boolean }> {+ return linkMember(engine, (await memberByEmail(engine, rawEmail)).id, system, rawId, opts);+}+/** Removes one link; the next attested call naming the id is refused (actor_unlinked). */export async function unlinkMember(engine: BrainEngine, system: string, rawId: unknown, opts: { dryRun?: boolean } = {}): Promise<{ link: MemberLink; applied: boolean }> {const externalId = assertExternalId(rawId);diff --git a/src/core/access/members.ts b/src/core/access/members.tsindex c9778bba91..9d2587ccc9 100644--- a/src/core/access/members.ts+++ b/src/core/access/members.ts@@ -10,6 +10,10 @@* refuses a tombstoned id (access_member_id_retired). `disableMember` is the* reversible option. A credential bound to a disabled, tombstoned or missing* member is refused at verification (`verifiedMember`, access_member_disabled).+ *+ * GST-1158: a member may carry one operator-declared email (case-folded,+ * unique per brain), only so the operator can find the member when linking a+ * trusted system's id (`memberByEmail`). It never creates a member or a link.*/import type { BrainEngine } from '../engine.ts';import type { SqlQuery } from '../sql-query.ts';@@ -21,6 +25,7 @@ import { ACTOR_DEFERRED_OPS } from './actor-model.ts';export interface MemberRecord {id: string;display_name: string | null;+ email: string | null;status: 'enabled' | 'disabled' | 'removed';groups: string[];created_at: string | null;@@ -62,6 +67,17 @@ export function assertAccessId(raw: unknown, what: 'member' | 'group' = 'member''Ids are matched exactly against page readers, so only one canonical spelling is accepted.');}+const EMAIL_RE = /^[^@\s]+@[^@\s]+$/;++/** GST-1158: a declared email, trimmed and case-folded (ASCII only); throws access_member_invalid (invalid_email) otherwise. */+export function assertMemberEmail(raw: unknown): string {+ const email = typeof raw === 'string' ? raw.trim().replace(/[A-Z]/g, c => c.toLowerCase()) : '';+ if (email.length <= 254 && EMAIL_RE.test(email) && !/[\x00-\x1f\x7f]/.test(email)) return email;+ throw memberInvalid('That is not a valid email address.', 'invalid_email',+ 'Use one address with a single @ and no spaces, at most 254 characters (for example [email protected]).',+ 'An email only finds the member an operator links, so one canonical spelling keeps that lookup exact.');+}+/** A comma-separated list of ids, each validated; empty entries dropped. */export function parseIdList(raw: string | undefined, what: 'member' | 'group'): string[] {return [...new Set((raw ?? '').split(',').map(s => s.trim()).filter(Boolean).map(s => assertAccessId(s, what)))];@@ -76,13 +92,14 @@ function toRecord(row: Record<string, unknown>): MemberRecord {return {id: String(row.id),display_name: (row.display_name as string | null) ?? null,+ email: (row.email as string | null) ?? null,status: row.tombstoned_at != null ? 'removed' : row.disabled_at != null ? 'disabled' : 'enabled',groups: Array.isArray(row.groups) ? (row.groups as string[]) : [],created_at: iso(row.created_at),};}-const MEMBER_SELECT = `SELECT m.id, m.display_name, m.disabled_at, m.tombstoned_at, m.created_at,+const MEMBER_SELECT = `SELECT m.id, m.display_name, m.email, m.disabled_at, m.tombstoned_at, m.created_at,COALESCE(array_agg(g.group_id ORDER BY g.group_id) FILTER (WHERE g.group_id IS NOT NULL), '{}') AS groupsFROM access_members m LEFT JOIN access_group_members g ON g.member_id = m.id`;@@ -106,6 +123,29 @@ async function existingMember(engine: BrainEngine, raw: unknown, action: string)`Only an existing member can be ${action}; an unknown id is refused rather than read as unbound.`);}+async function assertEmailFree(engine: BrainEngine, email: string, memberId: string): Promise<void> {+ const [row] = await engine.executeRaw<{ id: string }>('SELECT id FROM access_members WHERE email = $1', [email]);+ if (!row || row.id === memberId) return;+ throw memberInvalid(`Member "${row.id}" already declares that email.`, 'email_taken',+ `Check the address, or clear it there first: gbrain access member set ${row.id} --email none.`,+ 'An email finds exactly one member, so it is unique per brain.');+}++/** GST-1158: the one member whose declared email is `raw`; not_found when none, refused when several. Never creates one. */+export async function memberByEmail(engine: BrainEngine, raw: unknown): Promise<MemberRecord> {+ const email = assertMemberEmail(raw);+ const rows = await engine.executeRaw<Record<string, unknown>>(`${MEMBER_SELECT} WHERE m.email = $1 GROUP BY m.id ORDER BY m.id`, [email]);+ if (rows.length === 1) return toRecord(rows[0]!);+ if (!rows.length) {+ throw opError('not_found', 'No member declares that email.',+ 'List members and their emails with gbrain access member list, or declare it: gbrain access member set <id> --email <addr>.',+ { why: 'An email only finds a member an operator declared it on; it never creates a member or a link.', fix: MEMBER_LIST_FIX });+ }+ throw memberInvalid(`${rows.length} members declare that email.`, 'email_ambiguous',+ 'Link by member id instead (gbrain access member link <id> --qm <canonical id>), and clear the duplicate with gbrain access member set <id> --email none.',+ 'A link by email is made only when exactly one member declares it.');+}+/** The enabled member `raw` names, or a refusal saying why it cannot be used. */async function requireEnabledMember(engine: BrainEngine, raw: unknown): Promise<MemberRecord> {const member = await existingMember(engine, raw, 'bound or previewed');@@ -142,9 +182,10 @@ export async function legacyTokenByName(engine: BrainEngine, name: string): Promexport interface AddMemberResult { member: MemberRecord; groups_created: string[]; bound: CredentialRef | null }-export async function addMember(engine: BrainEngine, rawId: unknown, opts: { name?: string; groups?: readonly string[]; bindToken?: string } = {}): Promise<AddMemberResult> {+export async function addMember(engine: BrainEngine, rawId: unknown, opts: { name?: string; email?: unknown; groups?: readonly string[]; bindToken?: string } = {}): Promise<AddMemberResult> {const id = assertAccessId(rawId);const groups = (opts.groups ?? []).map(g => assertAccessId(g, 'group'));+ const email = opts.email === undefined ? null : assertMemberEmail(opts.email);const existing = await getMember(engine, id);if (existing?.status === 'removed') {throw retired(id, 'Choose a new member id (for example with a numeric suffix).',@@ -155,10 +196,11 @@ export async function addMember(engine: BrainEngine, rawId: unknown, opts: { namexisting.status === 'disabled' ? `Enable it with gbrain access member enable ${id}.` : `Change its groups with gbrain access group add <group> --members ${id}.`,'add creates a member once; it never edits an existing one.');}+ if (email !== null) await assertEmailFree(engine, email, id);const bindTarget = opts.bindToken ? await legacyTokenByName(engine, opts.bindToken) : null;let created: string[] = [];await engine.transaction(async tx => {- await tx.executeRaw('INSERT INTO access_members (id, display_name) VALUES ($1, $2)', [id, opts.name ?? null]);+ await tx.executeRaw('INSERT INTO access_members (id, display_name, email) VALUES ($1, $2, $3)', [id, opts.name ?? null, email]);created = await ensureGroups(tx, groups);for (const g of groups) await tx.executeRaw('INSERT INTO access_group_members (group_id, member_id) VALUES ($1, $2) ON CONFLICT DO NOTHING', [g, id]);if (bindTarget) await tx.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id::text = $1', [bindTarget.id, id]);@@ -176,6 +218,17 @@ async function setDisabled(engine: BrainEngine, rawId: unknown, disabled: booleaexport const disableMember = (engine: BrainEngine, id: unknown) => setDisabled(engine, id, true);export const enableMember = (engine: BrainEngine, id: unknown) => setDisabled(engine, id, false);+/** GST-1158: declares (or, with null, clears) a member's email; refuses an invalid address or one another member declares. */+export async function setMemberEmail(engine: BrainEngine, rawId: unknown, rawEmail: unknown): Promise<{ member: MemberRecord; changed: boolean }> {+ const member = await existingMember(engine, rawId, 'changed');+ if (member.status === 'removed') throw retired(member.id, 'Add a new member id instead.', 'A removed member stays removed; its email was cleared when it was removed.');+ const email = rawEmail === null ? null : assertMemberEmail(rawEmail);+ if (email === member.email) return { member, changed: false };+ if (email !== null) await assertEmailFree(engine, email, member.id);+ await engine.executeRaw('UPDATE access_members SET email = $2, updated_at = now() WHERE id = $1', [member.id, email]);+ return { member: (await getMember(engine, member.id))!, changed: true };+}+/** Credentials whose stored binding names `id` (active tokens, clients not deleted). */export async function boundCredentials(engine: BrainEngine, id: string): Promise<CredentialRef[]> {const tokens = await engine.executeRaw<{ id: string; name: string }>(@@ -206,7 +259,7 @@ export async function removeMember(engine: BrainEngine, rawId: unknown): Promiseconst preview = await previewRemoveMember(engine, rawId);if (preview.member.status === 'removed') return preview;await engine.transaction(async tx => {- await tx.executeRaw('UPDATE access_members SET tombstoned_at = now(), disabled_at = COALESCE(disabled_at, now()), updated_at = now() WHERE id = $1', [preview.member.id]);+ await tx.executeRaw('UPDATE access_members SET tombstoned_at = now(), disabled_at = COALESCE(disabled_at, now()), email = NULL, updated_at = now() WHERE id = $1', [preview.member.id]);await tx.executeRaw('DELETE FROM access_group_members WHERE member_id = $1', [preview.member.id]);});return { ...preview, member: (await getMember(engine, preview.member.id))! };diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex aa0d6eac1b..bd349413cf 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1412,6 +1412,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.550.0', id: 'mcp_lane_launcher_8426', text: 'The stdio MCP entry `gbrain setup claude-code|codex` and `gbrain bootstrap hooks` (opencode\'s user-global entry included) register now starts `gbrain serve` through `<gbrain config dir>/hook-launcher/gbrain-hook`, and the hooks from `gbrain bootstrap hooks`, `gbrain bootstrap harness`, the Codex SessionEnd capture and the gbrain plugins start gbrain from the launcher\'s or the plugin\'s own directory, so a session opened in a cloned repository never runs that repository\'s bunfig.toml preload or loads its .env; serve still reads .gbrain-source from the session directory. `gbrain post-upgrade` moves a Claude Code setup MCP entry setup still owns and names the command for every Codex (the turn-rule hook included) and bootstrap entry, doctor `hook_session_cwd` covers them, and `gbrain hook` git probes skip core.fsmonitor and run only in the workspace the install receipt names.' },// GST-927 (GBRA-280) schema-ruled-out empty arguments; release:restamp stamps since at the merge slot.{ since: '0.60.553.0', id: 'empty_nonstring_args_gst927', text: 'Read tools now treat an optional argument as not provided when its own schema rules the value out: 0 where the range starts above zero (limit: 0, around_chunk_id: 0, schema_version: 0 and others), [] where the list must not be empty (types, only, traverse_graph hops), {} where the object needs a field (get_page lines and bytes), false on get_versions diff, and get_page context without grep. These calls used to refuse with invalid_params; now they answer as if the argument were left out. get_page known_as_of beside window or view arguments still refuses, and the refusal names the arguments to drop.' },+ { since: 'TBD', id: 'member_email_link_gst1158', text: 'A member can carry an operator-declared email: `gbrain access member add <id> --email <addr>` or `gbrain access member set <id> --email <addr>|none`, shown by `member list`, stored lower-case and unique per brain, and cleared when the member is removed. `gbrain access member link --email <addr> --qm <id>` (and `gbrain mcp admin link --email`, `member-add --email`, `member-set` over the owner session) links the one member that declares it, exactly as linking by member id does; an unknown email is `not_found` and creates nothing. No OAuth token, attested call or MCP tool can set an email or make a link.' },{ since: 'TBD', id: 'qm_admin_http_gst1094', text: 'The brain owner can now manage the attest right, members and canonical-id links over the running server: `gbrain mcp admin attest <client> --attest-actor qm|none [--attest-ops <list>]`, `member-add`, `member-disable`, `member-enable`, `members`, `link <member> --qm <id>`, `unlink --qm <id>` and `links`, backed by `/admin/api/access/attest`, `/admin/api/access/members` and `/admin/api/access/member-links`. These routes take the owner session only (never an OAuth token or an MCP tool), refuse what the local `gbrain auth rescope` and `gbrain access member` commands refuse, preview with `--dry-run` where those do, and log each applied change as `access_admin`. Removing a member stays a brain-host command.' },];diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex b1aa9c1698..2a1938a1b2 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -14,13 +14,13 @@// (help-text mentions count): accepting an ignored flag is the pre-#2185// status quo; missing a real one breaks working invocations.export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {- 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--approved', '--as', '--attest-actor', '--attest-ops', '--bind-token', '--brain', '--client', '--dry-run', '--expect', '--file', '--grant-types', '--groups', '--help', '--http', '--id', '--if-version', '--json', '--limit', '--may-act-for', '--member', '--members', '--migrate-legacy', '--name', '--operation', '--operations', '--prefix', '--private-pages', '--qm', '--readers', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--source', '--sources', '--takes-holders', '--to', '--token', '--tools-json', '--yes'],+ 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--approved', '--as', '--attest-actor', '--attest-ops', '--bind-token', '--brain', '--client', '--dry-run', '--email', '--expect', '--file', '--grant-types', '--groups', '--help', '--http', '--id', '--if-version', '--json', '--limit', '--may-act-for', '--member', '--members', '--migrate-legacy', '--name', '--operation', '--operations', '--prefix', '--private-pages', '--qm', '--readers', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--source', '--sources', '--takes-holders', '--to', '--token', '--tools-json', '--yes'],'advisor': ['--apply', '--brain', '--help', '--json', '--skills-dir', '--source', '--workspace', '--yes'],'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],'anomalies': ['--all', '--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--request-id', '--sigma', '--since', '--source'],'append': ['--brain', '--expect-tail', '--expected-revision', '--file', '--force', '--help', '--json', '--region', '--request-id', '--separator', '--source'],'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--install', '--json', '--legacy-lock', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--only', '--path', '--prefer-postgres', '--probe', '--repo', '--require-db', '--skip-verify', '--source', '--statement-timeout', '--uninstall', '--url', '--yes'],- 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--allowed-operations', '--apply', '--attest-actor', '--attest-ops', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--enable', '--enable-dcr-insecure', '--expect', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--may-act-for', '--member', '--members', '--migrate-legacy', '--min-trust', '--no-pull', '--operation', '--operations', '--origin', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--private-pages', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retire', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--unsettle', '--usage', '--wait', '--warn-only', '--yes'],+ 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--allowed-operations', '--apply', '--attest-actor', '--attest-ops', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--category', '--cleanup-dead-local-locks', '--client', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--disable', '--dry-run', '--email', '--enable', '--enable-dcr-insecure', '--expect', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--group-by', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--may-act-for', '--member', '--members', '--migrate-legacy', '--min-trust', '--no-pull', '--operation', '--operations', '--origin', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--private-pages', '--probe', '--profile', '--qm', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retire', '--scopes', '--self-transfer', '--shared-skills', '--since', '--slug-prefixes', '--source', '--source-ids', '--sources', '--state', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--unsettle', '--usage', '--wait', '--warn-only', '--yes'],'autopilot': ['--apply', '--batch', '--brain', '--channel', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-embed-cache', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--pause', '--phase', '--quiet', '--reader-mode', '--reason', '--refresh-cache', '--refs', '--remediation-plan', '--repo', '--restart-only', '--resume', '--retry-global', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],'backup': ['--accept-pending', '--as', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--source', '--timeout', '--timings', '--wait'],@@ -51,7 +51,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -77,7 +77,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--gbrain-bin', '--get', '--harness', '--help', '--instructions', '--instructions-only', '--jq', '--json', '--limit', '--name-only', '--no-instructions', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--source-ids', '--workspace', '--yes'],'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--unsettle', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--unsettle', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--as', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],@@ -85,7 +85,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--session', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--yes'],- 'mcp': ['--admin-token-file', '--advertise', '--agent', '--all', '--arg', '--attest-actor', '--attest-ops', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--groups', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--member', '--name', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--qm', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],+ 'mcp': ['--admin-token-file', '--advertise', '--agent', '--all', '--arg', '--attest-actor', '--attest-ops', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--email', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--groups', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--member', '--name', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--qm', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex 5260f9eca3..24d33b04fe 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -38,7 +38,7 @@ const ROWS: readonly Row[] = [['access_group_members', 'out_of_scope', 'no_memory_text', 'group_id member_id'],['access_groups', 'out_of_scope', 'no_memory_text', 'id'],['access_member_links', 'out_of_scope', 'no_memory_text', 'system external_id member_id'],- ['access_members', 'out_of_scope', 'no_memory_text', 'id display_name'],+ ['access_members', 'out_of_scope', 'no_memory_text', 'id display_name email'],['access_pending_coverage', 'out_of_scope', 'no_memory_text', 'source_id prefix reason detail'],['access_policy_migrations', 'out_of_scope', 'no_memory_text', 'id source_id direction phase receipts'],['access_policy_revisions', 'out_of_scope', 'no_memory_text', 'source_id rules digest origin proposed_by approved_by change_kind operation_id'],diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 3bfd94f6ea..c805ed8781 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -77,7 +77,7 @@ export const CODES = {access_policy_store_mismatch: { class: 'host_only', actor: 'user', summary: "A source's persisted folder-rule store (sources.config.access_store) disagrees with what this host sees (a git store with no visible work tree, or a database store whose root became a repository), so the persisted store and its applied rules stay in force and nothing switches on its own.", why: 'Inferring the store per host would let a missing checkout or a stray git init change which rules apply; only gbrain access rule migrate moves them, and neither direction widens.', suggestion: 'On the brain host, preview the move with gbrain access rule migrate --source <id>, then apply it by adding --yes.', fix: { argv: ['gbrain', 'access', 'rule', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the persisted store and the applied rules; changes nothing.' } },access_rule_invalid: { class: 'caller', docs: 'docs/guides/write-refusals.md#access_rule_invalid', summary: 'A folder rule given to gbrain access rule add is invalid (its prefix is not a literal lower-case folder ending in /, holds .. or *, its readers are not member ids or group:<id>, or another rule already covers the prefix), so nothing was written.', why: 'Prefixes are matched literally against slugs; a pattern or a typo would silently restrict the wrong pages or none.', suggestion: 'Write the prefix as a slug folder ending in / (partners/alice-example/) and the readers as member ids or group:<id>.' },access_member_id_retired: { class: 'caller', summary: "The member id was removed earlier and member ids are never reused, so nothing was created or enabled.", why: 'Pages and audit history may still name a removed id; reusing it would hand that history to a different person.', docs: 'docs/guides/write-refusals.md#access_member_id_retired', suggestion: 'Choose a new member id.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status, removed ones included.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },- access_member_invalid: { class: 'caller', reasons: ['ill_formed', 'unknown', 'disabled', 'removed', 'exists', 'unknown_group', 'invalid_external_id', 'link_exists', 'unknown_link'], summary: "A member or group id given to an access command, a credential binding or --as is ill-formed or names no usable member, so nothing was read or changed.", why: 'Ids are matched exactly against page readers; an unknown or disabled member is refused rather than read as unbound, so a typo never previews or binds the wrong view.', docs: 'docs/guides/write-refusals.md#access_member_invalid', suggestion: 'Check the id with gbrain access member list --all, or add the member first.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },+ access_member_invalid: { class: 'caller', reasons: ['ill_formed', 'unknown', 'disabled', 'removed', 'exists', 'unknown_group', 'invalid_external_id', 'link_exists', 'unknown_link', 'invalid_email', 'email_taken', 'email_ambiguous'], summary: "A member or group id given to an access command, a credential binding or --as is ill-formed or names no usable member, or a declared member email is invalid, taken or ambiguous, so nothing was read or changed.", why: 'Ids are matched exactly against page readers; an unknown or disabled member is refused rather than read as unbound, so a typo never previews or binds the wrong view.', docs: 'docs/guides/write-refusals.md#access_member_invalid', suggestion: 'Check the id with gbrain access member list --all, or add the member first.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },access_denied_test_user: { class: 'host_only', summary: "Google connect credential error: access denied test user.", docs: 'docs/guides/google-connect.md#troubleshooting' },access_env_missing: { class: 'caller', summary: "Google connect credential error: access env missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },acknowledgment_unavailable: { class: 'unavailable', summary: "This batch is unknown or outside the retained replay window." },diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.tsindex a6c4d0f167..329bb6364d 100644--- a/src/core/persistence/graduation-inventory.ts+++ b/src/core/persistence/graduation-inventory.ts@@ -32,7 +32,7 @@ export const GRADUATION_INVENTORY: Inventory = {carry('access_group_members', 'security', 'Group membership behind readable_by group:<id> grants; without it carried pages would resolve readers differently.'),carry('access_groups', 'security', 'Access groups that readable_by names; carried so grants keep meaning the same people.'),carry('access_member_links', 'security', 'Links from attested outside identities (QM actors) to brain members; dropping them would unlink every attested person.'),- carry('access_members', 'security', 'Brain members that readable_by member:<id> names; carried so per-page readers stay the same people.'),+ carry('access_members', 'security', 'Brain members that readable_by member:<id> names, with each declared email; carried so per-page readers stay the same people.'),carry('access_pending_coverage', 'security', 'Prefixes that read as nobody while a narrowing stamps or a policy file is invalid; dropping them would reveal pages.'),carry('access_policy_migrations', 'operational', 'In-flight folder-policy store switches (git and database) and their receipts.'),carry('access_policy_revisions', 'security', 'Folder-policy revision history: desired rules, change class, proposer and approver.'),diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 1cc03f5078..7f0d6e1be8 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 286;+export const LATEST_SCHEMA_VERSION = 287;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 7bb4dcc090..ea870c560b 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -287,6 +287,7 @@ import { v283 } from './v283-folder-access-rules.ts';import { v284 } from './v284-access-page-indexes.ts';import { v285 } from './v285-slug-rename-history.ts';import { v286 } from './v286-qm-actor-links.ts';+import { v287 } from './v287-member-email.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -572,4 +573,5 @@ export const MIGRATIONS: Migration[] = [v284,v285,v286,+ v287,];diff --git a/src/core/schema-migrations/v287-member-email.ts b/src/core/schema-migrations/v287-member-email.tsnew file mode 100644index 0000000000..b19b032052--- /dev/null+++ b/src/core/schema-migrations/v287-member-email.ts@@ -0,0 +1,24 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// GST-1158 (F10a): an operator-declared email on a member, so the operator can+// find the member when linking a trusted system's canonical id+// (gbrain access member link --qm <id> --email <addr>). The operator still makes+// every link; nothing links or changes an email from an attested call. Stored+// case-folded (trimmed, lower-case ASCII) by src/core/access/members.ts, unique+// per brain when set, NULL for every existing member, and cleared when a member+// is removed. Database only, so a repo-less brain gets it unchanged. Nothing is+// rewritten on upgrade. No schema.sql mirror: like v282 and v286, it exists only+// through migrations. Provisional number: renumbered at the merge slot.+export const v287: Migration = {+ version: 287,+ name: 'member_email',+ idempotent: true,+ sql: `+ALTER TABLE access_members ADD COLUMN IF NOT EXISTS email TEXT+ CHECK (email IS NULL OR (length(email) <= 254 AND email ~ '^[^@[:space:]]+@[^@[:space:]]+$'));+CREATE UNIQUE INDEX IF NOT EXISTS access_members_email_key ON access_members (email);+`,+};diff --git a/test/access-binding.serial.test.ts b/test/access-binding.serial.test.tsindex 202d0b5961..0ec83b02b8 100644--- a/test/access-binding.serial.test.ts+++ b/test/access-binding.serial.test.ts@@ -8,6 +8,9 @@* writes no binding; `--may-act-for` is stored normalized; `gbrain access* member rm` previews without `--yes` and a removed id is refused on re-add* with access_member_id_retired (the contract envelope under --json).+ * GST-1158: `member add|set --email` declares a case-folded email, list+ * shows it, and `member link --qm <id> --email <addr>` links the member it+ * names; an unknown email is not_found and creates nothing.* 2. Fails when: a typo mints an unbound token, a rescope preview writes, a* removed id is reused, or the refusal loses its code.* 3. Existing coverage: test/access-members.test.ts (the service in process).@@ -115,6 +118,35 @@ describe('access and auth binding CLI (repo-less PGLite)', () => {expect(await binding('oauth_clients', 'client_id', clientId)).toEqual({ member_id: 'bob-example', may_act_for: null });}, 120_000);+ test('GST-1158: member add and set --email, list shows it, and link --qm --email links the declared member', async () => {+ expect((await cli(['access', 'member', 'add', 'gina-example', '--email', '[email protected]'])).exitCode).toBe(0);+ expect((await cli(['access', 'member', 'add', 'hal-example'])).exitCode).toBe(0);+ expect((await cli(['access', 'member', 'set', 'hal-example', '--email', '[email protected]'])).exitCode).toBe(0);+ const listed = await cli(['access', 'member', 'list']);+ expect(listed.stdout).toContain('gina-example enabled email: [email protected]');+ expect(listed.stdout).toContain('email: [email protected]');+ const taken = await cli(['access', 'member', 'set', 'hal-example', '--email', '[email protected]', '--json']);+ expect(taken.exitCode).not.toBe(0);+ expect(JSON.parse(taken.stdout)).toMatchObject({ code: 'access_member_invalid', reason: 'email_taken' });+ const preview = await cli(['access', 'member', 'link', '--qm', 'U0GINA', '--email', '[email protected]', '--dry-run']);+ expect(preview.exitCode).toBe(0);+ expect(preview.stdout).toContain('Would link qm:U0GINA -> gina-example');+ const linked = await cli(['access', 'member', 'link', '--qm', 'U0GINA', '--email', '[email protected]', '--json']);+ expect(linked.exitCode).toBe(0);+ expect(JSON.parse(linked.stdout)).toMatchObject({ applied: true, link: { system: 'qm', external_id: 'U0GINA', member_id: 'gina-example' } });+ const unknown = await cli(['access', 'member', 'link', '--qm', 'U0NOBODY', '--email', '[email protected]', '--json']);+ expect(unknown.exitCode).not.toBe(0);+ expect(JSON.parse(unknown.stdout)).toMatchObject({ code: 'not_found' });+ const both = await cli(['access', 'member', 'link', 'hal-example', '--qm', 'U0HAL', '--email', '[email protected]']);+ expect(both.exitCode).not.toBe(0);+ expect((await cli(['access', 'member', 'set', 'hal-example', '--email', 'none'])).exitCode).toBe(0);+ await withBrain(async engine => {+ expect(await engine.executeRaw('SELECT id, email FROM access_members WHERE id IN ($1, $2) ORDER BY id', ['gina-example', 'hal-example'])).toEqual([+ { id: 'gina-example', email: '[email protected]' }, { id: 'hal-example', email: null }]);+ expect(await engine.executeRaw('SELECT external_id, member_id FROM access_member_links ORDER BY external_id')).toEqual([{ external_id: 'U0GINA', member_id: 'gina-example' }]);+ });+ }, 180_000);+test('access check reports the binding; member rm previews, --yes removes, and the id is never reused', async () => {const check = await cli(['access', 'check', '--token', 'alice-laptop', '--json']);expect(check.exitCode).toBe(0);diff --git a/test/access-members.test.ts b/test/access-members.test.tsindex 5c771175b6..5f41cad560 100644--- a/test/access-members.test.ts+++ b/test/access-members.test.ts@@ -25,7 +25,7 @@ import { mintLegacyToken } from '../src/core/token-mint.ts';import { OperationError } from '../src/core/ops/contract.ts';import {addGroup, addMember, bindCredential, disableMember, enableMember, getMember, listGroups, listMembers, memberIdentity,- parseMayActFor, previewRemoveGroup, previewRemoveMember, removeGroup, removeGroupMembers, removeMember,+ memberByEmail, parseMayActFor, previewRemoveGroup, previewRemoveMember, removeGroup, removeGroupMembers, removeMember, setMemberEmail,} from '../src/core/access/members.ts';import { accessCheck, whoCanRead } from '../src/commands/access.ts';import { testBackends } from './helpers/test-backends.ts';@@ -175,5 +175,32 @@ for (const kind of testBackends()) {expect((await accessCheck(engine, { token: 'alice-laptop', as: 'bob-example,group:team-a' })).audience).toEqual([{ principal: 'member:bob-example', covered_by_may_act_for: false }, { principal: 'group:team-a', covered_by_may_act_for: false }]);});++ test('GST-1158: a declared email is case-folded, validated and unique; set changes or clears it; rm frees it', async () => {+ const added = await addMember(engine, 'gina-example', { email: ' [email protected] ' });+ expect(added.member).toMatchObject({ id: 'gina-example', email: '[email protected]' });+ expect((await memberByEmail(engine, '[email protected]')).id).toBe('gina-example');+ for (const bad of ['', ' ', 'no-at-sign', 'two@@example.com', 'a@[email protected]', 'has [email protected]', 'tab\[email protected]', '@example.com', 'gina@', `${'x'.repeat(250)}@e.co`, 42]) {+ expect(await refusal(addMember(engine, 'hal-example', { email: bad as string }))).toEqual({ code: 'access_member_invalid', reason: 'invalid_email' });+ }+ expect(await getMember(engine, 'hal-example')).toBeNull();+ expect(await refusal(addMember(engine, 'hal-example', { email: '[email protected]' }))).toEqual({ code: 'access_member_invalid', reason: 'email_taken' });+ expect(await getMember(engine, 'hal-example')).toBeNull();+ expect((await addMember(engine, 'hal-example')).member.email).toBeNull();+ expect(await refusal(setMemberEmail(engine, 'hal-example', '[email protected]'))).toEqual({ code: 'access_member_invalid', reason: 'email_taken' });+ expect(await refusal(setMemberEmail(engine, 'hal-example', 'not an email'))).toEqual({ code: 'access_member_invalid', reason: 'invalid_email' });+ expect(await refusal(setMemberEmail(engine, 'nobody-example', '[email protected]'))).toEqual({ code: 'access_member_invalid', reason: 'unknown' });+ expect(await setMemberEmail(engine, 'hal-example', '[email protected]')).toMatchObject({ member: { id: 'hal-example', email: '[email protected]' }, changed: true });+ expect(await setMemberEmail(engine, 'hal-example', '[email protected]')).toMatchObject({ changed: false });+ expect((await listMembers(engine)).find(m => m.id === 'hal-example')?.email).toBe('[email protected]');+ await expect(engine.executeRaw("UPDATE access_members SET email = '[email protected]' WHERE id = 'gina-example'")).rejects.toThrow();+ expect(await setMemberEmail(engine, 'gina-example', null)).toMatchObject({ member: { email: null }, changed: true });+ expect(await refusal(memberByEmail(engine, '[email protected]'))).toEqual({ code: 'not_found' });+ expect(await refusal(memberByEmail(engine, 'not an email'))).toEqual({ code: 'access_member_invalid', reason: 'invalid_email' });+ await removeMember(engine, 'hal-example');+ expect(await getMember(engine, 'hal-example')).toMatchObject({ status: 'removed', email: null });+ expect(await refusal(setMemberEmail(engine, 'hal-example', '[email protected]'))).toEqual({ code: 'access_member_id_retired' });+ expect((await addMember(engine, 'hal2-example', { email: '[email protected]' })).member.email).toBe('[email protected]');+ });});}diff --git a/test/access-qm-actor.test.ts b/test/access-qm-actor.test.tsindex dd58088d71..aa40e46cd6 100644--- a/test/access-qm-actor.test.ts+++ b/test/access-qm-actor.test.ts@@ -31,8 +31,8 @@ import { startHttpTransport } from '../src/mcp/http-transport.ts';import { RateLimiter } from '../src/mcp/rate-limit.ts';import { GBRAIN_MCP_INSTRUCTIONS, MCP_SERVER_DESCRIPTION } from '../src/mcp/instructions.ts';import { __resetPrivateVisibilityCacheForTests, withCallerAccess } from '../src/core/search/private-visibility.ts';-import { addMember, bindCredential, disableMember, enableMember } from '../src/core/access/members.ts';-import { ACTOR_DEFERRED_OPS, attestedCallerAccess, linkMember, listMemberLinks, parseAttestOps, unlinkMember } from '../src/core/access/actor.ts';+import { addMember, bindCredential, disableMember, enableMember, setMemberEmail } from '../src/core/access/members.ts';+import { ACTOR_DEFERRED_OPS, attestedCallerAccess, linkMember, linkMemberByEmail, listMemberLinks, parseAttestOps, unlinkMember } from '../src/core/access/actor.ts';import { readAudienceAssertions } from '../src/core/access/audience.ts';import { operationsByName } from '../src/core/operations.ts';import { submissionAuthority, authorizeStoredRequest } from '../src/core/persistence/authority.ts';@@ -292,6 +292,43 @@ for (const kind of testBackends()) {expect((await listMemberLinks(engine, { member: 'alice-example' })).map(l => l.external_id).sort()).toEqual([ALICE_ID, LONG_ID, OIDC_ID].sort());}, 60_000);+ test('GST-1158: link by declared email links exactly as link by member id; it never creates a member or picks among several', async () => {+ await setMemberEmail(engine, 'dan-example', '[email protected]');+ try {+ const preview = await linkMemberByEmail(engine, '[email protected]', 'qm', 'U0DAN-EMAIL', { dryRun: true });+ expect(preview).toEqual({ applied: false, link: { system: 'qm', external_id: 'U0DAN-EMAIL', member_id: 'dan-example', created_at: null } });+ expect(await listMemberLinks(engine, { member: 'dan-example' })).toEqual([]);+ expect(await linkMemberByEmail(engine, '[email protected]', 'qm', 'U0DAN-EMAIL')).toMatchObject({ applied: true, link: { system: 'qm', external_id: 'U0DAN-EMAIL', member_id: 'dan-example' } });+ await expect(linkMemberByEmail(engine, '[email protected]', 'qm', 'U0DAN-EMAIL')).rejects.toMatchObject({ code: 'access_member_invalid', reason: 'link_exists' });+ await expect(linkMemberByEmail(engine, '[email protected]', 'qm', ALICE_ID)).rejects.toMatchObject({ code: 'access_member_invalid', reason: 'link_exists' });+ await expect(linkMemberByEmail(engine, '[email protected]', 'qm', 'has space')).rejects.toMatchObject({ code: 'access_member_invalid', reason: 'invalid_external_id' });+ const count = async () => (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM access_members'))[0]!.n;+ const members = await count();+ await expect(linkMemberByEmail(engine, '[email protected]', 'qm', 'U0NOBODY')).rejects.toMatchObject({ code: 'not_found' });+ expect(await count()).toBe(members);+ expect(await engine.executeRaw("SELECT 1 FROM access_member_links WHERE external_id = 'U0NOBODY'")).toEqual([]);+ await disableMember(engine, 'dan-example');+ try {+ await expect(linkMemberByEmail(engine, '[email protected]', 'qm', 'U0DAN-2')).rejects.toMatchObject({ code: 'access_member_invalid', reason: 'disabled' });+ } finally {+ await enableMember(engine, 'dan-example');+ }+ const rollback = new Error('rollback');+ await expect(engine.transaction(async tx => {+ await tx.executeRaw('DROP INDEX access_members_email_key');+ await tx.executeRaw("UPDATE access_members SET email = '[email protected]' WHERE id = 'bob-example'");+ await expect(linkMemberByEmail(tx, '[email protected]', 'qm', 'U0AMBIG')).rejects.toMatchObject({ code: 'access_member_invalid', reason: 'email_ambiguous' });+ expect(await tx.executeRaw("SELECT 1 FROM access_member_links WHERE external_id = 'U0AMBIG'")).toEqual([]);+ throw rollback;+ })).rejects.toBe(rollback);+ expect((await engine.executeRaw<{ email: string | null }>("SELECT email FROM access_members WHERE id = 'bob-example'"))[0]!.email).toBeNull();+ await expect(engine.executeRaw("UPDATE access_members SET email = '[email protected]' WHERE id = 'bob-example'")).rejects.toThrow();+ } finally {+ await unlinkMember(engine, 'qm', 'U0DAN-EMAIL').catch(() => undefined);+ await setMemberEmail(engine, 'dan-example', null);+ }+ }, 60_000);+test('the attest right is granted only to a member-less client-credentials client or legacy token, for attestable ops', async () => {await expect(bindCredential(engine, { kind: 'client', id: clients.code!.id }, { attestActor: 'qm' })).rejects.toMatchObject({ code: 'invalid_params' });await expect(bindCredential(engine, { kind: 'client', id: clients.qm!.id }, { member: 'dan-example' })).rejects.toMatchObject({ code: 'invalid_params' });diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex f4198bc7d4..7dd0352331 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -10,6 +10,7 @@"access_member_links.access_member_links_member_id_fkey": "f FOREIGN KEY (member_id) REFERENCES access_members(id) ON DELETE CASCADE","access_member_links.access_member_links_pkey": "p PRIMARY KEY (system, external_id)","access_member_links.access_member_links_system_check": "c CHECK ((system ~ '^[a-z][a-z0-9_-]{0,31}$'::text))",+ "access_members.access_members_email_check": "c CHECK (((email IS NULL) OR ((length(email) <= 254) AND (email ~ '^[^@[:space:]]+@[^@[:space:]]+$'::text))))","access_members.access_members_id_check": "c CHECK ((id ~ '^[a-z0-9][a-z0-9._-]{0,63}$'::text))","access_members.access_members_pkey": "p PRIMARY KEY (id)","access_pending_coverage.access_pending_coverage_pkey": "p PRIMARY KEY (source_id, prefix, reason)",@@ -1144,6 +1145,7 @@"access_groups_pkey": "CREATE UNIQUE INDEX access_groups_pkey ON public.access_groups USING btree (id)","access_member_links_member_idx": "CREATE INDEX access_member_links_member_idx ON public.access_member_links USING btree (member_id)","access_member_links_pkey": "CREATE UNIQUE INDEX access_member_links_pkey ON public.access_member_links USING btree (system, external_id)",+ "access_members_email_key": "CREATE UNIQUE INDEX access_members_email_key ON public.access_members USING btree (email)","access_members_pkey": "CREATE UNIQUE INDEX access_members_pkey ON public.access_members USING btree (id)","access_pending_coverage_pkey": "CREATE UNIQUE INDEX access_pending_coverage_pkey ON public.access_pending_coverage USING btree (source_id, prefix, reason)","access_policy_migrations_pkey": "CREATE UNIQUE INDEX access_policy_migrations_pkey ON public.access_policy_migrations USING btree (id)",@@ -1737,7 +1739,8 @@"3 disabled_at timestamp with time zone/timestamptz NULL","4 tombstoned_at timestamp with time zone/timestamptz NULL","5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "7 email text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex e4f7385f81..a2de10e2a2 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -10,6 +10,7 @@"access_member_links.access_member_links_member_id_fkey": "f FOREIGN KEY (member_id) REFERENCES access_members(id) ON DELETE CASCADE","access_member_links.access_member_links_pkey": "p PRIMARY KEY (system, external_id)","access_member_links.access_member_links_system_check": "c CHECK ((system ~ '^[a-z][a-z0-9_-]{0,31}$'::text))",+ "access_members.access_members_email_check": "c CHECK (((email IS NULL) OR ((length(email) <= 254) AND (email ~ '^[^@[:space:]]+@[^@[:space:]]+$'::text))))","access_members.access_members_id_check": "c CHECK ((id ~ '^[a-z0-9][a-z0-9._-]{0,63}$'::text))","access_members.access_members_pkey": "p PRIMARY KEY (id)","access_pending_coverage.access_pending_coverage_pkey": "p PRIMARY KEY (source_id, prefix, reason)",@@ -1144,6 +1145,7 @@"access_groups_pkey": "CREATE UNIQUE INDEX access_groups_pkey ON public.access_groups USING btree (id)","access_member_links_member_idx": "CREATE INDEX access_member_links_member_idx ON public.access_member_links USING btree (member_id)","access_member_links_pkey": "CREATE UNIQUE INDEX access_member_links_pkey ON public.access_member_links USING btree (system, external_id)",+ "access_members_email_key": "CREATE UNIQUE INDEX access_members_email_key ON public.access_members USING btree (email)","access_members_pkey": "CREATE UNIQUE INDEX access_members_pkey ON public.access_members USING btree (id)","access_pending_coverage_pkey": "CREATE UNIQUE INDEX access_pending_coverage_pkey ON public.access_pending_coverage USING btree (source_id, prefix, reason)","access_policy_migrations_pkey": "CREATE UNIQUE INDEX access_policy_migrations_pkey ON public.access_policy_migrations USING btree (id)",@@ -1737,7 +1739,8 @@"3 disabled_at timestamp with time zone/timestamptz NULL","4 tombstoned_at timestamp with time zone/timestamptz NULL","5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "7 email text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex c5a2315f26..e9dacf7509 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -10,6 +10,7 @@"access_member_links.access_member_links_member_id_fkey": "f FOREIGN KEY (member_id) REFERENCES access_members(id) ON DELETE CASCADE","access_member_links.access_member_links_pkey": "p PRIMARY KEY (system, external_id)","access_member_links.access_member_links_system_check": "c CHECK ((system ~ '^[a-z][a-z0-9_-]{0,31}$'::text))",+ "access_members.access_members_email_check": "c CHECK (((email IS NULL) OR ((length(email) <= 254) AND (email ~ '^[^@[:space:]]+@[^@[:space:]]+$'::text))))","access_members.access_members_id_check": "c CHECK ((id ~ '^[a-z0-9][a-z0-9._-]{0,63}$'::text))","access_members.access_members_pkey": "p PRIMARY KEY (id)","access_pending_coverage.access_pending_coverage_pkey": "p PRIMARY KEY (source_id, prefix, reason)",@@ -1144,6 +1145,7 @@"access_groups_pkey": "CREATE UNIQUE INDEX access_groups_pkey ON public.access_groups USING btree (id)","access_member_links_member_idx": "CREATE INDEX access_member_links_member_idx ON public.access_member_links USING btree (member_id)","access_member_links_pkey": "CREATE UNIQUE INDEX access_member_links_pkey ON public.access_member_links USING btree (system, external_id)",+ "access_members_email_key": "CREATE UNIQUE INDEX access_members_email_key ON public.access_members USING btree (email)","access_members_pkey": "CREATE UNIQUE INDEX access_members_pkey ON public.access_members USING btree (id)","access_pending_coverage_pkey": "CREATE UNIQUE INDEX access_pending_coverage_pkey ON public.access_pending_coverage USING btree (source_id, prefix, reason)","access_policy_migrations_pkey": "CREATE UNIQUE INDEX access_policy_migrations_pkey ON public.access_policy_migrations USING btree (id)",@@ -1733,7 +1735,8 @@"3 disabled_at timestamp with time zone/timestamptz NULL","4 tombstoned_at timestamp with time zone/timestamptz NULL","5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "7 email text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex ee9ef3da61..87fddde808 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 281,+ "count": 282,"gaps": [17,18,@@ -94,7 +94,7 @@"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67","withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"},- "latest": 286,+ "latest": 287,"records": [{"handler": {@@ -4648,6 +4648,19 @@"transaction": "absent","verify": "absent","version": 286+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "member_email",+ "sql": {+ "length": 247,+ "sha256": "1b29d7c6c2eb5da8c9a81d5580526d5e408a6dd1405b24e0aa24a153d30944c9"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 287}],"versions": [@@ -4931,7 +4944,8 @@283,284,285,- 286+ 286,+ 287]},"normalizer": "migrations-record-v1"diff --git a/test/fixtures/goldens/serve-http/routes-runtime.json b/test/fixtures/goldens/serve-http/routes-runtime.jsonindex dabcb5f177..0229075226 100644--- a/test/fixtures/goldens/serve-http/routes-runtime.json+++ b/test/fixtures/goldens/serve-http/routes-runtime.json@@ -617,6 +617,49 @@"method": "post","path": "/admin/api/rescope-client"},+ {+ "handlers": [+ "requireAdmin#4",+ "<anonymous>"+ ],+ "method": "get",+ "path": "/admin/api/access/members"+ },+ {+ "handlers": [+ "requireAdmin#4",+ "jsonParser",+ "<anonymous>"+ ],+ "method": "post",+ "path": "/admin/api/access/members"+ },+ {+ "handlers": [+ "requireAdmin#4",+ "<anonymous>"+ ],+ "method": "get",+ "path": "/admin/api/access/member-links"+ },+ {+ "handlers": [+ "requireAdmin#4",+ "jsonParser",+ "<anonymous>"+ ],+ "method": "post",+ "path": "/admin/api/access/member-links"+ },+ {+ "handlers": [+ "requireAdmin#4",+ "jsonParser",+ "<anonymous>"+ ],+ "method": "post",+ "path": "/admin/api/access/attest"+ },{"handlers": ["requireAdmin#4",@@ -1341,6 +1384,49 @@"method": "post","path": "/admin/api/rescope-client"},+ {+ "handlers": [+ "requireAdmin#4",+ "<anonymous>"+ ],+ "method": "get",+ "path": "/admin/api/access/members"+ },+ {+ "handlers": [+ "requireAdmin#4",+ "jsonParser",+ "<anonymous>"+ ],+ "method": "post",+ "path": "/admin/api/access/members"+ },+ {+ "handlers": [+ "requireAdmin#4",+ "<anonymous>"+ ],+ "method": "get",+ "path": "/admin/api/access/member-links"+ },+ {+ "handlers": [+ "requireAdmin#4",+ "jsonParser",+ "<anonymous>"+ ],+ "method": "post",+ "path": "/admin/api/access/member-links"+ },+ {+ "handlers": [+ "requireAdmin#4",+ "jsonParser",+ "<anonymous>"+ ],+ "method": "post",+ "path": "/admin/api/access/attest"+ },{"handlers": ["requireAdmin#4",diff --git a/test/fixtures/goldens/serve-http/routes.json b/test/fixtures/goldens/serve-http/routes.jsonindex ce46c0055d..bc28666c85 100644--- a/test/fixtures/goldens/serve-http/routes.json+++ b/test/fixtures/goldens/serve-http/routes.json@@ -454,6 +454,54 @@"path": "/admin/api/rescope-client","when": []},+ {+ "handlers": [+ "requireAdmin",+ "<inline>"+ ],+ "method": "get",+ "path": "/admin/api/access/members",+ "when": []+ },+ {+ "handlers": [+ "requireAdmin",+ "express.json()",+ "<inline>"+ ],+ "method": "post",+ "path": "/admin/api/access/members",+ "when": []+ },+ {+ "handlers": [+ "requireAdmin",+ "<inline>"+ ],+ "method": "get",+ "path": "/admin/api/access/member-links",+ "when": []+ },+ {+ "handlers": [+ "requireAdmin",+ "express.json()",+ "<inline>"+ ],+ "method": "post",+ "path": "/admin/api/access/member-links",+ "when": []+ },+ {+ "handlers": [+ "requireAdmin",+ "express.json()",+ "<inline>"+ ],+ "method": "post",+ "path": "/admin/api/access/attest",+ "when": []+ },{"handlers": ["requireAdmin",diff --git a/test/mcp-admin-cli.serial.test.ts b/test/mcp-admin-cli.serial.test.tsindex c50793e259..453d88559a 100644--- a/test/mcp-admin-cli.serial.test.ts+++ b/test/mcp-admin-cli.serial.test.ts@@ -203,3 +203,28 @@ test('people administration commands send owner-session requests to the access rexpect(serverRefusal.exitCode).toBe(1);});+test('GST-1158: member-add and member-set send a declared email, and link finds the member by --email', async () => {+ const cases: Array<[string[], string, unknown]> = [+ [['member-add', 'alice-example', '--email', '[email protected]'], '/admin/api/access/members', { action: 'add', id: 'alice-example', email: '[email protected]' }],+ [['member-set', 'alice-example', '--email', '[email protected]'], '/admin/api/access/members', { action: 'set', id: 'alice-example', email: '[email protected]' }],+ [['member-set', 'alice-example', '--email', 'none'], '/admin/api/access/members', { action: 'set', id: 'alice-example', email: null }],+ [['link', '--qm', 'ext-alice', '--email', '[email protected]', '--dry-run'], '/admin/api/access/member-links', { action: 'link', externalId: 'ext-alice', dryRun: true, email: '[email protected]' }],+ ];+ for (const [args, path, body] of cases) {+ expect(mcpNeedsEngine(['admin', args[0]!], undefined)).toBe(false);+ const run = await capture(args, () => Response.json({ applied: false }));+ expect(run.exitCode).toBe(0);+ const sent = run.requests.at(-1)!;+ expect(sent.url).toBe(base + path);+ expect(JSON.parse(String(sent.init.body))).toEqual(body);+ expect(run.output).not.toContain(owner);+ }+ for (const args of [['member-set', 'alice-example'], ['link', 'alice-example', '--qm', 'ext-alice', '--email', '[email protected]'], ['link', '--qm', 'ext-alice']]) {+ const refused = await capture(args, () => Response.json({}));+ expect(refused.result).toMatchObject({ status: 'error', reason: 'invalid_arguments' });+ expect(refused.requests.filter(r => !r.url.endsWith('/admin/login'))).toEqual([]);+ }+ const notFound = await capture(['link', '--qm', 'ext-nobody', '--email', '[email protected]'], () => Response.json({ error: 'not_found', code: 'not_found', message: 'No member has that email.', outcome: 'failed' }, { status: 400 }));+ expect(notFound.result.status).toBe('error');+ expect(notFound.exitCode).toBe(1);+});diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex e003c79540..c5cb927c52 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -1217,6 +1217,10 @@ const COLUMN_EXEMPTIONS = new Set<string>(['oauth_clients.attest_actor','oauth_clients.attest_ops','oauth_tokens.grant_type',+ // GST-1158 (migration v287) - a member's operator-declared email. Same posture as v286: access_members exists only+ // through migrations, so no index or function in either blob references it, and only the operator's access commands+ // and owner-session routes read or write it.+ 'access_members.email',// GBRA-218 A2 (migration v283) - folder rules. Same posture as v282: absent from both schema blobs; the migration// creates the folder_rule_ids trigger and functions itself, and no index or function in either blob references it.'pages.folder_rule_ids',diff --git a/test/serve-http-access.test.ts b/test/serve-http-access.test.tsindex fbf5146e24..2cc4cebc92 100644--- a/test/serve-http-access.test.ts+++ b/test/serve-http-access.test.ts@@ -7,6 +7,8 @@* leaves an audit row.* 2. Fails when: a route answers without the owner session, an HTTP change skips a refusal the local CLI makes, a* preview writes, or a change leaves no audit row.+ * GST-1158: a declared member email is set only here and on the brain host, and a link made by email is the same link+ * an id makes; no OAuth token, attested call or MCP operation reaches either.* 3. Real seams: the routes mounted on an Express app over a real socket, OAuth clients registered and issued tokens by* the provider's client-credentials grant and verified by it, on a repo-less brain (PGLite, and Postgres when* DATABASE_URL is set).@@ -24,6 +26,7 @@ import { addMember, bindCredential, getMember } from '../src/core/access/membersimport { listMemberLinks } from '../src/core/access/actor.ts';import { mountAdminAccess } from '../src/commands/serve-http-access.ts';import { createRequireAdmin } from '../src/commands/serve-http-admin-api.ts';+import { operations } from '../src/core/operations.ts';import { testBackends } from './helpers/test-backends.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';@@ -109,6 +112,51 @@ for (const kind of testBackends()) {.toEqual([{ actor: 'admin-api', action: 'member_link', system: 'qm', external_id: 'ext-bob', member: 'bob-example' }, { actor: 'admin-api', action: 'member_unlink', system: 'qm', external_id: 'ext-bob', member: 'bob-example' }]);});+ test('GST-1158: email on member add and set, and link by email, apply with audit rows; refusals hold; nothing changes without the owner session', async () => {+ const qm = await register('qm-email', ['client_credentials']);+ await bindCredential(engine, { kind: 'client', id: qm.clientId }, { attestActor: 'qm' });+ const bearer = (await provider().exchangeClientCredentials(qm.clientId, qm.clientSecret!)).access_token;+ const outsider = async (path: string, body: unknown) => (await fetch(base + path, { method: 'POST', body: JSON.stringify(body),+ headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + bearer, 'x-qm-actor': 'ext-carol' } })).status;+ const before = (await audits()).length;+ expect(await outsider('/admin/api/access/members', { action: 'add', id: 'carol-example', email: '[email protected]' })).toBe(401);+ expect(await outsider('/admin/api/access/members', { action: 'set', id: 'bob-example', email: '[email protected]' })).toBe(401);+ expect(await outsider('/admin/api/access/member-links', { action: 'link', email: '[email protected]', externalId: 'ext-carol' })).toBe(401);+ expect((await call('POST', '/admin/api/access/members', { action: 'set', id: 'bob-example', email: '[email protected]' }, false)).status).toBe(401);+ expect(await getMember(engine, 'carol-example')).toBeNull();+ expect((await getMember(engine, 'bob-example'))!.email).toBeNull();+ expect((await audits()).length).toBe(before);+ for (const op of operations) expect(Object.keys(op.params)).not.toContain('email');++ const added = await call('POST', '/admin/api/access/members', { action: 'add', id: 'carol-example', email: '[email protected]' });+ expect(added.json).toMatchObject({ applied: true, member: { id: 'carol-example', email: '[email protected]' } });+ expect((await call('POST', '/admin/api/access/members', { action: 'add', id: 'dave-example', email: '[email protected]' })).json).toMatchObject({ code: 'access_member_invalid', reason: 'email_taken' });+ expect((await call('POST', '/admin/api/access/members', { action: 'add', id: 'dave-example', email: 'no-at-sign' })).json).toMatchObject({ code: 'access_member_invalid', reason: 'invalid_email' });+ expect((await call('POST', '/admin/api/access/members', { action: 'add', id: 'dave-example', email: 7 })).json).toMatchObject({ code: 'invalid_params' });+ expect(await getMember(engine, 'dave-example')).toBeNull();+ expect((await call('POST', '/admin/api/access/members', { action: 'set', id: 'bob-example' })).json).toMatchObject({ code: 'invalid_params' });+ expect((await call('POST', '/admin/api/access/members', { action: 'set', id: 'bob-example', email: '[email protected]' })).json).toMatchObject({ applied: true, changed: true, member: { id: 'bob-example', email: '[email protected]' } });+ expect((await call('POST', '/admin/api/access/members', { action: 'set', id: 'bob-example', email: '[email protected]' })).json).toMatchObject({ code: 'access_member_invalid', reason: 'email_taken' });+ expect((await call('POST', '/admin/api/access/members', { action: 'set', id: 'bob-example', email: null })).json).toMatchObject({ applied: true, member: { email: null } });+ expect((await call('GET', '/admin/api/access/members')).json.members.find((m: { id: string }) => m.id === 'carol-example')).toMatchObject({ email: '[email protected]' });++ const preview = await call('POST', '/admin/api/access/member-links', { action: 'link', email: '[email protected]', externalId: 'ext-carol', dryRun: true });+ expect(preview.json).toMatchObject({ applied: false, link: { member_id: 'carol-example', external_id: 'ext-carol' } });+ expect(await listMemberLinks(engine, { member: 'carol-example' })).toEqual([]);+ expect((await call('POST', '/admin/api/access/member-links', { action: 'link', email: '[email protected]', member: 'carol-example', externalId: 'ext-carol' })).json).toMatchObject({ code: 'invalid_params' });+ expect((await call('POST', '/admin/api/access/member-links', { action: 'link', email: '[email protected]', externalId: 'ext-nobody' })).json).toMatchObject({ code: 'not_found', outcome: 'failed' });+ expect(await getMember(engine, 'nobody-example')).toBeNull();+ expect((await call('POST', '/admin/api/access/member-links', { action: 'link', email: '[email protected]', externalId: 'ext-carol' })).json).toMatchObject({ applied: true, link: { member_id: 'carol-example' } });+ expect(await listMemberLinks(engine, { member: 'carol-example' })).toMatchObject([{ system: 'qm', external_id: 'ext-carol', member_id: 'carol-example' }]);+ expect((await call('POST', '/admin/api/access/member-links', { action: 'unlink', email: '[email protected]', externalId: 'ext-carol' })).json).toMatchObject({ code: 'invalid_params' });+ expect((await audits()).slice(before)).toEqual([+ { actor: 'admin-api', action: 'member_add', member: 'carol-example', groups_created: [] },+ { actor: 'admin-api', action: 'member_set', member: 'bob-example', email: 'declared' },+ { actor: 'admin-api', action: 'member_set', member: 'bob-example', email: 'cleared' },+ { actor: 'admin-api', action: 'member_link', system: 'qm', external_id: 'ext-carol', member: 'carol-example' },+ ]);+ });+test('attest: a confidential client-credentials client gets the right its next token carries; every CLI refusal holds', async () => {const qm = await register('qm-http', ['client_credentials']);const preview = await call('POST', '/admin/api/access/attest', { clientId: qm.clientId, attestActor: 'qm', dryRun: true });