Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
access: personal-source binding for attested reads (GST-359 wave 2)
garrytan19c5b5914e42
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c3a552280a..232efbcc07 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,8 @@ identifiers and attribution are available in the pre-removal Git revision## [Unreleased]+**An attested person can now read their own DM and member sources through a shared QM client, and nobody else's.** Until now an attested client read only its credential's grant, usually the default source, so facts ingested into a member's own source were never recalled; granting every DM source to the client would have let every attested person read every other person's DM. `gbrain access member source add <member> <source>` now binds a source to the member it belongs to, and a bound source is personal: an attested call (`x-qm-actor`) reads its credential's grant minus every personal source bound to someone else, and a scope read (an attested read that names `source_id` or `source_ids` without `--attest-read person`) reads no personal source at all, not even the speaker's own. A personal source that is hidden is refused exactly like a source outside the grant (`permission_denied`, same message), and an unnamed read simply skips it. The rule only hides inside each credential's grant, so it never makes a source readable: add the DM sources to the client's `federated_read` and bind each to its member. It applies once in MCP dispatch (and to the tool calls of an agent job submitted for an attested person), so `memory_recall`, `query`, `search`, `get_page` and every other read inherit it. Unattested calls and member-bound credentials are unchanged, and nothing changes on upgrade until an operator binds a source. `gbrain access member source remove` previews first and says when the source would stop being personal; `list` shows the bindings. Database state (migration v288), so a repo-less brain works the same. `v1.json` and `v2.json` are unchanged.+**An attested read that names its sources now reads as those sources' audience for every read QM can list, and an operator can say whether a credential serves rooms or one person's own turns.** `get_page`, `entity`, `whois`, `get_backlinks`, `get_timeline`, `find_experts`, `volunteer_context` and `query`, called with `x-qm-actor` and `source_id` or `source_ids`, now read the way `memory_recall` does: the person's restricted pages and their member page read as missing, a source outside the grant is refused, and `__all__` or `all_sources` is refused, so a shared turn can never pull one member's private pages into a channel. `get_timeline` gains `source_id` and `source_ids`, and `find_experts` and `volunteer_context` gain `source_ids`; `volunteer_context` refuses `stats: true` under that read. `gbrain auth rescope --attest-read person|scope|none` sets how a credential reads named sources: `person` narrows to them but reads as the person (for a DM client), and `scope` keeps the audience read and also refuses any call that names no person (`actor_not_attested`, reason `actor_required`). Unset keeps today's behavior, so no existing client changes. `gbrain doctor` warns (`attest_read_shared_scope`) when a person credential reads a source another attest credential reads as the scope. `context_pack` is not covered yet. `v1.json` and `v2.json` are unchanged; on a repo-less brain all of it is database state and works the same.**An attested call can no longer write pages directly: `add_timeline_entry`, `add_link`, `put_page` and `edit_page` are not attestable.** They write to pages that everyone who reads the page sees, so a trusted system acting as one person could put that person's words in front of a whole audience with no one approving them. They now wait for owner-approved proposals, the way `capture` and take writes already do. An operator whose `--attest-ops` list names one of them sees `gbrain auth rescope` refuse the list, and each attested call to it is refused (`actor_not_attested`, reason `op_not_attested`); a queued attested write of one fails when it publishes. Unattested calls, and credentials bound to a member, are unchanged. `v2.json` lists the new deferred operations; `v1.json` is unchanged.diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.mdindex 76e00b13e9..8fcdd1fa60 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`. GST-1158: `scope-read.ts` holds `SCOPE_READ_ACCESS` (no identity, actor or audience; privacy never relaxed) and `SCOPE_READ_OPS`; dispatch runs an attested call to one of those ops that names `source_id`/`source_ids` under that record (`attestedReadMode`, which refuses `__all__`/`all_sources`), or as the person when the right's `attest_read` (v287, `--attest-read`) is `person`, and handlers read the mode with `currentReadMode`. `attest_read = 'scope'` refuses a call that names no actor (`actor_required`). Tests: `test/qm-scope-read.test.ts` (both engines), `test/doctor-attest-read-shared-scope.test.ts`. `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`. GST-1158: `scope-read.ts` holds `SCOPE_READ_ACCESS` (no identity, actor or audience; privacy never relaxed) and `SCOPE_READ_OPS`; dispatch runs an attested call to one of those ops that names `source_id`/`source_ids` under that record (`attestedReadMode`, which refuses `__all__`/`all_sources`), or as the person when the right's `attest_read` (v287, `--attest-read`) is `person`, and handlers read the mode with `currentReadMode`. `attest_read = 'scope'` refuses a call that names no actor (`actor_required`). Tests: `test/qm-scope-read.test.ts` (both engines), `test/doctor-attest-read-shared-scope.test.ts`. GBRA-284: `member-sources.ts` binds a source to its member (`access_member_sources`, v288; `gbrain access member source add|remove|list`); `attestedReadScope`, called in dispatch for every attested call and in `minions/tools/brain-allowlist.ts` for an attested job's tool calls, replaces the call's read grant with the grant minus personal sources bound to another member (every personal source under a scope read), so every resolver refuses or skips them like out-of-grant sources and nothing is added. Test: `test/qm-personal-sources.test.ts` (both engines). `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/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/multi-source-brains.md b/docs/guides/multi-source-brains.mdindex caf237412a..7b4244be60 100644--- a/docs/guides/multi-source-brains.md+++ b/docs/guides/multi-source-brains.md@@ -221,6 +221,13 @@ current member's sources, but a prompt-injected or buggy bot can omit it, soit does not separate members who must not see each other's pages. Useper-member tokens for that, and `source_ids` to narrow further.+A trusted system that names the person on each call (QM's `x-qm-actor`) can+share one client instead: grant it every member's source and bind each source+to its member (`gbrain access member source add alice-example dm-alice-example`).+An attested call then reads the grant minus sources bound to other members,+and binding never adds a source to a grant+([QM guide](qm.md#each-persons-own-sources)).+### Lay out sources by who may read themSource grants are the coarse boundary: without page readers, two pages in onediff --git a/docs/guides/qm.md b/docs/guides/qm.mdindex b2fe867c88..ff9b339c30 100644--- a/docs/guides/qm.md+++ b/docs/guides/qm.md@@ -51,6 +51,32 @@ serves only one person's own conversations; a `person` client that reads a sourcroom client reads is flagged by `gbrain doctor` (`attest_read_shared_scope`). Unset(`none`) reads named sources as the scope and still serves calls that name no person.+### Each person's own sources++A client reads only the sources its credential is granted, usually the default+source, so facts in a member's own DM or member source are not recalled until the+client is granted that source. Grant the client every DM source and bind each one to+its member, so a person reads their own and nobody else's:++```bash+gbrain auth rescope --client <client_id> --sources source-a,dm-alice-example,dm-bob-example+gbrain access member source add alice-example dm-alice-example+gbrain access member source add bob-example dm-bob-example+gbrain access member source list+```++A bound source is personal. An attested call reads its credential's grant minus every+personal source bound to someone else: alice-example's unnamed `memory_recall` reads+source-a and dm-alice-example, never dm-bob-example. A read that names sources as+their audience (the reads above, unless the client is `--attest-read person`) reads+no personal source, not even the speaker's own, so a room never reads a DM. A hidden+source named in `source_id` or `source_ids` is refused exactly like a source outside+the grant (`permission_denied`). Binding only hides inside the grant: a source the+credential is not granted stays unreadable. Unattested calls and member-bound+credentials are unchanged. `gbrain access member source remove <member> <source>`+previews first and says whether the source stays personal; `--yes` applies. Bindings+are database state, so a repo-less brain works the same.+## What the tools do- `memory_recall {query, max_chars?, source_id?, source_ids?}` answers plain text, one fact per linediff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex b0bdd081f0..7595383219 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -267,6 +267,10 @@ An attested read that names `source_id` or `source_ids` (`get_page`, `entity`, ``get_timeline`, `find_experts`, `volunteer_context`, `query`, `memory_recall`) reads those sources as theiraudience, never as the person; `--attest-read person` makes such reads run as the person, and `--attest-read scope`also refuses every call that names no person (`actor_required`) ([QM guide](../guides/qm.md#reads-that-name-sources)).+A source bound to a member (`gbrain access member source add <member> <source>`, trusted local CLI only) is personal:+an attested call reads its grant minus personal sources bound to anyone else, a read that names sources as their+audience reads none, and a hidden source is refused like one outside the grant. Binding never widens a grant+([QM guide](../guides/qm.md#each-persons-own-sources)).`gbrain access check --token <name>` shows theresult ([Model C](../tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape)).diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 02c4a7def9..b9efe22aed 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 1614 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; +4 GST-1094/GST-900: the memory_recall scope-read, member-bound acting_user, recall max_chars and unknown_param _meta-only rows (since TBD until the merge slot)+src/core/behavior-change-notice.ts 1617 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; +4 GST-1094/GST-900: the memory_recall scope-read, member-bound acting_user, recall max_chars and unknown_param _meta-only rows (since TBD until the merge slot); +2 GST-1158 attest_scope_read_ops_gst1158 and attest_direct_page_writes_deferred_gst1158 rows (since TBD until the merge slot); +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot)diff --git a/src/commands/access.ts b/src/commands/access.tsindex 12db4eeeae..f5da9f79aa 100644--- a/src/commands/access.ts+++ b/src/commands/access.ts@@ -3,6 +3,7 @@** 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 source add|remove|list <member> [<source>]* 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]@@ -23,6 +24,7 @@ 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 { bindMemberSource, listMemberSources, unbindMemberSource } from '../core/access/member-sources.ts';import {addGroup, addMember, assertAccessId, disableMember, enableMember, getMember, legacyTokenByName, listGroups, listMembers,parseIdList, previewRemoveGroup, previewRemoveMember, removeGroup, removeGroupMembers, removeMember, type MemberRecord,@@ -40,6 +42,13 @@ Members and groups:An attested QM call naming that person reads and writes as <id>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 member source add <id> <source> [--dry-run]+ Personal source: attested calls for anyone else, and scope+ reads, stop reading it (hide-only, inside each grant)+ gbrain access member source remove <id> <source> [--yes]+ Preview first; removing the last binding makes it readable+ again to every attested person whose credential grants it+ gbrain access member source list [<id>]gbrain access group add <group> [--members a,b]gbrain access group rm <group> [--members a,b] [--yes]With --members, removes those members; otherwise previews@@ -233,8 +242,10 @@ async function memberCmd(engine: BrainEngine, sub: string | undefined, args: strcase 'unlink':case 'links':return memberLinksCmd(engine, sub, args, json, id);+ case 'source':+ return memberSourceCmd(engine, args, json);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, disable, enable, rm, list, link, unlink, links or source (gbrain access --help).');}}@@ -253,6 +264,41 @@ async function memberLinksCmd(engine: BrainEngine, sub: 'link' | 'unlink' | 'linr.applied ? 'Takes effect on the next attested call.' : `Apply without --dry-run.`]);}+/** GBRA-284: personal sources, bound to the member they belong to (database only, repo-less or not). */+async function memberSourceCmd(engine: BrainEngine, args: string[], json: boolean): Promise<void> {+ const [sub, member, source] = positionals(args);+ switch (sub) {+ case 'add': {+ if (!member || !source) throw usageError('access member source add needs a member and a source.', 'gbrain access member source add <id> <source> [--dry-run]');+ const r = await bindMemberSource(engine, member, source, { dryRun: args.includes('--dry-run') });+ return print(json, r, () => [+ `${r.applied ? 'Bound' : r.changed ? 'Would bind' : 'Already bound:'} ${r.binding.source_id} to ${r.binding.member_id}`,+ ` Owners of ${r.binding.source_id}: ${r.owners.join(', ')}`,+ ` Attested calls for anyone else, and every scope read, stop reading ${r.binding.source_id}; it is read only where a credential already grants it.`,+ ...(r.changed && !r.applied ? ['Apply without --dry-run.'] : r.applied ? ['Takes effect on the next attested call.'] : [])]);+ }+ case 'remove': {+ if (!member || !source) throw usageError('access member source remove needs a member and a source.', 'gbrain access member source remove <id> <source> [--yes]');+ const yes = args.includes('--yes');+ const r = await unbindMemberSource(engine, member, source, { apply: yes });+ return print(json, r, () => [+ `${yes ? 'Unbound' : 'Would unbind'} ${r.binding.source_id} from ${r.binding.member_id}`,+ r.still_personal+ ? ` ${r.binding.source_id} stays personal (owners: ${r.owners.join(', ')}).`+ : ` ${r.binding.source_id} stops being personal: every attested person whose credential grants it reads it again.`,+ ...(yes ? [] : [`Apply with: gbrain access member source remove ${r.binding.member_id} ${r.binding.source_id} --yes`])]);+ }+ case 'list': {+ const bindings = await listMemberSources(engine, member ? { member } : {});+ return print(json, { bindings }, () => bindings.length+ ? ['Personal sources:', ...bindings.map(b => ` ${b.source_id} -> ${b.member_id}`)]+ : ['No personal sources. Bind one: gbrain access member source add <id> <source>']);+ }+ default:+ throw usageError(`Unknown access member source subcommand: ${sub ?? '(none)'}.`, 'Use add, remove or list (gbrain access --help).');+ }+}+async function groupCmd(engine: BrainEngine, sub: string | undefined, args: string[], json: boolean): Promise<void> {const id = positionals(args)[0];const members = parseIdList(flagValue(args, '--members'), 'member');diff --git a/src/core/access/member-sources.ts b/src/core/access/member-sources.tsnew file mode 100644index 0000000000..74b5a20157--- /dev/null+++ b/src/core/access/member-sources.ts@@ -0,0 +1,127 @@+/**+ * GBRA-284 (GST-359 G1 wave 2): personal sources. `access_member_sources` (v288) binds a source (a person's DM or+ * member source) to the member it belongs to; a source with at least one binding is personal. Sources are not keyed to+ * members otherwise, so without this an attest client granted every person's DM source would let every attested person+ * read every other person's DM source.+ *+ * The read rule (`attestedReadScope`, applied once in MCP dispatch for every attested call) only hides inside the+ * credential's grant: it drops every personal source not bound to the attested member, and under a scope read+ * (`SCOPE_READ_ACCESS`) every personal source, the speaker's own included. It never adds a source, so a narrowed read+ * refuses a hidden source exactly like an out-of-grant one (resolveRequestedScope's permission_denied). Unattested+ * callers and member-bound credentials are unchanged (a member-bound credential could take the same rule later).+ * Everything lives in the database, so a repo-less brain gets it unchanged.+ */+import type { BrainEngine } from '../engine.ts';+import { opError, type AuthInfo, type ExplicitReadBinding } from '../ops/contract.ts';+import { isValidSourceId, NO_SOURCES } from '../source-id.ts';+import { isMissingSchemaObject } from '../utils.ts';+import { existingMember } from './members.ts';++export interface MemberSource { member_id: string; source_id: string; created_at: string | null }++function toBinding(row: Record<string, unknown>): MemberSource {+ return { member_id: String(row.member_id), source_id: String(row.source_id), created_at: row.created_at ? new Date(row.created_at as string).toISOString() : null };+}++async function liveSource(engine: BrainEngine, raw: unknown): Promise<string> {+ if (!isValidSourceId(raw)) {+ throw opError('invalid_params', `"${String(raw ?? '')}" is not a valid source id.`, 'Pass a source id from gbrain sources list.');+ }+ const [row] = await engine.executeRaw<{ ok: number }>('SELECT 1 AS ok FROM sources WHERE id = $1 AND archived IS NOT TRUE', [raw]);+ if (!row) throw opError('unknown_source', `No live source "${raw}" exists on this brain.`, 'Pick an id from gbrain sources list.');+ return raw;+}++/** Binds a source to a member (a narrowing: attested callers for anyone else stop reading it); dryRun previews. */+export async function bindMemberSource(engine: BrainEngine, rawMember: unknown, rawSource: unknown, opts: { dryRun?: boolean } = {}): Promise<{ binding: MemberSource; applied: boolean; changed: boolean; owners: string[] }> {+ const member = await existingMember(engine, rawMember, 'bound to a source');+ if (member.status === 'removed') {+ throw opError('access_member_invalid', `Member "${member.id}" was removed.`, 'Removed ids are never reused; bind the source to a live member.', { reason: 'removed' });+ }+ const source = await liveSource(engine, rawSource);+ const owners = await sourceOwners(engine, source);+ const changed = !owners.includes(member.id);+ if (changed && !opts.dryRun) {+ await engine.executeRaw('INSERT INTO access_member_sources (member_id, source_id) VALUES ($1, $2) ON CONFLICT DO NOTHING', [member.id, source]);+ }+ const [row] = await engine.executeRaw<Record<string, unknown>>('SELECT member_id, source_id, created_at FROM access_member_sources WHERE member_id = $1 AND source_id = $2', [member.id, source]);+ return { binding: row ? toBinding(row) : { member_id: member.id, source_id: source, created_at: null }, applied: changed && !opts.dryRun, changed,+ owners: changed ? [...owners, member.id].sort() : owners };+}++/**+ * Unbinds a source from a member. When it was the source's last binding the source stops being personal, so every+ * attested person through a credential that grants it reads it again (a widening): preview unless apply is set.+ */+export async function unbindMemberSource(engine: BrainEngine, rawMember: unknown, rawSource: unknown, opts: { apply?: boolean } = {}): Promise<{ binding: MemberSource; applied: boolean; owners: string[]; still_personal: boolean }> {+ const member = await existingMember(engine, rawMember, 'unbound from a source');+ if (!isValidSourceId(rawSource)) throw opError('invalid_params', `"${String(rawSource ?? '')}" is not a valid source id.`, 'Pass a source id from gbrain access member source list.');+ const [row] = await engine.executeRaw<Record<string, unknown>>('SELECT member_id, source_id, created_at FROM access_member_sources WHERE member_id = $1 AND source_id = $2', [member.id, rawSource]);+ if (!row) {+ throw opError('invalid_params', `Source "${rawSource}" is not bound to member "${member.id}".`, `List the bindings with gbrain access member source list ${member.id}.`, { reason: 'unknown_binding' });+ }+ if (opts.apply) await engine.executeRaw('DELETE FROM access_member_sources WHERE member_id = $1 AND source_id = $2', [member.id, rawSource]);+ const owners = (await sourceOwners(engine, rawSource)).filter(o => o !== member.id);+ return { binding: toBinding(row), applied: opts.apply === true, owners, still_personal: owners.length > 0 };+}++export async function listMemberSources(engine: BrainEngine, opts: { member?: string } = {}): Promise<MemberSource[]> {+ const member = opts.member === undefined ? undefined : (await existingMember(engine, opts.member, 'listed')).id;+ const rows = await engine.executeRaw<Record<string, unknown>>(+ `SELECT member_id, source_id, created_at FROM access_member_sources${member ? ' WHERE member_id = $1' : ''} ORDER BY member_id, source_id`, member ? [member] : []);+ return rows.map(toBinding);+}++async function sourceOwners(engine: BrainEngine, source: string): Promise<string[]> {+ const rows = await engine.executeRaw<{ member_id: string }>('SELECT member_id FROM access_member_sources WHERE source_id = $1 ORDER BY member_id', [source]);+ return rows.map(r => r.member_id);+}++/**+ * The personal sources among `sources` an attested call for `member` must not read: every personal source not bound to+ * that member, or every personal source under a scope read. A schema before v288 has no personal source.+ */+export async function hiddenPersonalSources(engine: Pick<BrainEngine, 'executeRaw'>, sources: readonly string[], member: string, scopeRead: boolean): Promise<Set<string>> {+ const ids = [...new Set(sources)];+ if (!ids.length) return new Set();+ let rows: { source_id: string; member_id: string }[];+ try {+ rows = await engine.executeRaw<{ source_id: string; member_id: string }>('SELECT source_id, member_id FROM access_member_sources WHERE source_id = ANY($1::text[])', [ids]);+ } catch (e) {+ if (!isMissingSchemaObject(e, 'table', 'access_member_sources')) throw e;+ return new Set();+ }+ const own = new Set(scopeRead ? [] : rows.filter(r => r.member_id === member).map(r => r.source_id));+ return new Set(rows.map(r => r.source_id).filter(s => !own.has(s)));+}++export interface ReadScopeOpts { auth?: AuthInfo; sourceId?: string; localFederatedSourceIds?: string[]; explicitReadBinding?: ExplicitReadBinding }++/**+ * The read scope of one attested call: the credential's granted read sources (its federated grant, else the+ * transport's federated set for an unqualified read, else its scalar source) minus the hidden personal sources, as an+ * explicit grant so every resolver (sourceScopeOpts, resolveRequestedScope, federatedSearchScope) reads the same set.+ * A hidden scalar source (the call's sourceId, which writes and scalar reads use directly) moves to the first kept+ * source, or to NO_SOURCES, which refuses. Unchanged (the same object) when nothing is hidden. A grant left empty reads+ * nothing (NO_SOURCES never names a source).+ */+export async function attestedReadScope<T extends ReadScopeOpts>(engine: Pick<BrainEngine, 'executeRaw'>, opts: T, member: string, scopeRead: boolean): Promise<T> {+ const auth = opts.auth;+ if (!auth || auth.sourceId === NO_SOURCES) return opts;+ const federated = opts.localFederatedSourceIds;+ const scalar = opts.sourceId ?? 'default';+ const grant = auth.allowedSources?.length ? auth.allowedSources : federated && federated.length > 1 ? federated : [scalar];+ const scalars = [scalar, ...(auth.sourceId ? [auth.sourceId] : [])];+ const hidden = await hiddenPersonalSources(engine, [...grant, ...scalars, ...(federated ?? []), ...(opts.explicitReadBinding?.sourceIds ?? [])], member, scopeRead);+ if (!hidden.size) return opts;+ const keep = (ids: string[]) => ids.filter(s => !hidden.has(s));+ const allowed = keep(grant);+ const moved = allowed[0] ?? NO_SOURCES;+ return {+ ...opts,+ ...(hidden.has(scalar) ? { sourceId: moved } : {}),+ auth: { ...auth, allowedSources: allowed.length ? allowed : [NO_SOURCES], ...(auth.sourceId && hidden.has(auth.sourceId) ? { sourceId: moved } : {}) },+ ...(federated ? { localFederatedSourceIds: keep(federated) } : {}),+ ...(opts.explicitReadBinding ? { explicitReadBinding: { ...opts.explicitReadBinding, sourceIds: keep(opts.explicitReadBinding.sourceIds) } } : {}),+ };+}diff --git a/src/core/access/members.ts b/src/core/access/members.tsindex 0e8f39addc..a5d3cf44be 100644--- a/src/core/access/members.ts+++ b/src/core/access/members.ts@@ -97,7 +97,7 @@ export async function listMembers(engine: BrainEngine, opts: { includeRemoved?:return rows.map(toRecord);}-async function existingMember(engine: BrainEngine, raw: unknown, action: string): Promise<MemberRecord> {+export async function existingMember(engine: BrainEngine, raw: unknown, action: string): Promise<MemberRecord> {const id = assertAccessId(raw);const member = await getMember(engine, id);if (member) return member;diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 43af8b1859..5135c37f8f 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1418,6 +1418,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', id: 'attest_scope_read_ops_gst1158', text: 'An attested call (`x-qm-actor`) to `get_page`, `entity`, `whois`, `get_backlinks`, `get_timeline`, `find_experts`, `volunteer_context` or `query` that names `source_id` or `source_ids` now reads as those sources\' audience, as `memory_recall` already did: the person\'s pages restricted to named readers and their member page `memory/members/<member>` read as missing, a source outside the credential\'s read grant is refused, and `__all__` or `all_sources` beside a named source is refused (`invalid_params`). `get_timeline` gains `source_id` and `source_ids`, `find_experts` and `volunteer_context` gain `source_ids`, and `volunteer_context` refuses `stats: true` under that read. `gbrain auth rescope --attest-read person|scope|none` sets how an attest credential reads named sources: `person` narrows to them but reads as the person; `scope` reads them as their audience and refuses every call that names no person (`actor_not_attested` reason `actor_required`), reading nothing; unset (the default) keeps the scope read and still serves calls that name no person. `gbrain doctor` warns (`attest_read_shared_scope`) when a person credential reads a source another attest credential reads as the scope.' },{ since: 'TBD', id: 'attest_direct_page_writes_deferred_gst1158', text: 'An attested call (`x-qm-actor`) may no longer run `add_timeline_entry`, `add_link`, `put_page` or `edit_page`: they write pages every reader of the page sees, so they wait for owner-approved proposals. `gbrain auth rescope --attest-ops` refuses a list that names one, a credential whose list already names one is refused for it on every attested call (`actor_not_attested`, reason `op_not_attested`), and a queued attested write of one fails when it publishes. Unattested calls and member-bound credentials are unchanged.' },{ since: 'TBD', id: 'unknown_param_meta_only_harn15', text: 'A read that ignores a parameter the tool does not declare (`mcp.strict_params` `warn`, the default) no longer adds a `[gbrain notice unknown_param kind=info]` text block to the result: the warning is only in `_meta.warnings` (`{code: \'unknown_param\', param, suggestion?}`), so a harness that stores tool output in its turns never stores it. Writes still refuse unknown parameters, and `reject` mode is unchanged.' },+ { since: 'TBD', id: 'personal_sources_gbra284', text: 'An operator can bind a source to the member it belongs to (`gbrain access member source add <member> <source>`, migration v288); a bound source is personal. An attested call (`x-qm-actor`) now reads its credential\'s grant minus every personal source bound to another member, and a read that names sources as their audience (the scope read) reads no personal source at all, not even the speaker\'s own. A hidden personal source named in `source_id` or `source_ids` is refused exactly like a source outside the grant (`permission_denied`); an unnamed read skips it. The rule only hides inside the grant and never makes a source readable, so it is within the existing trust posture (gate_rev 6). On an existing install nothing changes until an operator binds a source; after that, a credential whose grant already includes the bound source stops showing it to attested callers for anyone else. Unattested calls and member-bound credentials are unchanged.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex 4a349b72d5..166ddfdc7e 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -38,6 +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_member_sources', 'out_of_scope', 'no_memory_text', 'member_id source_id'],['access_members', 'out_of_scope', 'no_memory_text', 'id display_name'],['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'],diff --git a/src/core/minions/tools/brain-allowlist.ts b/src/core/minions/tools/brain-allowlist.tsindex 8c5ce0aa0c..2e91275c6b 100644--- a/src/core/minions/tools/brain-allowlist.ts+++ b/src/core/minions/tools/brain-allowlist.ts@@ -37,6 +37,7 @@ import { stagePutPage } from './staged-put-page.ts';import { withCallerAccess } from '../../search/private-visibility.ts';import { remoteCallerAccess } from '../../access/caller.ts';import { attestedCallerAccess, storedActorIdentity } from '../../access/actor.ts';+import { attestedReadScope } from '../../access/member-sources.ts';import type { AudiencePrincipal } from '../../access/audience.ts';import { currentSubmissionAuthority } from '../submission-authority.ts';@@ -309,9 +310,9 @@ function brainTool(op: Operation, opts: BuildBrainToolsOpts): ToolDef {const validationError = validateParams(op, params);if (validationError) throw new Error(`${toolName}: ${validationError}`);const write = op.name === 'put_page' && opts.stageWrites ? stagePutPage : op.handler;- const run = () => op.name === 'put_page'- ? write(opCtx, params).catch(e => rethrowWithCurrentRevision(ctx.engine, opCtx.sourceId ?? 'default', params.slug, e))- : op.handler(opCtx, params);+ const run = (c: typeof opCtx = opCtx) => op.name === 'put_page'+ ? write(c, params).catch(e => rethrowWithCurrentRevision(ctx.engine, c.sourceId ?? 'default', params.slug, e))+ : op.handler(c, params);// GBRA-218: a remote-owned job reads as its client's member, looked up live on every call (a disabled member or// removed binding takes effect at the next tool call); never a GBRA-156 private-pages grant.// GBRA-231: a job a shared agent submitted for an audience reads as that audience, re-checked the same way.@@ -321,7 +322,8 @@ function brainTool(op: Operation, opts: BuildBrainToolsOpts): ToolDef {const agent = submitted?.kind === 'remote_agent' ? submitted : undefined;const actor = agent?.grant.actor;const output = agent && actor- ? await withCallerAccess(await attestedCallerAccess(ctx.engine, actor, await storedActorIdentity(ctx.engine, agent.principal, actor, op.name)), run)+ ? await withCallerAccess(await attestedCallerAccess(ctx.engine, actor, await storedActorIdentity(ctx.engine, agent.principal, actor, op.name)),+ async () => run(await attestedReadScope(ctx.engine, opCtx, actor.member, false))): opCtx.auth? await withCallerAccess(await remoteCallerAccess(ctx.engine, opCtx.auth, [], undefined, actingFor), run): await run();diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.tsindex a6c4d0f167..ecbdc47395 100644--- a/src/core/persistence/graduation-inventory.ts+++ b/src/core/persistence/graduation-inventory.ts@@ -32,6 +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_member_sources', 'security', 'Personal sources bound to their members; dropping them would let every attested person read every member\'s personal source.'),carry('access_members', 'security', 'Brain members that readable_by member:<id> names; 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.'),diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 7f0d6e1be8..4c44d8705c 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 = 287;+export const LATEST_SCHEMA_VERSION = 288;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 3dc804572f..f4851f87f3 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -288,6 +288,7 @@ 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-attest-read.ts';+import { v288 } from './v288-access-member-sources.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -574,4 +575,5 @@ export const MIGRATIONS: Migration[] = [v285,v286,v287,+ v288,];diff --git a/src/core/schema-migrations/v288-access-member-sources.ts b/src/core/schema-migrations/v288-access-member-sources.tsnew file mode 100644index 0000000000..679eb94854--- /dev/null+++ b/src/core/schema-migrations/v288-access-member-sources.ts@@ -0,0 +1,35 @@+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.+//+// GBRA-284 (GST-359 G1 wave 2): personal sources. A row binds a source (a+// person's DM or member source) to the member it belongs to; a source with at+// least one binding is personal. An attested call (x-qm-actor) reads its+// credential's grant minus every personal source not bound to the attested+// member, and a scope read never reads a personal source (access/member-sources.ts).+// The rule only hides inside the grant, so no source becomes readable. source_id+// has no foreign key on purpose: removing and re-adding a source with the same id+// keeps it personal (hidden), never public. Database only, so a repo-less brain+// gets it unchanged. Nothing is rewritten on upgrade; with no binding every read+// is unchanged. No schema.sql mirror, like v286. Numbered on the GBRA-284+// branch; expect a renumber at the merge slot.+export const v288: Migration = {+ version: 288,+ name: 'access_member_sources',+ idempotent: true,+ sql: `+CREATE TABLE IF NOT EXISTS access_member_sources (+ member_id TEXT NOT NULL REFERENCES access_members(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (member_id, source_id)+);+CREATE INDEX IF NOT EXISTS access_member_sources_source_idx ON access_member_sources (source_id);+DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles pr WHERE pg_has_role(current_user, pr.oid, 'USAGE') AND (pr.rolbypassrls OR pr.rolsuper)) THEN+ ALTER TABLE access_member_sources ENABLE ROW LEVEL SECURITY;+ END IF;+END $rls$;+`,+};diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 587d57f0d7..90c83bc998 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -19,6 +19,7 @@ import { appliedAccessSummary, remoteCallerAccess } from '../core/access/caller.import { audienceInArguments, audienceInArgumentsError, logAudienceAssertion, parseAudience, type AudienceAuditEvent, type AudienceChannels, type AudiencePrincipal } from '../core/access/audience.ts';import { ACTOR_ARGUMENT, actorNotAttested, EXTERNAL_ID_RE, resolveAttestedActor, type ActorChannels } from '../core/access/actor.ts';import { attestedReadMode, SCOPE_READ_ACCESS, withReadMode, type ReadMode } from '../core/access/scope-read.ts';+import { attestedReadScope } from '../core/access/member-sources.ts';import { qmMemoryToolResult, recallArguments, unlinkedRecallResult } from '../core/ops/qm-memory.ts';import { resolveBrainId } from '../core/brain-resolver.ts';import { getCliOptions } from '../core/cli-options.ts';@@ -925,6 +926,7 @@ export async function dispatchToolCall(let attested: Awaited<ReturnType<typeof resolveAttestedActor>> = null;let access: Awaited<ReturnType<typeof remoteCallerAccess>>;let readMode: ReadMode | null = null;+ let scoped = resolved;const header = opts.actor?.header ?? undefined;const actorNamed = header !== undefined || opts.actor?.audience != null || (!!args && Object.prototype.hasOwnProperty.call(args, ACTOR_ARGUMENT));const assertion = (outcome: AudienceAuditEvent['outcome'], reason?: string) => logAudienceAssertion({ outcome, op: name,@@ -939,6 +941,8 @@ export async function dispatchToolCall(// GST-1158 E1: an attested read that names sources reads as the scope (access/scope-read.ts), or as the person on an attest_read person credential.readMode = attested?.actor ? attestedReadMode(name, attested.params, attested.read) : null;access = readMode === 'scope' ? SCOPE_READ_ACCESS : attested?.access ?? await remoteCallerAccess(engine, opts.auth, privateSources, opts.transport, audience);+ // GBRA-284: an attested call reads its grant minus other members' personal sources, a scope read minus every personal source (access/member-sources.ts).+ if (attested?.actor) scoped = await attestedReadScope(engine, resolved, attested.actor.member, readMode === 'scope');} catch (e) {// GST-359: a call that names a person gets every failure here (a lock timeout reading its link included) in the// envelope QM reads, never a thrown call; anything else keeps the caller's own error path.@@ -952,9 +956,9 @@ export async function dispatchToolCall(if (audience || attested?.actor) assertion('accepted');const callParams = attested ? attested.params : args;return withCallerAccess(access, async () => {- const out = await withRequestIdentityMemo(() => withReadMode(readMode, () => dispatchResolvedCall(engine, name, callParams, resolved)));+ const out = await withRequestIdentityMemo(() => withReadMode(readMode, () => dispatchResolvedCall(engine, name, callParams, scoped)));// _meta.access (MCP_META_CHANNELS.md): the view this call was answered under, for the harness; own producer, isolated.- try { out._meta = { ...(out._meta ?? {}), access: await appliedAccessSummary(engine, opts.auth, [opts.sourceId, ...(opts.localFederatedSourceIds ?? [])]) }; } catch { /* the key is absent */ }+ try { out._meta = { ...(out._meta ?? {}), access: await appliedAccessSummary(engine, scoped.auth, [scoped.sourceId, ...(scoped.localFederatedSourceIds ?? [])]) }; } catch { /* the key is absent */ }return qmMemoryToolResult(name, out);});};diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex a34f21ad2e..b63c0ae5f2 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -10,6 +10,8 @@"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_member_sources.access_member_sources_member_id_fkey": "f FOREIGN KEY (member_id) REFERENCES access_members(id) ON DELETE CASCADE",+ "access_member_sources.access_member_sources_pkey": "p PRIMARY KEY (member_id, source_id)","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)",@@ -627,6 +629,9 @@"access_member_links": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "access_member_sources": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"access_members": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1144,6 +1149,8 @@"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_member_sources_pkey": "CREATE UNIQUE INDEX access_member_sources_pkey ON public.access_member_sources USING btree (member_id, source_id)",+ "access_member_sources_source_idx": "CREATE INDEX access_member_sources_source_idx ON public.access_member_sources USING btree (source_id)","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)",@@ -1730,6 +1737,14 @@],"flags": "relkind=r rls=true force_rls=false"},+ "access_member_sources": {+ "columns": [+ "1 member_id text/text NOT NULL",+ "2 source_id text/text NOT NULL",+ "3 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"access_members": {"columns": ["1 id text/text NOT NULL",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex fc1a42191f..9f1d28529b 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,8 @@"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_member_sources.access_member_sources_member_id_fkey": "f FOREIGN KEY (member_id) REFERENCES access_members(id) ON DELETE CASCADE",+ "access_member_sources.access_member_sources_pkey": "p PRIMARY KEY (member_id, source_id)","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)",@@ -627,6 +629,9 @@"access_member_links": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "access_member_sources": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"access_members": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1144,6 +1149,8 @@"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_member_sources_pkey": "CREATE UNIQUE INDEX access_member_sources_pkey ON public.access_member_sources USING btree (member_id, source_id)",+ "access_member_sources_source_idx": "CREATE INDEX access_member_sources_source_idx ON public.access_member_sources USING btree (source_id)","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)",@@ -1730,6 +1737,14 @@],"flags": "relkind=r rls=true force_rls=false"},+ "access_member_sources": {+ "columns": [+ "1 member_id text/text NOT NULL",+ "2 source_id text/text NOT NULL",+ "3 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"access_members": {"columns": ["1 id text/text NOT NULL",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 126addd9dd..b755ca5ad4 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,8 @@"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_member_sources.access_member_sources_member_id_fkey": "f FOREIGN KEY (member_id) REFERENCES access_members(id) ON DELETE CASCADE",+ "access_member_sources.access_member_sources_pkey": "p PRIMARY KEY (member_id, source_id)","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)",@@ -627,6 +629,9 @@"access_member_links": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "access_member_sources": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"access_members": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1144,6 +1149,8 @@"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_member_sources_pkey": "CREATE UNIQUE INDEX access_member_sources_pkey ON public.access_member_sources USING btree (member_id, source_id)",+ "access_member_sources_source_idx": "CREATE INDEX access_member_sources_source_idx ON public.access_member_sources USING btree (source_id)","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)",@@ -1726,6 +1733,14 @@],"flags": "relkind=r rls=true force_rls=false"},+ "access_member_sources": {+ "columns": [+ "1 member_id text/text NOT NULL",+ "2 source_id text/text NOT NULL",+ "3 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"access_members": {"columns": ["1 id text/text NOT NULL",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 598ecc77a4..c43a2d4aeb 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -10,6 +10,8 @@"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_member_sources.access_member_sources_member_id_fkey": "f FOREIGN KEY (member_id) REFERENCES access_members(id) ON DELETE CASCADE",+ "access_member_sources.access_member_sources_pkey": "p PRIMARY KEY (member_id, source_id)","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)",@@ -631,6 +633,9 @@"access_member_links": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "access_member_sources": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"access_members": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1145,6 +1150,8 @@"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_member_sources_pkey": "CREATE UNIQUE INDEX access_member_sources_pkey ON public.access_member_sources USING btree (member_id, source_id)",+ "access_member_sources_source_idx": "CREATE INDEX access_member_sources_source_idx ON public.access_member_sources USING btree (source_id)","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)",@@ -1731,6 +1738,14 @@],"flags": "relkind=r rls=true force_rls=false"},+ "access_member_sources": {+ "columns": [+ "1 member_id text/text NOT NULL",+ "2 source_id text/text NOT NULL",+ "3 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"access_members": {"columns": ["1 id text/text NOT NULL",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 08a81c4be7..3bd14572c0 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -10,6 +10,8 @@"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_member_sources.access_member_sources_member_id_fkey": "f FOREIGN KEY (member_id) REFERENCES access_members(id) ON DELETE CASCADE",+ "access_member_sources.access_member_sources_pkey": "p PRIMARY KEY (member_id, source_id)","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)",@@ -631,6 +633,9 @@"access_member_links": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "access_member_sources": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"access_members": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1145,6 +1150,8 @@"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_member_sources_pkey": "CREATE UNIQUE INDEX access_member_sources_pkey ON public.access_member_sources USING btree (member_id, source_id)",+ "access_member_sources_source_idx": "CREATE INDEX access_member_sources_source_idx ON public.access_member_sources USING btree (source_id)","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)",@@ -1731,6 +1738,14 @@],"flags": "relkind=r rls=true force_rls=false"},+ "access_member_sources": {+ "columns": [+ "1 member_id text/text NOT NULL",+ "2 source_id text/text NOT NULL",+ "3 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"access_members": {"columns": ["1 id text/text NOT NULL",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex 69ff55ca7a..fcfbb3eef5 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -10,6 +10,8 @@"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_member_sources.access_member_sources_member_id_fkey": "f FOREIGN KEY (member_id) REFERENCES access_members(id) ON DELETE CASCADE",+ "access_member_sources.access_member_sources_pkey": "p PRIMARY KEY (member_id, source_id)","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)",@@ -631,6 +633,9 @@"access_member_links": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "access_member_sources": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"access_members": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1145,6 +1150,8 @@"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_member_sources_pkey": "CREATE UNIQUE INDEX access_member_sources_pkey ON public.access_member_sources USING btree (member_id, source_id)",+ "access_member_sources_source_idx": "CREATE INDEX access_member_sources_source_idx ON public.access_member_sources USING btree (source_id)","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)",@@ -1727,6 +1734,14 @@],"flags": "relkind=r rls=true force_rls=false"},+ "access_member_sources": {+ "columns": [+ "1 member_id text/text NOT NULL",+ "2 source_id text/text NOT NULL",+ "3 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"access_members": {"columns": ["1 id text/text NOT NULL",diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 3bf5e87d41..130ad8c2ef 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 282,+ "count": 283,"gaps": [17,18,@@ -94,7 +94,7 @@"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67","withSchemaLockTimeout": "95605bd3004955e11e936c7a4aa6889319b401098abf9db18ef3e48da2c3fc59"},- "latest": 287,+ "latest": 288,"records": [{"handler": {@@ -4661,6 +4661,19 @@"transaction": "absent","verify": "absent","version": 287+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "access_member_sources",+ "sql": {+ "length": 573,+ "sha256": "63da00dc6df6d19b1da78d752ab0e5566c1511a1cff16a2838e54b5fbf701ff9"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 288}],"versions": [@@ -4945,7 +4958,8 @@284,285,286,- 287+ 287,+ 288]},"normalizer": "migrations-record-v1"diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.tsindex 57238451b6..c8c056f0d3 100644--- a/test/graduation-inventory.test.ts+++ b/test/graduation-inventory.test.ts@@ -60,7 +60,7 @@ describe('graduation inventory', () => {expect(new Set(names).size).toBe(names.length);const counts: Record<string, number> = {};for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;- expect(counts).toEqual({ carry: 156, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });+ expect(counts).toEqual({ carry: 157, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });for (const e of GRADUATION_INVENTORY.entries) {expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres }).toEqual({ relation: e.relation, reason: true, present: true });@@ -68,7 +68,7 @@ describe('graduation inventory', () => {expect(expectedRelations('pglite').filter(r => !expectedRelations('postgres').includes(r))).toEqual(['planner_stats_deltas', 'planner_stats_state']);expect(expectedRelations('postgres').filter(r => !expectedRelations('pglite').includes(r))).toEqual(['file_migration_ledger']);expect(GRADUATION_INVENTORY.entries.filter(e => e.lossKind === 'security').map(e => e.relation).sort()).toEqual([- 'access_group_members', 'access_groups', 'access_member_links', 'access_members', 'access_pending_coverage', 'access_policy_revisions',+ 'access_group_members', 'access_groups', 'access_member_links', 'access_member_sources', 'access_members', 'access_pending_coverage', 'access_policy_revisions','access_policy_state', 'access_rules', 'access_tokens', 'oauth_clients', 'oauth_codes', 'oauth_grant_audit', 'oauth_tokens','persistence_local_writers', 'shared_skill_state', 'slug_rename_history']);});diff --git a/test/qm-personal-sources.test.ts b/test/qm-personal-sources.test.tsnew file mode 100644index 0000000000..3c3e44d4d4--- /dev/null+++ b/test/qm-personal-sources.test.ts@@ -0,0 +1,300 @@+/**+ * GBRA-284 (GST-359 G1 wave 2): personal sources. A source bound to a member (access_member_sources, v288) is read by an+ * attested call only for that member, and never by a scope read; the rule only hides inside the credential's grant.+ *+ * 1. Protects: the HARN-1 gate shape. An attest client granted {source-a, dm-alice-example, dm-bob-example}, each DM+ * source bound to its member: attested alice-example's unnamed memory_recall returns her DM-source fact and her+ * memory_write fact, never bob-example's DM-source fact (and the reverse for bob); query and get_page follow the same+ * rule; a scope read naming a DM source (even the speaker's own) is refused exactly like an out-of-grant source; a+ * person credential naming another member's DM source is refused the same way. A client whose grant omits the DM+ * sources never reads them (the rule adds nothing). Unattested calls are unchanged.+ * 2. Fails when: an attested person reads another member's personal source through any of those ops, a scope read+ * reads a personal source, a refusal differs from the out-of-grant refusal, a person loses their own personal source,+ * or the rule widens a grant.+ * 3. Existing coverage: test/qm-scope-read.test.ts pins the scope read; test/access-qm-actor.test.ts the attested actor.+ * 4. Real seams: OAuth clients issued tokens by the provider's client-credentials grant, verified by the provider,+ * dispatched through MCP dispatch with remote=true on a repo-less brain (no git checkout anywhere); writes go through+ * the persistence coordinator; embeddings stubbed. PGLite always, Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { addMember, bindCredential, removeMember } from '../src/core/access/members.ts';+import { linkMember } from '../src/core/access/actor.ts';+import { bindMemberSource, listMemberSources, unbindMemberSource } from '../src/core/access/member-sources.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { attestedCallerAccess } from '../src/core/access/actor.ts';+import { withCallerAccess } from '../src/core/search/private-visibility.ts';+import { buildBrainTools } from '../src/core/minions/tools/brain-allowlist.ts';+import { prepareRemoteAgent, withSubmissionAuthority, type RemoteAgentAuthority } from '../src/core/minions/submission-authority.ts';+import type { AuthInfo, OperationContext } from '../src/core/ops/contract.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const DIMS = 1536;+function vectorFor(text: string): number[] {+ const v = new Array<number>(DIMS).fill(0);+ for (const w of text.toLowerCase().match(/[a-z]+/g) ?? []) {+ let h = 0;+ for (const ch of w) h = (h * 31 + ch.charCodeAt(0)) >>> 0;+ v[h % DIMS] += 1;+ }+ const n = Math.hypot(...v) || 1;+ return v.map(x => x / n);+}++const SRC = 'source-a';+const DM_A = 'dm-alice-example';+const DM_B = 'dm-bob-example';+const OTHER = 'source-other';+const ALICE_ID = 'U0ALICE';+const BOB_ID = 'U0BOB';+const OPS = ['entity', 'find_experts', 'get_backlinks', 'get_page', 'get_timeline', 'get_write_request', 'memory_recall', 'memory_write', 'query', 'search', 'volunteer_context', 'whois'];+const PAGE_A = 'notes/alice-dm-example';+const PAGE_B = 'notes/bob-dm-example';+const Q = 'harbor tide charts';+const note = (title: string, body: string) => ['---', 'type: note', 'title: ' + title, '---', '# ' + title, '', body].join('\n');++for (const kind of testBackends()) {+ describe('personal sources: an attested person reads only their own (' + kind + ', repo-less)', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ const clients: Record<string, string> = {};+ const verify = async (bearer: string) => await provider().verifyAccessToken(bearer) as unknown as AuthInfo;++ async function call(client: string, op: string, params: Record<string, unknown>, actor: string | null = ALICE_ID, extra: { writeWaitMs?: number } = {}) {+ const auth = await verify(clients[client]!);+ const out: ToolResult = await dispatchToolCall(engine, op, { ...params }, {+ remote: true, transport: 'http', auth, sourceId: auth.sourceId ?? SRC, takesHoldersAllowList: ['world'],+ ...(actor !== null ? { actor: { header: actor } } : {}), ...(extra.writeWaitMs ? { writeWaitMs: extra.writeWaitMs } : {}),+ });+ const text = out.content.map(c => c.text).join('\n');+ let json: Record<string, any> = {};+ try { json = JSON.parse(out.content[0]?.text ?? ''); } catch { /* prose */ }+ return { isError: out.isError === true, text, json, structured: out.structuredContent as Record<string, any> | undefined,+ all: text + JSON.stringify(out._meta ?? {}) + JSON.stringify(out.structuredContent ?? {}) };+ }+ const recall = (client: string, actor: string | null, extra: Record<string, unknown> = {}) => call(client, 'memory_recall', { query: Q, max_chars: 12_000, ...extra }, actor);+ /** The refusal a source outside the grant gets; a hidden personal source must get exactly this (no existence oracle). */+ async function outOfGrant(client: string, op: string, params: Record<string, unknown>, actor: string | null = ALICE_ID) {+ const out = await call(client, op, { ...params, ...('source_id' in params ? { source_id: OTHER } : { source_ids: [OTHER] }) }, actor);+ expect({ isError: out.isError, code: out.json.code }).toEqual({ isError: true, code: 'permission_denied' });+ return out;+ }+ async function refusedLikeOutOfGrant(client: string, op: string, params: Record<string, unknown>, actor: string | null = ALICE_ID) {+ const out = await call(client, op, params, actor);+ const ref = await outOfGrant(client, op, params, actor);+ expect({ isError: out.isError, code: out.json.code, message: out.json.message }).toEqual({ isError: true, code: 'permission_denied', message: ref.json.message });+ const named = typeof params.source_id === 'string' ? params.source_id : Array.isArray(params.source_ids) && params.source_ids.length === 1 ? params.source_ids[0] as string : null;+ if (named) expect(JSON.stringify(out.json).replaceAll(named, OTHER)).toBe(JSON.stringify(ref.json));+ for (const c of ['canarydmalice', 'canarydmbob']) expect(out.all).not.toContain(c);+ }++ beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(vectorFor) })) as never);+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ __resetPrivateVisibilityCacheForTests();+ for (const id of [SRC, DM_A, DM_B, OTHER]) await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [id]);+ for (const id of ['alice-example', 'bob-example', 'carol-example']) await addMember(engine, id);+ await linkMember(engine, 'alice-example', 'qm', ALICE_ID);+ await linkMember(engine, 'bob-example', 'qm', BOB_ID);+ // World facts and pages ingested locally into each DM source (what a DM import or a local remember leaves).+ await engine.insertFact({ fact: 'Alice keeps the harbor tide charts in a red folder canarydmalice', kind: 'fact', entity_slug: null, source: 'test', visibility: 'world' }, { source_id: DM_A });+ await engine.insertFact({ fact: 'Bob keeps the harbor tide charts in a blue folder canarydmbob', kind: 'fact', entity_slug: null, source: 'test', visibility: 'world' }, { source_id: DM_B });+ await importFromContent(engine, PAGE_A, note('Alice DM Example', 'Harbor tide charts from the alice thread canarydmalicepage.'), { sourceId: DM_A });+ await importFromContent(engine, PAGE_B, note('Bob DM Example', 'Harbor tide charts from the bob thread canarydmbobpage.'), { sourceId: DM_B });+ await importFromContent(engine, 'notes/world-example', note('World Example', 'Harbor tide charts for everyone canaryworldpage.'), { sourceId: SRC });+ const register = async (name: string, grant: string[], read?: 'person' | 'scope') => {+ const c = await provider().registerClientManual('personal-' + name + '-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], grant[0]!);+ await provider().rescopeClient(c.clientId, { federatedRead: grant });+ await bindCredential(engine, { kind: 'client', id: c.clientId }, { attestActor: 'qm', attestOps: OPS, ...(read ? { attestRead: read } : {}) });+ clients[name] = (await provider().exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token;+ };+ await register('narrow', [SRC]);+ await register('wide', [SRC, DM_A, DM_B]);+ await register('person', [SRC, DM_A, DM_B], 'person');+ await register('scope', [SRC, DM_A, DM_B], 'scope');+ await register('bobdm', [DM_B]);+ await register('bobfirst', [DM_B, SRC]);+ for (const [actor, who] of [[ALICE_ID, 'alice'], [BOB_ID, 'bob']] as const) {+ const wrote = await call('wide', 'memory_write', { facts: [{ fact: `${who} wants the harbor tide charts by Friday canarymember${who}`, provenance: 'turn 1' }], idempotency_key: randomUUID() }, actor, { writeWaitMs: 30_000 });+ expect(wrote.structured?.status).toBe('committed');+ }+ expect((await bindMemberSource(engine, 'alice-example', DM_A)).applied).toBe(true);+ expect((await bindMemberSource(engine, 'bob-example', DM_B)).applied).toBe(true);+ __resetPrivateVisibilityCacheForTests();+ }, 240_000);++ afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await disposePersistenceConsumer(engine).catch(() => undefined);+ await close?.();+ }, 60_000);++ test('HARN-1: attested alice-example recalls her own DM-source fact and memory_write fact, never bob-example\'s; bob gets the reverse', async () => {+ const alice = await recall('wide', ALICE_ID);+ expect(alice.isError).toBe(false);+ expect(alice.text).toContain('canarydmalice');+ expect(alice.text).toContain('canarymemberalice');+ expect(alice.all).not.toContain('canarydmbob');+ expect(alice.all).not.toContain('canarymemberbob');+ const bob = await recall('wide', BOB_ID);+ expect(bob.text).toContain('canarydmbob');+ expect(bob.text).toContain('canarymemberbob');+ expect(bob.all).not.toContain('canarydmalice');+ expect(bob.all).not.toContain('canarymemberalice');+ for (const client of ['scope', 'person']) {+ const out = await recall(client, ALICE_ID);+ expect(out.text).toContain('canarydmalice');+ expect(out.all).not.toContain('canarydmbob');+ }+ }, 120_000);++ test('a grant without the DM sources never reads them (0 of 2): the rule only hides, it never adds a source', async () => {+ const out = await recall('narrow', ALICE_ID);+ expect(out.isError).toBe(false);+ expect(out.text).toContain('canarymemberalice');+ for (const c of ['canarydmalice', 'canarydmbob']) expect(out.all).not.toContain(c);+ await refusedLikeOutOfGrant('narrow', 'memory_recall', { query: Q, source_ids: [DM_A] });+ }, 120_000);++ test('a scope read never reads a personal source, not even the speaker\'s own: refused like an out-of-grant source', async () => {+ for (const client of ['wide', 'scope']) {+ for (const dm of [DM_A, DM_B]) {+ await refusedLikeOutOfGrant(client, 'memory_recall', { query: Q, source_ids: [dm] });+ await refusedLikeOutOfGrant(client, 'memory_recall', { query: Q, source_ids: [SRC, dm] });+ await refusedLikeOutOfGrant(client, 'query', { query: Q, source_ids: [dm] });+ await refusedLikeOutOfGrant(client, 'get_page', { slug: dm === DM_A ? PAGE_A : PAGE_B, source_id: dm });+ }+ const room = await recall(client, ALICE_ID, { source_ids: [SRC] });+ expect(room.isError).toBe(false);+ for (const c of ['canarydmalice', 'canarydmbob', 'canarymemberalice']) expect(room.all).not.toContain(c);+ }+ }, 120_000);++ test('a person read names its own personal source; another member\'s is refused like an out-of-grant source', async () => {+ expect((await recall('person', ALICE_ID, { source_ids: [DM_A] })).text).toContain('canarydmalice');+ expect((await call('person', 'get_page', { slug: PAGE_A, source_id: DM_A })).text).toContain('canarydmalicepage');+ await refusedLikeOutOfGrant('person', 'memory_recall', { query: Q, source_ids: [DM_B] });+ await refusedLikeOutOfGrant('person', 'memory_recall', { query: Q, source_ids: [DM_A, DM_B] });+ await refusedLikeOutOfGrant('person', 'get_page', { slug: PAGE_B, source_id: DM_B });+ await refusedLikeOutOfGrant('person', 'query', { query: Q, source_ids: [DM_B] });+ await refusedLikeOutOfGrant('person', 'get_page', { slug: PAGE_A, source_id: DM_A }, BOB_ID);+ }, 120_000);++ test('get_page: another member\'s DM page reads as missing, the person\'s own reads', async () => {+ const missing = await call('wide', 'get_page', { slug: 'notes/nobody-example' });+ expect(missing.json.code).toBe('page_not_found');+ const theirs = await call('wide', 'get_page', { slug: PAGE_B });+ expect({ isError: theirs.isError, code: theirs.json.code, message: theirs.json.message })+ .toEqual({ isError: true, code: missing.json.code, message: missing.json.message.replace('notes/nobody-example', PAGE_B) });+ expect(theirs.all).not.toContain('canarydmbobpage');+ expect((await call('wide', 'get_page', { slug: PAGE_A })).text).toContain('canarydmalicepage');+ expect((await call('wide', 'get_page', { slug: PAGE_B }, BOB_ID)).text).toContain('canarydmbobpage');+ }, 120_000);++ test('query and search: unnamed reads span the grant minus other members\' personal sources', async () => {+ for (const op of ['query', 'search']) {+ const alice = await call('wide', op, { query: Q, limit: 20 });+ expect(alice.isError).toBe(false);+ expect(alice.text).toContain('canaryworldpage');+ expect(alice.text).toContain('canarydmalicepage');+ expect(alice.all).not.toContain('canarydmbobpage');+ const bob = await call('wide', op, { query: Q, limit: 20 }, BOB_ID);+ expect(bob.text).toContain('canarydmbobpage');+ expect(bob.all).not.toContain('canarydmalicepage');+ }+ }, 120_000);++ test('a linked member with no personal source reads neither DM source; unattested calls are unchanged', async () => {+ await linkMember(engine, 'carol-example', 'qm', 'U0CAROL');+ const carol = await recall('wide', 'U0CAROL');+ expect(carol.isError).toBe(false);+ for (const c of ['canarydmalice', 'canarydmbob']) expect(carol.all).not.toContain(c);+ const bare = await recall('wide', null);+ expect(bare.isError).toBe(false);+ for (const c of ['canarydmalice', 'canarydmbob']) expect(bare.text).toContain(c);+ expect((await call('wide', 'get_page', { slug: PAGE_B, source_id: DM_B }, null)).text).toContain('canarydmbobpage');+ }, 120_000);++ test('an agent job submitted for an attested person reads the same way: its own personal source, never another member\'s', async () => {+ const { clientId } = await provider().registerClientManual('personal-agent-' + randomUUID().slice(0, 8), ['client_credentials'], 'read', [], SRC);+ await bindCredential(engine, { kind: 'client', id: clientId }, { attestActor: 'qm', attestOps: ['get_page', 'query'] });+ await engine.executeRaw("UPDATE oauth_clients SET scope = 'read agent', bound_tools = ARRAY['get_page','query'], bound_source_id = source_id, federated_read = $2::text[], delegated_namespace = 'job', delegated_slug_prefixes = NULL, bound_max_concurrent = 1 WHERE client_id = $1", [clientId, [SRC, DM_A, DM_B]]);+ const actor = { system: 'qm', external_id: ALICE_ID, member: 'alice-example' };+ const agentAuth = { token: 'x', clientId, scopes: ['read', 'agent'], sourceId: SRC, allowedSources: [SRC, DM_A, DM_B], principal: { kind: 'oauth_client', id: clientId } } as unknown as AuthInfo;+ const submitted = await withCallerAccess(await attestedCallerAccess(engine, actor, ['member:alice-example']),+ () => prepareRemoteAgent({ engine, auth: agentAuth, remote: true } as unknown as OperationContext, { source_id: SRC, allowed_tools: ['get_page', 'query'], allowed_slug_prefixes: [] }));+ const tools = buildBrainTools({ subagentId: 12, engine, config: { engine: 'pglite' } as never, sourceId: SRC,+ delegatedAuth: { clientId, scopes: ['read', 'agent'], sourceId: SRC, allowedSources: [SRC, DM_A, DM_B] } });+ const authority: RemoteAgentAuthority = { ...submitted, payloadHash: '0'.repeat(64) };+ const run = async (tool: string, input: Record<string, unknown>) => {+ try { return JSON.stringify(await withSubmissionAuthority(authority, () => tools.find(t => t.name === tool)!.execute(input, { engine, jobId: 1, remote: true } as never))); }+ catch (e) { return 'ERR ' + String((e as Error).message); }+ };+ expect(await run('brain_get_page', { slug: PAGE_A, source_id: DM_A })).toContain('canarydmalicepage');+ const theirs = await run('brain_get_page', { slug: PAGE_B, source_id: DM_B });+ expect(theirs).toContain('outside your granted sources');+ expect(theirs).not.toContain('canarydmbobpage');+ expect(await run('brain_get_page', { slug: PAGE_B })).not.toContain('canarydmbobpage');+ const found = await run('brain_query', { query: Q, limit: 20 });+ expect(found).toContain('canarydmalicepage');+ expect(found).not.toContain('canarydmbobpage');+ }, 120_000);++ test('a credential whose scalar source is another member\'s personal source neither reads nor writes there for the attested person: reads move to the kept grant, writes refuse', async () => {+ const memberPageIn = async (source: string, member: string) => Number((await engine.executeRaw<{ n: number | string }>(+ 'SELECT count(*) AS n FROM pages WHERE source_id = $1 AND slug = $2', [source, 'memory/members/' + member]))[0]!.n);+ const factsIn = async (source: string, canary: string) => Number((await engine.executeRaw<{ n: number | string }>(+ "SELECT count(*) AS n FROM facts WHERE source_id = $1 AND fact LIKE '%' || $2 || '%'", [source, canary]))[0]!.n);+ expect((await verify(clients.bobdm!)).sourceId).toBe(DM_B);+ const page = await call('bobdm', 'get_page', { slug: PAGE_B });+ expect(page.isError).toBe(true);+ expect(page.all).not.toContain('canarydmbobpage');+ const wrote = await call('bobdm', 'memory_write', { facts: [{ fact: 'Alice note on the harbor tide charts canaryscalaralice', provenance: 'turn 2' }], idempotency_key: randomUUID() }, ALICE_ID, { writeWaitMs: 30_000 });+ expect({ isError: wrote.isError, status: wrote.structured?.status }).toEqual({ isError: true, status: undefined });+ expect(wrote.json.code).toBe('permission_denied');+ expect({ page: await memberPageIn(DM_B, 'alice-example'), facts: await factsIn(DM_B, 'canaryscalaralice') }).toEqual({ page: 0, facts: 0 });+ expect((await call('bobdm', 'get_page', { slug: PAGE_B }, BOB_ID)).text).toContain('canarydmbobpage');++ const first = await call('bobfirst', 'get_page', { slug: PAGE_B });+ expect(first.json.code).toBe('page_not_found');+ expect(first.all).not.toContain('canarydmbobpage');+ expect((await call('bobfirst', 'get_page', { slug: 'notes/world-example' })).text).toContain('canaryworldpage');+ const moved = await call('bobfirst', 'memory_write', { facts: [{ fact: 'Alice second note on the harbor tide charts canaryscalarfirst', provenance: 'turn 3' }], idempotency_key: randomUUID() }, ALICE_ID, { writeWaitMs: 30_000 });+ expect({ isError: moved.isError, code: moved.json.code, status: moved.structured?.status }).toEqual({ isError: true, code: 'scope_denied', status: undefined });+ expect({ dm: await factsIn(DM_B, 'canaryscalarfirst'), src: await factsIn(SRC, 'canaryscalarfirst'), page: await memberPageIn(DM_B, 'alice-example') }).toEqual({ dm: 0, src: 0, page: 0 });+ expect((await recall('bobfirst', ALICE_ID)).text).toContain('canarymemberalice');+ }, 120_000);++ test('bindings: add is idempotent and previews with dryRun; remove previews, says when the source stops being personal, and applies with apply', async () => {+ expect(await bindMemberSource(engine, 'alice-example', DM_A)).toMatchObject({ applied: false, changed: false, owners: ['alice-example'] });+ expect(await bindMemberSource(engine, 'carol-example', DM_A, { dryRun: true })).toMatchObject({ applied: false, changed: true, owners: ['alice-example', 'carol-example'] });+ expect((await listMemberSources(engine)).map(b => [b.member_id, b.source_id])).toEqual([['alice-example', DM_A], ['bob-example', DM_B]]);+ expect((await listMemberSources(engine, { member: 'bob-example' })).map(b => b.source_id)).toEqual([DM_B]);+ await expect(bindMemberSource(engine, 'alice-example', 'source-missing')).rejects.toMatchObject({ code: 'unknown_source' });+ await expect(bindMemberSource(engine, 'nobody-example', DM_A)).rejects.toMatchObject({ code: 'access_member_invalid' });+ await expect(unbindMemberSource(engine, 'carol-example', DM_A)).rejects.toMatchObject({ code: 'invalid_params' });+ const preview = await unbindMemberSource(engine, 'bob-example', DM_B);+ expect(preview).toMatchObject({ applied: false, still_personal: false, owners: [] });+ expect((await listMemberSources(engine, { member: 'bob-example' })).length).toBe(1);+ await addMember(engine, 'dora-example');+ await bindMemberSource(engine, 'dora-example', DM_B);+ expect(await unbindMemberSource(engine, 'dora-example', DM_B, { apply: true })).toMatchObject({ applied: true, still_personal: true, owners: ['bob-example'] });+ await removeMember(engine, 'dora-example');+ await expect(bindMemberSource(engine, 'dora-example', DM_B)).rejects.toMatchObject({ code: 'access_member_invalid' });+ expect((await recall('wide', ALICE_ID)).all).not.toContain('canarydmbob');+ }, 120_000);+ });+}